From 2b4b1cc157bc4950afc70df566b6f70c4f7dce4f Mon Sep 17 00:00:00 2001 From: Matevz Jekovec Date: Thu, 4 Jun 2009 23:25:39 +0000 Subject: [PATCH 0001/1048] 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 0002/1048] 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 0003/1048] 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 0004/1048] 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 0005/1048] 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 0006/1048] 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 0007/1048] 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 0008/1048] 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 0009/1048] 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 0010/1048] 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 0011/1048] 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 0012/1048] 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 0013/1048] 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 0014/1048] 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 0015/1048] 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 0016/1048] 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 0017/1048] 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 0018/1048] 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 0019/1048] 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 0020/1048] 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 0021/1048] 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 0022/1048] 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 0023/1048] 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 0024/1048] 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 0025/1048] 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 0026/1048] 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 0027/1048] 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 0028/1048] 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 0029/1048] 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 0030/1048] 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 0031/1048] 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 0032/1048] 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 0033/1048] 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 0034/1048] 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 0035/1048] 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 0036/1048] 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 0037/1048] 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 0038/1048] 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 0039/1048] 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 0040/1048] 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 0041/1048] 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 0042/1048] 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 0043/1048] 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 0044/1048] 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 0045/1048] 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 0046/1048] 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 0047/1048] 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 0048/1048] 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 0049/1048] 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 0050/1048] 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 0051/1048] 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 0052/1048] 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 0053/1048] 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 0054/1048] 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 0055/1048] 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 0056/1048] 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 0057/1048] 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 0058/1048] 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 0059/1048] 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 0060/1048] 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 0061/1048] 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 d6060ceced397c2dd3baaba94c783d0045ddc38e Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 11 May 2012 13:55:16 +0000 Subject: [PATCH 0062/1048] Add copyright entry for Oliver Buchtala. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13067 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- COPYRIGHT | 1 + 1 file changed, 1 insertion(+) diff --git a/COPYRIGHT b/COPYRIGHT index 2fe0099b8..774761a48 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -60,6 +60,7 @@ Past SWIG developers and major contributors include: Ian Lance Taylor (Go) Vadim Zeitlin (PCRE) Stefan Zager (szager@gmail.com) (Python) + Oliver Buchtala (Javascript) Past contributors include: James Michael DuPont, Clark McGrew, Dustin Mitchell, Ian Cooke, Catalin Dumitrescu, Baran From c86ce942c2d0498169d4371bdd6c9acd503fdffa Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 11 May 2012 19:20:07 +0000 Subject: [PATCH 0063/1048] Correct place of copyright entry. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13070 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- COPYRIGHT | 1 + 1 file changed, 1 insertion(+) diff --git a/COPYRIGHT b/COPYRIGHT index 774761a48..173d1807d 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -16,6 +16,7 @@ Active SWIG Developers: Joseph Wang (joequant@gmail.com) (R) Xavier Delacour (xavier.delacour@gmail.com) (Octave) David Nadlinger (code@klickverbot.at) (D) + Oliver Buchtala (Javascript) Past SWIG developers and major contributors include: Dave Beazley (dave-swig@dabeaz.com) (SWIG core, Python, Tcl, Perl) From d71a5f483a6ad3307ff306ce2c72cfcd0e361556 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:44:54 +0000 Subject: [PATCH 0064/1048] Add module for Javascript target. This module comes with a design that allows different code emitter implementations. For the the phase of development the module is split into multiple files which will be merged together when development converges. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13737 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/javascript.swg | 15 ++ Lib/javascript/javascriptkw.swg | 40 +++++ Source/Makefile.am | 2 + Source/Modules/javascript.cxx | 246 ++++++++++++++++++++++++++ Source/Modules/javascript_emitter.cxx | 198 +++++++++++++++++++++ Source/Modules/javascript_emitter.h | 139 +++++++++++++++ Source/Modules/swigmain.cxx | 2 + 7 files changed, 642 insertions(+) create mode 100644 Lib/javascript/javascript.swg create mode 100644 Lib/javascript/javascriptkw.swg create mode 100644 Source/Modules/javascript.cxx create mode 100644 Source/Modules/javascript_emitter.cxx create mode 100644 Source/Modules/javascript_emitter.h diff --git a/Lib/javascript/javascript.swg b/Lib/javascript/javascript.swg new file mode 100644 index 000000000..fb01a63bb --- /dev/null +++ b/Lib/javascript/javascript.swg @@ -0,0 +1,15 @@ +/* ----------------------------------------------------------------------------- + * javascript.swg + * + * Javascript typemaps + * ----------------------------------------------------------------------------- */ + +%include + +%include + +%include + +%include + +%include diff --git a/Lib/javascript/javascriptkw.swg b/Lib/javascript/javascriptkw.swg new file mode 100644 index 000000000..c3c118391 --- /dev/null +++ b/Lib/javascript/javascriptkw.swg @@ -0,0 +1,40 @@ +#ifndef JAVASCRIPT_JAVASCRIPTKW_SWG_ +#define JAVASCRIPT_JAVASCRIPTKW_SWG_ + +/* Warnings for Java keywords */ +#define JAVASCRIPTKW(x) %keywordwarn("'" `x` "' is a javascript keyword, renaming to '_"`x`"'",rename="_%s") `x` + +/* Taken from https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Reserved_Words */ + +JAVASCRIPTKW(break); +JAVASCRIPTKW(case); +JAVASCRIPTKW(catch); +JAVASCRIPTKW(continue); +JAVASCRIPTKW(default); +JAVASCRIPTKW(delete); +JAVASCRIPTKW(do); +JAVASCRIPTKW(else); +JAVASCRIPTKW(finally); +JAVASCRIPTKW(for); +JAVASCRIPTKW(function); +JAVASCRIPTKW(if); +JAVASCRIPTKW(in); +JAVASCRIPTKW(instanceof); +JAVASCRIPTKW(new); +JAVASCRIPTKW(return); +JAVASCRIPTKW(switch); +JAVASCRIPTKW(this); +JAVASCRIPTKW(throw); +JAVASCRIPTKW(try); +JAVASCRIPTKW(typeof); +JAVASCRIPTKW(var); +JAVASCRIPTKW(void); +JAVASCRIPTKW(while); +JAVASCRIPTKW(with); + +/* others bad names if any*/ +// for example %namewarn("321:clone() is a javascript bad method name") *::clone(); + +#undef JAVASCRIPTKW + +#endif //JAVASCRIPT_JAVASCRIPTKW_SWG_ diff --git a/Source/Makefile.am b/Source/Makefile.am index 984b9c268..fa11bfdcb 100644 --- a/Source/Makefile.am +++ b/Source/Makefile.am @@ -49,6 +49,8 @@ eswig_SOURCES = CParse/cscanner.c \ Modules/guile.cxx \ Modules/java.cxx \ Modules/lang.cxx \ + Modules/javascript.cxx \ + Modules/javascript_emitter.cxx \ Modules/lua.cxx \ Modules/main.cxx \ Modules/modula3.cxx \ diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx new file mode 100644 index 000000000..e1336d82a --- /dev/null +++ b/Source/Modules/javascript.cxx @@ -0,0 +1,246 @@ +#include "swigmod.h" + +#include +#include +#include + +#include "javascript_emitter.h" + +/* ******************************************************************** + * JAVASCRIPT + * ********************************************************************/ + +class JAVASCRIPT : public Language { + +public: + JAVASCRIPT() {} + ~JAVASCRIPT() {} + + virtual int functionHandler(Node *n); + virtual int globalfunctionHandler(Node *n); + virtual int variableHandler(Node *n); + virtual int globalvariableHandler(Node *n); + virtual int classHandler(Node *n); + virtual int functionWrapper(Node *n); + + /** + * Registers all %fragments assigned to section "templates" with the Emitter. + **/ + virtual int fragmentDirective(Node *n); + + virtual void main(int argc, char *argv[]); + virtual int top(Node *n); + +private: + + JSEmitter* emitter; +}; + +/* --------------------------------------------------------------------- + * functionWrapper() + * + * Low level code generator for functions + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::functionWrapper(Node *n) { + + Language::functionWrapper(n); + + emitter->EmitWrapperFunction(n); + + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * functionHandler() + * + * Function handler for generating wrappers for functions + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::functionHandler(Node *n) { + + emitter->EnterFunction(n); + + Language::functionHandler(n); + + emitter->ExitFunction(n); + + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * globalfunctionHandler() + * + * Function handler for generating wrappers for functions + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::globalfunctionHandler(Node *n) { + emitter->SwitchContext(n); + + Language::globalfunctionHandler(n); + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * variableHandler() + * + * Function handler for generating wrappers for variables + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::variableHandler(Node *n) { + + emitter->EnterVariable(n); + + Language::variableHandler(n); + + emitter->ExitVariable(n); + + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * globalvariableHandler() + * + * Function handler for generating wrappers for global variables + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::globalvariableHandler(Node *n) { + + emitter->SwitchContext(n); + + Language::globalvariableHandler(n); + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * classHandler() + * + * Function handler for generating wrappers for class + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::classHandler(Node *n) { + emitter->SwitchContext(n); + + emitter->EnterClass(n); + Language::classHandler(n); + emitter->ExitClass(n); + + return SWIG_OK; +} + +int JAVASCRIPT::fragmentDirective(Node *n) { + + // catch all fragment directives that have "templates" as location + // and register them at the emitter. + String *section = Getattr(n, "section"); + + if(Cmp(section, "templates") == 0) { + emitter->RegisterTemplate(Getattr(n, "value"), Getattr(n, "code")); + } else { + Swig_fragment_register(n); + } + + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * top() + * + * Function handler for processing top node of the parse tree + * Wrapper code generation essentially starts from here + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::top(Node *n) { + + emitter->Initialize(n); + + Language::top(n); + + emitter->Dump(n); + emitter->Close(); + + delete emitter; + + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * main() + * + * Entry point for the JAVASCRIPT module + * --------------------------------------------------------------------- */ + +void JAVASCRIPT::main(int argc, char *argv[]) { + + const char* lib_dir; + + // Set javascript subdirectory in SWIG library + SWIG_library_directory("javascript"); + + int mode = -1; + + for (int i = 1; i < argc; i++) { + if (argv[i]) { + if (strcmp(argv[i], "-v8") == 0) { + Swig_mark_arg(i); + mode = JSEmitter::V8; + SWIG_library_directory("javascript/v8"); + } else if (strcmp(argv[i], "-jsc") == 0) { + Swig_mark_arg(i); + mode = JSEmitter::JavascriptCore; + SWIG_library_directory("javascript/jsc"); + } else if (strcmp(argv[i], "-qt") == 0) { + Swig_mark_arg(i); + mode = JSEmitter::QtScript; + SWIG_library_directory("javascript/qt"); + } + } + } + + switch(mode) { + case JSEmitter::V8: + { + // TODO: emitter = create_v8_emitter(); + break; + } + case JSEmitter::JavascriptCore: + { + // TODO: emitter = create_jsc_emitter(); + break; + } + case JSEmitter::QtScript: + { + // TODO: emitter = create_qtscript_emitter(); + break; + } + default: + { + Printf(stderr, "Unknown emitter type."); + SWIG_exit(-1); + } + } + + + // Add a symbol to the parser for conditional compilation + Preprocessor_define("SWIGJAVASCRIPT 1", 0); + + // Add typemap definitions + SWIG_typemap_lang("javascript"); + + // Set configuration file + SWIG_config_file("javascript.swg"); + + allow_overloading(); +} + +/* ----------------------------------------------------------------------------- + * swig_JAVASCRIPT() - Instantiate module + * ----------------------------------------------------------------------------- */ + +static Language *new_swig_javascript() { + return new JAVASCRIPT(); +} + +extern "C" Language *swig_javascript(void) { + return new_swig_javascript(); +} diff --git a/Source/Modules/javascript_emitter.cxx b/Source/Modules/javascript_emitter.cxx new file mode 100644 index 000000000..7b49aaf5d --- /dev/null +++ b/Source/Modules/javascript_emitter.cxx @@ -0,0 +1,198 @@ +#include "javascript_emitter.h" + +#include "swigmod.h" + +/* ----------------------------------------------------------------------------- + * JSEmitter() + * ----------------------------------------------------------------------------- */ + +JSEmitter::JSEmitter() + : empty_string(NewString("")) +{ + templates = NewHash(); +} + +/* ----------------------------------------------------------------------------- + * ~JSEmitter() + * ----------------------------------------------------------------------------- */ + +JSEmitter::~JSEmitter() +{ + Delete(empty_string); + Delete(templates); +} + +/* ----------------------------------------------------------------------------- + * JSEmitter::RegisterTemplate() : Registers a code template + * ----------------------------------------------------------------------------- */ + +int JSEmitter::RegisterTemplate(const String *name, const String *code) +{ + return Setattr(templates, name, code); +} + +/* ----------------------------------------------------------------------------- + * JSEmitter::GetTemplate() : Retrieves a registered a code template + * ----------------------------------------------------------------------------- */ + +const String* JSEmitter::GetTemplate(const String *name) +{ + String* templ = Getattr(templates, name); + + if(!templ) { + Printf(stderr, "Could not find template %s\n.", name); + SWIG_exit(EXIT_FAILURE); + } + + return templ; +} + +/* ----------------------------------------------------------------------------- + * JSEmitter::typemapLookup() + * n - for input only and must contain info for Getfile(n) and Getline(n) to work + * tmap_method - typemap method name + * type - typemap type to lookup + * warning - warning number to issue if no typemaps found + * typemap_attributes - the typemap attributes are attached to this node and will + * also be used for temporary storage if non null + * return is never NULL, unlike Swig_typemap_lookup() + * ----------------------------------------------------------------------------- */ + +const String *JSEmitter::typemapLookup(Node *n, const_String_or_char_ptr tmap_method, + SwigType *type, int warning, Node *typemap_attributes) { + Node *node = !typemap_attributes ? NewHash() : typemap_attributes; + Setattr(node, "type", type); + Setfile(node, Getfile(n)); + Setline(node, Getline(n)); + const String *tm = Swig_typemap_lookup(tmap_method, node, "", 0); + if (!tm) { + tm = empty_string; + if (warning != WARN_NONE) { + Swig_warning(warning, Getfile(n), Getline(n), + "No %s typemap defined for %s\n", tmap_method, SwigType_str(type, 0)); + } + } + if (!typemap_attributes) { + Delete(node); + } + return tm; +} + +/* ----------------------------------------------------------------------------- + * JSEmitter::GetBaseClass() : the node of the base class or NULL + * ----------------------------------------------------------------------------- */ + +Node* JSEmitter::GetBaseClass(Node* n) +{ + // retrieve the first base class that is not %ignored + List *baselist = Getattr(n, "bases"); + if (baselist) { + Iterator base = First(baselist); + while (base.item && GetFlag(base.item, "feature:ignore")) { + base = Next(base); + } + + return base.item; + } + + return NULL; +} + +/* ----------------------------------------------------------------------------- + * JSEmitter::EmitWrapperFunction() : dispatches emitter functions + * ----------------------------------------------------------------------------- */ + +int JSEmitter::EmitWrapperFunction(Node* n) +{ + int ret = SWIG_OK; + + current_wrapper = NewWrapper(); + Setattr(n, "wrap:name", Getattr(n, "sym:name")); + + String* kind = Getattr(n, "kind"); + + if(kind) { + bool is_member = GetFlag(n, "ismember"); + if( Cmp(kind, "function") == 0 ) { + ret = EmitFunction(n, is_member); + } else if (Cmp(kind, "variable") == 0) { + if(IsSetterMethod(n)) { + ret = EmitSetter(n, is_member); + } else { + ret = EmitGetter(n, is_member); + } + } else { + Printf(stderr, "Warning: unsupported wrapper function type\n"); + Swig_print_node(n); + } + } else { + String *view = Getattr(n, "view"); + + if( Cmp(view, "constructorHandler") == 0 ) { + ret = EmitCtor(n); + + } else if( Cmp(view, "destructorHandler") == 0 ) { + ret = EmitDtor(n); + + } else { + Printf(stderr, "Warning: unsupported wrapper function type"); + Swig_print_node(n); + } + } + + DelWrapper(current_wrapper); + current_wrapper = 0; + + return ret; +} + +/* ----------------------------------------------------------------------------- + * str_ends_with() : c string helper to check suffix match + * ----------------------------------------------------------------------------- */ + +// TODO: shift this to DOH string API +int str_ends_with(const char * str, const char * suffix) { + + if( str == NULL || suffix == NULL ) + return 0; + + size_t str_len = strlen(str); + size_t suffix_len = strlen(suffix); + + if(suffix_len > str_len) + return 0; + + return 0 == strncmp( str + str_len - suffix_len, suffix, suffix_len ); +} + +/* ----------------------------------------------------------------------------- + * JSEmitter::IsSetterMethod() : helper to check if a method is a setter function + * ----------------------------------------------------------------------------- */ + +bool JSEmitter::IsSetterMethod(Node *n) { + String* symname = Getattr(n, "sym:name"); + return ( str_ends_with( (char*) Data(symname), "_set") != 0 ); +} + +Template::Template(const String* code) +{ + if(!code) { + Printf(stdout, "Template code was null. Illegal input for template."); + SWIG_exit(EXIT_FAILURE); + } + + m_code = NewString(code); +} + +Template::~Template() { + Delete(m_code); +} + +String* Template::str() { + return m_code; +} + +Template& Template::Replace(const String* pattern, const String* repl) { + ::Replaceall(m_code, pattern, repl); + return *this; +} diff --git a/Source/Modules/javascript_emitter.h b/Source/Modules/javascript_emitter.h new file mode 100644 index 000000000..b73bb55b4 --- /dev/null +++ b/Source/Modules/javascript_emitter.h @@ -0,0 +1,139 @@ +#ifndef JAVASCRIPT_EMITTER_H +#define JAVASCRIPT_EMITTER_H + +#include "swigmod.h" + +/** + * A class that wraps a code snippet used as template for code generation. + */ +class Template { + +public: + Template(const String* code); + + ~Template(); + + String* str(); + + Template& Replace(const String* pattern, const String* repl); + +private: + String* m_code; +}; + +class JSEmitter { + +public: + + enum JSEmitterType { + JavascriptCore, + V8, + QtScript + }; + + JSEmitter(); + + virtual ~JSEmitter(); + + /** + * Opens output files and temporary output DOHs. + */ + virtual int Initialize(Node *n) = 0; + + /** + * Writes all collected code into the output file(s). + */ + virtual int Dump(Node *n) = 0; + + /** + * Cleans up all open output DOHs. + */ + virtual int Close() = 0; + + /** + * Switches the context for code generation. + * + * Classes, global variables and global functions may need to + * be registered in certain static tables. + * This method should be used to switch output DOHs correspondingly. + */ + virtual int SwitchContext(Node *n) { return SWIG_OK; }; + + /** + * Invoked at the beginning of the classHandler. + */ + virtual int EnterClass(Node *n) { return SWIG_OK; }; + + /** + * Invoked at the end of the classHandler. + */ + virtual int ExitClass(Node *n) { return SWIG_OK; }; + + /** + * Invoked at the beginning of the variableHandler. + */ + virtual int EnterVariable(Node *n) { return SWIG_OK; }; + + /** + * Invoked at the end of the variableHandler. + */ + virtual int ExitVariable(Node *n) { return SWIG_OK; }; + + /** + * Invoked at the beginning of the functionHandler. + */ + virtual int EnterFunction(Node *n) { return SWIG_OK; }; + + /** + * Invoked at the end of the functionHandler. + */ + virtual int ExitFunction(Node *n) { return SWIG_OK; }; + + /** + * Invoked by functionWrapper callback after call to Language::functionWrapper. + */ + virtual int EmitWrapperFunction(Node *n); + + /** + * Registers a given code snippet for a given key name. + * + * This method is called by the fragmentDirective handler + * of the JAVASCRIPT language module. + */ + int RegisterTemplate(const String *name, const String *code); + + /** + * Retrieve the code template registered for a given name. + */ + const String* GetTemplate(const String *name); + +protected: + + virtual int EmitCtor(Node *n) = 0; + + virtual int EmitDtor(Node *n) = 0; + + virtual int EmitFunction(Node *n, bool is_member) = 0; + + virtual int EmitGetter(Node *n, bool is_member) = 0; + + virtual int EmitSetter(Node *n, bool is_member) = 0; + + bool IsSetterMethod(Node *n); + + Node* GetBaseClass(Node *n); + + const String* typemapLookup(Node *n, const_String_or_char_ptr tmap_method, + SwigType *type, int warning, Node *typemap_attributes = 0); + +protected: + + // empty string used at different places in the code + String *empty_string; + + Hash *templates; + + Wrapper* current_wrapper; +}; + +#endif // JAVASCRIPT_EMITTER_H diff --git a/Source/Modules/swigmain.cxx b/Source/Modules/swigmain.cxx index 01ab1b79f..f4c86addc 100644 --- a/Source/Modules/swigmain.cxx +++ b/Source/Modules/swigmain.cxx @@ -53,6 +53,7 @@ extern "C" { Language *swig_r(void); Language *swig_go(void); Language *swig_d(void); + Language *swig_javascript(void); } struct swig_module { @@ -94,6 +95,7 @@ static swig_module modules[] = { {"-tcl8", swig_tcl, 0}, {"-uffi", swig_uffi, "Common Lisp / UFFI"}, {"-xml", swig_xml, "XML"}, + {"-javascript", swig_javascript, "Javascript"}, {NULL, NULL, NULL} }; From ba40fffd91bc07fc5020fe7870a6104863a39f94 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:45:35 +0000 Subject: [PATCH 0065/1048] Add initial specification of code generator templates for V8 module. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13738 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .../V8_CodeGeneratorSpecification.md | 290 ++++++++++++++++++ 1 file changed, 290 insertions(+) create mode 100644 Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md diff --git a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md new file mode 100644 index 000000000..b8e2b8a78 --- /dev/null +++ b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md @@ -0,0 +1,290 @@ +Javascript: Specification of a Code Generator for V8 +==================================================== + +The aim of this is to evolve a specification for a code generator. + +## Top Level structure + +The generated code consists of the following blocks: + +~~~~ + + + + + + + + + + +~~~~ + +- `HELPER_FUNCTIONS`: static, from swg-file +- `INCLUDES`: static, module property +- `CLASS_TEMPLATES`: dynamically growing, on class declarations +- `FUNCTION_WRAPPERS`: dynamically growing, on method declarations +- `INITIALIZER`: dynamically growing, aggregates everything (to be specified in more detail) + +## INCLUDES + +~~~~ +#include + + +~~~~ + +`USER_DEFINED_INCLUDES`: a module property + +## CLASS_TEMPLATES + +Static references to class templates which are (should be) read-only and can be reused. + +~~~~ +v8::Persistent SWIGV8_$CLASSNAME; +~~~~ + +Notes: + - it is very important to consider namespaces from the beginning. + `CLASSNAME` should be fully canonical, e.g., `foo_bar_MyClass` for `foo::bar::MyClass` + - namespaces do not need a function template, as they will not be + instantiated + +## FUNCTION_WRAPPERS + +There are different types of function wrappers: + + - Static Functions (global/namespace/class) + - Constructors / Destructors + - Getters / Settters + - Member Functions + +## Static Functions + +TODO + +## Constructors + +~~~~ +v8::Handle $CLASSNAME_new(const v8::Arguments& args) { + v8::HandleScope scope; + + // retrieve the instance + v8::Handle self = args.Holder(); + + // TODO: declare arguments + + //convert JS arguments to C++ + // TODO: apply input typemaps + + $CLASS_LVAL* ptr = new $CLASS_LVAL($ARGS); + self->SetInternalField(0, v8::External::New(ptr)); + + return self; +} +~~~~ + +- `$CLASS_LVAL`: should be the canonical name of the class, e.g. `ns1::ns2::MyClass` +- `$ARGS`: arguments should be declared at the beginning and checked and set in the + input typemap block + +## Destructors + +TODO + +## Getters + +~~~~ +v8::Handle $CLASSNAME_get$VARNAME(v8::Local property, const v8::AccessorInfo& info) { + v8::HandleScope scope; + + // retrieve pointer to C++-this + $CLASS_LVAL* self = SWIGV8_UnwrapThisPointer<$CLASS_LVAL>(info.Holder()); + $RET_LVAL retval = self->$VARNAME; + + v8::Handle ret = ; + return scope.Close(ret); +} +~~~~ + +- TODO: output typemapping + +## Setters + +~~~~ +void $CLASSNAME_set$VARNAME(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { + v8::HandleScope scope; + + // retrieve pointer to this + $CLASS_LVAL* self = SWIGV8_UnwrapThisPointer<$CLASS_LVAL>(info.Holder()); + + // TODO: declare input arg + + // map java-script type to C++ type + self->$VARNAME = ; + +} +~~~~ + +TODO: + - input type mapping should be addressed in extra step, together with type check + +## Member functions + +~~~~ +v8::Handle $CLASSNAME_$FUNCTIONNAME(const v8::Arguments& args) +{ + v8::HandleScope scope; + + $CLASS_LVAL* self = SWIGV8_UnwrapThisPointer<$CLASS_LVAL>(args.Holder()); + + // TODO: declare input args + + //convert JS arguments to C++ + // TODO: input typemappings and type checking + + //call C++ method + $RET_LTYPE result = self->$FUNCTIONNAME($ARGS); + + //convert C++ JS arguments to C++ + v8::Handle ret = ; + + return scope.Close(ret); +} +~~~~ + +- if the function does not have a return value, return v8::Undefined + +## Initializer + +~~~~ +void $MODULENAME_Initialize(v8::Handle context) +{ + v8::HandleScope scope; + + // register the module in globale context + v8::Local global = context->Global(); + + + + + + + + + + +} +~~~~ + +## Namespaces + +Namespaces are objects without class templates. I.e., instances are created, +referenced locally, used as contexts for other registrations, and stored +in the according parent contexts. + +## Create Class Template + +~~~~ + SWIGV8_$CLASSNAME = SWIGV8_CreateClassTemplate("$LOCAL_CLASSNAME" , $CLASSNAME_new); +~~~~ + +- `LOCAL_CLASSNAME`: the class name without context, i.e., namespaces + +## Add Member Function + +~~~~ + SWIGV8_AddClassMethod(SWIGV8_$CLASSNAME, "$METHODNAME", $METHOD_WRAPPER); +~~~~ + +- `METHODNAME`: the name of the function as in C++ +- `METHOD_WRAPPER`: the name of the generated wrapper function + TODO: specify different versions + +## Add Property + +~~~~ + SWIGV8_AddProperty(SWIGV8_$CLASSNAME, "$VARNAME", $GET_WRAPPER, $SET_WRAPPER); +~~~~ + +- `GET_WRAPPER`: the name of the generated wrapper for the property getter +- `SET_WRAPPER`: the name of the generated wrapper for property setter; optional (i.e., maybe `NULL`) + +## Inheritance + +~~~~ + SWIGV8_$CLASSNAME->Inherit(SWIGV8_$SUPERCLASS); +~~~~ + +- Note: multiple inheritance is not possible; thus we will always take the first parent class + +## Register class + +~~~~ + $CONTEXT->Set(v8::String::NewSymbol("$LOCAL_CLASSNAME"), SWIGV8_$CLASSNAME->GetFunction()); +~~~~ + +- Note: every class template has an associated ctor function wrapper, which is registered here +- `CONTEXT`: either global, or the according namespace instance + +## HELPER_FUNCTIONS + +A lot of boiler-plate code can be shifted into static helper functions: + +~~~~ + +/** + * Creates a class template for a class without extra initialization function. + */ +v8::Persistent SWIGV8_CreateClassTemplate(const char* symbol) { + v8::Local class_templ = v8::FunctionTemplate::New(); + class_templ->SetClassName(v8::String::NewSymbol(symbol)); + + v8::Handle inst_templ = class_templ->InstanceTemplate(); + inst_templ->SetInternalFieldCount(1); + + return v8::Persistent::New(class_templ); +} + +/** + * Creates a class template for a class with specified initialization function. + */ +v8::Persistent SWIGV8_CreateClassTemplate(const char* symbol, v8::InvocationCallback _func) { + v8::Local class_templ = v8::FunctionTemplate::New(_func); + class_templ->SetClassName(v8::String::NewSymbol(symbol)); + + v8::Handle inst_templ = class_templ->InstanceTemplate(); + inst_templ->SetInternalFieldCount(1); + + return v8::Persistent::New(class_templ); +} + +/** + * Sets the pimpl data of a V8 class. + */ +v8::Handle V8GeneratorUtils::SetInstance(const v8::Arguments& args, void* data) { + v8::HandleScope scope; + + v8::Handle self = args.Holder(); + self->SetInternalField(0, v8::External::New(data)); + + return self; +} + +/** + * Registers a class method with given name for a given class template. + */ +void V8GeneratorUtils::AddClassMethod(v8::Handle class_templ, const char* symbol, v8::InvocationCallback _func) { + v8::Handle proto_templ = class_templ->PrototypeTemplate(); + proto_templ->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)); +} + +/** + * Registers a class property with given name for a given class template. + */ +void V8GeneratorUtils::AddProperty(v8::Handle class_templ, const char* varname, v8::AccessorGetter getter, v8::AccessorSetter setter) { + v8::Handle proto_templ = class_templ->InstanceTemplate(); + proto_templ->SetAccessor(v8::String::New(varname), getter, setter); +} + +~~~~ From 5c3fef6367ba41982032dea8a2b29f6a7f62de9f Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:45:49 +0000 Subject: [PATCH 0066/1048] Add initial version of a CMake configuration. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13739 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- CMakeLists.txt | 175 +++++++++++++++++++++++++++++++++++++++ Tools/swigconfig.h.cmake | 89 ++++++++++++++++++++ 2 files changed, 264 insertions(+) create mode 100644 CMakeLists.txt create mode 100644 Tools/swigconfig.h.cmake diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 000000000..442fa6d6a --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,175 @@ +project(swig) +cmake_minimum_required(VERSION 2.8) + +# Project wide configuration variables +# ------------------------------------ + +set(SWIG_VERSION 2.0.6) +set(SWIG_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/Source" CACHE INTERNAL "Path of swig sources" FORCE) + +# Configure +# --------- + +include(CheckIncludeFiles) +include(CheckIncludeFile) +include(CheckTypeSize) +include(CheckSymbolExists) +include(CheckLibraryExists) +include(CheckCSourceCompiles) + +# HACK: didn't get the bool check working for Visual Studio 2008 +if(MSVC) +set(HAVE_BOOL 1) +else() +set(CMAKE_EXTRA_INCLUDE_FILES stdbool.h) +check_type_size("bool" HAVE_BOOL) +set(CMAKE_EXTRA_INCLUDE_FILES) +endif() + +check_include_file("inttypes.h" HAVE_INTTYPES_H) +check_include_file("memory.h" HAVE_MEMORY_H) +check_include_file("stddef.h" HAVE_STDDEF_H) +check_include_file("stdint.h" HAVE_STDINT_H) +check_include_file("stdlib.h" HAVE_STDLIB_H) +check_include_file("string.h" HAVE_STRING_H) +check_include_file("strings.h" HAVE_STRINGS_H) +check_include_file("sys/stat.h" HAVE_SYS_STAT_H) +check_include_file("sys/types.h" HAVE_SYS_TYPES_H) +check_include_file("unistd.h" HAVE_UNISTD_H) +check_include_files( "stdlib.h;stdarg.h;string.h;float.h" HAVE_STDC_HEADERS ) + +check_library_exists(dl dlopen "" HAVE_LIBDL) + +configure_file(${CMAKE_CURRENT_SOURCE_DIR}/Tools/swigconfig.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/Source/Include/swigconfig.h) + +# Compiler flags +# -------------- + +include_directories("${SWIG_SOURCE_DIR}/CParse" + "${SWIG_SOURCE_DIR}/Include" + "${SWIG_SOURCE_DIR}/DOH" + "${SWIG_SOURCE_DIR}/Swig" + "${SWIG_SOURCE_DIR}/Preprocessor" + "${SWIG_SOURCE_DIR}/Modules" + "${PROJECT_BINARY_DIR}/Source/Include" +) + +# Pre-Build +# --------- + +# Copy Lib directory into the build dist folder +file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/Dist) +file(COPY ${PROJECT_SOURCE_DIR}/Lib DESTINATION ${PROJECT_BINARY_DIR}/Dist) + +# add the command to generate the source code (depends on bison) +file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/Source/CParse) +add_custom_command ( + OUTPUT ${PROJECT_BINARY_DIR}/Source/CParse/parser.c + DEPENDS ${SWIG_SOURCE_DIR}/CParse/parser.y + COMMAND bison -o ${PROJECT_BINARY_DIR}/Source/CParse/parser.c --defines=${PROJECT_BINARY_DIR}/Source/Include/parser.h ${SWIG_SOURCE_DIR}/CParse/parser.y +) +set_property(SOURCE ${PROJECT_BINARY_DIR}/Source/CParse/parser.c PROPERTY GENERATED 1) +set_property(SOURCE ${PROJECT_BINARY_DIR}/Source/CParse/parser.h PROPERTY GENERATED 1) + +# generate swigwarn.swg +file(READ ${SWIG_SOURCE_DIR}/Include/swigwarn.h SWIG_WARN_H) +string(REGEX REPLACE "#define WARN([^ \\t]*)[ \\t]*([0-9]+)" "%define SWIGWARN\\1 \\2 %enddef" SWIG_WARN_SWG ${SWIG_WARN_H}) +file(WRITE ${PROJECT_BINARY_DIR}/Dist/Lib/swigwarn.swg ${SWIG_WARN_SWG}) +set_property(SOURCE ${PROJECT_BINARY_DIR}/Dist/Lib/swigwarn.swg PROPERTY GENERATED 1) + +# Libraries +# --------- + +add_library(cparse "${SWIG_SOURCE_DIR}/CParse/cscanner.c" + "${SWIG_SOURCE_DIR}/CParse/templ.c" + "${SWIG_SOURCE_DIR}/CParse/util.c" + "${PROJECT_BINARY_DIR}/Source/CParse/parser.c" + "${PROJECT_BINARY_DIR}/Source/CParse/parser.h" +) + +add_library(preprocessor "${SWIG_SOURCE_DIR}/Preprocessor/cpp.c" + "${SWIG_SOURCE_DIR}/Preprocessor/expr.c" +) + +add_library(doh "${SWIG_SOURCE_DIR}/DOH/base.c" + "${SWIG_SOURCE_DIR}/DOH/file.c" + "${SWIG_SOURCE_DIR}/DOH/fio.c" + "${SWIG_SOURCE_DIR}/DOH/hash.c" + "${SWIG_SOURCE_DIR}/DOH/list.c" + "${SWIG_SOURCE_DIR}/DOH/memory.c" + "${SWIG_SOURCE_DIR}/DOH/string.c" + "${SWIG_SOURCE_DIR}/DOH/void.c" +) + +add_library(core "${SWIG_SOURCE_DIR}/Swig/cwrap.c" + "${SWIG_SOURCE_DIR}/Swig/deprecate.c" + "${SWIG_SOURCE_DIR}/Swig/error.c" + "${SWIG_SOURCE_DIR}/Swig/fragment.c" + "${SWIG_SOURCE_DIR}/Swig/getopt.c" + "${SWIG_SOURCE_DIR}/Swig/include.c" + "${SWIG_SOURCE_DIR}/Swig/misc.c" + "${SWIG_SOURCE_DIR}/Swig/naming.c" + "${SWIG_SOURCE_DIR}/Swig/parms.c" + "${SWIG_SOURCE_DIR}/Swig/scanner.c" + "${SWIG_SOURCE_DIR}/Swig/stype.c" + "${SWIG_SOURCE_DIR}/Swig/symbol.c" + "${SWIG_SOURCE_DIR}/Swig/tree.c" + "${SWIG_SOURCE_DIR}/Swig/typemap.c" + "${SWIG_SOURCE_DIR}/Swig/typeobj.c" + "${SWIG_SOURCE_DIR}/Swig/typesys.c" + "${SWIG_SOURCE_DIR}/Swig/wrapfunc.c" +) + +add_library(modules "${SWIG_SOURCE_DIR}/Modules/allegrocl.cxx" + "${SWIG_SOURCE_DIR}/Modules/allocate.cxx" + "${SWIG_SOURCE_DIR}/Modules/browser.cxx" + "${SWIG_SOURCE_DIR}/Modules/cffi.cxx" + "${SWIG_SOURCE_DIR}/Modules/chicken.cxx" + "${SWIG_SOURCE_DIR}/Modules/clisp.cxx" + "${SWIG_SOURCE_DIR}/Modules/contract.cxx" + "${SWIG_SOURCE_DIR}/Modules/csharp.cxx" + "${SWIG_SOURCE_DIR}/Modules/d.cxx" + "${SWIG_SOURCE_DIR}/Modules/directors.cxx" + "${SWIG_SOURCE_DIR}/Modules/emit.cxx" + "${SWIG_SOURCE_DIR}/Modules/go.cxx" + "${SWIG_SOURCE_DIR}/Modules/guile.cxx" + "${SWIG_SOURCE_DIR}/Modules/java.cxx" + "${SWIG_SOURCE_DIR}/Modules/javascript.cxx" + "${SWIG_SOURCE_DIR}/Modules/javascript_emitter.h" + "${SWIG_SOURCE_DIR}/Modules/javascript_emitter.cxx" + "${SWIG_SOURCE_DIR}/Modules/lang.cxx" + "${SWIG_SOURCE_DIR}/Modules/lua.cxx" + "${SWIG_SOURCE_DIR}/Modules/modula3.cxx" + "${SWIG_SOURCE_DIR}/Modules/module.cxx" + "${SWIG_SOURCE_DIR}/Modules/mzscheme.cxx" + "${SWIG_SOURCE_DIR}/Modules/ocaml.cxx" + "${SWIG_SOURCE_DIR}/Modules/octave.cxx" + "${SWIG_SOURCE_DIR}/Modules/overload.cxx" + "${SWIG_SOURCE_DIR}/Modules/perl5.cxx" + "${SWIG_SOURCE_DIR}/Modules/php.cxx" + "${SWIG_SOURCE_DIR}/Modules/pike.cxx" + "${SWIG_SOURCE_DIR}/Modules/python.cxx" + "${SWIG_SOURCE_DIR}/Modules/r.cxx" + "${SWIG_SOURCE_DIR}/Modules/ruby.cxx" + "${SWIG_SOURCE_DIR}/Modules/s-exp.cxx" + "${SWIG_SOURCE_DIR}/Modules/tcl8.cxx" + "${SWIG_SOURCE_DIR}/Modules/typepass.cxx" + "${SWIG_SOURCE_DIR}/Modules/uffi.cxx" + "${SWIG_SOURCE_DIR}/Modules/utils.cxx" + "${SWIG_SOURCE_DIR}/Modules/xml.cxx" + "${PROJECT_BINARY_DIR}/Source/Include/swigconfig.h" + "${SWIG_SOURCE_DIR}/Include/swigwarn.h" +) + +add_executable(swig + "${SWIG_SOURCE_DIR}/Modules/main.cxx" + "${SWIG_SOURCE_DIR}/Modules/swigmain.cxx" +) + +target_link_libraries(swig cparse preprocessor doh core modules) + +# copy binary into Dist folder +get_property(SWIG_EXECUTABLE TARGET swig PROPERTY LOCATION) +add_custom_command(TARGET swig POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy ${SWIG_EXECUTABLE} ${PROJECT_BINARY_DIR}/Dist +) diff --git a/Tools/swigconfig.h.cmake b/Tools/swigconfig.h.cmake new file mode 100644 index 000000000..e4f0b42c4 --- /dev/null +++ b/Tools/swigconfig.h.cmake @@ -0,0 +1,89 @@ +/* Define to 1 if the system has the type `bool'. */ +#cmakedefine HAVE_BOOL 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the `dl' library (-ldl). */ +#cmakedefine HAVE_LIBDL 1 + +/* Define to 1 if you have the `dld' library (-ldld). */ +#cmakedefine HAVE_LIBDLD 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_MEMORY_H 1 + +/* Define if popen is available */ +#cmakedefine HAVE_POPEN 1 + +/* Define if rxspencer is available */ +#cmakedefine HAVE_RXSPENCER 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STDLIB_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STRING_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_UNISTD_H 1 + +/* Define to 1 if your C compiler doesn't accept -c and -o together. */ +#cmakedefine NO_MINUS_C_MINUS_O 1 + +/* Define to 1 if you have the ANSI C header files. */ +#cmakedefine STDC_HEADERS 1 + +/* Name of package */ +#define PACKAGE "swig" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "http://www.swig.org" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "swig" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "swig @SWIG_VERSION@" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "swig" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "@SWIG_VERSION@" + +/* Compiler that built SWIG */ +#define SWIG_CXX "@SWIG_CXX@" + +/* Directory for SWIG system-independent libraries */ +#define SWIG_LIB "/usr/local/share/swig/2.0.0" + +/* Directory for SWIG system-independent libraries (Unix install on native + Windows) */ +#define SWIG_LIB_WIN_UNIX "C:/cygwin/usr/local/share/swig/2.0.0" + +/* Platform that SWIG is built for */ +#define SWIG_PLATFORM "i686-pc-cygwin" + +/* Version number of package */ +#define VERSION "@SWIG_VERSION@" + +/* Default language */ +#define SWIG_LANG "-tcl" + +/* Deal with Microsoft's attempt at deprecating C standard runtime functions */ +#if defined(_MSC_VER) +# define _CRT_SECURE_NO_DEPRECATE +#endif From 5b5fdb171e720228b24c2f9fbb1667649693b3ab Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:46:03 +0000 Subject: [PATCH 0067/1048] Add a paragraph about control flow analysis to V8 specification. Control flow analysis for use cases: - static variables - simple class - class properties - class methods - static class variables and functions - inheritance. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13740 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .../V8_CodeGeneratorSpecification.md | 318 ++++++++++++++++++ 1 file changed, 318 insertions(+) diff --git a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md index b8e2b8a78..2990f1d00 100644 --- a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md +++ b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md @@ -288,3 +288,321 @@ void V8GeneratorUtils::AddProperty(v8::Handle class_templ, } ~~~~ + +# Control flow analysis + +## Global variables + +### Example: +~~~~ +int x; + +namespace foo { + double y; +} +~~~~ + +### Control flow: +Command: +~~~~ +swig -analyze -c++ functionWrapper +before globalvariableHandler +before example.i +~~~~ + +~~~~ +enter top() of example +enter variableHandler() of x +enter globalvariableHandler() of x + | sym:name - "x" + | name - "x" + | type - "int" + + enter variableWrapper() of x + + enter functionWrapper() of x + | name - "x" + | sym:name - "x_set" + | parms - int + | wrap:action - "x = arg1;" + | type - "void" + exit functionWrapper() of x + + enter functionWrapper() of x + | name - "x" + | sym:name - "x_get" + | type - "int" + exit functionWrapper() of x + exit variableWrapper() of x +exit globalvariableHandler() of x +exit variableHandler() of x + +enter variableHandler() of foo::y +enter globalvariableHandler() of foo::y + | sym:name - "y" + | name - "foo::y" + | type - "double" + + enter variableWrapper() of foo::y + enter functionWrapper() of foo::y + | name - "foo::y" + | sym:name - "y_set" + | parms - double + | wrap:action - "foo::y = arg1;" + | type - "void" + exit functionWrapper() of foo::y + + enter functionWrapper() of foo::y + | name - "foo::y" + | sym:name - "y_get" + | wrap:action - "result = (double)foo::y;" + | type - "double" + exit functionWrapper() of foo::y + exit variableWrapper() of foo::y +exit globalvariableHandler() of foo::y +exit variableHandler() of foo::y +exit top() of example + +~~~~ + +## Simple class + +### Example: + +~~~~ +class A { +public: + A(); + ~A(); +}; + +namespace foo { + class B { + }; +} +~~~~ + +### Control flow: + +~~~~ +enter top() of example + enter classHandler() of A + enter constructorHandler() of A + enter functionWrapper() of A + | name - "A" + | sym:name - "new_A" + | access - "public" + | wrap:action - "result = (A *)new A();" + | type - "p.A" + exit functionWrapper() of A + exit constructorHandler() of A + enter destructorHandler() of ~A + enter functionWrapper() of ~A + | name - "~A" + | sym:name - "delete_A" + | parms - A * + | wrap:action - "delete arg1;" + exit functionWrapper() of ~A + exit destructorHandler() of ~A +exit classHandler() of A +enter classHandler() of foo::B + enter constructorHandler() of foo::B::B + enter functionWrapper() of foo::B::B + | name - "foo::B::B" + | sym:name - "new_B" + | access - "public" + | wrap:action - "result = (foo::B *)new foo::B();" + | type - "p.foo::B" + exit functionWrapper() of foo::B::B + exit constructorHandler() of foo::B::B + enter destructorHandler() of foo::B::~B + enter functionWrapper() of foo::B::~B + | name - "foo::B::~B" + | sym:name - "delete_B" + | parms - foo::B * + | wrap:action - "delete arg1;" + | type - "void" + exit functionWrapper() of foo::B::~B + exit destructorHandler() of foo::B::~B +exit classHandler() of foo::B +exit top() of example + +~~~~ + +### Example + +~~~~ +class A { +public: + int x; +}; +~~~~ + + +### Control flow + +~~~~ +enter top() of example +enter classHandler() of A + enter variableHandler() of x + enter membervariableHandler() of x + enter functionWrapper() of x + | name - "x" + | sym:name - "A_x_set" + | access - "public" + | parms - A *,int + | wrap:action - "if (arg1) (arg1)->x = arg2;" + | type - "void" + | memberset - "1" + exit functionWrapper() of x + enter functionWrapper() of x + | name - "x" + | sym:name - "A_x_get" + | access - "public" + | parms - A * + | wrap:action - "result = (int) ((arg1)->x);" + | type - "int" + | memberset - "1" + | memberget - "1" + exit functionWrapper() of x + exit membervariableHandler() of x + exit variableHandler() of x + enter constructorHandler() of A::A + enter functionWrapper() of A::A + exit functionWrapper() of A::A + exit constructorHandler() of A::A + enter destructorHandler() of A::~A + enter functionWrapper() of A::~A + exit functionWrapper() of A::~A + exit destructorHandler() of A::~A +exit classHandler() of A +exit top() of example +~~~~ + +## Class method + +### Example + +~~~~ +class A { +public: + void foo(int x, double y); +private: + void bar(); +}; +~~~~ + +### Control flow + +~~~~ +enter top() of example +enter classHandler() of A + enter functionHandler() of foo + enter memberfunctionHandler() of foo + enter functionWrapper() of foo + | name - "foo" + | sym:name - "A_foo" + | access - "public" + | parms - A *,int,double + | wrap:action - "(arg1)->foo(arg2,arg3);" + | type - "void" + exit functionWrapper() of foo + exit memberfunctionHandler() of foo + exit functionHandler() of foo +... +exit classHandler() of A +exit top() of example +~~~~ + +## Static class variable and method + +### Example + +~~~~ +class A { +public: + static int x; + + static void foo(); +}; +~~~~ + +### Control flow + +~~~~ +enter top() of example +enter classHandler() of A + enter variableHandler() of x + enter staticmembervariableHandler() of x + enter variableWrapper() of A::x + enter functionWrapper() of A::x + | name - "A::x" + | sym:name - "A_x_set" + | parms - int + | wrap:action - "A::x = arg1;" + | type - "void" + exit functionWrapper() of A::x + enter functionWrapper() of A::x + +++ cdecl ---------------------------------------- + | name - "A::x" + | ismember - "1" + | sym:name - "A_x_get" + | variableWrapper:sym:name - "A_x" + | wrap:action - "result = (int)A::x;" + | type - "int" + exit functionWrapper() of A::x + exit variableWrapper() of A::x + exit staticmembervariableHandler() of x + exit variableHandler() of x + enter functionHandler() of foo + enter staticmemberfunctionHandler() of foo + enter globalfunctionHandler() of A::foo + enter functionWrapper() of A::foo + | name - "A::foo" + | sym:name - "A_foo" + | wrap:action - "A::foo();" + | type - "void" + exit functionWrapper() of A::foo + exit globalfunctionHandler() of A::foo + exit staticmemberfunctionHandler() of foo + exit functionHandler() of foo + enter constructorHandler() of A::A + exit constructorHandler() of A::A + enter destructorHandler() of A::~A + exit destructorHandler() of A::~A +exit classHandler() of A +exit top() of example +~~~~ + +## Inheritance + +### Example + +~~~~ +class A { +}; + +class B: public A { +}; +~~~~ + +### Control flow + +~~~~ +enter top() of example +enter classHandler() of A + +++ class ---------------------------------------- + | name - "A" + | sym:name - "A" +... +exit classHandler() of A +enter classHandler() of B + | name - "B" + | sym:name - "B" + | privatebaselist - 0xf1238f10 + | protectedbaselist - 0xf1238ef0 + | baselist - 0xf1238ed0 + | bases - 0xf1239830 + | allbases - 0xf1239c30 +... +exit classHandler() of B +exit top() of example +~~~~ From e888d7a892702aa0a3e42449737c8f1bfb747a2f Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:46:18 +0000 Subject: [PATCH 0068/1048] Add a document about mapping C++ language features to Javascript. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13741 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .../Javascript/MappingC++ToJavascript.md | 220 ++++++++++++++++++ 1 file changed, 220 insertions(+) create mode 100644 Doc/Devel/Javascript/MappingC++ToJavascript.md diff --git a/Doc/Devel/Javascript/MappingC++ToJavascript.md b/Doc/Devel/Javascript/MappingC++ToJavascript.md new file mode 100644 index 000000000..c77064933 --- /dev/null +++ b/Doc/Devel/Javascript/MappingC++ToJavascript.md @@ -0,0 +1,220 @@ +# Mapping C++ language features to Javascript + +## Namespaces + +A namespace is represented as a static instance (global variable) +containing other namespaces, global variables and functions +and class templates + +### Example: + +C++: + +~~~~c++ +namespace foo { + int x; + namespace bar { + double y; + } +} +~~~~ + +Javascript: + +~~~~javascript +var foo = new Object(); +foo.x = 0; +foo.bar = new Object(); +foo.bar.y = 0.0; +~~~~ + +## Global variables and functions + +Global variables and functions are properties of other context objects +(global or namespaces). + +### Example: + +C++: + +~~~~c++ +int x; +namespace foo { + void bar(); +} +~~~~ + +Javascript: + +~~~~javascript +var x = 0; +var foo = new Object(); +foo.bar = function() { + return undefined; +} +~~~~ + +## Classes + +Classes are defined as class templates and instantiated using the `new` +operator. +Class members are set in the constructor function using the `this` reference. +Private class members are set using the `var` keyword. + +### Example: + +C++: + +~~~~c++ +class Foo { + int bar(); + +private: + int x; +} +~~~~ + +Javascript: + +~~~~javascript +var Foo = function() { + var x = 42; + this.bar = function() { return x; }; +}; + +var foo = new Foo(); +foo.bar(); +~~~~ + +## Static class members and functions + +Static variables and functions should be added to the class template object. + +~~~~c++ +class Foo { + static std::string foo(); + std::string bar(); +} +~~~~ + +Javascript: + +~~~~javascript +var Foo = function() { + this.bar = function() { + return "bar"; + } +}; +Foo.foo = function() { + return "foo"; +}; + +var foo = new Foo(); +foo.foo() +> TypeError: Object [object Object] has no method 'foo' +Foo.foo() +> "foo" +foo.bar(); +> "bar" +~~~~ + +## Inheritance + +Javascript uses a prototype based inheritance mechanism. This limits +feature support to single inheritance. + +### Example: + +C++: + +~~~~c++ +class Foo { +public: + int foo(); + +private: + int x; +} + +class Bar: public Foo { +public: + int bar(); +} +~~~~ + +Javascript: + +~~~~javascript +var Foo = function() { + var x = 42; + this.foo = function() { return x; }; +}; + +var Bar = function() { + this.bar = function() { return 6; }; +} +Bar.prototype = new Foo(); +Bar.prototype.constructor = Bar; + +var foo = new Foo(); +var bar = new Bar(); + +foo.foo() +> 42 +foo.bar() +> TypeError: Object [object Object] has no method 'bar' +bar.foo() +> 42 +bar.bar() +> 6 +~~~~ + +## Virtual methods + +The prototype mechanism of Javascript allows method overriding which is +needed to map the concept of virtual functions. + +### Example: + +C++: + +~~~~c++ +class Foo { +public: + virtual int foo(); +} + +class Bar: public Foo { +public: + virtual int foo(); +} +~~~~ + +Javascript: + +~~~~javascript +var Foo = function() { + this.foo = function() { return 1; }; +}; + +var Bar = function() {} +Bar.prototype = new Foo(); +Bar.prototype.constructor = Bar; +Bar.prototype.foo = function() { return 42; }; + +var foo = new Foo(); +var bar = new Bar(); + +foo.foo() +> 1 +bar.foo() +> 42 +~~~~ + +## Overloading + +In Javascript like in other scripting languages method overloading is not +available. I.e., there can only be one function for one function name. +Therefore, it is necessary to implement a method dispatching mechanism +for these methods. + From 4bcfca05dd0eff51c4ecfa11ed182a6bcf147dbf Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:46:31 +0000 Subject: [PATCH 0069/1048] Add some implementation details to specification of v8 code generator. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13742 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .../Javascript/V8_CodeGeneratorSpecification.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md index 2990f1d00..b7d06e220 100644 --- a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md +++ b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md @@ -46,7 +46,8 @@ v8::Persistent SWIGV8_$CLASSNAME; Notes: - it is very important to consider namespaces from the beginning. - `CLASSNAME` should be fully canonical, e.g., `foo_bar_MyClass` for `foo::bar::MyClass` + `CLASSNAME` should be the mangled qualified class name, e.g., `foo_bar_MyClass` for `foo::bar::MyClass`, + which is retrieved ny `Swig_string_mangle(Getattr(n, "name"))` - namespaces do not need a function template, as they will not be instantiated @@ -84,7 +85,8 @@ v8::Handle $CLASSNAME_new(const v8::Arguments& args) { } ~~~~ -- `$CLASS_LVAL`: should be the canonical name of the class, e.g. `ns1::ns2::MyClass` +- `$CLASS_LVAL`: should be the canonical name of the class, e.g. `ns1::ns2::MyClass`, + which can be retrieved using `Getattr(n, "name")` - `$ARGS`: arguments should be declared at the beginning and checked and set in the input typemap block @@ -189,7 +191,8 @@ in the according parent contexts. SWIGV8_$CLASSNAME = SWIGV8_CreateClassTemplate("$LOCAL_CLASSNAME" , $CLASSNAME_new); ~~~~ -- `LOCAL_CLASSNAME`: the class name without context, i.e., namespaces +- `LOCAL_CLASSNAME`: the class name without context, i.e., namespaces, + which is retrieved by `Getattr(n, "sym:name")` ## Add Member Function @@ -198,8 +201,8 @@ in the according parent contexts. ~~~~ - `METHODNAME`: the name of the function as in C++ -- `METHOD_WRAPPER`: the name of the generated wrapper function - TODO: specify different versions +- `METHOD_WRAPPER`: the name of the generated wrapper function, which + should have the form `wrap__` ## Add Property From 3c30e2d382cbbacef66563bcc8d54289f9543339 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:47:19 +0000 Subject: [PATCH 0070/1048] Add initial Javascript V8 emitter implementation. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13743 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- CMakeLists.txt | 2 + Lib/javascript/v8/javascriptcode.swg | 73 ++++ Lib/javascript/v8/javascripthelpers.swg | 58 ++++ Lib/javascript/v8/javascriptprimitives.swg | 265 +++++++++++++++ Lib/javascript/v8/javascriptruntime.swg | 9 + Source/Makefile.am | 1 + Source/Modules/javascript.cxx | 4 +- Source/Modules/javascript_v8.cxx | 369 +++++++++++++++++++++ Source/Modules/javascript_v8.h | 77 +++++ 9 files changed, 857 insertions(+), 1 deletion(-) create mode 100644 Lib/javascript/v8/javascriptcode.swg create mode 100644 Lib/javascript/v8/javascripthelpers.swg create mode 100644 Lib/javascript/v8/javascriptprimitives.swg create mode 100644 Lib/javascript/v8/javascriptruntime.swg create mode 100644 Source/Modules/javascript_v8.cxx create mode 100644 Source/Modules/javascript_v8.h diff --git a/CMakeLists.txt b/CMakeLists.txt index 442fa6d6a..e7d96cc8e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -137,6 +137,8 @@ add_library(modules "${SWIG_SOURCE_DIR}/Modules/allegrocl.cxx" "${SWIG_SOURCE_DIR}/Modules/javascript.cxx" "${SWIG_SOURCE_DIR}/Modules/javascript_emitter.h" "${SWIG_SOURCE_DIR}/Modules/javascript_emitter.cxx" + "${SWIG_SOURCE_DIR}/Modules/javascript_v8.h" + "${SWIG_SOURCE_DIR}/Modules/javascript_v8.cxx" "${SWIG_SOURCE_DIR}/Modules/lang.cxx" "${SWIG_SOURCE_DIR}/Modules/lua.cxx" "${SWIG_SOURCE_DIR}/Modules/modula3.cxx" diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg new file mode 100644 index 000000000..1b6d33662 --- /dev/null +++ b/Lib/javascript/v8/javascriptcode.swg @@ -0,0 +1,73 @@ + +%fragment("v8_initializer", "templates") %{ +void ${MODULE}_Initialize(v8::Handle context) +{ + v8::HandleScope scope; + + // register the module in globale context + v8::Local global = context->Global(); + + ${PART_NAMESPACES} + + ${PART_CLASS_TEMPLATES} + + ${PART_WRAPPERS} + + ${PART_INHERITANCE} + + ${PART_REGISTER} +}%} + +%fragment("v8_declare_class_template", "templates") %{ +v8::Persistent SWIGV8_${NAME_MANGLED};%} + +%fragment("v8_define_class_template", "templates") %{ +SWIGV8_${NAME_MANGLED} = SWIGV8_CreateClassTemplate("${NAME_UNQUALIFIED}" , ${NAME_MANGLED}_new);%} + +%fragment("v8_inherit", "templates") %{ +SWIGV8_${NAME_MANGLED}->Inherit(SWIGV8_${BASE_CLASS});%} + +%fragment("v8_register_class", "templates") %{ +${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}", SWIGV8_${NAME_MANGLED}->GetFunction()));%} + +%fragment("v8_ctor_wrapper", "templates") %{ +v8::Handle ${NAME_MANGLED}_new(const v8::Arguments& args) { + v8::HandleScope scope; + v8::Handle self = args.Holder(); + ${LOCALS} + ${ACTION} + self->SetInternalField(0, v8::External::New(ptr)); + return self; +} +%} + +%fragment("v8_getter", "templates") %{ +v8::Handle ${NAME_MANGLED}_get(v8::Local property, const v8::AccessorInfo& info) { + v8::HandleScope scope; + v8::Handle ret; + ${LOCALS} + ${ACTION} + ${MARSHAL_OUTPUT} + return scope.Close(ret); +} +%} + +%fragment("v8_setter", "templates") %{ +void ${NAME_MANGLED}_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { + ${LOCALS} + ${MARSHAL_INPUT} + ${ACTION} +} +%} + +%fragment("v8_function", "templates") %{ +v8::Handle ${NAME_MANGLED}(const Arguments &args) { + v8::HandleScope scope; + v8::Handle ret; + ${LOCALS} + ${MARSHAL_INPUT} + ${ACTION} + ${MARSHAL_OUTPUT} + return scope.Close(ret); +} +%} diff --git a/Lib/javascript/v8/javascripthelpers.swg b/Lib/javascript/v8/javascripthelpers.swg new file mode 100644 index 000000000..61836c87d --- /dev/null +++ b/Lib/javascript/v8/javascripthelpers.swg @@ -0,0 +1,58 @@ + +%insert(runtime) %{ + +/** + * Creates a class template for a class without extra initialization function. + */ +v8::Persistent SWIGV8_CreateClassTemplate(const char* symbol) { + v8::Local class_templ = v8::FunctionTemplate::New(); + class_templ->SetClassName(v8::String::NewSymbol(symbol)); + + v8::Handle inst_templ = class_templ->InstanceTemplate(); + inst_templ->SetInternalFieldCount(1); + + return v8::Persistent::New(class_templ); +} + +/** + * Creates a class template for a class with specified initialization function. + */ +v8::Persistent SWIGV8_CreateClassTemplate(const char* symbol, v8::InvocationCallback _func) { + v8::Local class_templ = v8::FunctionTemplate::New(_func); + class_templ->SetClassName(v8::String::NewSymbol(symbol)); + + v8::Handle inst_templ = class_templ->InstanceTemplate(); + inst_templ->SetInternalFieldCount(1); + + return v8::Persistent::New(class_templ); +} + +/** + * Sets the pimpl data of a V8 class. + */ +v8::Handle V8GeneratorUtils::SetInstance(const v8::Arguments& args, void* data) { + v8::HandleScope scope; + + v8::Handle self = args.Holder(); + self->SetInternalField(0, v8::External::New(data)); + + return self; +} + +/** + * Registers a class method with given name for a given class template. + */ +void V8GeneratorUtils::AddClassMethod(v8::Handle class_templ, const char* symbol, v8::InvocationCallback _func) { + v8::Handle proto_templ = class_templ->PrototypeTemplate(); + proto_templ->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)); +} + +/** + * Registers a class property with given name for a given class template. + */ +void V8GeneratorUtils::AddProperty(v8::Handle class_templ, const char* varname, v8::AccessorGetter getter, v8::AccessorSetter setter) { + v8::Handle proto_templ = class_templ->InstanceTemplate(); + proto_templ->SetAccessor(v8::String::New(varname), getter, setter); +} + +%} // v8_helper_functions diff --git a/Lib/javascript/v8/javascriptprimitives.swg b/Lib/javascript/v8/javascriptprimitives.swg new file mode 100644 index 000000000..d5c89c690 --- /dev/null +++ b/Lib/javascript/v8/javascriptprimitives.swg @@ -0,0 +1,265 @@ +// Primitive types +%typemap(in) char, + signed char, + unsigned char, + short, + unsigned short, + int, + unsigned int, + long, + unsigned long, + long long, + unsigned long long, + float, + double +%{ $1 = ($1_ltype)JSValueToNumber(context, $input, NULL); %} + +%typemap(in) const bool &, bool &, + const char &, char &, + const signed char &, signed char &, + const unsigned char &, unsigned char &, + const short &, short &, + const unsigned short &, unsigned short &, + const int &, int &, + const unsigned int &, unsigned int &, + const long &, long &, + const unsigned long &, unsigned long &, + const long long &, long long &, + const unsigned long long &,unsigned long long &, + const float &, float &, + const double &, double & +%{ $1 = ($1_ltype)&$input; %} + +%typemap(out) char, + signed char, + unsigned char, + short, + unsigned short, + int, + unsigned int, + long, + unsigned long, + long long, + unsigned long long, + float, + double +%{ $result = JSValueMakeNumber(context, $1); %} + +%typemap(out) const bool &, bool &, + const char &, char &, + const signed char &, signed char &, + const unsigned char &, unsigned char &, + const short &, short &, + const unsigned short &, unsigned short &, + const int &, int &, + const unsigned int &, unsigned int &, + const long &, long &, + const unsigned long &, unsigned long &, + const long long &, long long &, + const unsigned long long &,unsigned long long &, + const float &, float &, + const double &, double & +%{ $result = JSValueMakeNumber(context,*$1); %} + + +%typemap(in) short *, + unsigned short *, + int *, + unsigned int *, + long *, + unsigned long *, + long long *, + unsigned long long *, + float *, + double * +%{ + JSObjectRef o$1 = JSValueToObject(context,$input, NULL); + SWIG_PRV_DATA *$1_privatedata = (SWIG_PRV_DATA *)JSObjectGetPrivate(o$1); + $1 = ($1_ltype)$1_privatedata->swigCObject; +%} + + +%typemap(out) short *, + unsigned short *, + int *, + unsigned int *, + long *, + unsigned long *, + long long *, + unsigned long long *, + float *, + double * +%{ + SWIG_PRV_DATA *privatedata = new SWIG_PRV_DATA(); + privatedata->swigCMemOwn = false; + privatedata->swigCObject = result; + $result = JSObjectMake(context, _wrap_swig_ptr_$*1_ltype_createJSClass(context), privatedata); +%} + +%typemap(in) bool +%{ + $1 = ($1_ltype)JSValueToBoolean(context, $input); +%} + +%typemap(out) bool +%{ + $result = JSValueMakeBoolean(context, $1); +%} + + +%typemap(out) void +%{ $result = JSValueMakeUndefined(context); %} + + +%typemap(in) char * +%{ + JSStringRef $1_str = JSValueToStringCopy(context, $input, NULL); + size_t $1_strsize = JSStringGetMaximumUTF8CStringSize($1_str); + $1 = (char *)malloc($1_strsize * sizeof(char)); + JSStringGetUTF8CString($1_str, $1, $1_strsize); +%} + +%typemap(out) char * +%{ + JSStringRef jsstring = JSStringCreateWithUTF8CString($1); + $result = JSValueMakeString(context, jsstring); + JSStringRelease(jsstring); +%} + +%typemap(arginit) char * "" + +%typemap(in) char *& ($*1_ltype temp = 0) %{ + temp = ($*1_ltype)$input; + JSStringRef $1_str = JSValueToStringCopy(context, $input, NULL); + size_t $1_strsize = JSStringGetMaximumUTF8CStringSize($1_str); + $1 = (char *)malloc($1_strsize * sizeof(char)); + JSStringGetUTF8CString($1_str, $1, $1_strsize); +%} + +%typemap(out) char *& +%{ + JSStringRef jsstring = JSStringCreateWithUTF8CString((const char *)*$1); + $result = JSValueMakeString(context, jsstring); + JSStringRelease(jsstring); +%} + +/* char arrays - treat as String */ +%typemap(in) char[ANY], char[] %{ + JSStringRef $1_str = JSValueToStringCopy(context, $input, NULL); + size_t $1_strsize = JSStringGetMaximumUTF8CStringSize($1_str); + JSStringGetUTF8CString($1_str, $1, $1_strsize); +%} + +%typemap(out) char[ANY], char[] +%{ + JSStringRef jsstring = JSStringCreateWithUTF8CString($1); + $result = JSValueMakeString(context, jsstring); + JSStringRelease(jsstring); +%} + +%typemap(freearg) char *, char *&, char[ANY], char[] //TODO: Not working: A memory leak +%{ free($1); %} + + +/* Typemaps for composite types */ +%typemap(in) SWIGTYPE ($&1_type argp) // Objects passed by value, convert to a pointer +%{ + JSObjectRef o$1 = JSValueToObject(context,$input, NULL); + SWIG_PRV_DATA *$1_privatedata = (SWIG_PRV_DATA *)JSObjectGetPrivate(o$1); + argp = ($&1_ltype)$1_privatedata->swigCObject; + $1 = *argp; +%} + +%typemap(out) SWIGTYPE ($&1_type temp) +#ifdef __cplusplus +%{ + temp = new $1_ltype((const $1_ltype &)$1); + SWIG_PRV_DATA *privatedata = new SWIG_PRV_DATA(); + privatedata->swigCMemOwn = false; + privatedata->swigCObject = temp; + $result = JSObjectMake(context, _wrap_$1_type_createJSClass(context), privatedata); + //$result = JSObjectMake(context, _wrap_$1_basetype_createJSClass(context), privatedata); + //$result = JSObjectMake(context, _wrap_$objecttype_createJSClass(context), privatedata); + // $1_mangle + // $1_descriptor +%} +#else +{ + $&1_ltype $1ptr = ($&1_ltype) malloc(sizeof($1_ltype)); + memmove($1ptr, &$1, sizeof($1_type)); + temp = $1ptr; + SWIG_PRV_DATA *privatedata = (SWIG_PRV_DATA *)malloc(sizeof(SWIG_PRV_DATA()); + privatedata->swigCMemOwn = false; + privatedata->swigCObject = temp; + $result = JSObjectMake(context, _wrap_$1_ltype_createJSClass(context), privatedata); + //$result = JSObjectMake(context, _wrap_$1_basetype_createJSClass(context), privatedata); + //$result = JSObjectMake(context, _wrap_$objecttype_createJSClass(context), privatedata); + // $1_mangle + // $1_descriptor +} +#endif + +%typemap(in) SWIGTYPE *, SWIGTYPE & +%{ + JSObjectRef o$1 = JSValueToObject(context,$input, NULL); + SWIG_PRV_DATA *$1_privatedata = (SWIG_PRV_DATA *)JSObjectGetPrivate(o$1); + $1 = ($1_ltype)$1_privatedata->swigCObject; +%} + +%typemap(out) SWIGTYPE *, SWIGTYPE & +%{ + SWIG_PRV_DATA *privatedata = new SWIG_PRV_DATA(); + privatedata->swigCMemOwn = false; + privatedata->swigCObject = result; + $result = JSObjectMake(context, _wrap_$*1_ltype_createJSClass(context), privatedata); + //$result = JSObjectMake(context, _wrap_$1_basetype_createJSClass(context), privatedata); + //$result = JSObjectMake(context, _wrap_$objecttype_createJSClass(context), privatedata); + // $1_mangle + // $1_descriptor +%} + +%typemap(arginit) SWIGTYPE * +%{ + // Sanity check if the call is not on the global object + if (!JSValueIsEqual(context, + JSValueToObject(context,thisObject,NULL), + JSValueToObject(context,JSContextGetGlobalObject(context), NULL), + NULL)) { + SWIG_PRV_DATA* $1_swigprivatedata = (SWIG_PRV_DATA*)JSObjectGetPrivate(thisObject); + $1 = ($1_ltype)$1_swigprivatedata->swigCObject; + } +%} + +%typemap(in) SWIGTYPE (CLASS::*) "" + +%typemap(out) SWIGTYPE (CLASS::*) +%{ + // Class* out typemap + $result = JSObjectMake(context, _wrap_$*1_ltype_createJSClass(context), result); +%} + + + +/* Typecheck typemaps - The purpose of these is merely to issue a warning for overloaded C++ functions + * that cannot be overloaded in Javascript as more than one C++ type maps to a single Javascript type */ +// TODO + + +// Default array handling +%typemap(in) SWIGTYPE [] %{ $1 = ($1_ltype)$input; %} +%typemap(out) SWIGTYPE [] %{ $result = $1; %} + + +// Javascript specific directives +//TODO + +// Some ANSI C typemaps */ +%apply unsigned long { size_t }; + +%apply const unsigned long & { const size_t & }; + +// Array reference typemaps +%apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } + +// const pointers +%apply SWIGTYPE * { SWIGTYPE *const } diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg new file mode 100644 index 000000000..ad34b6df2 --- /dev/null +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -0,0 +1,9 @@ +/* ----------------------------------------------------------------------------- + * javascriptruntime.swg + * + * Javascript support code + * ----------------------------------------------------------------------------- */ + +%insert(runtime) %{ +#include +%} diff --git a/Source/Makefile.am b/Source/Makefile.am index fa11bfdcb..85530fd45 100644 --- a/Source/Makefile.am +++ b/Source/Makefile.am @@ -51,6 +51,7 @@ eswig_SOURCES = CParse/cscanner.c \ Modules/lang.cxx \ Modules/javascript.cxx \ Modules/javascript_emitter.cxx \ + Modules/javascript_v8.cxx \ Modules/lua.cxx \ Modules/main.cxx \ Modules/modula3.cxx \ diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index e1336d82a..64d943453 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -6,6 +6,8 @@ #include "javascript_emitter.h" +extern JSEmitter* create_v8_emitter(); + /* ******************************************************************** * JAVASCRIPT * ********************************************************************/ @@ -200,7 +202,7 @@ void JAVASCRIPT::main(int argc, char *argv[]) { switch(mode) { case JSEmitter::V8: { - // TODO: emitter = create_v8_emitter(); + emitter = create_v8_emitter(); break; } case JSEmitter::JavascriptCore: diff --git a/Source/Modules/javascript_v8.cxx b/Source/Modules/javascript_v8.cxx new file mode 100644 index 000000000..7d2583aca --- /dev/null +++ b/Source/Modules/javascript_v8.cxx @@ -0,0 +1,369 @@ +#include "javascript_v8.h" +#include "swigmod.h" + +/* ----------------------------------------------------------------------- + * String constants that are used in Lib/javascript/v8/javascriptcode.swg + *------------------------------------------------------------------------ */ + +// name of templates +#define V8_INITIALIZER "v8_initializer" +#define V8_DECL_CLASSTEMPLATE "v8_declare_class_template" +#define V8_DEFINE_CLASSTEMPLATE "v8_define_class_template" +#define V8_INHERIT "v8_inherit" +#define V8_REGISTER_CLASS "v8_register_class" +#define V8_CTOR_WRAPPER "v8_ctor_wrapper" +#define V8_GETTER "v8_getter" +#define V8_SETTER "v8_setter" +#define V8_FUNCTION "v8_function" +#define V8_RETRIEVE_THIS "v8_retrieve_this" + +// keywords used in templates +#define KW_MODULE_NAME "${MODULE}" +#define KW_MANGLED_NAME "${NAME_MANGLED}" +#define KW_UNQUALIFIED_NAME "${NAME_UNQUALIFIED}" +#define KW_BASE_CLASS "${BASE_CLASS}" +#define KW_CONTEXT "${CONTEXT}" + +#define KW_NAME_SPACES "${PART_NAMESPACES}" +#define KW_CLASS_TEMPLATES "${PART_CLASS_TEMPLATES}" +#define KW_WRAPPERS "${PART_WRAPPERS}" +#define KW_INHERITANCE "${PART_INHERITANCE}" +#define KW_REGISTER "${PART_REGISTER}" + +#define KW_LOCALS "${LOCALS}" +#define KW_MARSHAL_INPUT "${MARSHAL_INPUT}" +#define KW_ACTION "${ACTION}" +#define KW_MARSHAL_OUTPUT "${MARSHAL_OUTPUT}" + +V8Emitter::V8Emitter() + : JSEmitter(), + GLOBAL(NewString("global")), + namespaces(NewHash()) +{ +} + +V8Emitter::~V8Emitter() +{ + Delete(GLOBAL); + Delete(namespaces); +} + +int V8Emitter::Initialize(Node *n) +{ + + /* Get the output file name */ + String *outfile = Getattr(n,"outfile"); + f_wrap_cpp = NewFile(outfile, "w", SWIG_output_files()); + if (!f_wrap_cpp) { + FileErrorDisplay(outfile); + SWIG_exit(EXIT_FAILURE); + } + + f_runtime = NewString(""); + f_header = NewString(""); + f_class_templates = NewString(""); + f_wrapper = NewString(""); + + f_init_namespaces = NewString(""); + f_init_class_templates = NewString(""); + f_init_wrappers = NewString(""); + f_init_inheritance = NewString(""); + f_init_register = NewString(""); + + Swig_register_filebyname("runtime", f_runtime); + Swig_register_filebyname("header", f_header); + Swig_register_filebyname("wrapper", f_wrapper); + + return SWIG_OK; +} + +int V8Emitter::Dump(Node *n) +{ + /* Get the module name */ + String* module = Getattr(n,"name"); + + // write the swig banner + Swig_banner(f_wrap_cpp); + + Printv(f_wrap_cpp, f_runtime, "\n", 0); + Printv(f_wrap_cpp, f_header, "\n", 0); + Printv(f_wrap_cpp, f_class_templates, "\n", 0); + Printv(f_wrap_cpp, f_wrapper, "\n", 0); + + // compose the initializer function using a template + // filled with sub-parts + Template initializer(GetTemplate(V8_INITIALIZER)); + initializer.Replace(KW_MODULE_NAME, module) + .Replace(KW_NAME_SPACES, f_init_namespaces) + .Replace(KW_CLASS_TEMPLATES, f_init_class_templates) + .Replace(KW_WRAPPERS, f_init_wrappers) + .Replace(KW_INHERITANCE, f_init_inheritance) + .Replace(KW_REGISTER, f_init_register); + Wrapper_pretty_print(initializer.str(), f_wrap_cpp); + + return SWIG_OK; +} + +int V8Emitter::Close() +{ + Delete(f_runtime); + Delete(f_header); + Delete(f_class_templates); + Delete(f_wrapper); + Delete(f_init_namespaces); + Delete(f_init_class_templates); + Delete(f_init_wrappers); + Delete(f_init_inheritance); + Delete(f_init_register); + ::Close(f_wrap_cpp); + Delete(f_wrap_cpp); + + return SWIG_OK; +} + +int V8Emitter::SwitchContext(Node *n) +{ + String* scope = Swig_scopename_prefix(Getattr(n, "name")); + + if (scope) { + // if the scope is not yet registered + // create all scopes/namespaces recursively + if(!Getattr(namespaces, scope)) { + CreateNamespace(scope); + } + current_context = Getattr(namespaces, scope); + } else { + current_context = GLOBAL; + } + + return SWIG_OK; +} + +int V8Emitter::CreateNamespace(String* scope) { + String* parent_scope = Swig_scopename_prefix(scope); + + if (parent_scope && !Getattr(namespaces, parent_scope)) { + CreateNamespace(parent_scope); + } + + String* ns = Swig_string_mangle(scope); + Setattr(namespaces, scope, ns); + + // TODO: create namespace object and register it to the parent scope + Printf(f_init_namespaces, "create_ns(%s);\n", ns); + + return SWIG_OK; +} + +int V8Emitter::EnterClass(Node *n) +{ + current_classname_mangled = Swig_string_mangle(Getattr(n, "name")); + current_classname_unqualified = Swig_scopename_last(Getattr(n, "name")); + + // emit declaration of a v8 class template in part + Template t(GetTemplate(V8_DECL_CLASSTEMPLATE)); + t.Replace(KW_MANGLED_NAME, current_classname_mangled); + Printv(f_class_templates, t.str(), 0); + + // emit definition of v8 class template in part + Template t2(GetTemplate(V8_DEFINE_CLASSTEMPLATE)); + t2.Replace(KW_MANGLED_NAME, current_classname_mangled) + .Replace(KW_UNQUALIFIED_NAME, current_classname_unqualified); + Printv(f_init_class_templates, t2.str(), 0); + + return SWIG_OK; +} + +int V8Emitter::ExitClass(Node *n) +{ + // emit inheritance setup + Node* baseClass = GetBaseClass(n); + if(baseClass) { + Template t(GetTemplate(V8_INHERIT)); + t.Replace(KW_MANGLED_NAME, current_classname_mangled) + .Replace(KW_BASE_CLASS, Swig_string_mangle(Getattr(baseClass, "name"))); + Printv(f_init_inheritance, t.str(), 0); + } + + // emit registeration of class template + Template t(GetTemplate(V8_REGISTER_CLASS)); + t.Replace(KW_MANGLED_NAME, current_classname_mangled) + .Replace(KW_UNQUALIFIED_NAME, current_classname_unqualified) + .Replace(KW_CONTEXT, Swig_string_mangle(current_context)); + Printv(f_init_register, t.str(), 0); + + Delete(current_classname_mangled); + Delete(current_classname_unqualified); + current_classname_mangled = 0; + current_classname_unqualified = 0; + + return SWIG_OK; +} + +int V8Emitter::EnterVariable(Node* n) +{ + current_variable_unqualified = Swig_scopename_last(Getattr(n, "name")); + if(GetFlag(n, "ismember")) { + current_variable_mangled = NewString(""); + Printf(current_variable_mangled, "%s_%s", current_classname_mangled, current_variable_unqualified); + } else { + current_variable_mangled = Swig_string_mangle(Getattr(n, "name")); + } + + return SWIG_OK; +} + +int V8Emitter::ExitVariable(Node* n) +{ + + // TODO: Register variable in context + + Delete(current_variable_mangled); + Delete(current_variable_unqualified); + current_variable_mangled = 0; + current_variable_unqualified = 0; + + return SWIG_OK; +} + +int V8Emitter::EnterFunction(Node* n) +{ + current_function_unqualified = Swig_scopename_last(Getattr(n, "name")); + if(GetFlag(n, "ismember")) { + current_function_mangled = NewString(""); + Printf(current_function_mangled, "%s_%s", current_classname_mangled, current_function_unqualified); + } else { + current_function_mangled = Swig_string_mangle(Getattr(n, "name")); + } + + return SWIG_OK; +} + +int V8Emitter::ExitFunction(Node* n) +{ + // TODO: Register function in context + + Delete(current_function_mangled); + Delete(current_function_unqualified); + current_function_mangled = 0; + current_function_unqualified = 0; + + return SWIG_OK; +} + +int V8Emitter::EmitCtor(Node* n) +{ + // TODO: + // - handle overloaded ctors using a dispatcher + // - marshal inputs + Template t(GetTemplate(V8_CTOR_WRAPPER)); + + ParmList *params = Getattr(n,"parms"); + String* action = Getattr(n, "wrap:action"); + String* input = NewString(""); + + emit_parameter_variables(params, current_wrapper); + emit_attach_parmmaps(params, current_wrapper); + + t.Replace(KW_MANGLED_NAME, current_classname_mangled) + .Replace(KW_UNQUALIFIED_NAME, current_classname_unqualified) + .Replace(KW_LOCALS, current_wrapper->locals) + .Replace(KW_ACTION, action) + .Replace(KW_MARSHAL_INPUT, input); + + Wrapper_pretty_print(t.str(), f_wrapper); + + return SWIG_OK; +} + +int V8Emitter::EmitDtor(Node* n) +{ + // TODO: + // find out how to register a dtor in v8 + + Printv(f_wrapper, "/* TODO: Wrap dtor */\n", 0); + + return SWIG_OK; +} + +int V8Emitter::EmitGetter(Node *n, bool is_member) { + Template t(GetTemplate(V8_GETTER)); + + Setattr(n, "wrap:name", Getattr(n, "sym:name")); + Printf(current_wrapper->locals, "%s result;\n", SwigType_str(Getattr(n, "type"), 0)); + + String* action = emit_action(n); + String* output = NewString("// TODO: marshal output.\n ret = v8::Undefined();"); + + t.Replace(KW_MANGLED_NAME, current_variable_mangled) + .Replace(KW_LOCALS, current_wrapper->locals) + .Replace(KW_ACTION, action) + .Replace(KW_MARSHAL_OUTPUT, output); + + Wrapper_pretty_print(t.str(), f_wrapper); + + Delete(output); + + return SWIG_OK; +} + +int V8Emitter::EmitSetter(Node* n, bool is_member) +{ + Template t(GetTemplate(V8_SETTER)); + + Setattr(n, "wrap:name", Getattr(n, "sym:name")); + ParmList *params = Getattr(n,"parms"); + + emit_parameter_variables(params, current_wrapper); + emit_attach_parmmaps(params, current_wrapper); + + String* action = emit_action(n); + String* input = NewString("// TODO: marshal input.\n"); + + t.Replace(KW_MANGLED_NAME, current_variable_mangled) + .Replace(KW_LOCALS, current_wrapper->locals) + .Replace(KW_ACTION, action) + .Replace(KW_MARSHAL_INPUT, input); + + Wrapper_pretty_print(t.str(), f_wrapper); + + Delete(input); + + return SWIG_OK; +} + + +int V8Emitter::EmitFunction(Node* n, bool is_member) +{ + Template t(GetTemplate(V8_FUNCTION)); + + Setattr(n, "wrap:name", Getattr(n, "sym:name")); + ParmList *params = Getattr(n,"parms"); + + emit_parameter_variables(params, current_wrapper); + emit_attach_parmmaps(params, current_wrapper); + Printf(current_wrapper->locals, "%s result;\n", SwigType_str(Getattr(n, "type"), 0)); + + + String* input = NewString("// TODO: marshal input"); + String* action = emit_action(n); + String* output = NewString("// TODO: marshal output.\n ret = v8::Undefined();"); + + t.Replace(KW_MANGLED_NAME, current_function_mangled) + .Replace(KW_LOCALS, current_wrapper->locals) + .Replace(KW_ACTION, action) + .Replace(KW_MARSHAL_INPUT, input) + .Replace(KW_MARSHAL_OUTPUT, output); + + Wrapper_pretty_print(t.str(), f_wrapper); + + Delete(input); + Delete(output); + + return SWIG_OK; +} + +JSEmitter* create_v8_emitter() +{ + return new V8Emitter(); +} diff --git a/Source/Modules/javascript_v8.h b/Source/Modules/javascript_v8.h new file mode 100644 index 000000000..bb190a71b --- /dev/null +++ b/Source/Modules/javascript_v8.h @@ -0,0 +1,77 @@ +#ifndef JAVASCRIPT_V8_H +#define JAVASCRIPT_V8_H + +#include "javascript_emitter.h" + +class V8Emitter: public JSEmitter { + +public: + + V8Emitter(); + + virtual ~V8Emitter(); + + virtual int Initialize(Node *n); + + virtual int Dump(Node *n); + + virtual int Close(); + + virtual int SwitchContext(Node *n); + + virtual int EnterClass(Node *n); + + virtual int ExitClass(Node *n); + + virtual int EnterVariable(Node *n); + + virtual int ExitVariable(Node *n); + + virtual int EnterFunction(Node *n); + + virtual int ExitFunction(Node *n); + +protected: + + int CreateNamespace(String* scope); + + virtual int EmitCtor(Node *n); + + virtual int EmitDtor(Node *n); + + virtual int EmitFunction(Node *n, bool is_member); + + virtual int EmitGetter(Node *n, bool is_member); + + virtual int EmitSetter(Node *n, bool is_member); + +private: + + File *f_runtime; + File *f_header; + File *f_class_templates; + File *f_wrapper; + + File *f_init_namespaces; + File *f_init_class_templates; + File *f_init_wrappers; + File *f_init_inheritance; + File *f_init_register; + + // the output cpp file + File *f_wrap_cpp; + + // state variables + String* current_context; + String* current_classname_mangled; + String* current_classname_unqualified; + String* current_variable_mangled; + String* current_variable_unqualified; + String* current_function_mangled; + String* current_function_unqualified; + + String* GLOBAL; + Hash* namespaces; +}; + +#endif // JAVASCRIPT_V8_H From a0b71935f278ff342583e17cdf6e94d43ac77c58 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:47:38 +0000 Subject: [PATCH 0071/1048] Update v8 code generator specification. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13744 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .../V8_CodeGeneratorSpecification.md | 118 ++++++++---------- Lib/javascript/v8/javascriptcode.swg | 1 + 2 files changed, 50 insertions(+), 69 deletions(-) diff --git a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md index b7d06e220..891b46b17 100644 --- a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md +++ b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md @@ -41,12 +41,12 @@ The generated code consists of the following blocks: Static references to class templates which are (should be) read-only and can be reused. ~~~~ -v8::Persistent SWIGV8_$CLASSNAME; +v8::Persistent SWIGV8_${NAME_MANGLED}; ~~~~ Notes: - it is very important to consider namespaces from the beginning. - `CLASSNAME` should be the mangled qualified class name, e.g., `foo_bar_MyClass` for `foo::bar::MyClass`, + `NAME_MANGLED` is the mangled qualified class name, e.g., `foo_bar_MyClass` for `foo::bar::MyClass`, which is retrieved ny `Swig_string_mangle(Getattr(n, "name"))` - namespaces do not need a function template, as they will not be instantiated @@ -67,115 +67,96 @@ TODO ## Constructors ~~~~ -v8::Handle $CLASSNAME_new(const v8::Arguments& args) { +v8::Handle ${NAME_MANGLED}_new(const v8::Arguments& args) { v8::HandleScope scope; - - // retrieve the instance v8::Handle self = args.Holder(); - - // TODO: declare arguments - - //convert JS arguments to C++ - // TODO: apply input typemaps - - $CLASS_LVAL* ptr = new $CLASS_LVAL($ARGS); + ${LOCALS} + ${MARSHAL_INPUT} + ${ACTION} self->SetInternalField(0, v8::External::New(ptr)); - return self; } ~~~~ -- `$CLASS_LVAL`: should be the canonical name of the class, e.g. `ns1::ns2::MyClass`, - which can be retrieved using `Getattr(n, "name")` -- `$ARGS`: arguments should be declared at the beginning and checked and set in the - input typemap block +- `LOCALS`: declaration and marshalling for input arguments +- `MARSHAL_INPUT`: code is generated by applying input typemaps +- `ACTION`: the C/C++ ctor to be executed ## Destructors -TODO +TODO: I haven't found out yet how a descrtuctor can be registered ## Getters ~~~~ -v8::Handle $CLASSNAME_get$VARNAME(v8::Local property, const v8::AccessorInfo& info) { +v8::Handle ${NAME_MANGLED}_get(v8::Local property, const v8::AccessorInfo& info) { v8::HandleScope scope; - - // retrieve pointer to C++-this - $CLASS_LVAL* self = SWIGV8_UnwrapThisPointer<$CLASS_LVAL>(info.Holder()); - $RET_LVAL retval = self->$VARNAME; - - v8::Handle ret = ; + v8::Handle ret; + ${LOCALS} + ${ACTION} + ${MARSHAL_OUTPUT} return scope.Close(ret); } ~~~~ -- TODO: output typemapping +- `NAME_MANGLED`: the qualified mangled name of the variable, E.g., `foo::x -> foo_x`, `A.x -> A_x` +- `LOCALS`: declare C return variable +- `MARSHAL_OUTPUT`: code is generated by applying output typemaps ## Setters ~~~~ -void $CLASSNAME_set$VARNAME(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { - v8::HandleScope scope; - - // retrieve pointer to this - $CLASS_LVAL* self = SWIGV8_UnwrapThisPointer<$CLASS_LVAL>(info.Holder()); - - // TODO: declare input arg - - // map java-script type to C++ type - self->$VARNAME = ; - +void ${NAME_MANGLED}_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { + ${LOCALS} + ${MARSHAL_INPUT} + ${ACTION} } ~~~~ +- `NAME_MANGLED`: the qualified mangled name of the variable, E.g., `foo::x -> foo_x`, `A.x -> A_x` +- `LOCALS`: declarations for input arguments +- `MARSHAL_INPUT`: code is generated by applying input typemaps -TODO: - - input type mapping should be addressed in extra step, together with type check - -## Member functions +## Functions ~~~~ -v8::Handle $CLASSNAME_$FUNCTIONNAME(const v8::Arguments& args) -{ +v8::Handle ${NAME_MANGLED}(const Arguments &args) { v8::HandleScope scope; - - $CLASS_LVAL* self = SWIGV8_UnwrapThisPointer<$CLASS_LVAL>(args.Holder()); - - // TODO: declare input args - - //convert JS arguments to C++ - // TODO: input typemappings and type checking - - //call C++ method - $RET_LTYPE result = self->$FUNCTIONNAME($ARGS); - - //convert C++ JS arguments to C++ - v8::Handle ret = ; - + v8::Handle ret; + ${LOCALS} + ${MARSHAL_INPUT} + ${ACTION} + ${MARSHAL_OUTPUT} return scope.Close(ret); } ~~~~ - if the function does not have a return value, return v8::Undefined +## Overloading + +TODO: if a function or a ctor is overloaded, a dispatcher function +must be generated which calls overloading wrappers depending on number +and type of input arguments. + ## Initializer ~~~~ -void $MODULENAME_Initialize(v8::Handle context) +void ${MODULE}_Initialize(v8::Handle context) { v8::HandleScope scope; // register the module in globale context v8::Local global = context->Global(); - - - + ${PART_NAMESPACES} - + ${PART_CLASS_TEMPLATES} - + ${PART_WRAPPERS} - + ${PART_INHERITANCE} + + ${PART_REGISTER} } ~~~~ @@ -188,11 +169,10 @@ in the according parent contexts. ## Create Class Template ~~~~ - SWIGV8_$CLASSNAME = SWIGV8_CreateClassTemplate("$LOCAL_CLASSNAME" , $CLASSNAME_new); +SWIGV8_${NAME_MANGLED} = SWIGV8_CreateClassTemplate("${NAME_UNQUALIFIED}" , ${NAME_MANGLED}_new); ~~~~ -- `LOCAL_CLASSNAME`: the class name without context, i.e., namespaces, - which is retrieved by `Getattr(n, "sym:name")` +- `NAME_UNQUALIFIED`: the class name without context, i.e., namespaces ## Add Member Function @@ -216,7 +196,7 @@ in the according parent contexts. ## Inheritance ~~~~ - SWIGV8_$CLASSNAME->Inherit(SWIGV8_$SUPERCLASS); +SWIGV8_${NAME_MANGLED}->Inherit(SWIGV8_${BASE_CLASS}); ~~~~ - Note: multiple inheritance is not possible; thus we will always take the first parent class @@ -224,7 +204,7 @@ in the according parent contexts. ## Register class ~~~~ - $CONTEXT->Set(v8::String::NewSymbol("$LOCAL_CLASSNAME"), SWIGV8_$CLASSNAME->GetFunction()); +${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}", SWIGV8_${NAME_MANGLED}->GetFunction())); ~~~~ - Note: every class template has an associated ctor function wrapper, which is registered here diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 1b6d33662..2671fc117 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -35,6 +35,7 @@ v8::Handle ${NAME_MANGLED}_new(const v8::Arguments& args) { v8::HandleScope scope; v8::Handle self = args.Holder(); ${LOCALS} + ${MARSHAL_INPUT} ${ACTION} self->SetInternalField(0, v8::External::New(ptr)); return self; From 83ac7193155a0d91fad992f197a448591f3e829c Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:47:51 +0000 Subject: [PATCH 0072/1048] Add manual generated v8 wrapper examples to v8 specification. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13745 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .../V8_CodeGeneratorSpecification.md | 161 +++++++++++++++++- 1 file changed, 160 insertions(+), 1 deletion(-) diff --git a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md index 891b46b17..095936ff8 100644 --- a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md +++ b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md @@ -166,6 +166,10 @@ Namespaces are objects without class templates. I.e., instances are created, referenced locally, used as contexts for other registrations, and stored in the according parent contexts. +~~~~~ +v8::Handle ${NAME_MANGLED} = v8::ObjectTemplate::New(); +~~~~~ + ## Create Class Template ~~~~ @@ -201,7 +205,24 @@ SWIGV8_${NAME_MANGLED}->Inherit(SWIGV8_${BASE_CLASS}); - Note: multiple inheritance is not possible; thus we will always take the first parent class -## Register class +## Registration + +The registration part consists of registering classes at contexts (i.e., global or namespace), +methods and properties at classes or contexts, and namespaces as objects at +parent contexts. + +### Global Variable + +~~~~ +${CONTEXT}->SetAccessor(v8::String::NewSymbol("${NAME_UNQUALIFIED}"), ${GETTER}, ${SETTER}); +~~~~ + +- `CONTEXT`: either global, or the according namespace template +- `${SETTER} = 0` for read-only variables + +### Global Function + +### Class ~~~~ ${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}", SWIGV8_${NAME_MANGLED}->GetFunction())); @@ -210,6 +231,32 @@ ${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}", SWIGV8_${NAME_MANGL - Note: every class template has an associated ctor function wrapper, which is registered here - `CONTEXT`: either global, or the according namespace instance +### Class method + +### Class variable + +## Namespace + +~~~~ +${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}", ${NAME_MANGLED}->NewInstance())); +~~~~ + +Note: it is important to register the namespace objects in reverse order, +e.g., + +~~~~ +namespace foo { + namespace bar {} +} +~~~~ + +would be registered in this order: + +~~~~ +foo->Set(v8::String::NewSymbol("bar", bar->NewInstance())); +global->Set(v8::String::NewSymbol("foo", foo->NewInstance())); +~~~~ + ## HELPER_FUNCTIONS A lot of boiler-plate code can be shifted into static helper functions: @@ -589,3 +636,115 @@ enter classHandler() of B exit classHandler() of B exit top() of example ~~~~ + +Examples +======== + +## Global variable + +~~~~~ +static double Foo = 42.0; + +void Foo_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { + v8::HandleScope scope; + double arg1 ; + arg1 = value->NumberValue(); + Foo = arg1; +} + +v8::Handle Foo_get(v8::Local property, const v8::AccessorInfo& info) { + v8::HandleScope scope; + v8::Handle ret; + double result; + + result = Foo; + + ret = v8::Number::New(result); + return scope.Close(ret); +} + +int GlobalVar_Initialize(v8::Handle context) { + + v8::Local global = context->Global(); + global->SetAccessor(v8::String::New("Foo"), Foo_get, Foo_set); + + return 0; +} +~~~~~ + +## Global functions + +~~~~~ + +static double foo(int bla) { + return (bla * 2.1); +} + +v8::Handle wrap_foo(const v8::Arguments &args) { + v8::HandleScope scope; + v8::Handle ret; + + int arg1 ; + double result; + + arg1 = args[0]->Int32Value(); + + result = foo(arg1); + + ret = v8::Number::New(result); + + return scope.Close(ret); +} + +int GlobalFunc_Initialize(v8::Handle context) { + + v8::Local global = context->Global(); + + global->Set(v8::String::NewSymbol("foo"), v8::FunctionTemplate::New(wrap_foo)->GetFunction()); + + return 0; +} +~~~~~ + + +## Namespaces + +~~~~~ + +namespace foo { + static double bar = 42.0; +} + +void foo_bar_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { + v8::HandleScope scope; + + double arg1 ; + arg1 = value->NumberValue(); + foo::bar = arg1; + +} + +v8::Handle foo_bar_get(v8::Local property, const v8::AccessorInfo& info) { + v8::HandleScope scope; + v8::Handle ret; + double result; + + result = foo::bar; + + ret = v8::Number::New(result); + return scope.Close(ret); +} + +int Namespace_Initialize(v8::Handle context) { + + v8::Local global = context->Global(); + + v8::Handle foo = v8::ObjectTemplate::New(); + + foo->SetAccessor(v8::String::New("bar"), foo_bar_get, foo_bar_set); + + global->Set(v8::String::New("foo"), foo->NewInstance()); + return 0; +} + +~~~~~ From 6c90d1eb6d46bd1dd52aa3121d38511974423d8b Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:48:11 +0000 Subject: [PATCH 0073/1048] Minor improvements in v8 emitter implementation git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13746 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptcode.swg | 4 ++ Lib/javascript/v8/javascripthelpers.swg | 17 +++++- Source/Modules/javascript_v8.cxx | 76 +++++++++++++++---------- 3 files changed, 64 insertions(+), 33 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 2671fc117..d83ded12e 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -72,3 +72,7 @@ v8::Handle ${NAME_MANGLED}(const Arguments &args) { return scope.Close(ret); } %} + +%fragment("v8_register_member_function", "templates") %{ +SWIGV8_AddClassMethod(SWIGV8_${CLASSNAME_MANGLED}, "${NAME_UNQUALIFIED}", ${WRAPPER}); +%} diff --git a/Lib/javascript/v8/javascripthelpers.swg b/Lib/javascript/v8/javascripthelpers.swg index 61836c87d..c96bd346a 100644 --- a/Lib/javascript/v8/javascripthelpers.swg +++ b/Lib/javascript/v8/javascripthelpers.swg @@ -27,10 +27,14 @@ v8::Persistent SWIGV8_CreateClassTemplate(const char* symb return v8::Persistent::New(class_templ); } +v8::Handle SWIGV8_CreateNamespace(const char* name, v8::Handle parentContext) { + Handle namespace = ObjectTemplate::New(); +} + /** * Sets the pimpl data of a V8 class. */ -v8::Handle V8GeneratorUtils::SetInstance(const v8::Arguments& args, void* data) { +v8::Handle SWIGV8_SetInstance(const v8::Arguments& args, void* data) { v8::HandleScope scope; v8::Handle self = args.Holder(); @@ -42,15 +46,22 @@ v8::Handle V8GeneratorUtils::SetInstance(const v8::Arguments& args, v /** * Registers a class method with given name for a given class template. */ -void V8GeneratorUtils::AddClassMethod(v8::Handle class_templ, const char* symbol, v8::InvocationCallback _func) { +void SWIGV8_AddClassMethod(v8::Handle class_templ, const char* symbol, v8::InvocationCallback _func) { v8::Handle proto_templ = class_templ->PrototypeTemplate(); proto_templ->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)); } +/** + * Registers a class method with given name for a given class template. + */ +void SWIGV8_AddGlobalMethod(v8::Handle obj_templ, const char* symbol, v8::InvocationCallback _func) { + obj_templ->Set(String::New(symbol), FunctionTemplate::New(_func)); +} + /** * Registers a class property with given name for a given class template. */ -void V8GeneratorUtils::AddProperty(v8::Handle class_templ, const char* varname, v8::AccessorGetter getter, v8::AccessorSetter setter) { +void SWIGV8_AddProperty(v8::Handle class_templ, const char* varname, v8::AccessorGetter getter, v8::AccessorSetter setter) { v8::Handle proto_templ = class_templ->InstanceTemplate(); proto_templ->SetAccessor(v8::String::New(varname), getter, setter); } diff --git a/Source/Modules/javascript_v8.cxx b/Source/Modules/javascript_v8.cxx index 7d2583aca..9abb66976 100644 --- a/Source/Modules/javascript_v8.cxx +++ b/Source/Modules/javascript_v8.cxx @@ -16,13 +16,16 @@ #define V8_SETTER "v8_setter" #define V8_FUNCTION "v8_function" #define V8_RETRIEVE_THIS "v8_retrieve_this" +#define V8_REGISTER_MEMBER_FUNCTION "v8_register_member_function" // keywords used in templates #define KW_MODULE_NAME "${MODULE}" #define KW_MANGLED_NAME "${NAME_MANGLED}" #define KW_UNQUALIFIED_NAME "${NAME_UNQUALIFIED}" +#define KW_CLASSNAME_MANGLED "${CLASSNAME_MANGLED}" #define KW_BASE_CLASS "${BASE_CLASS}" #define KW_CONTEXT "${CONTEXT}" +#define KW_WRAPPER "${WRAPPER}" #define KW_NAME_SPACES "${PART_NAMESPACES}" #define KW_CLASS_TEMPLATES "${PART_CLASS_TEMPLATES}" @@ -70,9 +73,8 @@ int V8Emitter::Initialize(Node *n) f_init_inheritance = NewString(""); f_init_register = NewString(""); + // note: this is necessary for built-in generation of swig runtime code Swig_register_filebyname("runtime", f_runtime); - Swig_register_filebyname("header", f_header); - Swig_register_filebyname("wrapper", f_wrapper); return SWIG_OK; } @@ -179,18 +181,18 @@ int V8Emitter::ExitClass(Node *n) // emit inheritance setup Node* baseClass = GetBaseClass(n); if(baseClass) { - Template t(GetTemplate(V8_INHERIT)); - t.Replace(KW_MANGLED_NAME, current_classname_mangled) + Template t_inherit(GetTemplate(V8_INHERIT)); + t_inherit.Replace(KW_MANGLED_NAME, current_classname_mangled) .Replace(KW_BASE_CLASS, Swig_string_mangle(Getattr(baseClass, "name"))); - Printv(f_init_inheritance, t.str(), 0); + Printv(f_init_inheritance, t_inherit.str(), 0); } // emit registeration of class template - Template t(GetTemplate(V8_REGISTER_CLASS)); - t.Replace(KW_MANGLED_NAME, current_classname_mangled) + Template t_register(GetTemplate(V8_REGISTER_CLASS)); + t_register.Replace(KW_MANGLED_NAME, current_classname_mangled) .Replace(KW_UNQUALIFIED_NAME, current_classname_unqualified) .Replace(KW_CONTEXT, Swig_string_mangle(current_context)); - Printv(f_init_register, t.str(), 0); + Printv(f_init_register, t_register.str(), 0); Delete(current_classname_mangled); Delete(current_classname_unqualified); @@ -229,6 +231,7 @@ int V8Emitter::ExitVariable(Node* n) int V8Emitter::EnterFunction(Node* n) { current_function_unqualified = Swig_scopename_last(Getattr(n, "name")); + if(GetFlag(n, "ismember")) { current_function_mangled = NewString(""); Printf(current_function_mangled, "%s_%s", current_classname_mangled, current_function_unqualified); @@ -259,11 +262,11 @@ int V8Emitter::EmitCtor(Node* n) Template t(GetTemplate(V8_CTOR_WRAPPER)); ParmList *params = Getattr(n,"parms"); - String* action = Getattr(n, "wrap:action"); - String* input = NewString(""); - emit_parameter_variables(params, current_wrapper); emit_attach_parmmaps(params, current_wrapper); + + String* action = Getattr(n, "wrap:action"); + String* input = NewString(""); t.Replace(KW_MANGLED_NAME, current_classname_mangled) .Replace(KW_UNQUALIFIED_NAME, current_classname_unqualified) @@ -272,7 +275,7 @@ int V8Emitter::EmitCtor(Node* n) .Replace(KW_MARSHAL_INPUT, input); Wrapper_pretty_print(t.str(), f_wrapper); - + return SWIG_OK; } @@ -287,21 +290,21 @@ int V8Emitter::EmitDtor(Node* n) } int V8Emitter::EmitGetter(Node *n, bool is_member) { - Template t(GetTemplate(V8_GETTER)); + Template t_getter(GetTemplate(V8_GETTER)); - Setattr(n, "wrap:name", Getattr(n, "sym:name")); Printf(current_wrapper->locals, "%s result;\n", SwigType_str(Getattr(n, "type"), 0)); String* action = emit_action(n); String* output = NewString("// TODO: marshal output.\n ret = v8::Undefined();"); - t.Replace(KW_MANGLED_NAME, current_variable_mangled) + t_getter.Replace(KW_MANGLED_NAME, current_variable_mangled) .Replace(KW_LOCALS, current_wrapper->locals) .Replace(KW_ACTION, action) .Replace(KW_MARSHAL_OUTPUT, output); - Wrapper_pretty_print(t.str(), f_wrapper); - + Wrapper_pretty_print(t_getter.str(), f_wrapper); + + // clean up Delete(output); return SWIG_OK; @@ -309,24 +312,23 @@ int V8Emitter::EmitGetter(Node *n, bool is_member) { int V8Emitter::EmitSetter(Node* n, bool is_member) { - Template t(GetTemplate(V8_SETTER)); - - Setattr(n, "wrap:name", Getattr(n, "sym:name")); + Template t_setter(GetTemplate(V8_SETTER)); + ParmList *params = Getattr(n,"parms"); - emit_parameter_variables(params, current_wrapper); emit_attach_parmmaps(params, current_wrapper); String* action = emit_action(n); String* input = NewString("// TODO: marshal input.\n"); - t.Replace(KW_MANGLED_NAME, current_variable_mangled) + t_setter.Replace(KW_MANGLED_NAME, current_variable_mangled) .Replace(KW_LOCALS, current_wrapper->locals) .Replace(KW_ACTION, action) .Replace(KW_MARSHAL_INPUT, input); - Wrapper_pretty_print(t.str(), f_wrapper); + Wrapper_pretty_print(t_setter.str(), f_wrapper); + // clean up Delete(input); return SWIG_OK; @@ -335,30 +337,44 @@ int V8Emitter::EmitSetter(Node* n, bool is_member) int V8Emitter::EmitFunction(Node* n, bool is_member) { - Template t(GetTemplate(V8_FUNCTION)); + Template t_function(GetTemplate(V8_FUNCTION)); - Setattr(n, "wrap:name", Getattr(n, "sym:name")); + String* wrap_name = NewString(""); + Printv(wrap_name, current_function_mangled, 0); + Setattr(n, "wrap:name", wrap_name); + ParmList *params = Getattr(n,"parms"); - emit_parameter_variables(params, current_wrapper); emit_attach_parmmaps(params, current_wrapper); Printf(current_wrapper->locals, "%s result;\n", SwigType_str(Getattr(n, "type"), 0)); - - + String* input = NewString("// TODO: marshal input"); String* action = emit_action(n); String* output = NewString("// TODO: marshal output.\n ret = v8::Undefined();"); - t.Replace(KW_MANGLED_NAME, current_function_mangled) + t_function.Replace(KW_MANGLED_NAME, current_function_mangled) .Replace(KW_LOCALS, current_wrapper->locals) .Replace(KW_ACTION, action) .Replace(KW_MARSHAL_INPUT, input) .Replace(KW_MARSHAL_OUTPUT, output); - Wrapper_pretty_print(t.str(), f_wrapper); + Wrapper_pretty_print(t_function.str(), f_wrapper); + // register the function at the specific context + if (is_member) { + Template t_register(GetTemplate(V8_REGISTER_MEMBER_FUNCTION)); + t_register.Replace(KW_UNQUALIFIED_NAME, current_function_unqualified) + .Replace(KW_WRAPPER, wrap_name) + .Replace(KW_CLASSNAME_MANGLED, current_classname_mangled); + Printv(f_init_register, t_register.str(), "\n", 0); + } else { + // TODO + } + + // clean up Delete(input); Delete(output); + Delete(wrap_name); return SWIG_OK; } From 90bbc6430bf5fb8f234c5ea46a09ef5f528ec72d Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:48:24 +0000 Subject: [PATCH 0074/1048] Update v8 specification. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13747 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .../V8_CodeGeneratorSpecification.md | 328 ++++++++++-------- 1 file changed, 175 insertions(+), 153 deletions(-) diff --git a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md index 095936ff8..fcd581755 100644 --- a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md +++ b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md @@ -26,7 +26,7 @@ The generated code consists of the following blocks: - `FUNCTION_WRAPPERS`: dynamically growing, on method declarations - `INITIALIZER`: dynamically growing, aggregates everything (to be specified in more detail) -## INCLUDES +### INCLUDES ~~~~ #include @@ -36,7 +36,7 @@ The generated code consists of the following blocks: `USER_DEFINED_INCLUDES`: a module property -## CLASS_TEMPLATES +### CLASS_TEMPLATES Static references to class templates which are (should be) read-only and can be reused. @@ -55,16 +55,28 @@ Notes: There are different types of function wrappers: - - Static Functions (global/namespace/class) + - Global Functions (global/namespace/class) - Constructors / Destructors - Getters / Settters - Member Functions -## Static Functions +### Global Functions -TODO +~~~~ +v8::Handle wrap_${NAME_MANGLED}(const v8::Arguments &args) { + v8::HandleScope scope; + v8::Handle ret; -## Constructors + ${LOCALS} + ${MARSHAL_INPUT} + ${ACTION} + ${MARSHAL_OUTPUT} + + return scope.Close(ret); +} +~~~~ + +### Constructors ~~~~ v8::Handle ${NAME_MANGLED}_new(const v8::Arguments& args) { @@ -82,11 +94,11 @@ v8::Handle ${NAME_MANGLED}_new(const v8::Arguments& args) { - `MARSHAL_INPUT`: code is generated by applying input typemaps - `ACTION`: the C/C++ ctor to be executed -## Destructors +### Destructors TODO: I haven't found out yet how a descrtuctor can be registered -## Getters +### Getters ~~~~ v8::Handle ${NAME_MANGLED}_get(v8::Local property, const v8::AccessorInfo& info) { @@ -103,7 +115,7 @@ v8::Handle ${NAME_MANGLED}_get(v8::Local property, const - `LOCALS`: declare C return variable - `MARSHAL_OUTPUT`: code is generated by applying output typemaps -## Setters +### Setters ~~~~ void ${NAME_MANGLED}_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { @@ -116,7 +128,7 @@ void ${NAME_MANGLED}_set(v8::Local property, v8::Local va - `LOCALS`: declarations for input arguments - `MARSHAL_INPUT`: code is generated by applying input typemaps -## Functions +### Functions ~~~~ v8::Handle ${NAME_MANGLED}(const Arguments &args) { @@ -132,12 +144,13 @@ v8::Handle ${NAME_MANGLED}(const Arguments &args) { - if the function does not have a return value, return v8::Undefined -## Overloading +### Overloading TODO: if a function or a ctor is overloaded, a dispatcher function must be generated which calls overloading wrappers depending on number and type of input arguments. + ## Initializer ~~~~ @@ -160,7 +173,7 @@ void ${MODULE}_Initialize(v8::Handle context) } ~~~~ -## Namespaces +### Namespaces Namespaces are objects without class templates. I.e., instances are created, referenced locally, used as contexts for other registrations, and stored @@ -170,7 +183,7 @@ in the according parent contexts. v8::Handle ${NAME_MANGLED} = v8::ObjectTemplate::New(); ~~~~~ -## Create Class Template +### Class Templates ~~~~ SWIGV8_${NAME_MANGLED} = SWIGV8_CreateClassTemplate("${NAME_UNQUALIFIED}" , ${NAME_MANGLED}_new); @@ -178,26 +191,7 @@ SWIGV8_${NAME_MANGLED} = SWIGV8_CreateClassTemplate("${NAME_UNQUALIFIED}" , ${NA - `NAME_UNQUALIFIED`: the class name without context, i.e., namespaces -## Add Member Function - -~~~~ - SWIGV8_AddClassMethod(SWIGV8_$CLASSNAME, "$METHODNAME", $METHOD_WRAPPER); -~~~~ - -- `METHODNAME`: the name of the function as in C++ -- `METHOD_WRAPPER`: the name of the generated wrapper function, which - should have the form `wrap__` - -## Add Property - -~~~~ - SWIGV8_AddProperty(SWIGV8_$CLASSNAME, "$VARNAME", $GET_WRAPPER, $SET_WRAPPER); -~~~~ - -- `GET_WRAPPER`: the name of the generated wrapper for the property getter -- `SET_WRAPPER`: the name of the generated wrapper for property setter; optional (i.e., maybe `NULL`) - -## Inheritance +### Inheritance ~~~~ SWIGV8_${NAME_MANGLED}->Inherit(SWIGV8_${BASE_CLASS}); @@ -205,13 +199,13 @@ SWIGV8_${NAME_MANGLED}->Inherit(SWIGV8_${BASE_CLASS}); - Note: multiple inheritance is not possible; thus we will always take the first parent class -## Registration +### Registration The registration part consists of registering classes at contexts (i.e., global or namespace), methods and properties at classes or contexts, and namespaces as objects at parent contexts. -### Global Variable +#### Global Variable ~~~~ ${CONTEXT}->SetAccessor(v8::String::NewSymbol("${NAME_UNQUALIFIED}"), ${GETTER}, ${SETTER}); @@ -220,9 +214,15 @@ ${CONTEXT}->SetAccessor(v8::String::NewSymbol("${NAME_UNQUALIFIED}"), ${GETTER}, - `CONTEXT`: either global, or the according namespace template - `${SETTER} = 0` for read-only variables -### Global Function +#### Global Function -### Class +~~~~ +${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}"), v8::FunctionTemplate::New(wrap_${NAME_QUALIFIED})->GetFunction()); +~~~~ + +- `CONTEXT`: either global, or the according namespace template + +#### Class ~~~~ ${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}", SWIGV8_${NAME_MANGLED}->GetFunction())); @@ -231,11 +231,24 @@ ${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}", SWIGV8_${NAME_MANGL - Note: every class template has an associated ctor function wrapper, which is registered here - `CONTEXT`: either global, or the according namespace instance -### Class method +#### Class method -### Class variable +~~~~ +SWIGV8_AddClassMethod(SWIGV8_${CLASSNAME_MANGLED}, "${NAME_UNQUALIFIED}", wrap_${NAME_MANGLED}); +~~~~ -## Namespace +Note: implemented in static helper function + +#### Class variable + +~~~~ +SWIGV8_AddProperty(SWIGV8_${CLASSNAME_MANGLED}, "${NAME_UNQUALIFIED}", ${GETTER}, ${SETTER}); +~~~~ + +- `GETTER`: the name of the generated wrapper for the property getter +- `SETTER`: the name of the generated wrapper for property setter; optional (i.e., maybe `NULL`) + +### Namespace ~~~~ ${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}", ${NAME_MANGLED}->NewInstance())); @@ -319,7 +332,128 @@ void V8GeneratorUtils::AddProperty(v8::Handle class_templ, ~~~~ -# Control flow analysis +------------------------- + +Examples +======== + +In this chapter manually coded wrappers are presented. +This has been useful for studying the addressed code generation on basis +of examples. + +## Global variable + +~~~~~ +static double Foo = 42.0; + +void Foo_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { + v8::HandleScope scope; + double arg1 ; + arg1 = value->NumberValue(); + Foo = arg1; +} + +v8::Handle Foo_get(v8::Local property, const v8::AccessorInfo& info) { + v8::HandleScope scope; + v8::Handle ret; + double result; + + result = Foo; + + ret = v8::Number::New(result); + return scope.Close(ret); +} + +int GlobalVar_Initialize(v8::Handle context) { + + v8::Local global = context->Global(); + global->SetAccessor(v8::String::New("Foo"), Foo_get, Foo_set); + + return 0; +} +~~~~~ + +## Global functions + +~~~~~ + +static double foo(int bla) { + return (bla * 2.1); +} + +v8::Handle wrap_foo(const v8::Arguments &args) { + v8::HandleScope scope; + v8::Handle ret; + + int arg1 ; + double result; + + arg1 = args[0]->Int32Value(); + + result = foo(arg1); + + ret = v8::Number::New(result); + + return scope.Close(ret); +} + +int GlobalFunc_Initialize(v8::Handle context) { + + v8::Local global = context->Global(); + + global->Set(v8::String::NewSymbol("foo"), v8::FunctionTemplate::New(wrap_foo)->GetFunction()); + + return 0; +} +~~~~~ + + +## Namespaces + +~~~~~ + +namespace foo { + static double bar = 42.0; +} + +void foo_bar_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { + v8::HandleScope scope; + + double arg1 ; + arg1 = value->NumberValue(); + foo::bar = arg1; + +} + +v8::Handle foo_bar_get(v8::Local property, const v8::AccessorInfo& info) { + v8::HandleScope scope; + v8::Handle ret; + double result; + + result = foo::bar; + + ret = v8::Number::New(result); + return scope.Close(ret); +} + +int Namespace_Initialize(v8::Handle context) { + + v8::Local global = context->Global(); + + v8::Handle foo = v8::ObjectTemplate::New(); + + foo->SetAccessor(v8::String::New("bar"), foo_bar_get, foo_bar_set); + + global->Set(v8::String::New("foo"), foo->NewInstance()); + return 0; +} + +~~~~~ + +------------------------- + +Control flow analysis +===================== ## Global variables @@ -636,115 +770,3 @@ enter classHandler() of B exit classHandler() of B exit top() of example ~~~~ - -Examples -======== - -## Global variable - -~~~~~ -static double Foo = 42.0; - -void Foo_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { - v8::HandleScope scope; - double arg1 ; - arg1 = value->NumberValue(); - Foo = arg1; -} - -v8::Handle Foo_get(v8::Local property, const v8::AccessorInfo& info) { - v8::HandleScope scope; - v8::Handle ret; - double result; - - result = Foo; - - ret = v8::Number::New(result); - return scope.Close(ret); -} - -int GlobalVar_Initialize(v8::Handle context) { - - v8::Local global = context->Global(); - global->SetAccessor(v8::String::New("Foo"), Foo_get, Foo_set); - - return 0; -} -~~~~~ - -## Global functions - -~~~~~ - -static double foo(int bla) { - return (bla * 2.1); -} - -v8::Handle wrap_foo(const v8::Arguments &args) { - v8::HandleScope scope; - v8::Handle ret; - - int arg1 ; - double result; - - arg1 = args[0]->Int32Value(); - - result = foo(arg1); - - ret = v8::Number::New(result); - - return scope.Close(ret); -} - -int GlobalFunc_Initialize(v8::Handle context) { - - v8::Local global = context->Global(); - - global->Set(v8::String::NewSymbol("foo"), v8::FunctionTemplate::New(wrap_foo)->GetFunction()); - - return 0; -} -~~~~~ - - -## Namespaces - -~~~~~ - -namespace foo { - static double bar = 42.0; -} - -void foo_bar_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { - v8::HandleScope scope; - - double arg1 ; - arg1 = value->NumberValue(); - foo::bar = arg1; - -} - -v8::Handle foo_bar_get(v8::Local property, const v8::AccessorInfo& info) { - v8::HandleScope scope; - v8::Handle ret; - double result; - - result = foo::bar; - - ret = v8::Number::New(result); - return scope.Close(ret); -} - -int Namespace_Initialize(v8::Handle context) { - - v8::Local global = context->Global(); - - v8::Handle foo = v8::ObjectTemplate::New(); - - foo->SetAccessor(v8::String::New("bar"), foo_bar_get, foo_bar_set); - - global->Set(v8::String::New("foo"), foo->NewInstance()); - return 0; -} - -~~~~~ From 886f17c34372ded14504ad684b71cd786faa8e42 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:48:43 +0000 Subject: [PATCH 0075/1048] Implement namespace support for v8 generator. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13748 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptcode.swg | 27 ++++++++++++++------ Source/Modules/javascript_v8.cxx | 38 ++++++++++++++++++++++++---- Source/Modules/javascript_v8.h | 1 + 3 files changed, 53 insertions(+), 13 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index d83ded12e..4f4d5e292 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -3,19 +3,25 @@ void ${MODULE}_Initialize(v8::Handle context) { v8::HandleScope scope; - - // register the module in globale context v8::Local global = context->Global(); + /* create object templates for namespaces */ ${PART_NAMESPACES} - + + /* create class templates */ ${PART_CLASS_TEMPLATES} - + + /* register wrapper functions */ ${PART_WRAPPERS} - + + /* setup inheritances */ ${PART_INHERITANCE} - + + /* some registration TODO: what specifically?*/ ${PART_REGISTER} + + /* create and register namespace objects */ + ${PART_REGISTER_NS} }%} %fragment("v8_declare_class_template", "templates") %{ @@ -74,5 +80,10 @@ v8::Handle ${NAME_MANGLED}(const Arguments &args) { %} %fragment("v8_register_member_function", "templates") %{ -SWIGV8_AddClassMethod(SWIGV8_${CLASSNAME_MANGLED}, "${NAME_UNQUALIFIED}", ${WRAPPER}); -%} +SWIGV8_AddClassMethod(SWIGV8_${CLASSNAME_MANGLED}, "${NAME_UNQUALIFIED}", ${WRAPPER});%} + +%fragment("v8_create_namespace", "templates") %{ +v8::Handle ${NAME_MANGLED} = v8::ObjectTemplate::New();%} + +%fragment("v8_register_namespace", "templates") %{ +${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}", ${NAME_MANGLED}->NewInstance()));%} diff --git a/Source/Modules/javascript_v8.cxx b/Source/Modules/javascript_v8.cxx index 9abb66976..36c24c15f 100644 --- a/Source/Modules/javascript_v8.cxx +++ b/Source/Modules/javascript_v8.cxx @@ -17,6 +17,9 @@ #define V8_FUNCTION "v8_function" #define V8_RETRIEVE_THIS "v8_retrieve_this" #define V8_REGISTER_MEMBER_FUNCTION "v8_register_member_function" +#define V8_CREATE_NAMESPACE "v8_create_namespace" +#define V8_REGISTER_NAMESPACE "v8_register_namespace" + // keywords used in templates #define KW_MODULE_NAME "${MODULE}" @@ -32,6 +35,7 @@ #define KW_WRAPPERS "${PART_WRAPPERS}" #define KW_INHERITANCE "${PART_INHERITANCE}" #define KW_REGISTER "${PART_REGISTER}" +#define KW_REGISTER_NS "${PART_REGISTER_NS}" #define KW_LOCALS "${LOCALS}" #define KW_MARSHAL_INPUT "${MARSHAL_INPUT}" @@ -72,6 +76,7 @@ int V8Emitter::Initialize(Node *n) f_init_wrappers = NewString(""); f_init_inheritance = NewString(""); f_init_register = NewString(""); + f_init_register_namespaces = NewString(""); // note: this is necessary for built-in generation of swig runtime code Swig_register_filebyname("runtime", f_runtime); @@ -100,7 +105,8 @@ int V8Emitter::Dump(Node *n) .Replace(KW_CLASS_TEMPLATES, f_init_class_templates) .Replace(KW_WRAPPERS, f_init_wrappers) .Replace(KW_INHERITANCE, f_init_inheritance) - .Replace(KW_REGISTER, f_init_register); + .Replace(KW_REGISTER, f_init_register) + .Replace(KW_REGISTER_NS, f_init_register_namespaces); Wrapper_pretty_print(initializer.str(), f_wrap_cpp); return SWIG_OK; @@ -117,6 +123,7 @@ int V8Emitter::Close() Delete(f_init_wrappers); Delete(f_init_inheritance); Delete(f_init_register); + Delete(f_init_register_namespaces); ::Close(f_wrap_cpp); Delete(f_wrap_cpp); @@ -143,17 +150,38 @@ int V8Emitter::SwitchContext(Node *n) int V8Emitter::CreateNamespace(String* scope) { String* parent_scope = Swig_scopename_prefix(scope); + String* parent_scope_mangled = 0; + + if(!parent_scope) { + parent_scope_mangled = NewString("global"); + } else { + parent_scope_mangled = Swig_name_mangle(parent_scope); + + } if (parent_scope && !Getattr(namespaces, parent_scope)) { CreateNamespace(parent_scope); } - String* ns = Swig_string_mangle(scope); - Setattr(namespaces, scope, ns); + String* scope_mangled = Swig_string_mangle(scope); + String* scope_unqualified = Swig_scopename_last(scope); + Setattr(namespaces, scope, scope_mangled); - // TODO: create namespace object and register it to the parent scope - Printf(f_init_namespaces, "create_ns(%s);\n", ns); + // create namespace object and register it to the parent scope + Template t_create_ns(GetTemplate(V8_CREATE_NAMESPACE)); + t_create_ns.Replace(KW_MANGLED_NAME, scope_mangled); + Template t_register_ns(GetTemplate(V8_REGISTER_NAMESPACE)); + t_register_ns.Replace(KW_MANGLED_NAME, scope_mangled) + .Replace(KW_CONTEXT, parent_scope_mangled) + .Replace(KW_UNQUALIFIED_NAME, scope_unqualified); + Printv(f_init_namespaces, t_create_ns.str(), 0); + // prepend in order to achieve reversed order of registration statements + Insert(f_init_register_namespaces, 0, t_register_ns.str()); + + Delete(parent_scope); + Delete(parent_scope_mangled); + Delete(scope_unqualified); return SWIG_OK; } diff --git a/Source/Modules/javascript_v8.h b/Source/Modules/javascript_v8.h index bb190a71b..29bb381ee 100644 --- a/Source/Modules/javascript_v8.h +++ b/Source/Modules/javascript_v8.h @@ -57,6 +57,7 @@ private: File *f_init_wrappers; File *f_init_inheritance; File *f_init_register; + File *f_init_register_namespaces; // the output cpp file File *f_wrap_cpp; From 9a599be8ab6c3426362beb3dd572cd399620da8d Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:49:02 +0000 Subject: [PATCH 0076/1048] Fix order of registration in v8 generator. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13749 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptcode.swg | 4 ++-- Source/Modules/javascript_v8.cxx | 12 ++++++------ Source/Modules/javascript_v8.h | 2 +- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 4f4d5e292..1eb20c20d 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -17,8 +17,8 @@ void ${MODULE}_Initialize(v8::Handle context) /* setup inheritances */ ${PART_INHERITANCE} - /* some registration TODO: what specifically?*/ - ${PART_REGISTER} + /* register classes */ + ${PART_REGISTER_CLASSES} /* create and register namespace objects */ ${PART_REGISTER_NS} diff --git a/Source/Modules/javascript_v8.cxx b/Source/Modules/javascript_v8.cxx index 36c24c15f..3ec8393b4 100644 --- a/Source/Modules/javascript_v8.cxx +++ b/Source/Modules/javascript_v8.cxx @@ -34,7 +34,7 @@ #define KW_CLASS_TEMPLATES "${PART_CLASS_TEMPLATES}" #define KW_WRAPPERS "${PART_WRAPPERS}" #define KW_INHERITANCE "${PART_INHERITANCE}" -#define KW_REGISTER "${PART_REGISTER}" +#define KW_REGISTER_CLASSES "${PART_REGISTER_CLASSES}" #define KW_REGISTER_NS "${PART_REGISTER_NS}" #define KW_LOCALS "${LOCALS}" @@ -75,7 +75,7 @@ int V8Emitter::Initialize(Node *n) f_init_class_templates = NewString(""); f_init_wrappers = NewString(""); f_init_inheritance = NewString(""); - f_init_register = NewString(""); + f_init_register_classes = NewString(""); f_init_register_namespaces = NewString(""); // note: this is necessary for built-in generation of swig runtime code @@ -105,7 +105,7 @@ int V8Emitter::Dump(Node *n) .Replace(KW_CLASS_TEMPLATES, f_init_class_templates) .Replace(KW_WRAPPERS, f_init_wrappers) .Replace(KW_INHERITANCE, f_init_inheritance) - .Replace(KW_REGISTER, f_init_register) + .Replace(KW_REGISTER_CLASSES, f_init_register_classes) .Replace(KW_REGISTER_NS, f_init_register_namespaces); Wrapper_pretty_print(initializer.str(), f_wrap_cpp); @@ -122,7 +122,7 @@ int V8Emitter::Close() Delete(f_init_class_templates); Delete(f_init_wrappers); Delete(f_init_inheritance); - Delete(f_init_register); + Delete(f_init_register_classes); Delete(f_init_register_namespaces); ::Close(f_wrap_cpp); Delete(f_wrap_cpp); @@ -220,7 +220,7 @@ int V8Emitter::ExitClass(Node *n) t_register.Replace(KW_MANGLED_NAME, current_classname_mangled) .Replace(KW_UNQUALIFIED_NAME, current_classname_unqualified) .Replace(KW_CONTEXT, Swig_string_mangle(current_context)); - Printv(f_init_register, t_register.str(), 0); + Printv(f_init_register_classes, t_register.str(), 0); Delete(current_classname_mangled); Delete(current_classname_unqualified); @@ -394,7 +394,7 @@ int V8Emitter::EmitFunction(Node* n, bool is_member) t_register.Replace(KW_UNQUALIFIED_NAME, current_function_unqualified) .Replace(KW_WRAPPER, wrap_name) .Replace(KW_CLASSNAME_MANGLED, current_classname_mangled); - Printv(f_init_register, t_register.str(), "\n", 0); + Printv(f_init_wrappers, t_register.str(), "\n", 0); } else { // TODO } diff --git a/Source/Modules/javascript_v8.h b/Source/Modules/javascript_v8.h index 29bb381ee..0738b930b 100644 --- a/Source/Modules/javascript_v8.h +++ b/Source/Modules/javascript_v8.h @@ -56,7 +56,7 @@ private: File *f_init_class_templates; File *f_init_wrappers; File *f_init_inheritance; - File *f_init_register; + File *f_init_register_classes; File *f_init_register_namespaces; // the output cpp file From 7ba26c8a26e52d2f499e20b866b273571c6264b8 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:49:15 +0000 Subject: [PATCH 0077/1048] Minor change in v8 emitter. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13750 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/Modules/javascript_v8.cxx | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/Source/Modules/javascript_v8.cxx b/Source/Modules/javascript_v8.cxx index 3ec8393b4..5c404b07c 100644 --- a/Source/Modules/javascript_v8.cxx +++ b/Source/Modules/javascript_v8.cxx @@ -190,16 +190,16 @@ int V8Emitter::EnterClass(Node *n) current_classname_mangled = Swig_string_mangle(Getattr(n, "name")); current_classname_unqualified = Swig_scopename_last(Getattr(n, "name")); - // emit declaration of a v8 class template in part - Template t(GetTemplate(V8_DECL_CLASSTEMPLATE)); - t.Replace(KW_MANGLED_NAME, current_classname_mangled); - Printv(f_class_templates, t.str(), 0); + // emit declaration of a v8 class template + Template t_decl_class(GetTemplate(V8_DECL_CLASSTEMPLATE)); + t_decl_class.Replace(KW_MANGLED_NAME, current_classname_mangled); + Printv(f_class_templates, t_decl_class.str(), 0); - // emit definition of v8 class template in part - Template t2(GetTemplate(V8_DEFINE_CLASSTEMPLATE)); - t2.Replace(KW_MANGLED_NAME, current_classname_mangled) - .Replace(KW_UNQUALIFIED_NAME, current_classname_unqualified); - Printv(f_init_class_templates, t2.str(), 0); + // emit definition of v8 class template + Template t_def_class(GetTemplate(V8_DEFINE_CLASSTEMPLATE)); + t_def_class.Replace(KW_MANGLED_NAME, current_classname_mangled) + .Replace(KW_UNQUALIFIED_NAME, current_classname_unqualified); + Printv(f_init_class_templates, t_def_class.str(), 0); return SWIG_OK; } From 285badb95b03a3f1ee7a84fa1b473b06c477f35d Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:49:32 +0000 Subject: [PATCH 0078/1048] Improve v8 generator regarding registration of function wrappers. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13751 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptcode.swg | 11 +++++++---- Source/Modules/javascript_v8.cxx | 15 +++++++++------ 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 1eb20c20d..dbc5c788d 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -68,7 +68,7 @@ void ${NAME_MANGLED}_set(v8::Local property, v8::Local va %} %fragment("v8_function", "templates") %{ -v8::Handle ${NAME_MANGLED}(const Arguments &args) { +v8::Handle wrap_${NAME_MANGLED}(const Arguments &args) { v8::HandleScope scope; v8::Handle ret; ${LOCALS} @@ -79,11 +79,14 @@ v8::Handle ${NAME_MANGLED}(const Arguments &args) { } %} -%fragment("v8_register_member_function", "templates") %{ -SWIGV8_AddClassMethod(SWIGV8_${CLASSNAME_MANGLED}, "${NAME_UNQUALIFIED}", ${WRAPPER});%} - %fragment("v8_create_namespace", "templates") %{ v8::Handle ${NAME_MANGLED} = v8::ObjectTemplate::New();%} +%fragment("v8_register_member_function", "templates") %{ +SWIGV8_AddClassMethod(SWIGV8_${CLASSNAME_MANGLED}, "${NAME_UNQUALIFIED}", wrap_${NAME_MANGLED});%} + +%fragment("v8_register_global_function", "templates") %{ +${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}"), v8::FunctionTemplate::New(wrap_${NAME_MANGLED})->GetFunction());%} + %fragment("v8_register_namespace", "templates") %{ ${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}", ${NAME_MANGLED}->NewInstance()));%} diff --git a/Source/Modules/javascript_v8.cxx b/Source/Modules/javascript_v8.cxx index 5c404b07c..bf284aac5 100644 --- a/Source/Modules/javascript_v8.cxx +++ b/Source/Modules/javascript_v8.cxx @@ -17,6 +17,7 @@ #define V8_FUNCTION "v8_function" #define V8_RETRIEVE_THIS "v8_retrieve_this" #define V8_REGISTER_MEMBER_FUNCTION "v8_register_member_function" +#define V8_REGISTER_GLOBAL_FUNCTION "v8_register_global_function" #define V8_CREATE_NAMESPACE "v8_create_namespace" #define V8_REGISTER_NAMESPACE "v8_register_namespace" @@ -247,6 +248,7 @@ int V8Emitter::ExitVariable(Node* n) { // TODO: Register variable in context + Swig_print_node(n); Delete(current_variable_mangled); Delete(current_variable_unqualified); @@ -271,9 +273,7 @@ int V8Emitter::EnterFunction(Node* n) } int V8Emitter::ExitFunction(Node* n) -{ - // TODO: Register function in context - +{ Delete(current_function_mangled); Delete(current_function_unqualified); current_function_mangled = 0; @@ -385,18 +385,21 @@ int V8Emitter::EmitFunction(Node* n, bool is_member) .Replace(KW_ACTION, action) .Replace(KW_MARSHAL_INPUT, input) .Replace(KW_MARSHAL_OUTPUT, output); - Wrapper_pretty_print(t_function.str(), f_wrapper); // register the function at the specific context if (is_member) { Template t_register(GetTemplate(V8_REGISTER_MEMBER_FUNCTION)); t_register.Replace(KW_UNQUALIFIED_NAME, current_function_unqualified) - .Replace(KW_WRAPPER, wrap_name) + .Replace(KW_MANGLED_NAME, wrap_name) .Replace(KW_CLASSNAME_MANGLED, current_classname_mangled); Printv(f_init_wrappers, t_register.str(), "\n", 0); } else { - // TODO + Template t_register(GetTemplate(V8_REGISTER_GLOBAL_FUNCTION)); + t_register.Replace(KW_CONTEXT, current_context) + .Replace(KW_UNQUALIFIED_NAME, current_function_unqualified) + .Replace(KW_MANGLED_NAME, wrap_name); + Printv(f_init_wrappers, t_register.str(), 0); } // clean up From 8e0711cbc63ceb6b0adcc1a2ec4133b0fa198a25 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:49:44 +0000 Subject: [PATCH 0079/1048] Fix memory related bug in generalized javascript emitter. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13752 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/Modules/javascript_emitter.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/Modules/javascript_emitter.cxx b/Source/Modules/javascript_emitter.cxx index 7b49aaf5d..b9446663a 100644 --- a/Source/Modules/javascript_emitter.cxx +++ b/Source/Modules/javascript_emitter.cxx @@ -107,7 +107,7 @@ int JSEmitter::EmitWrapperFunction(Node* n) int ret = SWIG_OK; current_wrapper = NewWrapper(); - Setattr(n, "wrap:name", Getattr(n, "sym:name")); + Setattr(n, "wrap:name", NewString(Getattr(n, "sym:name"))); String* kind = Getattr(n, "kind"); From 71bee1e78c52a65c5a159768c2f6f02cf3eb903f Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:50:06 +0000 Subject: [PATCH 0080/1048] Complement variable processing in v8 generator. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13753 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptcode.swg | 8 ++++++- Lib/javascript/v8/javascripthelpers.swg | 12 +++++++--- Source/Modules/javascript_v8.cxx | 32 ++++++++++++++++++++++--- Source/Modules/javascript_v8.h | 3 +++ 4 files changed, 48 insertions(+), 7 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index dbc5c788d..52a0651b3 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -86,7 +86,13 @@ v8::Handle ${NAME_MANGLED} = v8::ObjectTemplate::New();%} SWIGV8_AddClassMethod(SWIGV8_${CLASSNAME_MANGLED}, "${NAME_UNQUALIFIED}", wrap_${NAME_MANGLED});%} %fragment("v8_register_global_function", "templates") %{ -${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}"), v8::FunctionTemplate::New(wrap_${NAME_MANGLED})->GetFunction());%} +SWIGV8_AddGlobalMethod(${CONTEXT}, "${NAME_UNQUALIFIED}", wrap_${NAME_MANGLED});%} + +%fragment("v8_register_member_variable", "templates") %{ +SWIGV8_AddClassVariable(SWIGV8_${CLASSNAME_MANGLED}, "${NAME_UNQUALIFIED}", ${GETTER}, ${SETTER});%} + +%fragment("v8_register_global_variable", "templates") %{ +SWIGV8_AddGlobalVariable(${CONTEXT}, "${NAME_UNQUALIFIED}", ${GETTER}, ${SETTER});%} %fragment("v8_register_namespace", "templates") %{ ${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}", ${NAME_MANGLED}->NewInstance()));%} diff --git a/Lib/javascript/v8/javascripthelpers.swg b/Lib/javascript/v8/javascripthelpers.swg index c96bd346a..bc2822c8f 100644 --- a/Lib/javascript/v8/javascripthelpers.swg +++ b/Lib/javascript/v8/javascripthelpers.swg @@ -55,15 +55,21 @@ void SWIGV8_AddClassMethod(v8::Handle class_templ, const c * Registers a class method with given name for a given class template. */ void SWIGV8_AddGlobalMethod(v8::Handle obj_templ, const char* symbol, v8::InvocationCallback _func) { - obj_templ->Set(String::New(symbol), FunctionTemplate::New(_func)); + obj_templ->Set(String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)->GetFunction()); } /** * Registers a class property with given name for a given class template. */ -void SWIGV8_AddProperty(v8::Handle class_templ, const char* varname, v8::AccessorGetter getter, v8::AccessorSetter setter) { +void SWIGV8_AddClassVariable(v8::Handle class_templ, const char* symbol, v8::AccessorGetter getter, v8::AccessorSetter setter) { v8::Handle proto_templ = class_templ->InstanceTemplate(); - proto_templ->SetAccessor(v8::String::New(varname), getter, setter); + proto_templ->SetAccessor(v8::String::NewSymbol(symbol), getter, setter); } +/** + * Registers a class method with given name for a given class template. + */ +void SWIGV8_AddGlobalVariable(v8::Handle obj_templ, const char* symbol, v8::AccessorGetter getter, v8::AccessorSetter setter) { + obj_templ->SetAccessor(String::NewSymbol(symbol), getter, setter); +} %} // v8_helper_functions diff --git a/Source/Modules/javascript_v8.cxx b/Source/Modules/javascript_v8.cxx index bf284aac5..8c1667d25 100644 --- a/Source/Modules/javascript_v8.cxx +++ b/Source/Modules/javascript_v8.cxx @@ -18,10 +18,11 @@ #define V8_RETRIEVE_THIS "v8_retrieve_this" #define V8_REGISTER_MEMBER_FUNCTION "v8_register_member_function" #define V8_REGISTER_GLOBAL_FUNCTION "v8_register_global_function" +#define V8_REGISTER_MEMBER_VARIABLE "v8_register_member_variable" +#define V8_REGISTER_GLOBAL_VARIABLE "v8_register_global_variable" #define V8_CREATE_NAMESPACE "v8_create_namespace" #define V8_REGISTER_NAMESPACE "v8_register_namespace" - // keywords used in templates #define KW_MODULE_NAME "${MODULE}" #define KW_MANGLED_NAME "${NAME_MANGLED}" @@ -30,6 +31,8 @@ #define KW_BASE_CLASS "${BASE_CLASS}" #define KW_CONTEXT "${CONTEXT}" #define KW_WRAPPER "${WRAPPER}" +#define KW_GETTER "${GETTER}" +#define KW_SETTER "${SETTER}" #define KW_NAME_SPACES "${PART_NAMESPACES}" #define KW_CLASS_TEMPLATES "${PART_CLASS_TEMPLATES}" @@ -46,6 +49,7 @@ V8Emitter::V8Emitter() : JSEmitter(), GLOBAL(NewString("global")), + NULL_STR(NewString("0")), namespaces(NewHash()) { } @@ -53,6 +57,7 @@ V8Emitter::V8Emitter() V8Emitter::~V8Emitter() { Delete(GLOBAL); + Delete(NULL_STR); Delete(namespaces); } @@ -171,6 +176,7 @@ int V8Emitter::CreateNamespace(String* scope) { // create namespace object and register it to the parent scope Template t_create_ns(GetTemplate(V8_CREATE_NAMESPACE)); t_create_ns.Replace(KW_MANGLED_NAME, scope_mangled); + Template t_register_ns(GetTemplate(V8_REGISTER_NAMESPACE)); t_register_ns.Replace(KW_MANGLED_NAME, scope_mangled) .Replace(KW_CONTEXT, parent_scope_mangled) @@ -240,6 +246,9 @@ int V8Emitter::EnterVariable(Node* n) } else { current_variable_mangled = Swig_string_mangle(Getattr(n, "name")); } + + current_getter = NULL_STR; + current_setter = NULL_STR; return SWIG_OK; } @@ -247,8 +256,21 @@ int V8Emitter::EnterVariable(Node* n) int V8Emitter::ExitVariable(Node* n) { - // TODO: Register variable in context - Swig_print_node(n); + if(GetFlag(n, "ismember")) { + Template t_register(GetTemplate(V8_REGISTER_MEMBER_VARIABLE)); + t_register.Replace(KW_CLASSNAME_MANGLED, current_classname_mangled) + .Replace(KW_UNQUALIFIED_NAME, current_variable_unqualified) + .Replace(KW_GETTER, current_getter) + .Replace(KW_SETTER, current_setter); + Printv(f_init_wrappers, t_register.str(), 0); + } else { + Template t_register(GetTemplate(V8_REGISTER_GLOBAL_VARIABLE)); + t_register.Replace(KW_CONTEXT, current_context) + .Replace(KW_UNQUALIFIED_NAME, current_variable_unqualified) + .Replace(KW_GETTER, current_getter) + .Replace(KW_SETTER, current_setter); + Printv(f_init_wrappers, t_register.str(), 0); + } Delete(current_variable_mangled); Delete(current_variable_unqualified); @@ -320,6 +342,8 @@ int V8Emitter::EmitDtor(Node* n) int V8Emitter::EmitGetter(Node *n, bool is_member) { Template t_getter(GetTemplate(V8_GETTER)); + current_getter = Getattr(n,"wrap:name"); + Printf(current_wrapper->locals, "%s result;\n", SwigType_str(Getattr(n, "type"), 0)); String* action = emit_action(n); @@ -341,6 +365,8 @@ int V8Emitter::EmitGetter(Node *n, bool is_member) { int V8Emitter::EmitSetter(Node* n, bool is_member) { Template t_setter(GetTemplate(V8_SETTER)); + + current_setter = Getattr(n,"wrap:name"); ParmList *params = Getattr(n,"parms"); emit_parameter_variables(params, current_wrapper); diff --git a/Source/Modules/javascript_v8.h b/Source/Modules/javascript_v8.h index 0738b930b..c70d54e34 100644 --- a/Source/Modules/javascript_v8.h +++ b/Source/Modules/javascript_v8.h @@ -68,10 +68,13 @@ private: String* current_classname_unqualified; String* current_variable_mangled; String* current_variable_unqualified; + String* current_getter; + String* current_setter; String* current_function_mangled; String* current_function_unqualified; String* GLOBAL; + String* NULL_STR; Hash* namespaces; }; From 0e60acfebde30181f93b1acfa57c65b50a13e6c5 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:50:19 +0000 Subject: [PATCH 0081/1048] Minor restructuring in v8 generator. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13754 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/Modules/javascript_v8.cxx | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/Source/Modules/javascript_v8.cxx b/Source/Modules/javascript_v8.cxx index 8c1667d25..70e0402d4 100644 --- a/Source/Modules/javascript_v8.cxx +++ b/Source/Modules/javascript_v8.cxx @@ -296,6 +296,22 @@ int V8Emitter::EnterFunction(Node* n) int V8Emitter::ExitFunction(Node* n) { + // register the function at the specific context + if(GetFlag(n, "ismember")) { + Template t_register(GetTemplate(V8_REGISTER_MEMBER_FUNCTION)); + t_register.Replace(KW_CLASSNAME_MANGLED, current_classname_mangled) + .Replace(KW_UNQUALIFIED_NAME, current_function_unqualified) + .Replace(KW_MANGLED_NAME, Getattr(n, "wrap:name")); + Printv(f_init_wrappers, t_register.str(), "\n", 0); + } else { + Template t_register(GetTemplate(V8_REGISTER_GLOBAL_FUNCTION)); + t_register.Replace(KW_CONTEXT, current_context) + .Replace(KW_UNQUALIFIED_NAME, current_function_unqualified) + .Replace(KW_MANGLED_NAME, Getattr(n, "wrap:name")); + Printv(f_init_wrappers, t_register.str(), 0); + } + + Delete(current_function_mangled); Delete(current_function_unqualified); current_function_mangled = 0; @@ -413,25 +429,9 @@ int V8Emitter::EmitFunction(Node* n, bool is_member) .Replace(KW_MARSHAL_OUTPUT, output); Wrapper_pretty_print(t_function.str(), f_wrapper); - // register the function at the specific context - if (is_member) { - Template t_register(GetTemplate(V8_REGISTER_MEMBER_FUNCTION)); - t_register.Replace(KW_UNQUALIFIED_NAME, current_function_unqualified) - .Replace(KW_MANGLED_NAME, wrap_name) - .Replace(KW_CLASSNAME_MANGLED, current_classname_mangled); - Printv(f_init_wrappers, t_register.str(), "\n", 0); - } else { - Template t_register(GetTemplate(V8_REGISTER_GLOBAL_FUNCTION)); - t_register.Replace(KW_CONTEXT, current_context) - .Replace(KW_UNQUALIFIED_NAME, current_function_unqualified) - .Replace(KW_MANGLED_NAME, wrap_name); - Printv(f_init_wrappers, t_register.str(), 0); - } - // clean up Delete(input); Delete(output); - Delete(wrap_name); return SWIG_OK; } From 65d4769af8792f4193cba47ef56547f9998c247c Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:50:41 +0000 Subject: [PATCH 0082/1048] Add initial support for argument marshalling using typemaps to v8 module. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13755 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptcode.swg | 40 ++-- Lib/javascript/v8/javascriptprimitives.swg | 237 ++++++++------------- Source/Modules/javascript_v8.cxx | 173 +++++++++++---- Source/Modules/javascript_v8.h | 7 + 4 files changed, 246 insertions(+), 211 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 52a0651b3..855f72284 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -1,4 +1,3 @@ - %fragment("v8_initializer", "templates") %{ void ${MODULE}_Initialize(v8::Handle context) { @@ -41,43 +40,34 @@ v8::Handle ${NAME_MANGLED}_new(const v8::Arguments& args) { v8::HandleScope scope; v8::Handle self = args.Holder(); ${LOCALS} - ${MARSHAL_INPUT} - ${ACTION} - self->SetInternalField(0, v8::External::New(ptr)); + ${CODE} + self->SetInternalField(0, v8::External::New(result)); return self; -} -%} +}%} %fragment("v8_getter", "templates") %{ v8::Handle ${NAME_MANGLED}_get(v8::Local property, const v8::AccessorInfo& info) { v8::HandleScope scope; - v8::Handle ret; + v8::Handle jsresult; ${LOCALS} - ${ACTION} - ${MARSHAL_OUTPUT} - return scope.Close(ret); -} -%} + ${CODE} + return scope.Close(jsresult); +}%} %fragment("v8_setter", "templates") %{ void ${NAME_MANGLED}_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { ${LOCALS} - ${MARSHAL_INPUT} - ${ACTION} -} -%} + ${CODE} +}%} %fragment("v8_function", "templates") %{ v8::Handle wrap_${NAME_MANGLED}(const Arguments &args) { v8::HandleScope scope; - v8::Handle ret; + v8::Handle jsresult; ${LOCALS} - ${MARSHAL_INPUT} - ${ACTION} - ${MARSHAL_OUTPUT} - return scope.Close(ret); -} -%} + ${CODE} + return scope.Close(jsresult); +}%} %fragment("v8_create_namespace", "templates") %{ v8::Handle ${NAME_MANGLED} = v8::ObjectTemplate::New();%} @@ -96,3 +86,7 @@ SWIGV8_AddGlobalVariable(${CONTEXT}, "${NAME_UNQUALIFIED}", ${GETTER}, ${SETTER} %fragment("v8_register_namespace", "templates") %{ ${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}", ${NAME_MANGLED}->NewInstance()));%} + +%fragment("v8_this_ptr", "templates") %{ +arg1 = SWIGV8_UnwrapThisPointer<${TYPE}>(${ARG}.Holder()); +%} diff --git a/Lib/javascript/v8/javascriptprimitives.swg b/Lib/javascript/v8/javascriptprimitives.swg index d5c89c690..b9b255f86 100644 --- a/Lib/javascript/v8/javascriptprimitives.swg +++ b/Lib/javascript/v8/javascriptprimitives.swg @@ -1,66 +1,84 @@ +%typemap(in) bool +%{ $1 = ($1_ltype) $input->BooleanValue();%} + // Primitive types %typemap(in) char, signed char, unsigned char, - short, + short, unsigned short, - int, - unsigned int, + int +%{ $1 = ($1_ltype) $input->Int32Value();%} + +%typemap(in) unsigned int, long, unsigned long, long long, - unsigned long long, - float, - double -%{ $1 = ($1_ltype)JSValueToNumber(context, $input, NULL); %} + unsigned long long +%{ $1 = ($1_ltype) $input->UInt32Value();%} -%typemap(in) const bool &, bool &, - const char &, char &, - const signed char &, signed char &, - const unsigned char &, unsigned char &, - const short &, short &, - const unsigned short &, unsigned short &, - const int &, int &, - const unsigned int &, unsigned int &, - const long &, long &, - const unsigned long &, unsigned long &, - const long long &, long long &, - const unsigned long long &,unsigned long long &, - const float &, float &, - const double &, double & -%{ $1 = ($1_ltype)&$input; %} +%typemap(in) float, double +%{ $1 = ($1_ltype) $input->NumberValue();%} + + +%typemap(in) const bool &, bool &, + const char &, char &, + const signed char &, signed char &, + const unsigned char &, unsigned char &, + const short &, short &, + const unsigned short &, unsigned short &, + const int &, int &, + const unsigned int &, unsigned int &, + const long &, long &, + const unsigned long &, unsigned long &, + const long long &, long long &, + const unsigned long long &, unsigned long long &, + const float &, float &, + const double &, double & +%{ + // TODO: typemap(in) const bool& at al +} + +%typemap(out) bool +%{ $result = v8::Boolean::New($1);%} %typemap(out) char, signed char, unsigned char, - short, + short, unsigned short, - int, - unsigned int, + int +%{ $result = v8::Int32::New($1);%} + +%typemap(out) unsigned int, long, unsigned long, - long long, - unsigned long long, - float, - double -%{ $result = JSValueMakeNumber(context, $1); %} + long long, + unsigned long long +%{ $result = v8::UInt32::New($1);%} -%typemap(out) const bool &, bool &, - const char &, char &, - const signed char &, signed char &, - const unsigned char &, unsigned char &, - const short &, short &, - const unsigned short &, unsigned short &, - const int &, int &, - const unsigned int &, unsigned int &, - const long &, long &, - const unsigned long &, unsigned long &, - const long long &, long long &, - const unsigned long long &,unsigned long long &, - const float &, float &, - const double &, double & -%{ $result = JSValueMakeNumber(context,*$1); %} +%typemap(out) float, double +%{ $result = v8::Number::New($1); %} +%typemap(out) const bool &, bool &, + const char &, char &, + const signed char &, signed char &, + const unsigned char &, unsigned char &, + const short &, short &, + const unsigned short &, unsigned short &, + const int &, int & +%{ $result = v8::Int32::New((*$1);%} + +%typemap(out) const unsigned int &, unsigned int &, + const long &, long &, + const unsigned long &, unsigned long &, + const long long &, long long &, + const unsigned long long &, unsigned long long & +%{ $result = v8::UInt32::New(*$1);%} + +%typemap(out) const float &, float &, + const double &, double & +%{ $result = v8::Number::New(*$1);%} %typemap(in) short *, unsigned short *, @@ -73,9 +91,7 @@ float *, double * %{ - JSObjectRef o$1 = JSValueToObject(context,$input, NULL); - SWIG_PRV_DATA *$1_privatedata = (SWIG_PRV_DATA *)JSObjectGetPrivate(o$1); - $1 = ($1_ltype)$1_privatedata->swigCObject; + // TODO: typemap(in): short* et al. %} @@ -90,169 +106,88 @@ float *, double * %{ - SWIG_PRV_DATA *privatedata = new SWIG_PRV_DATA(); - privatedata->swigCMemOwn = false; - privatedata->swigCObject = result; - $result = JSObjectMake(context, _wrap_swig_ptr_$*1_ltype_createJSClass(context), privatedata); + // TODO: typemap(out) short* et al. %} -%typemap(in) bool -%{ - $1 = ($1_ltype)JSValueToBoolean(context, $input); -%} - -%typemap(out) bool -%{ - $result = JSValueMakeBoolean(context, $1); -%} - %typemap(out) void -%{ $result = JSValueMakeUndefined(context); %} +%{ $result = v8::Undefined(); %} %typemap(in) char * %{ - JSStringRef $1_str = JSValueToStringCopy(context, $input, NULL); - size_t $1_strsize = JSStringGetMaximumUTF8CStringSize($1_str); - $1 = (char *)malloc($1_strsize * sizeof(char)); - JSStringGetUTF8CString($1_str, $1, $1_strsize); + // TODO: input typemap for char* %} %typemap(out) char * %{ - JSStringRef jsstring = JSStringCreateWithUTF8CString($1); - $result = JSValueMakeString(context, jsstring); - JSStringRelease(jsstring); + // TODO: output typemap for char* %} -%typemap(arginit) char * "" - %typemap(in) char *& ($*1_ltype temp = 0) %{ - temp = ($*1_ltype)$input; - JSStringRef $1_str = JSValueToStringCopy(context, $input, NULL); - size_t $1_strsize = JSStringGetMaximumUTF8CStringSize($1_str); - $1 = (char *)malloc($1_strsize * sizeof(char)); - JSStringGetUTF8CString($1_str, $1, $1_strsize); + // TODO: input typemap for char*& %} %typemap(out) char *& %{ - JSStringRef jsstring = JSStringCreateWithUTF8CString((const char *)*$1); - $result = JSValueMakeString(context, jsstring); - JSStringRelease(jsstring); + // TODO: output typemap for char*& %} /* char arrays - treat as String */ %typemap(in) char[ANY], char[] %{ - JSStringRef $1_str = JSValueToStringCopy(context, $input, NULL); - size_t $1_strsize = JSStringGetMaximumUTF8CStringSize($1_str); - JSStringGetUTF8CString($1_str, $1, $1_strsize); + // TODO: input typemap for char[] %} %typemap(out) char[ANY], char[] %{ - JSStringRef jsstring = JSStringCreateWithUTF8CString($1); - $result = JSValueMakeString(context, jsstring); - JSStringRelease(jsstring); + // TODO: output typemap for char[] %} %typemap(freearg) char *, char *&, char[ANY], char[] //TODO: Not working: A memory leak -%{ free($1); %} +%{ + // TODO: freearg char* et al +%} /* Typemaps for composite types */ %typemap(in) SWIGTYPE ($&1_type argp) // Objects passed by value, convert to a pointer %{ - JSObjectRef o$1 = JSValueToObject(context,$input, NULL); - SWIG_PRV_DATA *$1_privatedata = (SWIG_PRV_DATA *)JSObjectGetPrivate(o$1); - argp = ($&1_ltype)$1_privatedata->swigCObject; - $1 = *argp; + // TODO: input typemap for composite types %} %typemap(out) SWIGTYPE ($&1_type temp) -#ifdef __cplusplus %{ - temp = new $1_ltype((const $1_ltype &)$1); - SWIG_PRV_DATA *privatedata = new SWIG_PRV_DATA(); - privatedata->swigCMemOwn = false; - privatedata->swigCObject = temp; - $result = JSObjectMake(context, _wrap_$1_type_createJSClass(context), privatedata); - //$result = JSObjectMake(context, _wrap_$1_basetype_createJSClass(context), privatedata); - //$result = JSObjectMake(context, _wrap_$objecttype_createJSClass(context), privatedata); - // $1_mangle - // $1_descriptor + // TODO: output typemap for composite types %} -#else -{ - $&1_ltype $1ptr = ($&1_ltype) malloc(sizeof($1_ltype)); - memmove($1ptr, &$1, sizeof($1_type)); - temp = $1ptr; - SWIG_PRV_DATA *privatedata = (SWIG_PRV_DATA *)malloc(sizeof(SWIG_PRV_DATA()); - privatedata->swigCMemOwn = false; - privatedata->swigCObject = temp; - $result = JSObjectMake(context, _wrap_$1_ltype_createJSClass(context), privatedata); - //$result = JSObjectMake(context, _wrap_$1_basetype_createJSClass(context), privatedata); - //$result = JSObjectMake(context, _wrap_$objecttype_createJSClass(context), privatedata); - // $1_mangle - // $1_descriptor -} -#endif %typemap(in) SWIGTYPE *, SWIGTYPE & %{ - JSObjectRef o$1 = JSValueToObject(context,$input, NULL); - SWIG_PRV_DATA *$1_privatedata = (SWIG_PRV_DATA *)JSObjectGetPrivate(o$1); - $1 = ($1_ltype)$1_privatedata->swigCObject; + // TODO: input typemap for ptr types %} %typemap(out) SWIGTYPE *, SWIGTYPE & %{ - SWIG_PRV_DATA *privatedata = new SWIG_PRV_DATA(); - privatedata->swigCMemOwn = false; - privatedata->swigCObject = result; - $result = JSObjectMake(context, _wrap_$*1_ltype_createJSClass(context), privatedata); - //$result = JSObjectMake(context, _wrap_$1_basetype_createJSClass(context), privatedata); - //$result = JSObjectMake(context, _wrap_$objecttype_createJSClass(context), privatedata); - // $1_mangle - // $1_descriptor + // TODO: output typemap for ptr types %} +// TODO: sanity check? %typemap(arginit) SWIGTYPE * -%{ - // Sanity check if the call is not on the global object - if (!JSValueIsEqual(context, - JSValueToObject(context,thisObject,NULL), - JSValueToObject(context,JSContextGetGlobalObject(context), NULL), - NULL)) { - SWIG_PRV_DATA* $1_swigprivatedata = (SWIG_PRV_DATA*)JSObjectGetPrivate(thisObject); - $1 = ($1_ltype)$1_swigprivatedata->swigCObject; - } -%} +%{%} %typemap(in) SWIGTYPE (CLASS::*) "" %typemap(out) SWIGTYPE (CLASS::*) %{ - // Class* out typemap - $result = JSObjectMake(context, _wrap_$*1_ltype_createJSClass(context), result); + // TODO: output typemap for CLASS::* %} - - -/* Typecheck typemaps - The purpose of these is merely to issue a warning for overloaded C++ functions - * that cannot be overloaded in Javascript as more than one C++ type maps to a single Javascript type */ -// TODO - - // Default array handling -%typemap(in) SWIGTYPE [] %{ $1 = ($1_ltype)$input; %} +%typemap(in) SWIGTYPE [] %{ + // TODO: typemap for arrays; +%} + %typemap(out) SWIGTYPE [] %{ $result = $1; %} - -// Javascript specific directives -//TODO - // Some ANSI C typemaps */ %apply unsigned long { size_t }; diff --git a/Source/Modules/javascript_v8.cxx b/Source/Modules/javascript_v8.cxx index 70e0402d4..7d6e9a327 100644 --- a/Source/Modules/javascript_v8.cxx +++ b/Source/Modules/javascript_v8.cxx @@ -22,6 +22,8 @@ #define V8_REGISTER_GLOBAL_VARIABLE "v8_register_global_variable" #define V8_CREATE_NAMESPACE "v8_create_namespace" #define V8_REGISTER_NAMESPACE "v8_register_namespace" +#define V8_THIS_PTR "v8_this_ptr" + // keywords used in templates #define KW_MODULE_NAME "${MODULE}" @@ -30,6 +32,8 @@ #define KW_CLASSNAME_MANGLED "${CLASSNAME_MANGLED}" #define KW_BASE_CLASS "${BASE_CLASS}" #define KW_CONTEXT "${CONTEXT}" +#define KW_TYPE "${TYPE}" +#define KW_ARG "${ARG}" #define KW_WRAPPER "${WRAPPER}" #define KW_GETTER "${GETTER}" #define KW_SETTER "${SETTER}" @@ -42,6 +46,7 @@ #define KW_REGISTER_NS "${PART_REGISTER_NS}" #define KW_LOCALS "${LOCALS}" +#define KW_CODE "${CODE}" #define KW_MARSHAL_INPUT "${MARSHAL_INPUT}" #define KW_ACTION "${ACTION}" #define KW_MARSHAL_OUTPUT "${MARSHAL_OUTPUT}" @@ -196,7 +201,8 @@ int V8Emitter::EnterClass(Node *n) { current_classname_mangled = Swig_string_mangle(Getattr(n, "name")); current_classname_unqualified = Swig_scopename_last(Getattr(n, "name")); - + current_class_type = Getattr(n, "classtype"); + // emit declaration of a v8 class template Template t_decl_class(GetTemplate(V8_DECL_CLASSTEMPLATE)); t_decl_class.Replace(KW_MANGLED_NAME, current_classname_mangled); @@ -233,6 +239,7 @@ int V8Emitter::ExitClass(Node *n) Delete(current_classname_unqualified); current_classname_mangled = 0; current_classname_unqualified = 0; + current_class_type = 0; return SWIG_OK; } @@ -322,23 +329,19 @@ int V8Emitter::ExitFunction(Node* n) int V8Emitter::EmitCtor(Node* n) { - // TODO: - // - handle overloaded ctors using a dispatcher - // - marshal inputs + // TODO: handle overloaded ctors using a dispatcher Template t(GetTemplate(V8_CTOR_WRAPPER)); + + //HACK: manually add declaration of instance pointer + Printf(current_wrapper->locals, "%sresult;", SwigType_str(Getattr(n, "type"),0)); - ParmList *params = Getattr(n,"parms"); - emit_parameter_variables(params, current_wrapper); - emit_attach_parmmaps(params, current_wrapper); - - String* action = Getattr(n, "wrap:action"); - String* input = NewString(""); + String* action = emit_action(n); + Printv(current_wrapper->code, action, 0); t.Replace(KW_MANGLED_NAME, current_classname_mangled) .Replace(KW_UNQUALIFIED_NAME, current_classname_unqualified) .Replace(KW_LOCALS, current_wrapper->locals) - .Replace(KW_ACTION, action) - .Replace(KW_MARSHAL_INPUT, input); + .Replace(KW_CODE, current_wrapper->code); Wrapper_pretty_print(t.str(), f_wrapper); @@ -360,21 +363,21 @@ int V8Emitter::EmitGetter(Node *n, bool is_member) { current_getter = Getattr(n,"wrap:name"); - Printf(current_wrapper->locals, "%s result;\n", SwigType_str(Getattr(n, "type"), 0)); - + ParmList *params = Getattr(n,"parms"); + emit_parameter_variables(params, current_wrapper); + emit_attach_parmmaps(params, current_wrapper); + + int num_args = emit_num_arguments(params); String* action = emit_action(n); - String* output = NewString("// TODO: marshal output.\n ret = v8::Undefined();"); + marshalInputArgs(n, params, num_args, current_wrapper); + marshalOutput(n, action, current_wrapper); t_getter.Replace(KW_MANGLED_NAME, current_variable_mangled) .Replace(KW_LOCALS, current_wrapper->locals) - .Replace(KW_ACTION, action) - .Replace(KW_MARSHAL_OUTPUT, output); + .Replace(KW_CODE, current_wrapper->code); Wrapper_pretty_print(t_getter.str(), f_wrapper); - - // clean up - Delete(output); - + return SWIG_OK; } @@ -388,19 +391,17 @@ int V8Emitter::EmitSetter(Node* n, bool is_member) emit_parameter_variables(params, current_wrapper); emit_attach_parmmaps(params, current_wrapper); + int num_args = emit_num_arguments(params); String* action = emit_action(n); - String* input = NewString("// TODO: marshal input.\n"); + marshalInputArgs(n, params, num_args, current_wrapper); + Printv(current_wrapper->code, action, 0); t_setter.Replace(KW_MANGLED_NAME, current_variable_mangled) .Replace(KW_LOCALS, current_wrapper->locals) - .Replace(KW_ACTION, action) - .Replace(KW_MARSHAL_INPUT, input); + .Replace(KW_CODE, current_wrapper->code); Wrapper_pretty_print(t_setter.str(), f_wrapper); - // clean up - Delete(input); - return SWIG_OK; } @@ -416,26 +417,124 @@ int V8Emitter::EmitFunction(Node* n, bool is_member) ParmList *params = Getattr(n,"parms"); emit_parameter_variables(params, current_wrapper); emit_attach_parmmaps(params, current_wrapper); - Printf(current_wrapper->locals, "%s result;\n", SwigType_str(Getattr(n, "type"), 0)); - String* input = NewString("// TODO: marshal input"); + int num_args = emit_num_arguments(params); String* action = emit_action(n); - String* output = NewString("// TODO: marshal output.\n ret = v8::Undefined();"); + marshalInputArgs(n, params, num_args, current_wrapper); + marshalOutput(n, action, current_wrapper); t_function.Replace(KW_MANGLED_NAME, current_function_mangled) .Replace(KW_LOCALS, current_wrapper->locals) - .Replace(KW_ACTION, action) - .Replace(KW_MARSHAL_INPUT, input) - .Replace(KW_MARSHAL_OUTPUT, output); + .Replace(KW_CODE, current_wrapper->code); Wrapper_pretty_print(t_function.str(), f_wrapper); - // clean up - Delete(input); - Delete(output); - return SWIG_OK; } + + +void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, int numarg, Wrapper *wrapper) { + String *tm; + Parm *p; + + bool is_member = (current_class_type != 0); + bool is_setter = IsSetterMethod(n); + bool is_function = (current_function_mangled != 0); + + int start_idx; + if(is_member) { + start_idx = 1; + } else { + start_idx = 0; + } + + // retrieve this pointer for member functions + if(is_member) { + + Template t_selfptr(GetTemplate(V8_THIS_PTR)); + String *type_str = SwigType_strip_qualifiers(SwigType_str(current_class_type,0)); + String *arg_str; + if(is_function) { + arg_str = NewString("args"); + } else { + arg_str = NewString("info"); + } + + t_selfptr.Replace(KW_TYPE, type_str) + .Replace(KW_ARG, arg_str); + Printv(wrapper->code, t_selfptr.str(), 0); + + Delete(type_str); + Delete(arg_str); + } + + int i = 0; + for (i = 0, p = parms; i < numarg; i++) + { + p = skipIgnoredArgs(p); + SwigType *pt = Getattr(p, "type"); + + String *arg = NewString(""); + if (i == 0) { + if(start_idx == 0) { + Printv(arg, is_setter?"value":"args[0]", 0); + } else { + p = Getattr(p, "tmap:in:next"); + Delete(arg); + continue; // special case: skip the typemaps for the first argument + } + } else { + Printf(arg, is_setter?"value":"args[%d]", i - start_idx); + } + + if ((tm = Getattr(p, "tmap:in"))) // Get typemap for this argument + { + Replaceall(tm, "$input", arg); + Setattr(p, "emit:input", arg); + Printf(wrapper->code, "%s\n", tm); + p = Getattr(p, "tmap:in:next"); + } else { + Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0)); + p = nextSibling(p); + } + Delete(arg); + } +} + +/* --------------------------------------------------------------------- + * marshalOutput() + * + * Process the return value of the C/C++ function call + * and convert them into the Javascript types using the + * supplied typemaps. + * --------------------------------------------------------------------- */ + +void V8Emitter::marshalOutput(Node *n, String *actioncode, Wrapper *wrapper) { + SwigType *type = Getattr(n, "type"); + Setattr(n, "type", type); + String *tm; + if ((tm = Swig_typemap_lookup_out("out", n, "result", wrapper, actioncode))) + { + Replaceall(tm, "$result", "jsresult"); + // TODO: May not be the correct way + Replaceall(tm, "$objecttype", Swig_scopename_last(SwigType_str(SwigType_strip_qualifiers(type), 0))); + Printf(wrapper->code, "%s", tm); + if (Len(tm)) + Printf(wrapper->code, "\n"); + } else { + Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(type, 0), Getattr(n, "name")); + } + emit_return_variable(n, type, wrapper); +} + +Parm* V8Emitter::skipIgnoredArgs(Parm *p) { + while (checkAttribute(p, "tmap:in:numinputs", "0")) { + p = Getattr(p, "tmap:in:next"); + } + return p; +} + + JSEmitter* create_v8_emitter() { return new V8Emitter(); diff --git a/Source/Modules/javascript_v8.h b/Source/Modules/javascript_v8.h index c70d54e34..7ff11f136 100644 --- a/Source/Modules/javascript_v8.h +++ b/Source/Modules/javascript_v8.h @@ -45,6 +45,12 @@ protected: virtual int EmitSetter(Node *n, bool is_member); + void marshalInputArgs(Node *n, ParmList *parms, int numarg, Wrapper *wrapper); + + void marshalOutput(Node *n, String *actioncode, Wrapper *wrapper); + + Parm *skipIgnoredArgs(Parm *p); + private: File *f_runtime; @@ -64,6 +70,7 @@ private: // state variables String* current_context; + String* current_class_type; String* current_classname_mangled; String* current_classname_unqualified; String* current_variable_mangled; From badf090cb5f2a3dd396b616ba0b997f562a28496 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:51:00 +0000 Subject: [PATCH 0083/1048] Extend and rename v8 helper functions. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13756 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .../V8_CodeGeneratorSpecification.md | 74 +++++++++++-------- Lib/javascript/v8/javascriptcode.swg | 6 +- 2 files changed, 47 insertions(+), 33 deletions(-) diff --git a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md index fcd581755..2265e6a5d 100644 --- a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md +++ b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md @@ -279,8 +279,9 @@ A lot of boiler-plate code can be shifted into static helper functions: /** * Creates a class template for a class without extra initialization function. */ -v8::Persistent SWIGV8_CreateClassTemplate(const char* symbol) { - v8::Local class_templ = v8::FunctionTemplate::New(); +v8::Persistent SWIGV8_CreateClassTemplate(const char* symbol, v8::InvocationCallback func) +{ + v8::Local class_templ = v8::FunctionTemplate::New(func); class_templ->SetClassName(v8::String::NewSymbol(symbol)); v8::Handle inst_templ = class_templ->InstanceTemplate(); @@ -289,47 +290,60 @@ v8::Persistent SWIGV8_CreateClassTemplate(const char* symb return v8::Persistent::New(class_templ); } -/** - * Creates a class template for a class with specified initialization function. - */ -v8::Persistent SWIGV8_CreateClassTemplate(const char* symbol, v8::InvocationCallback _func) { - v8::Local class_templ = v8::FunctionTemplate::New(_func); - class_templ->SetClassName(v8::String::NewSymbol(symbol)); - - v8::Handle inst_templ = class_templ->InstanceTemplate(); - inst_templ->SetInternalFieldCount(1); - - return v8::Persistent::New(class_templ); -} - -/** - * Sets the pimpl data of a V8 class. - */ -v8::Handle V8GeneratorUtils::SetInstance(const v8::Arguments& args, void* data) { - v8::HandleScope scope; - - v8::Handle self = args.Holder(); - self->SetInternalField(0, v8::External::New(data)); - - return self; -} - /** * Registers a class method with given name for a given class template. */ -void V8GeneratorUtils::AddClassMethod(v8::Handle class_templ, const char* symbol, v8::InvocationCallback _func) { +void SWIGV8_AddMemberFunction(v8::Handle class_templ, + const char* symbol, + v8::InvocationCallback func) +{ v8::Handle proto_templ = class_templ->PrototypeTemplate(); - proto_templ->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)); + proto_templ->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(func)); } /** * Registers a class property with given name for a given class template. */ -void V8GeneratorUtils::AddProperty(v8::Handle class_templ, const char* varname, v8::AccessorGetter getter, v8::AccessorSetter setter) { +void SWIGV8_AddMemberVariable(v8::Handle class_templ, + const char* varname, + v8::AccessorGetter getter, + v8::AccessorSetter setter) +{ v8::Handle proto_templ = class_templ->InstanceTemplate(); proto_templ->SetAccessor(v8::String::New(varname), getter, setter); } + +/** + * Adds a property with given name to a given context. + */ +void SWIGV8_AddGlobalVariable(v8::Handle context, + const char* varname, + v8::AccessorGetter getter, + v8::AccessorSetter setter) +{ + context->SetAccessor(v8::String::NewSymbol(varname), getter, setter); +} + +/** + * Adds a function with given name to a given context. + */ +void SWIGV8_AddGlobalFunction(v8::Handle context, + const char* symbol, + v8::InvocationCallback func) +{ + context->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(func)->GetFunction()); +} + +template +static T* SWIGV8_UnwrapThisPointer (v8::Handle handle) +{ + // assert(!handle.IsEmpty()); + // assert(handle->InternalFieldCount() > 0); + v8::Local wrap = v8::Local::Cast(handle->GetInternalField(0)); + return static_cast(wrap->Value()); +} + ~~~~ ------------------------- diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 855f72284..c8dc0a109 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -73,13 +73,13 @@ v8::Handle wrap_${NAME_MANGLED}(const Arguments &args) { v8::Handle ${NAME_MANGLED} = v8::ObjectTemplate::New();%} %fragment("v8_register_member_function", "templates") %{ -SWIGV8_AddClassMethod(SWIGV8_${CLASSNAME_MANGLED}, "${NAME_UNQUALIFIED}", wrap_${NAME_MANGLED});%} +SWIGV8_AddMemberFunction(SWIGV8_${CLASSNAME_MANGLED}, "${NAME_UNQUALIFIED}", wrap_${NAME_MANGLED});%} %fragment("v8_register_global_function", "templates") %{ -SWIGV8_AddGlobalMethod(${CONTEXT}, "${NAME_UNQUALIFIED}", wrap_${NAME_MANGLED});%} +SWIGV8_AddGlobalFunction(${CONTEXT}, "${NAME_UNQUALIFIED}", wrap_${NAME_MANGLED});%} %fragment("v8_register_member_variable", "templates") %{ -SWIGV8_AddClassVariable(SWIGV8_${CLASSNAME_MANGLED}, "${NAME_UNQUALIFIED}", ${GETTER}, ${SETTER});%} +SWIGV8_AddMemberVariable(SWIGV8_${CLASSNAME_MANGLED}, "${NAME_UNQUALIFIED}", ${GETTER}, ${SETTER});%} %fragment("v8_register_global_variable", "templates") %{ SWIGV8_AddGlobalVariable(${CONTEXT}, "${NAME_UNQUALIFIED}", ${GETTER}, ${SETTER});%} From 0fd30dc60f462afa797acf84f0f0ad6cea0077a3 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:51:16 +0000 Subject: [PATCH 0084/1048] Add examples to specification of v8 code generator. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13757 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .../V8_CodeGeneratorSpecification.md | 174 ++++++++++++++++++ 1 file changed, 174 insertions(+) diff --git a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md index 2265e6a5d..112cffbdb 100644 --- a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md +++ b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md @@ -464,6 +464,180 @@ int Namespace_Initialize(v8::Handle context) { ~~~~~ +## Class + +~~~~~ + +class A { +public: + A() { + x = 42; + } + + ~A() {} + + double foo(bool a) { + if(a) + return 11.11; + else + return 22.22; + } + + int x; +}; + +v8::Handle A_new(const v8::Arguments& args) { + v8::HandleScope scope; + v8::Handle self = args.Holder(); + A *result; + result = new A(); + self->SetInternalField(0, v8::External::New(result)); + return self; +} + +void A_x_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { + v8::HandleScope scope; + A *arg1; + int arg2; + + arg1 = SWIGV8_UnwrapThisPointer(info.Holder()); + arg2 = value->Int32Value(); + + arg1->x = arg2; + +} + +v8::Handle A_x_get(v8::Local property, const v8::AccessorInfo& info) { + v8::HandleScope scope; + v8::Handle jsresult; + A *arg1; + int result; + + arg1 = SWIGV8_UnwrapThisPointer(info.Holder()); + result = arg1->x; + + jsresult = v8::Int32::New(result); + return scope.Close(jsresult); +} + +v8::Handle wrap_A_foo(const v8::Arguments& args) +{ + v8::HandleScope scope; + v8::Handle jsresult; + A *arg1; + double arg2; + double result; + + arg1 = SWIGV8_UnwrapThisPointer(args.Holder()); + arg2 = args[0]->NumberValue(); + + result = arg1->foo(arg2); + + jsresult = v8::Number::New(result); + return scope.Close(jsresult); +} + +int Class_Initialize(v8::Handle context) { + + v8::Local global = context->Global(); + + v8::Persistent class_A = SWIGV8_CreateClassTemplate("A", A_new); + SWIGV8_AddMemberVariable(class_A, "x", A_x_get, A_x_set); + SWIGV8_AddMemberFunction(class_A, "foo", wrap_A_foo); + + global->Set(v8::String::NewSymbol("A"), class_A->GetFunction()); + + return 0; +} + +~~~~~ + +## Static variables and functions + +Static variables and functions are implemented similar to global ones. +They are added to the class object instead of the class template. +Therefore, these are only accessible via the class object and not via +instances of this class. + +~~~~~ + +class A { +public: + A() { + x = 7; + } + + ~A() {} + + static int foo() { + return 42; + } + + static int x; +}; + +int A::x = 7; + +v8::Handle A_new(const v8::Arguments& args) { + v8::HandleScope scope; + v8::Handle self = args.Holder(); + A *result; + result = new A(); + self->SetInternalField(0, v8::External::New(result)); + return self; +} + +void A_x_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { + v8::HandleScope scope; + int arg1; + + arg1 = value->Int32Value(); + + A::x = arg1; + +} + +v8::Handle A_x_get(v8::Local property, const v8::AccessorInfo& info) { + v8::HandleScope scope; + v8::Handle jsresult; + int result; + + result = A::x; + + jsresult = v8::Int32::New(result); + return scope.Close(jsresult); +} + +v8::Handle wrap_A_foo(const v8::Arguments& args) +{ + v8::HandleScope scope; + v8::Handle jsresult; + int result; + + result = A::foo(); + + jsresult = v8::Number::New(result); + return scope.Close(jsresult); +} + +int Class_Initialize(v8::Handle context) { + + v8::Local global = context->Global(); + + v8::Persistent classtempl_A = SWIGV8_CreateClassTemplate("A", A_new); + + v8::Handle class_A = classtempl_A->GetFunction(); + + SWIGV8_AddGlobalVariable(class_A, "x", A_x_get, A_x_set); + SWIGV8_AddGlobalFunction(class_A, "foo", wrap_A_foo); + + global->Set(v8::String::NewSymbol("A"), class_A); + + return 0; +} + +~~~~~ + ------------------------- Control flow analysis From e8dd979d165faa481b057a1b4cb145b3b789d36e Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:51:29 +0000 Subject: [PATCH 0085/1048] Update v8 specification. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13758 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .../V8_CodeGeneratorSpecification.md | 44 +++++++++---------- 1 file changed, 21 insertions(+), 23 deletions(-) diff --git a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md index 112cffbdb..7037c665d 100644 --- a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md +++ b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md @@ -66,16 +66,15 @@ There are different types of function wrappers: v8::Handle wrap_${NAME_MANGLED}(const v8::Arguments &args) { v8::HandleScope scope; v8::Handle ret; - ${LOCALS} - ${MARSHAL_INPUT} - ${ACTION} - ${MARSHAL_OUTPUT} - + ${CODE} return scope.Close(ret); } ~~~~ +- `LOCALS`: declarations for input and output arguments +- `CODE` contains input marshalling, the action, and output marshalling + ### Constructors ~~~~ @@ -83,16 +82,14 @@ v8::Handle ${NAME_MANGLED}_new(const v8::Arguments& args) { v8::HandleScope scope; v8::Handle self = args.Holder(); ${LOCALS} - ${MARSHAL_INPUT} - ${ACTION} + ${CODE} self->SetInternalField(0, v8::External::New(ptr)); return self; } ~~~~ -- `LOCALS`: declaration and marshalling for input arguments -- `MARSHAL_INPUT`: code is generated by applying input typemaps -- `ACTION`: the C/C++ ctor to be executed +- `LOCALS`: declarations for input arguments +- `CODE` contains input marshalling, and the action ### Destructors @@ -105,28 +102,26 @@ v8::Handle ${NAME_MANGLED}_get(v8::Local property, const v8::HandleScope scope; v8::Handle ret; ${LOCALS} - ${ACTION} - ${MARSHAL_OUTPUT} + ${CODE} return scope.Close(ret); } ~~~~ - `NAME_MANGLED`: the qualified mangled name of the variable, E.g., `foo::x -> foo_x`, `A.x -> A_x` -- `LOCALS`: declare C return variable -- `MARSHAL_OUTPUT`: code is generated by applying output typemaps +- `LOCALS`: declarations for output arguments +- `CODE` contains the action, and output marshalling ### Setters ~~~~ void ${NAME_MANGLED}_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { ${LOCALS} - ${MARSHAL_INPUT} - ${ACTION} + ${CODE} } ~~~~ - `NAME_MANGLED`: the qualified mangled name of the variable, E.g., `foo::x -> foo_x`, `A.x -> A_x` - `LOCALS`: declarations for input arguments -- `MARSHAL_INPUT`: code is generated by applying input typemaps +- `CODE` contains input marshalling, and the action ### Functions @@ -135,14 +130,15 @@ v8::Handle ${NAME_MANGLED}(const Arguments &args) { v8::HandleScope scope; v8::Handle ret; ${LOCALS} - ${MARSHAL_INPUT} - ${ACTION} - ${MARSHAL_OUTPUT} + ${CODE} return scope.Close(ret); } ~~~~ -- if the function does not have a return value, return v8::Undefined +- `NAME_MANGLED`: the qualified mangled name of the variable, E.g., `foo::x -> foo_x`, `A.x -> A_x` +- `LOCALS`: declarations for input arguments +- `CODE` contains input marshalling, the action, and output marshalling + ### Overloading @@ -169,7 +165,9 @@ void ${MODULE}_Initialize(v8::Handle context) ${PART_INHERITANCE} - ${PART_REGISTER} + ${PART_REGISTER_CLASSES} + + ${PART_REGISTER_NS} } ~~~~ @@ -217,7 +215,7 @@ ${CONTEXT}->SetAccessor(v8::String::NewSymbol("${NAME_UNQUALIFIED}"), ${GETTER}, #### Global Function ~~~~ -${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}"), v8::FunctionTemplate::New(wrap_${NAME_QUALIFIED})->GetFunction()); +SWIGV8_AddGlobalFunction(${CONTEXT}, "${NAME_UNQUALIFIED}", wrap_${NAME_QUALIFIED}); ~~~~ - `CONTEXT`: either global, or the according namespace template From 32a32633ba1ad9fe12e07f90b1eeaee2665b2631 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:51:47 +0000 Subject: [PATCH 0086/1048] Add support for static member variables and functions to v8 module. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13759 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptcode.swg | 11 ++++- Source/Modules/javascript_v8.cxx | 64 ++++++++++++++++++++++------ Source/Modules/javascript_v8.h | 2 + 3 files changed, 63 insertions(+), 14 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index c8dc0a109..e5a1f1eba 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -16,6 +16,12 @@ void ${MODULE}_Initialize(v8::Handle context) /* setup inheritances */ ${PART_INHERITANCE} + /* class instances */ + ${PART_CLASS_INSTANCES} + + /* add static class functions and variables */ + ${PART_STATIC_WRAPPERS} + /* register classes */ ${PART_REGISTER_CLASSES} @@ -29,11 +35,14 @@ v8::Persistent SWIGV8_${NAME_MANGLED};%} %fragment("v8_define_class_template", "templates") %{ SWIGV8_${NAME_MANGLED} = SWIGV8_CreateClassTemplate("${NAME_UNQUALIFIED}" , ${NAME_MANGLED}_new);%} +%fragment("v8_create_class_instance", "templates") %{ +v8::Handle class_${NAME_MANGLED} = SWIGV8_${NAME_MANGLED}->GetFunction();%} + %fragment("v8_inherit", "templates") %{ SWIGV8_${NAME_MANGLED}->Inherit(SWIGV8_${BASE_CLASS});%} %fragment("v8_register_class", "templates") %{ -${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}", SWIGV8_${NAME_MANGLED}->GetFunction()));%} +${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}"), class_${NAME_MANGLED});%} %fragment("v8_ctor_wrapper", "templates") %{ v8::Handle ${NAME_MANGLED}_new(const v8::Arguments& args) { diff --git a/Source/Modules/javascript_v8.cxx b/Source/Modules/javascript_v8.cxx index 7d6e9a327..cacceb214 100644 --- a/Source/Modules/javascript_v8.cxx +++ b/Source/Modules/javascript_v8.cxx @@ -9,6 +9,7 @@ #define V8_INITIALIZER "v8_initializer" #define V8_DECL_CLASSTEMPLATE "v8_declare_class_template" #define V8_DEFINE_CLASSTEMPLATE "v8_define_class_template" +#define V8_CREATE_CLASS_INSTANCE "v8_create_class_instance" #define V8_INHERIT "v8_inherit" #define V8_REGISTER_CLASS "v8_register_class" #define V8_CTOR_WRAPPER "v8_ctor_wrapper" @@ -42,6 +43,8 @@ #define KW_CLASS_TEMPLATES "${PART_CLASS_TEMPLATES}" #define KW_WRAPPERS "${PART_WRAPPERS}" #define KW_INHERITANCE "${PART_INHERITANCE}" +#define KW_CLASS_INSTANCES "${PART_CLASS_INSTANCES}" +#define KW_STATIC_WRAPPERS "${PART_STATIC_WRAPPERS}" #define KW_REGISTER_CLASSES "${PART_REGISTER_CLASSES}" #define KW_REGISTER_NS "${PART_REGISTER_NS}" @@ -86,6 +89,8 @@ int V8Emitter::Initialize(Node *n) f_init_class_templates = NewString(""); f_init_wrappers = NewString(""); f_init_inheritance = NewString(""); + f_init_class_instances = NewString(""); + f_init_static_wrappers = NewString(""); f_init_register_classes = NewString(""); f_init_register_namespaces = NewString(""); @@ -116,6 +121,8 @@ int V8Emitter::Dump(Node *n) .Replace(KW_CLASS_TEMPLATES, f_init_class_templates) .Replace(KW_WRAPPERS, f_init_wrappers) .Replace(KW_INHERITANCE, f_init_inheritance) + .Replace(KW_CLASS_INSTANCES, f_init_class_instances) + .Replace(KW_STATIC_WRAPPERS, f_init_static_wrappers) .Replace(KW_REGISTER_CLASSES, f_init_register_classes) .Replace(KW_REGISTER_NS, f_init_register_namespaces); Wrapper_pretty_print(initializer.str(), f_wrap_cpp); @@ -125,6 +132,7 @@ int V8Emitter::Dump(Node *n) int V8Emitter::Close() { + /* strings */ Delete(f_runtime); Delete(f_header); Delete(f_class_templates); @@ -133,8 +141,12 @@ int V8Emitter::Close() Delete(f_init_class_templates); Delete(f_init_wrappers); Delete(f_init_inheritance); + Delete(f_init_class_instances); + Delete(f_init_static_wrappers); Delete(f_init_register_classes); Delete(f_init_register_namespaces); + + /* files */ ::Close(f_wrap_cpp); Delete(f_wrap_cpp); @@ -210,9 +222,13 @@ int V8Emitter::EnterClass(Node *n) // emit definition of v8 class template Template t_def_class(GetTemplate(V8_DEFINE_CLASSTEMPLATE)); - t_def_class.Replace(KW_MANGLED_NAME, current_classname_mangled) + t_def_class.Replace(KW_MANGLED_NAME, current_classname_mangled) .Replace(KW_UNQUALIFIED_NAME, current_classname_unqualified); Printv(f_init_class_templates, t_def_class.str(), 0); + + Template t_class_instance(GetTemplate(V8_CREATE_CLASS_INSTANCE)); + t_class_instance.Replace(KW_MANGLED_NAME, current_classname_mangled); + Printv(f_init_class_instances, t_class_instance.str(), 0); return SWIG_OK; } @@ -262,14 +278,25 @@ int V8Emitter::EnterVariable(Node* n) int V8Emitter::ExitVariable(Node* n) { - if(GetFlag(n, "ismember")) { - Template t_register(GetTemplate(V8_REGISTER_MEMBER_VARIABLE)); - t_register.Replace(KW_CLASSNAME_MANGLED, current_classname_mangled) - .Replace(KW_UNQUALIFIED_NAME, current_variable_unqualified) - .Replace(KW_GETTER, current_getter) - .Replace(KW_SETTER, current_setter); - Printv(f_init_wrappers, t_register.str(), 0); + if(Equal(Getattr(n, "storage"), "static")) { + Template t_register(GetTemplate(V8_REGISTER_GLOBAL_VARIABLE)); + String *class_instance = NewString(""); + Printf(class_instance, "class_%s", current_classname_mangled); + t_register.Replace(KW_CONTEXT, class_instance) + .Replace(KW_UNQUALIFIED_NAME, current_variable_unqualified) + .Replace(KW_GETTER, current_getter) + .Replace(KW_SETTER, current_setter); + Printv(f_init_static_wrappers, t_register.str(), 0); + Delete(class_instance); + } else { + Template t_register(GetTemplate(V8_REGISTER_MEMBER_VARIABLE)); + t_register.Replace(KW_CLASSNAME_MANGLED, current_classname_mangled) + .Replace(KW_UNQUALIFIED_NAME, current_variable_unqualified) + .Replace(KW_GETTER, current_getter) + .Replace(KW_SETTER, current_setter); + Printv(f_init_wrappers, t_register.str(), 0); + } } else { Template t_register(GetTemplate(V8_REGISTER_GLOBAL_VARIABLE)); t_register.Replace(KW_CONTEXT, current_context) @@ -305,11 +332,22 @@ int V8Emitter::ExitFunction(Node* n) { // register the function at the specific context if(GetFlag(n, "ismember")) { - Template t_register(GetTemplate(V8_REGISTER_MEMBER_FUNCTION)); - t_register.Replace(KW_CLASSNAME_MANGLED, current_classname_mangled) - .Replace(KW_UNQUALIFIED_NAME, current_function_unqualified) - .Replace(KW_MANGLED_NAME, Getattr(n, "wrap:name")); - Printv(f_init_wrappers, t_register.str(), "\n", 0); + if(Equal(Getattr(n, "storage"), "static")) { + Template t_register(GetTemplate(V8_REGISTER_GLOBAL_FUNCTION)); + String *class_instance = NewString(""); + Printf(class_instance, "class_%s", current_classname_mangled); + t_register.Replace(KW_CONTEXT, class_instance) + .Replace(KW_UNQUALIFIED_NAME, current_function_unqualified) + .Replace(KW_MANGLED_NAME, Getattr(n, "wrap:name")); + Printv(f_init_static_wrappers, t_register.str(), 0); + Delete(class_instance); + } else { + Template t_register(GetTemplate(V8_REGISTER_MEMBER_FUNCTION)); + t_register.Replace(KW_CLASSNAME_MANGLED, current_classname_mangled) + .Replace(KW_UNQUALIFIED_NAME, current_function_unqualified) + .Replace(KW_MANGLED_NAME, Getattr(n, "wrap:name")); + Printv(f_init_wrappers, t_register.str(), "\n", 0); + } } else { Template t_register(GetTemplate(V8_REGISTER_GLOBAL_FUNCTION)); t_register.Replace(KW_CONTEXT, current_context) diff --git a/Source/Modules/javascript_v8.h b/Source/Modules/javascript_v8.h index 7ff11f136..8d9e6d0b0 100644 --- a/Source/Modules/javascript_v8.h +++ b/Source/Modules/javascript_v8.h @@ -62,6 +62,8 @@ private: File *f_init_class_templates; File *f_init_wrappers; File *f_init_inheritance; + File *f_init_class_instances; + File *f_init_static_wrappers; File *f_init_register_classes; File *f_init_register_namespaces; From 67a3de9a93433585a8daca77d3e300713bf91762 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:52:02 +0000 Subject: [PATCH 0087/1048] Add example for inheritance to v8 specification. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13760 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .../V8_CodeGeneratorSpecification.md | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md index 7037c665d..3b6af8108 100644 --- a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md +++ b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md @@ -636,6 +636,51 @@ int Class_Initialize(v8::Handle context) { ~~~~~ +## Inheritance + +~~~~~ +class A { +public: + A() {} + + ~A() {} + + double foo() { + return 11.11; + } +}; + +class B: public A { +public: + B() {} + ~B() {} + + int bar() { + return 7; + } +}; + +... (left out function wrappers) ... + +int Class_Initialize(v8::Handle context) { + + v8::Local global = context->Global(); + + v8::Persistent class_A = SWIGV8_CreateClassTemplate("A", A_new); + v8::Persistent class_B = SWIGV8_CreateClassTemplate("B", B_new); + + SWIGV8_AddMemberFunction(class_A, "foo", wrap_A_foo); + SWIGV8_AddMemberFunction(class_B, "bar", wrap_B_bar); + + class_B->Inherit(class_A); + + global->Set(v8::String::NewSymbol("A"), class_A->GetFunction()); + global->Set(v8::String::NewSymbol("B"), class_B->GetFunction()); + + return 0; +} +~~~~~ + ------------------------- Control flow analysis From 8168750c1b43d42a24efa598a1da14c9f56a95f4 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:52:16 +0000 Subject: [PATCH 0088/1048] Add example for string marshalling to v8 specification. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13761 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .../V8_CodeGeneratorSpecification.md | 68 +++++++++++++++++-- 1 file changed, 64 insertions(+), 4 deletions(-) diff --git a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md index 3b6af8108..63027b74d 100644 --- a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md +++ b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md @@ -84,7 +84,7 @@ v8::Handle ${NAME_MANGLED}_new(const v8::Arguments& args) { ${LOCALS} ${CODE} self->SetInternalField(0, v8::External::New(ptr)); - return self; + return self; } ~~~~ @@ -296,7 +296,7 @@ void SWIGV8_AddMemberFunction(v8::Handle class_templ, v8::InvocationCallback func) { v8::Handle proto_templ = class_templ->PrototypeTemplate(); - proto_templ->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(func)); + proto_templ->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(func)); } /** @@ -330,7 +330,7 @@ void SWIGV8_AddGlobalFunction(v8::Handle context, const char* symbol, v8::InvocationCallback func) { - context->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(func)->GetFunction()); + context->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(func)->GetFunction()); } template @@ -582,7 +582,7 @@ v8::Handle A_new(const v8::Arguments& args) { A *result; result = new A(); self->SetInternalField(0, v8::External::New(result)); - return self; + return self; } void A_x_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { @@ -681,6 +681,66 @@ int Class_Initialize(v8::Handle context) { } ~~~~~ +## String arguments + +At a first stage all strings are treated as Utf8. +For proper handling strings as return values I have to study +other modules. + +~~~~~ +int my_strlen(const char* s) { + return strlen(s); +} + +// creates a new string +const char* foo(int a) { + char* result = new char[a+1]; + result[a] = 0; + memset(result, 'a', a); + return result; +} + +v8::Handle wrap_my_strlen(const v8::Arguments& args) +{ + v8::HandleScope scope; + v8::Handle jsresult; + const char* arg1; + int result; + + v8::String::Utf8Value utf8(args[0]); + + result = my_strlen(*utf8); + + jsresult = v8::Number::New(result); + return scope.Close(jsresult); +} + +v8::Handle wrap_foo(const v8::Arguments& args) +{ + v8::HandleScope scope; + v8::Handle jsresult; + int arg1; + const char* result; + + arg1 = args[0]->Int32Value(); + result = foo(arg1); + + jsresult = v8::String::New(result); + + return scope.Close(jsresult); +} + +int Strings_Initialize(v8::Handle context) { + + v8::Local global = context->Global(); + + SWIGV8_AddGlobalFunction(global, "strlen", wrap_my_strlen); + SWIGV8_AddGlobalFunction(global, "foo", wrap_foo); + + return 0; +} +~~~~~ + ------------------------- Control flow analysis From 229f2d0fa5ffb71c36201a7c70f86e778d256128 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:52:28 +0000 Subject: [PATCH 0089/1048] Add v8 input typemap for cstrings. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13762 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptprimitives.swg | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/Lib/javascript/v8/javascriptprimitives.swg b/Lib/javascript/v8/javascriptprimitives.swg index b9b255f86..b8eb1e569 100644 --- a/Lib/javascript/v8/javascriptprimitives.swg +++ b/Lib/javascript/v8/javascriptprimitives.swg @@ -60,8 +60,10 @@ %typemap(out) float, double %{ $result = v8::Number::New($1); %} -%typemap(out) const bool &, bool &, - const char &, char &, +%typemap(out) const bool &, bool & +%{ $result = v8::Boolean::New((*$1);%} + +%typemap(out) const char &, char &, const signed char &, signed char &, const unsigned char &, unsigned char &, const short &, short &, @@ -109,14 +111,14 @@ // TODO: typemap(out) short* et al. %} - %typemap(out) void %{ $result = v8::Undefined(); %} %typemap(in) char * %{ - // TODO: input typemap for char* + v8::String::Utf8Value _$1($input); + $1 = *_$1; %} %typemap(out) char * @@ -148,7 +150,6 @@ // TODO: freearg char* et al %} - /* Typemaps for composite types */ %typemap(in) SWIGTYPE ($&1_type argp) // Objects passed by value, convert to a pointer %{ From 360ef44e09e9072702215c46306731ccbbbc1d03 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:52:41 +0000 Subject: [PATCH 0090/1048] Clean up in v8 helper functions. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13763 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascripthelpers.swg | 32 +++---------------------- 1 file changed, 3 insertions(+), 29 deletions(-) diff --git a/Lib/javascript/v8/javascripthelpers.swg b/Lib/javascript/v8/javascripthelpers.swg index bc2822c8f..b5b462b96 100644 --- a/Lib/javascript/v8/javascripthelpers.swg +++ b/Lib/javascript/v8/javascripthelpers.swg @@ -1,19 +1,5 @@ - %insert(runtime) %{ -/** - * Creates a class template for a class without extra initialization function. - */ -v8::Persistent SWIGV8_CreateClassTemplate(const char* symbol) { - v8::Local class_templ = v8::FunctionTemplate::New(); - class_templ->SetClassName(v8::String::NewSymbol(symbol)); - - v8::Handle inst_templ = class_templ->InstanceTemplate(); - inst_templ->SetInternalFieldCount(1); - - return v8::Persistent::New(class_templ); -} - /** * Creates a class template for a class with specified initialization function. */ @@ -31,22 +17,10 @@ v8::Handle SWIGV8_CreateNamespace(const char* name, v8::Hand Handle namespace = ObjectTemplate::New(); } -/** - * Sets the pimpl data of a V8 class. - */ -v8::Handle SWIGV8_SetInstance(const v8::Arguments& args, void* data) { - v8::HandleScope scope; - - v8::Handle self = args.Holder(); - self->SetInternalField(0, v8::External::New(data)); - - return self; -} - /** * Registers a class method with given name for a given class template. */ -void SWIGV8_AddClassMethod(v8::Handle class_templ, const char* symbol, v8::InvocationCallback _func) { +void SWIGV8_AddMemberFunction(v8::Handle class_templ, const char* symbol, v8::InvocationCallback _func) { v8::Handle proto_templ = class_templ->PrototypeTemplate(); proto_templ->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)); } @@ -54,14 +28,14 @@ void SWIGV8_AddClassMethod(v8::Handle class_templ, const c /** * Registers a class method with given name for a given class template. */ -void SWIGV8_AddGlobalMethod(v8::Handle obj_templ, const char* symbol, v8::InvocationCallback _func) { +void SWIGV8_AddGlobalFunction(v8::Handle obj_templ, const char* symbol, v8::InvocationCallback _func) { obj_templ->Set(String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)->GetFunction()); } /** * Registers a class property with given name for a given class template. */ -void SWIGV8_AddClassVariable(v8::Handle class_templ, const char* symbol, v8::AccessorGetter getter, v8::AccessorSetter setter) { +void SWIGV8_AddMemberVariable(v8::Handle class_templ, const char* symbol, v8::AccessorGetter getter, v8::AccessorSetter setter) { v8::Handle proto_templ = class_templ->InstanceTemplate(); proto_templ->SetAccessor(v8::String::NewSymbol(symbol), getter, setter); } From 050219d998c0a518b54366c6c543fa926e601e5b Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:56:48 +0000 Subject: [PATCH 0091/1048] Merge branch 'devel' of https://github.com/Neha03/gsoc2012-javascript into devel Conflicts: .project COPYRIGHT Doc/Manual/style.css Examples/Makefile.in Examples/test-suite/common.mk Lib/typemaps/strings.swg Makefile.in Source/DOH/fio.c Source/Makefile.am Source/Modules/emit.cxx Source/Modules/javascript.cxx configure.in git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13764 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .cproject | 72 + .project | 16 + COPYRIGHT | 6 +- Doc/Manual/Javascript.html | 770 ++++++++ Doc/Manual/Javascript.md | 1103 ++++++++++++ Doc/Manual/pandoc_template.html | 56 + Doc/Manual/style.css | 6 +- Examples/Makefile.in | 59 + Examples/javascript/class/Makefile | 24 + Examples/javascript/class/example.cpp | 28 + Examples/javascript/class/example.h | 35 + Examples/javascript/class/example.i | 10 + Examples/javascript/class/runme.js | 51 + Examples/javascript/constant/Makefile | 24 + Examples/javascript/constant/example.h | 8 + Examples/javascript/constant/example.i | 24 + Examples/javascript/constant/runme.js | 14 + Examples/javascript/enum/Makefile | 24 + Examples/javascript/enum/example.cpp | 37 + Examples/javascript/enum/example.h | 13 + Examples/javascript/enum/example.i | 11 + Examples/javascript/enum/runme.js | 34 + Examples/javascript/exception/Makefile | 24 + Examples/javascript/exception/example.cpp | 1 + Examples/javascript/exception/example.h | 53 + Examples/javascript/exception/example.i | 12 + Examples/javascript/exception/runme.js | 54 + Examples/javascript/functor/Makefile | 24 + Examples/javascript/functor/example.cpp | 0 Examples/javascript/functor/example.i | 25 + Examples/javascript/functor/runme.js | 16 + Examples/javascript/namespace/Makefile | 24 + Examples/javascript/namespace/example.cpp | 36 + Examples/javascript/namespace/example.h | 20 + Examples/javascript/namespace/example.i | 10 + Examples/javascript/namespace/runme.js | 11 + Examples/javascript/operator/Makefile | 24 + Examples/javascript/operator/example.cpp | 0 Examples/javascript/operator/example.h | 36 + Examples/javascript/operator/example.i | 34 + Examples/javascript/operator/runme.js | 25 + Examples/javascript/overload/Makefile | 24 + Examples/javascript/overload/example.cpp | 0 Examples/javascript/overload/example.h | 28 + Examples/javascript/overload/example.i | 20 + Examples/javascript/overload/runme.js | 7 + Examples/javascript/pointer/Makefile | 24 + Examples/javascript/pointer/example.cpp | 16 + Examples/javascript/pointer/example.i | 30 + Examples/javascript/pointer/runme.js | 38 + Examples/javascript/reference/Makefile | 24 + Examples/javascript/reference/example.cpp | 46 + Examples/javascript/reference/example.h | 26 + Examples/javascript/reference/example.i | 42 + Examples/javascript/reference/runme.js | 67 + Examples/javascript/simple/Makefile | 24 + Examples/javascript/simple/example.cpp | 28 + Examples/javascript/simple/example.i | 15 + Examples/javascript/simple/runme.js | 26 + Examples/javascript/template/Makefile | 24 + Examples/javascript/template/example.cpp | 0 Examples/javascript/template/example.h | 32 + Examples/javascript/template/example.i | 17 + Examples/javascript/template/runme.js | 32 + Examples/javascript/variables/Makefile | 24 + Examples/javascript/variables/example.c | 91 + Examples/javascript/variables/example.h | 6 + Examples/javascript/variables/example.i | 49 + Examples/javascript/variables/runme.js | 68 + Examples/test-suite/common.mk | 7 +- Examples/test-suite/javascript/Makefile.in | 94 + Examples/test-suite/javascript/README | 4 + .../javascript/abstract_access_runme.js | 5 + .../javascript/abstract_typedef2_runme.js | 4 + .../javascript/abstract_typedef_runme.js | 6 + .../javascript/abstract_virtual_runme.js | 9 + .../javascript/array_member_runme.js | 20 + .../javascript/arrays_global_runme.js | 16 + .../javascript/char_binary_runme.js | 36 + .../javascript/class_ignore_runme.js | 5 + .../javascript/class_scope_weird_runme.js | 5 + .../javascript/complextest_runme.js | 21 + .../test-suite/javascript/constover_runme.js | 31 + .../test-suite/javascript/cpp_enum_runme.js | 26 + .../javascript/cpp_namespace_runme.js | 45 + .../test-suite/javascript/cpp_static_runme.js | 7 + .../javascript/director_alternating_runme.js | 4 + .../javascript/enum_template_runme.js | 6 + .../namespace_virtual_method_runme.js | 2 + .../javascript/overload_copy_runme.js | 3 + .../javascript/preproc_include_runme.js | 22 + .../test-suite/javascript/preproc_runme.js | 13 + .../javascript/ret_by_value_runme.js | 7 + .../javascript/struct_value_runme.js | 10 + .../javascript/template_static_runme.js | 2 + .../javascript/typedef_class_runme.js | 5 + .../javascript/typedef_inherit_runme.js | 22 + .../javascript/typedef_scope_runme.js | 11 + .../javascript/typemap_arrays_runme.js | 4 + .../javascript/typemap_delete_runme.js | 4 + .../javascript/typemap_namespace_runme.js | 6 + .../javascript/typemap_ns_using_runme.js | 3 + .../test-suite/javascript/using1_runme.js | 4 + .../test-suite/javascript/using2_runme.js | 3 + Lib/javascript/jsc/ccomplex.i | 26 + Lib/javascript/jsc/complex.i | 6 + Lib/javascript/jsc/javascript.swg | 19 + Lib/javascript/jsc/javascriptcode.swg | 292 +++ Lib/javascript/jsc/javascriptcomplex.swg | 146 ++ Lib/javascript/jsc/javascriptfragments.swg | 0 Lib/javascript/jsc/javascripthelpers.swg | 69 + Lib/javascript/jsc/javascriptinit.swg | 15 + Lib/javascript/jsc/javascriptkw.swg | 40 + Lib/javascript/jsc/javascriptprimitives.swg | 104 ++ Lib/javascript/jsc/javascriptruntime.swg | 175 ++ Lib/javascript/jsc/javascriptstrings.swg | 171 ++ Lib/javascript/jsc/javascripttypemaps.swg | 26 + Lib/javascript/jsc/javascriptvaltypes.swg | 1 + Lib/javascript/jsc/std_common.i | 5 + Lib/javascript/jsc/std_complex.i | 19 + Lib/javascript/jsc/std_except.i | 1 + Lib/javascript/jsc/std_map.i | 74 + Lib/javascript/jsc/std_pair.i | 34 + Lib/javascript/jsc/std_string.i | 71 + Lib/javascript/jsc/std_vector.i | 85 + Lib/javascript/jsc/stl.i | 10 + Lib/typemaps/strings.swg | 4 +- Makefile.in | 17 +- Source/DOH/fio.c | 2 + Source/Makefile.am | 1 - Source/Modules/emit.cxx | 6 +- Source/Modules/javascript.cxx | 1591 +++++++++++++++-- Tools/javascript/javascript.cxx | 217 +++ Tools/swigprinters.gdb | 24 + Tools/swigprinters.py | 574 ++++++ configure.in | 149 ++ 136 files changed, 7987 insertions(+), 141 deletions(-) create mode 100644 .cproject create mode 100644 Doc/Manual/Javascript.html create mode 100644 Doc/Manual/Javascript.md create mode 100644 Doc/Manual/pandoc_template.html create mode 100755 Examples/javascript/class/Makefile create mode 100755 Examples/javascript/class/example.cpp create mode 100755 Examples/javascript/class/example.h create mode 100755 Examples/javascript/class/example.i create mode 100755 Examples/javascript/class/runme.js create mode 100755 Examples/javascript/constant/Makefile create mode 100644 Examples/javascript/constant/example.h create mode 100755 Examples/javascript/constant/example.i create mode 100755 Examples/javascript/constant/runme.js create mode 100755 Examples/javascript/enum/Makefile create mode 100755 Examples/javascript/enum/example.cpp create mode 100755 Examples/javascript/enum/example.h create mode 100755 Examples/javascript/enum/example.i create mode 100755 Examples/javascript/enum/runme.js create mode 100755 Examples/javascript/exception/Makefile create mode 100644 Examples/javascript/exception/example.cpp create mode 100644 Examples/javascript/exception/example.h create mode 100644 Examples/javascript/exception/example.i create mode 100644 Examples/javascript/exception/runme.js create mode 100755 Examples/javascript/functor/Makefile create mode 100644 Examples/javascript/functor/example.cpp create mode 100644 Examples/javascript/functor/example.i create mode 100644 Examples/javascript/functor/runme.js create mode 100755 Examples/javascript/namespace/Makefile create mode 100644 Examples/javascript/namespace/example.cpp create mode 100644 Examples/javascript/namespace/example.h create mode 100644 Examples/javascript/namespace/example.i create mode 100644 Examples/javascript/namespace/runme.js create mode 100755 Examples/javascript/operator/Makefile create mode 100644 Examples/javascript/operator/example.cpp create mode 100644 Examples/javascript/operator/example.h create mode 100644 Examples/javascript/operator/example.i create mode 100644 Examples/javascript/operator/runme.js create mode 100755 Examples/javascript/overload/Makefile create mode 100644 Examples/javascript/overload/example.cpp create mode 100644 Examples/javascript/overload/example.h create mode 100644 Examples/javascript/overload/example.i create mode 100644 Examples/javascript/overload/runme.js create mode 100755 Examples/javascript/pointer/Makefile create mode 100755 Examples/javascript/pointer/example.cpp create mode 100755 Examples/javascript/pointer/example.i create mode 100755 Examples/javascript/pointer/runme.js create mode 100755 Examples/javascript/reference/Makefile create mode 100755 Examples/javascript/reference/example.cpp create mode 100755 Examples/javascript/reference/example.h create mode 100755 Examples/javascript/reference/example.i create mode 100755 Examples/javascript/reference/runme.js create mode 100755 Examples/javascript/simple/Makefile create mode 100755 Examples/javascript/simple/example.cpp create mode 100755 Examples/javascript/simple/example.i create mode 100755 Examples/javascript/simple/runme.js create mode 100755 Examples/javascript/template/Makefile create mode 100644 Examples/javascript/template/example.cpp create mode 100644 Examples/javascript/template/example.h create mode 100644 Examples/javascript/template/example.i create mode 100644 Examples/javascript/template/runme.js create mode 100755 Examples/javascript/variables/Makefile create mode 100755 Examples/javascript/variables/example.c create mode 100755 Examples/javascript/variables/example.h create mode 100755 Examples/javascript/variables/example.i create mode 100755 Examples/javascript/variables/runme.js create mode 100755 Examples/test-suite/javascript/Makefile.in create mode 100755 Examples/test-suite/javascript/README create mode 100644 Examples/test-suite/javascript/abstract_access_runme.js create mode 100644 Examples/test-suite/javascript/abstract_typedef2_runme.js create mode 100644 Examples/test-suite/javascript/abstract_typedef_runme.js create mode 100644 Examples/test-suite/javascript/abstract_virtual_runme.js create mode 100644 Examples/test-suite/javascript/array_member_runme.js create mode 100644 Examples/test-suite/javascript/arrays_global_runme.js create mode 100644 Examples/test-suite/javascript/char_binary_runme.js create mode 100644 Examples/test-suite/javascript/class_ignore_runme.js create mode 100644 Examples/test-suite/javascript/class_scope_weird_runme.js create mode 100644 Examples/test-suite/javascript/complextest_runme.js create mode 100644 Examples/test-suite/javascript/constover_runme.js create mode 100644 Examples/test-suite/javascript/cpp_enum_runme.js create mode 100644 Examples/test-suite/javascript/cpp_namespace_runme.js create mode 100644 Examples/test-suite/javascript/cpp_static_runme.js create mode 100644 Examples/test-suite/javascript/director_alternating_runme.js create mode 100644 Examples/test-suite/javascript/enum_template_runme.js create mode 100644 Examples/test-suite/javascript/namespace_virtual_method_runme.js create mode 100644 Examples/test-suite/javascript/overload_copy_runme.js create mode 100644 Examples/test-suite/javascript/preproc_include_runme.js create mode 100644 Examples/test-suite/javascript/preproc_runme.js create mode 100644 Examples/test-suite/javascript/ret_by_value_runme.js create mode 100644 Examples/test-suite/javascript/struct_value_runme.js create mode 100644 Examples/test-suite/javascript/template_static_runme.js create mode 100644 Examples/test-suite/javascript/typedef_class_runme.js create mode 100644 Examples/test-suite/javascript/typedef_inherit_runme.js create mode 100644 Examples/test-suite/javascript/typedef_scope_runme.js create mode 100644 Examples/test-suite/javascript/typemap_arrays_runme.js create mode 100644 Examples/test-suite/javascript/typemap_delete_runme.js create mode 100644 Examples/test-suite/javascript/typemap_namespace_runme.js create mode 100644 Examples/test-suite/javascript/typemap_ns_using_runme.js create mode 100644 Examples/test-suite/javascript/using1_runme.js create mode 100644 Examples/test-suite/javascript/using2_runme.js create mode 100644 Lib/javascript/jsc/ccomplex.i create mode 100644 Lib/javascript/jsc/complex.i create mode 100644 Lib/javascript/jsc/javascript.swg create mode 100644 Lib/javascript/jsc/javascriptcode.swg create mode 100644 Lib/javascript/jsc/javascriptcomplex.swg create mode 100644 Lib/javascript/jsc/javascriptfragments.swg create mode 100644 Lib/javascript/jsc/javascripthelpers.swg create mode 100644 Lib/javascript/jsc/javascriptinit.swg create mode 100644 Lib/javascript/jsc/javascriptkw.swg create mode 100644 Lib/javascript/jsc/javascriptprimitives.swg create mode 100644 Lib/javascript/jsc/javascriptruntime.swg create mode 100644 Lib/javascript/jsc/javascriptstrings.swg create mode 100644 Lib/javascript/jsc/javascripttypemaps.swg create mode 100644 Lib/javascript/jsc/javascriptvaltypes.swg create mode 100755 Lib/javascript/jsc/std_common.i create mode 100644 Lib/javascript/jsc/std_complex.i create mode 100644 Lib/javascript/jsc/std_except.i create mode 100755 Lib/javascript/jsc/std_map.i create mode 100755 Lib/javascript/jsc/std_pair.i create mode 100755 Lib/javascript/jsc/std_string.i create mode 100755 Lib/javascript/jsc/std_vector.i create mode 100755 Lib/javascript/jsc/stl.i create mode 100644 Tools/javascript/javascript.cxx create mode 100644 Tools/swigprinters.gdb create mode 100755 Tools/swigprinters.py diff --git a/.cproject b/.cproject new file mode 100644 index 000000000..e3bfe5f2f --- /dev/null +++ b/.cproject @@ -0,0 +1,72 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + make + + cpp_static.cpptest + true + true + true + + + + diff --git a/.project b/.project index 86af75213..2139d8f0c 100644 --- a/.project +++ b/.project @@ -5,7 +5,23 @@ + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature diff --git a/COPYRIGHT b/COPYRIGHT index 173d1807d..18d821f5e 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -15,8 +15,9 @@ Active SWIG Developers: Olly Betts (olly@survex.com) (PHP) Joseph Wang (joequant@gmail.com) (R) Xavier Delacour (xavier.delacour@gmail.com) (Octave) - David Nadlinger (code@klickverbot.at) (D) - Oliver Buchtala (Javascript) + David Nadlinger (code@klickverbot.at) + Oliver Buchtala (oliver.buchtala@gmail.com) (Javascript) + Neha Narang (narangneha03@gmail.com) (Javascript) Past SWIG developers and major contributors include: Dave Beazley (dave-swig@dabeaz.com) (SWIG core, Python, Tcl, Perl) @@ -61,7 +62,6 @@ Past SWIG developers and major contributors include: Ian Lance Taylor (Go) Vadim Zeitlin (PCRE) Stefan Zager (szager@gmail.com) (Python) - Oliver Buchtala (Javascript) Past contributors include: James Michael DuPont, Clark McGrew, Dustin Mitchell, Ian Cooke, Catalin Dumitrescu, Baran diff --git a/Doc/Manual/Javascript.html b/Doc/Manual/Javascript.html new file mode 100644 index 000000000..a53e2a7cd --- /dev/null +++ b/Doc/Manual/Javascript.html @@ -0,0 +1,770 @@ + + + + + + + SWIG AND JAVASCRIPT + + + + + +
    +

    Overview

    +

    This chapter describes SWIG support for Javascript. The module is designed to support JavascriptCore and V8 as target engine. Currently only JavascriptCore support is implemented. JavaScriptCore is the built-in JavaScript engine for WebKit, whereas V8 is the engine used by Chromium.

    +

    JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. Its arguably the most popular language for web development. C++, on the other hand, is statically typed, compiled, general purpose programming language. The approach I followed here is "Test driven" where I have written the examples/test-cases to be supported for Javascript one-by-one and implemented the required module files in parallel. The support for Javascript would be added similar to other supported target languages in swig. Swig comes with an "Examples" directory for Javascript like other supported language. The directory contains examples for every supported feature of the target language. There is also a test-suite directory for javascript which contains additional tests.

    +

    Preliminaries

    +

    In order to use this module, you will need to have installed javascriptcore and you can install it by installing package libwebkit-dev You can find out some necessary compiler/linker flag by

    +
    pkg-config javascriptcoregtk-1.0 --cflags --libs
    +
    +

    Using the module

    +

    To generate an extension for JavascriptCore one would call swig as follows

    +

    swig -c++ -javascript -jsc example.i +
    +

    This generates a C++ source file containing the wrapper.

    +

    How does Javascript talk to C++?

    +

    JavascriptCore provides a C-API which allows to extend a Javascript interpreter with native methods and structures. Normally, this is used to implement the builtin features of the language. However, by extending the interpreter, it is also possible to add your own commands and variables. A reference manual of this API can be found here.

    +

    Typically, when you add a new command to the javascript interpreter you need to do two things: first you need to write a special "wrapper" function that serves as the glue between the interpreter and the underlying C function. Then you need to give the interpreter information about the wrapper by providing details about the name of the function, arguments, and so forth. The next few sections illustrate the process.

    +

    Wrapper functions

    +

    Suppose you have an ordinary C function like this :

    +

    int fact(int n) { + if (n <= 1) return 1; + else return n*fact(n-1); +} +
    +

    In order to access this function from a scripting language, it is necessary to write a special "wrapper" function that serves as the glue between the scripting language and the underlying C function. A wrapper function must do three things :

    +
      +
    • Gather function arguments and make sure they are valid.
    • +
    • Call the C function.
    • +
    • Convert the return value into a form recognized by the javascript.
    • +
    +

    As an example, the javascript wrapper function for the fact() function above example might look like the following :

    +

    JSValueRef wrap_fact(JSContextRef context, JSObjectRef function, JSObjectRef globalobj, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + int arg1 = (int)JSValueToNumber(context, argv[0], NULL); + int arg2 = (int)JSValueToNumber(context, argv[1], NULL); + int result = (int)fact(arg1,arg2); + JSValueRef jsresult = JSValueMakeNumber(context, result); + return jsresult; +} +
    +

    Once you have created a wrapper function, the final step is to tell the javascript about the new function. This is done by register function called by the javascript when the module is loaded. For example, adding the above function to the javascript interpreter requires code like the following :

    +

    bool jsc_registerFunction(JSGlobalContextRef context, JSObjectRef object, + const char* functionName, JSObjectCallAsFunctionCallback callback) +{ + JSStringRef js_globalvarsclassname = JSStringCreateWithUTF8CString(globalvarsclassname); + JSObjectSetProperty(context,js_globalvarsclassname,JSObjectMakeFunctionWithCallback(context, + js_globalvarsclassname, callback), kJSPropertyAttributeNone,NULL); + JSStringRelease(jsstring); + return true; +} + +int example_init(JSContextRef context) { + JSObjectRef global; + ... + jsc_registerFunction(context, global, "fact", wrap_fact); + ... +} +
    +

    When executed, javascript will now have a new command called "fact" that you can use like any other Javascript command. Although the process of adding a new function to javascript has been illustrated, the procedure is almost identical for Perl and Python. Both require special wrappers to be written and both need additional initialization code.

    +

    Variable Linking

    +

    Variable linking refers to the problem of mapping a C/C++ global variable to a variable in the scripting language interpreter. For example, suppose you had the following variable:

    +

    double Foo = 3.5; +
    +

    To provide such access, variables are commonly manipulated using a pair of get/set functions. For example, whenever the value of a variable is read, a "get" function is invoked. Similarly, whenever the value of a variable is changed, a "set" function is called.

    +

    bool Foo_set(JSContextRef context, JSObjectRef globalobj, JSStringRef propertyName, JSValueRef value, + JSValueRef* exception) +{ + JSValueRef jsresult; + double arg1 = (double)JSValueToNumber(context, value, NULL); + Foo = arg1; + jscresult = JSValueMakeUndefined(context); + return jsresult; +} + +JSValueRef Foo_get(JSContextRef context, JSObjectRef globalobj, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + double result = (double)Foo; + jsresult = JSValueMakeNumber(context, result); + return jsresult; +} +
    +

    In many languages, calls to the get/set functions can be attached to evaluation and assignment operators. Therefore, evaluating a variable such as Foo might implicitly call the get function. Similarly, typing Foo = 4 would call the underlying set function to change the value.

    +

    A tour of basic C/C++ wrapping

    +

    By default, SWIG tries to build a very natural javascript interface to your C/C++ code. Functions are wrapped as functions, classes are wrapped as classes, and so forth. This section briefly covers the essential aspects of this wrapping.

    +

    Modules

    +

    The SWIG %module directive specifies the name of the Javascript module. If you specify %module example, then everything is wrapped into a Javascript 'example' module. Underneath the covers, this module consists of a cpp source file example.cpp. When choosing a module name, make sure you don't use the same name as a built-in Javascript command or standard module name.

    +

    Global variables

    +

    C/C++ global variables are fully supported by SWIG. However, the underlying mechanism is somewhat different than you might expect due to the way that javascript works.

    +

    // SWIG interface file with global variables +%module example +... +%inline %{ +extern double Foo; +extern int gcd(int x, int y); +%} +... +
    +

    Now look at the javascript:

    +

    print("Global variable Foo=" + example.Foo); +example.Foo = 3.1415926; +print("Variable Foo changed to=" + example.Foo); +print("GCD of x and y is=" + example.gcd(x,y)); +
    +

    Constants and enums

    +

    C/C++ constants are installed as javascript objects containing the appropriate value. To create a constant, use #define, enum, or the %constant directive. For example:

    +

    #define ICONST 42 +#define FCONST 2.1828 +%constant int iconst = 37; +
    +

    In javascript they are treated as:

    +

    print("ICONST = " + example.ICONST + " (should be 42)\n"); +print("FCONST = " + example.FCONST + " (should be 2.1828)\n"); +print("iconst = " + example.iconst + " (should be 37)\n"); +
    +

    For enums, make sure that the definition of the enumeration actually appears in a header file or in the wrapper file somehow---if you just stick an enum in a SWIG interface without also telling the C compiler about it, the wrapper code won't compile. Enums are treated as constants.So if we have enums in c++ as:

    +

    void enum_test(color c, Foo::speed s); +
    +

    In javascript they are treated as:

    +

    example.enum_test(example.RED, example.Foo.IMPULSE); +example.enum_test(example.BLUE, example.Foo.WARP); +example.enum_test(example.GREEN, example.Foo.LUDICROUS); +
    +

    Inside the class

    +

    For class enums as below:

    +

    class Foo { +public: +Foo() { } +enum speed { IMPULSE, WARP, LUDICROUS }; +} +
    +

    In javascript they are treated as:

    +

    print(" Foo_IMPULSE =" + example.Foo.IMPULSE); +print(" Foo_WARP =" + example.Foo.WARP); +print(" Foo_LUDICROUS =" + example.Foo.LUDICROUS); +
    +

    Pointers

    +

    C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Here is a rather simple interface

    +

    /* File : example.i */ +%module example +%{ +extern void add(int *, int *, int *); +%} +
    +

    When wrapped, you will be able to use the functions in a natural way from javascript. For example:

    +

    // Call the add() function with some pointers +example.add(a, b, c); +
    +

    // In javascript the code look like as:

    +

    a = example.new_intp(); +example.intp_assign(a,37); +
    +
      +
    • The first one creates an int-pointer instance.
    • +
    • The second one assigns it the value 37.
    • +
    +

    C++ classes

    +

    C++ classes are wrapped by javascript classes as well. For example, if you have this class,

    +

    class Circle +{ +public: + Circle(); + Circle(double r); + double area(); + double radius; +}; +
    +

    you can use it in javascript like this:

    +

    print("Creating some objects:"); +c = new example.Circle(10); +print("area = " + c.area()); +
    +

    Class data members are accessed in the same manner as C structures.

    +

    Static class members and functions are mapped to javascript in a straight-forward manner:

    +

    class Spam { +public: + static void foo(); + static int bar; +}; +
    +

    In javascript, the static member can be access in this way:

    +

    // ----- Access a static member ----- +print("\nA access of static member is" + example.Spam.Foo); // access static member as properties of the class object. +
    +

    C++ inheritance

    +

    SWIG is fully aware of issues related to C++ inheritance. Therefore, if you have classes like this

    +

    class A { +public: + void foo(); + virtual void bar(); +}; +class B: public A { +public: + virtual void bar(); +}; +
    +

    Those classes are wrapped into a hierarchy of javascript classes that reflect the same inheritance structure. All of the usual javascript utility functions work normally:

    +

    var a = new example.A(); +a.foo(); +a.bar(); +var b = new example.B(); +b.foo(); +b.bar(); +print("b.cPtr = " + b.getCPtr()); +
    +

    C++ overloaded functions

    +

    C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example, if you have two functions like this:

    +

    void f(int val) { + std::cout << "Called f(int)." << std::endl; +} +void f(int val1, int val2) { + std::cout << "Called f(int, int)." << std::endl; +} +void f(const char* s) { + std::cout << "Called f(const char*)." << std::endl; +} +
    +

    You can use them in javascript in a straightforward manner:

    +

    example.f(1); +example.f(1, 2); +example.f("bla"); +
    +

    C++ operators

    +

    Certain C++ overloaded operators can be handled automatically by SWIG. Though, in javascript operator overloading is not possible. Instead one has to make use of the %rename feature.

    +

    For example, consider a class like this:

    +

    /* File : example.h */ +#include <math.h> +class Complex { +private: + double rpart, ipart; +public: + Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { } + Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { } + Complex &operator=(const Complex &c) { + rpart = c.rpart; + ipart = c.ipart; + return *this; + } + Complex operator+(const Complex &c) const { + return Complex(rpart+c.rpart, ipart+c.ipart); + } + Complex operator-(const Complex &c) const { + return Complex(rpart-c.rpart, ipart-c.ipart); + } + Complex operator*(const Complex &c) const { + return Complex(rpart*c.rpart - ipart*c.ipart, + rpart*c.ipart + c.rpart*ipart); + } + Complex operator-() const { + return Complex(-rpart, -ipart); + } + + double re() const { return rpart; } + double im() const { return ipart; } +}; +
    +

    When wrapped, it works like you expect:

    +

    a = new example.Complex(2,3); +b = new example.Complex(-5,10); + +print ("a =" + a); +print ("b =" + b); + +c = a.plus(b); + +print("c =" + c); +print("a*b =" + a.times(b)); +print("a-c =" + a.minus(c)); + +e = example.Complex.copy(a.minus(c)); +print("e =" + e); + +// Big expression +f = a.plus(b).times(c.plus(b.times(e))).plus(a.uminus()); +print("f =" + f); +
    +

    One restriction with operator overloading support is that SWIG is not able to fully handle operators that aren't defined as part of the class. For example, if you had code like this

    +

    class Complex { +... +friend Complex operator+(double, const Complex &c); +... +}; +
    +

    then SWIG ignores it and issues a warning. You can still wrap the operator, but you may have to encapsulate it in a special function. For example:

    +

    %rename(Complex_add_dc) operator+(double, const Complex &);

    +

    There are ways to make this operator appear as part of the class using the %extend directive.

    +

    C++ namespaces:

    +

    SWIG is aware of C++ namespaces, but namespace names do not appear in the module nor do namespaces result in a module that is broken up into submodules or packages. For example, if you have a file like this,

    +

    %module example +namespace nspace { +extern int gcd(int x, int y); +extern double Foo; +class Circle +{ +public: + Circle(); + Circle(double r); + double area(); + double radius; + }; +} +
    +

    for namespaces, you use the %feature directive in interface file. %feature attaches a new attribute to any parse tree node that matches given prototype.

    +

    /* File : example.i */ +%module example +%{ +#include "example.h" +%} +%feature("nspace", 1); +%include "example.h" +
    +

    it works in javascript as follows:

    +

    print("Global variable Foo=" + example.nspace.Foo); +example.nspace.Foo = 5; +print("Variable Foo changed to " + example.nspace.Foo); +print("GCD of number 6,18 is " + example.nspace.gcd(6,18)); +print("Creating some objects:"); +c = new example.nspace.Circle(10); +print("area = " + c.area()); +
    +

    If your program has more than one namespace, name conflicts (if any) can be resolved using %rename For example:

    +

    %rename(Bar_spam) Bar::spam; +namespace Foo { + int spam(); +} +namespace Bar { + int spam(); +} +
    +

    If you have more than one namespace and your want to keep their symbols separate, consider wrapping them as separate SWIG modules. For example, make the module name the same as the namespace and create extension modules for each namespace separately. If your program utilizes thousands of small deeply nested namespaces each with identical symbol names, well, then you get what you deserve. SWIG resolves overloaded functions and methods using a disambiguation scheme that ranks and sorts declarations according to a set of type-precedence rules. The order in which declarations appear in the input does not matter except in situations where ambiguity arises--in this case, the first declaration takes precedence.

    +

    C++ templates

    +

    C++ templates don't present a huge problem for SWIG. However, in order to create wrappers, you have to tell SWIG to create wrappers for a particular template instantiation. To do this, you use the %template directive. For example:

    +

    /* File : example.i */ +%module example +%{ +#include "example.h" +%} +/* Let's just grab the original header file here */ +%include "example.h" + +/* Now instantiate some specific template declarations */ +%template(maxint) max<int>; +%template(maxdouble) max<double>; +%template(vecint) vector<int>; +%template(vecdouble) vector<double>; +
    +

    In javascript:

    +

    //Call some templated functions +print(example.maxint(3,7)); +print(example.maxdouble(3.14,2.18)); + +// Create some class + +iv = new example.vecint(100); +dv = new example.vecdouble(1000); + +for(i=0;i<=100;i++) + iv.setitem(i,2*i); + +for(i=0;i<=1000;i++) + dv.setitem(i, 1.0/(i+1)); + +sum = 0; +for(i=0;i<=100;i++) + sum = sum + iv.getitem(i); + +print(sum); + +sum = 0.0; +for(i=0;i<=1000;i++) + sum = sum + dv.getitem(i); +print(sum); +
    +

    Exception handling

    +

    The SWIG %exception directive can be used to create a user-definable exception handler for converting exceptions in your C/C++ program into javascript exceptions. The chapter on customization features contains more details, but suppose you have a C++ class like the following:

    +

    Since several methods in this class can throw an exception for an out-of-bounds access, you might want to catch this in the javascript extension by writing the following in an interface file:

    +

    /* File : example.i */ +%module example +%{ +#include "example.h" +%} +%include "std_string.i" + +/* Let's just grab the original header file here */ +%include "example.h" +
    +

    Actually in JS there is no support for typed exceptions.For now there is support for integer and string exception. Example for integer exception

    +

    JSValueRef jsc_gcd(JSContextRef context, JSObjectRef function, JSObjectRef globalobj, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ +int arg1 = (int)JSValueToNumber(context, argv[0], NULL); +int arg2 = (int)JSValueToNumber(context, argv[1], NULL); +*exception = JSValueMakeNumber(context, 13); +int result = (int)gcd(arg1,arg2); +JSValueRef jsresult = JSValueMakeNumber(context, result); +
    +

    and for string exception:

    +

    JSValueRef wrap_gcd(JSContextRef context, JSObjectRef function, JSObjectRef globalobj, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ +int arg1 = (int)JSValueToNumber(context, argv[0], NULL); +int arg2 = (int)JSValueToNumber(context, argv[1], NULL); +JSStringRef message = JSStringCreateWithUTF8CString("This is a test error."); +*exception = JSValueMakeString(context, message); +JSStringRelease(message); +int result = (int)gcd(arg1,arg2); +JSValueRef jscresult = JSValueMakeNumber(context, result); +return jsresult; +} +
    +

    How to use generated modules?

    +

    Basically there is no standard extension mechanism in Javascript. We provided a custom interpreter with extension abilities. If JSC is embedded into a custom application, one has to make use of a generated module initializer function that allows easy extension of interpreter. The basic approach is as follows:

    +

    Basic Mechanism

    +
      +
    • Creating the context
    • +
    • Calling module initializer
    • +
    • Evaluate Javascript
    • +
    +

    Creating the context

    +

    JSGlobalContextRef context = JSGlobalContextCreate(NULL); +JSObjectRef globalObject = JSContextGetGlobalObject(context); +... +
    +

    Calling module initializer

    +

    extern int example_init(JSGlobalContextRef context); + ... + example_init(context); + ... +
    +

    Evaluate Javascript

    +

    // Evaluate the javascript +char* scriptContent = jsccreateStringWithContentsOfFile(scriptPath.c_str()); +JSStringRef jsScript; +if(!scriptContent) { + printf("FAIL: runme script could not be loaded.\n"); + failed = 1; + } + else { + JSValueRef ex; + jsScript = JSStringCreateWithUTF8CString(scriptContent); + JSValueRef jsResult = JSEvaluateScript(context, jsScript, 0, 0, 0, &ex); + if (!jsResult && ex) { + jsc_printError(context, ex, scriptPath); + failed = 1; + } + } + if (scriptContent != NULL) { + free(scriptContent); + } + JSStringRelease(jsScript); + JSGlobalContextRelease(context); + globalObject = 0; + for(std::vector<HANDLE>::iterator it = loaded_modules.begin(); + it != loaded_modules.end(); ++it) { + HANDLE handle = *it; + dlclose(handle); + } + if (failed) { + printf("FAIL: Some tests failed.\n"); + return 1; + } +} +
    +

    Typemaps

    +

    A typemap is nothing more than a code generation rule that is attached to a specific C datatype. For example, to convert integers from javascript to C, you might define a typemap like this:

    +

    %typemap(in) int { + $1 = ($1_ltype)JSValueToNumber(context, $input, NULL); %} + printf("Received an integer : %d\n",$1); +} +
    +

    Typemaps are always associated with some specific aspect of code generation. In this case, the "in" method refers to the conversion of input arguments to C/C++. The datatype int is the datatype to which the typemap will be applied. The supplied C code is used to convert values. In this code a number of special variable prefaced by a $ are used. The $1 variable is placeholder for a local variable of type int.

    +

    Javascript typemaps

    +

    The previous section illustrated an "in" typemap for converting javascript objects to C. A variety of different typemap methods are defined by the javascript module. For example, to convert a C integer back into a javascript object, you might define an "out" typemap like this:

    +

    %typemap(out) int { + $result = JSValueMakeNumber(context, $1); +} +
    +

    The Javascript module makes use of Swig's unified template library.

    +

    Typemap variables

    +

    Within typemap code, a number of special variables prefaced with a $ may appear. A full list of variables can be found in the "Typemaps" chapter. This is a list of the most common variables:

    +

    $1: A C local variable corresponding to the actual type specified in the %typemap directive. For input values, this is a C local variable that's supposed to hold an argument value. For output values, this is the raw result that's supposed to be returned to Javascript.

    +

    $input: A javascript Object * holding a raw javascript object with an argument or variable value.

    +

    $result: A javascript Object * that holds the result to be returned to javascript.

    +

    $1_name: The parameter name that was matched.

    +

    $1_type: The actual C datatype matched by the typemap.

    +

    $1_ltype: An assignable version of the datatype matched by the typemap (a type that can appear on the left-hand-side of a C assignment operation). This type is stripped of qualifiers and may be an altered version of $1_type. All arguments and local variables in wrapper functions are declared using this type so that their values can be properly assigned.

    +

    $symname: The javascript name of the wrapper function being created.

    +

    Javascript: Specification of a Code Generator for JSC

    +

    The module implementation tries to accomplish a separation of logic and code generation by making use of code templates. In the following, the templates are explained.

    +

    Top Level structure

    +

    The generated code consists of the following blocks:

    +

    <RUNTIME> +<INCLUDES> +<HELPER_FUNCTIONS> +<FUNCTION_WRAPPERS> +<INITIALIZER> +
    +
      +
    • RUNTIME: runtime code generated by swig
    • +
    • HELPER_FUNCTIONS: static, from swg-file
    • +
    • INCLUDES: static, module property
    • +
    • FUNCTION_WRAPPERS: dynamically growing, on method declarations
    • +
    • INITIALIZER: dynamically growing, aggregates everything
    • +
    +

    INCLUDES

    +

    #include <JavaScriptCore/JavaScript.h> +<USER_DEFINED_INCLUDES> +
    +

    USER_DEFINED_INCLUDES: a module property

    +

    HELPER_FUNCTIONS

    +

    A lot of boiler-plate code can be shifted into static helper functions:

    +

    bool JS_registerClass(JSGlobalContextRef& context, JSObjectRef& parentObject,const char* className, + JSClassDefinition* definition) { + JSStringRef js_className = JSStringCreateWithUTF8CString(className); + JSObjectRef classObject = JSObjectMake(context, JSClassCreate(definition), NULL); + JSObjectSetProperty(context, parentObject,js_className, classObject,kJSPropertyAttributeNone, NULL); + JSStringRelease(js_className); + return true; +} + +bool JS_registerNamespace(JSGlobalContextRef& context,JSObjectRef& namespaceObj,JSObjectRef& parentNamespace,const char* name) +{ + JSStringRef js_name = JSStringCreateWithUTF8CString(name); + JSObjectSetProperty(context, parentNamespace,js_name, namespaceObj,kJSPropertyAttributeNone, NULL); + JSStringRelease(js_name); + return true; +} + +bool JS_registerFunction(JSGlobalContextRef context, JSObjectRef object, const char* functionName, JSObjectCallAsFunctionCallback callback) +{ + JSStringRef js_functionName = JSStringCreateWithUTF8CString(functionName); + JSObjectSetProperty(context,object,js_functionName,JSObjectMakeFunctionWithCallback(context, + js_functionName, callback), kJSPropertyAttributeNone, NULL); + JSStringRelease(js_functionName); + return true; +} +bool JS_veto_set_variable(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + char buffer[256]; + char msg[512]; + int res; + JSStringGetUTF8CString(propertyName, buffer, 256); + res = sprintf(msg, "Tried to write read-only variable: %s.", buffer); + if(res<0) { + SWIG_exception(SWIG_ERROR, "Tried to write read-only variable."); + } else { + SWIG_exception(SWIG_ERROR, msg); + } + return false; +} + +JSValueRef JS_CharPtrToJSValue(JSContextRef context, char* cstr) { + JSValueRef val; + JSStringRef jsstring = JSStringCreateWithUTF8CString((char*) cstr); + val = JSValueMakeString(context, jsstring); + JSStringRelease(jsstring); + return val; +} +
    +

    FUNCTION_WRAPPERS

    +

    There are different types of function wrappers: - Member Functions - Getproperty / Setproperty - Global Functions (global/namespace/class) - Constructors / Destructors

    +

    Member Functions

    +

    JSValueRef ${functionname}(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + ${LOCALS} + ${CODE} + return jsresult; + + goto fail; + fail: + return NULL; +} +
    +
      +
    • functionname: the name of generated wrapper for function
    • +
    • LOCALS: declarations for input arguments
    • +
    • CODE: contains input marshalling, the action, and output marshalling
    • +
    +

    Setproperty

    +

    bool ${setname}(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + ${LOCALS} + ${CODE} + return jsresult; + + goto fail; + fail: + return NULL; +} +
    +
      +
    • setname: the name of the generated wrapper for setproperty.
    • +
    • LOCALS: declarations for input arguments
    • +
    • CODE: contains input marshalling, and the action
    • +
    +

    Getproperty

    +

    JSValueRef ${getname}(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + ${LOCALS} + ${CODE} + return jsresult; + + goto fail; + fail: + return NULL; +} +
    +
      +
    • getname: the name of the generated wrapper for the getproperty
    • +
    • LOCALS: declarations for output arguments
    • +
    • CODE: contains the action, and output marshalling
    • +
    +

    Global Functions

    +

    JSStaticValue ${namespace}_values[] = { + ${jsglobalvariables} + { 0, 0, 0, 0 } +}; +JSStaticFunction ${namespace}_functions[] = { + ${jsglobalfunctions} + { 0, 0, 0 } +}; +JSClassDefinition ${namespace}_classDefinition; +
    +

    Variable declaration

    +

    {"${propertyname}",${getname}, ${setname}, kJSPropertyAttributeNone} +
    +

    This is used to fill variable definition tables. kJSPropertyAttributeNone is JSC specific and means that the variable has a getter and setter. Even for read-only variables a setter is used which throws an exception.

    +

    Constructor

    +

    ~~

    +

    JSObjectRef wrap_createclassnamemangled{overloadext}(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { ${LOCALS} ${CODE} return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_${type_mangled}, SWIG_POINTER_OWN);

    +
    goto fail;
    +fail:
    +return NULL;
    +
    +

    }

    +
    - `classname_mangled` is the mangled qualified class name,   e.g., `foo::A -> foo_A`
    +- `LOCALS`: declarations for input arguments 
    +- `CODE`: contains input marshalling, and the action 
    +
    +## Destructors
    +
    +

    void wrap${classname_mangled}_finalize(JSObjectRef thisObject) { SWIG_PRV_DATA* t = (SWIG_PRV_DATA*)JSObjectGetPrivate(thisObject); if(t && t->swigCMemOwn) delete (${type}*)(t->swigCObject); if(t) delete t; }

    +

    - `classname_mangled` is the mangled qualified class name, e.g., `foo::A -> foo_A` + +## Initializer +
    +

    bool ${modulename}_initialize(JSGlobalContextRef context) { SWIG_InitializeModule(0);

    +
    JSObjectRef global_object = JSContextGetGlobalObject(context);
    +
    +/* Initialize the base swig type object */
    +_SwigObject_objectDefinition.staticFunctions = _SwigObject_functions;
    +_SwigObject_objectDefinition.staticValues = _SwigObject_values;
    +_SwigObject_classRef = JSClassCreate(&_SwigObject_objectDefinition);
    +
    +/* Create objects for namespaces */
    +${create_namespaces}
    +
    +/* Create classes */
    +${initializercode}
    +
    +/* Register namespaces */
    +${register_namespaces}
    +
    +return true;
    +
    +

    }

    +

    ## Class template defintions + +A class is specified by a static part (`*_classDefinition`) and a dynamic part (`*_objectDefinition`). +
    +

    ${classname_mangled}_classDefinition.staticFunctions = ${classname_mangled}_staticFunctions; ${classname_mangled}_classDefinition.staticValues = ${classname_mangled}_staticValues; ${classname_mangled}_classDefinition.callAsConstructor = _wrap_create_${classname_mangled}; ${classname_mangled}_objectDefinition.staticValues = ${classname_mangled}_values; ${classname_mangled}_objectDefinition.staticFunctions = ${classname_mangled}_functions; ${classname_mangled}_objectDefinition.parentClass = ${base_classname}_classRef; JSClassRef ${classname_mangled}_classRef = JSClassCreate(&${classname_mangled}objectDefinition); SWIGTYPE${classtype_mangled}->clientdata = ${classname_mangled}_classRef;%}

    +

    Notes: +- `classname_mangled` is the mangled qualified class name, e.g., `foo::A -> foo_A` + which is retrieved by `Swig_name_mangle(Getattr(n, "name"))` +- ClassDefinitions are built using the staticValues array and the staticFunction array. The staticValues and staticFunctions arrays are the simplest and most efficient means for vending custom properties to the class object. + +## Inheritance +
    +

    {${classname_mangled}_objectDefinition.parentClass = ${base_classname}_classRef};

    +

    - `classname_mangled` is the mangled qualified class name, e.g., `foo::A -> foo_A` +- Note: multiple inheritance is not possible; thus we will always take the first parent class + +## Namespaces + +Namespaces are objects without class templates. i.e., instances are created, referenced locally, used as contexts for other registrations, and stored in the according parent contexts. +
    +

    ${namespace}_classDefinition.staticFunctions = ${namespace}_functions; ${namespace}_classDefinition.staticValues = ${namespace}_values; JSObjectRef ${namespace}_object = JSObjectMake(context, JSClassCreate(&${namespace}_classDefinition), NULL);

    +

    ## Registration + +The registration part consists of registering classes at contexts (i.e., global or namespace), methods and properties at classes or contexts, and namespaces as objects at parent contexts. + +* Global functions +
    +

    JS_registerFunction(${context}, ${context_object}, "${functionname}", ${functionwrapper}

    +

    * Classes +
    +

    JS_registerClass(context, ${namespace}_object, "${classname}", &${classname_mangled}_classDefinition)

    +

    Note: every class template has an associated constructor function wrapper, which is registered here + +* Namespaces +
    +

    ${namespace}_classDefinition.staticFunctions = ${namespace}_functions; ${namespace}_classDefinition.staticValues = ${namespace}_values; JSObjectRef ${namespace}_object = JSObjectMake(context, JSClassCreate(&${namespace}_classDefinition), NULL);

    +

    Namespaces are registered using: +
    +

    JS_registerNamespace(context, ${namespace}_object, ${parent_namespace}_object, "${namespace}");

    +

    ~~

    +
    + + diff --git a/Doc/Manual/Javascript.md b/Doc/Manual/Javascript.md new file mode 100644 index 000000000..a01c630d8 --- /dev/null +++ b/Doc/Manual/Javascript.md @@ -0,0 +1,1103 @@ +% SWIG AND JAVASCRIPT + +# Overview + +This chapter describes SWIG support for Javascript. +The module is designed to support JavascriptCore and V8 as target engine. +Currently only JavascriptCore support is implemented. +JavaScriptCore is the built-in JavaScript engine for WebKit, whereas V8 is the engine used by Chromium. + +JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. Its arguably the most popular language for web development. C++, on the other hand, is statically typed, compiled, general purpose programming language. +The approach I followed here is "Test driven" where I have written the examples/test-cases to be supported for Javascript one-by-one and implemented the required module files in parallel. +The support for Javascript would be added similar to other supported target languages in swig. Swig comes with an "Examples" directory for Javascript like other supported language. The directory contains examples for every supported feature of the target language. There is also a test-suite directory for javascript which contains additional tests. + +# Preliminaries + +In order to use this module, you will need to have installed javascriptcore and you can install it by installing package libwebkit-dev +You can find out some necessary compiler/linker flag by + + pkg-config javascriptcoregtk-1.0 --cflags --libs + +## Using the module + +To generate an extension for JavascriptCore one would call swig as follows + +~~~~ + +swig -c++ -javascript -jsc example.i + +~~~~ + +This generates a C++ source file containing the wrapper. + +## How does Javascript talk to C++? + +JavascriptCore provides a C-API which allows to extend a Javascript interpreter with native methods and structures. Normally, this is used to implement the builtin features of the language. However, by extending the interpreter, it is also possible to add your own commands and variables. A reference manual of this API can be found +[here](http://developer.apple.com/library/mac/#documentation/Carbon/Reference/WebKit_JavaScriptCore_Ref/_index.html). + +Typically, when you add a new command to the javascript interpreter you need to do two things: first you need to write a special "wrapper" function that serves as the glue between the interpreter and the underlying C function. Then you need to give the interpreter information about the wrapper by providing details about the name of the function, arguments, and so forth. The next few sections illustrate the process. + +## Wrapper functions + +Suppose you have an ordinary C function like this : + +~~~~ + +int fact(int n) { + if (n <= 1) return 1; + else return n*fact(n-1); +} + +~~~~ + +In order to access this function from a scripting language, it is necessary to write a special "wrapper" function that serves as the glue between the scripting language and the underlying C function. A wrapper function must do three things : + + - Gather function arguments and make sure they are valid. + - Call the C function. + - Convert the return value into a form recognized by the javascript. + +As an example, the javascript wrapper function for the fact() function above example might look like the following : + +~~~~ + +JSValueRef wrap_fact(JSContextRef context, JSObjectRef function, JSObjectRef globalobj, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + int arg1 = (int)JSValueToNumber(context, argv[0], NULL); + int arg2 = (int)JSValueToNumber(context, argv[1], NULL); + int result = (int)fact(arg1,arg2); + JSValueRef jsresult = JSValueMakeNumber(context, result); + return jsresult; +} + +~~~~ + +Once you have created a wrapper function, the final step is to tell the javascript about the new function. This is done by register function called by the javascript when the module is loaded. For example, adding the above function to the javascript interpreter requires code like the following : + +~~~~ + +bool jsc_registerFunction(JSGlobalContextRef context, JSObjectRef object, + const char* functionName, JSObjectCallAsFunctionCallback callback) +{ + JSStringRef js_globalvarsclassname = JSStringCreateWithUTF8CString(globalvarsclassname); + JSObjectSetProperty(context,js_globalvarsclassname,JSObjectMakeFunctionWithCallback(context, + js_globalvarsclassname, callback), kJSPropertyAttributeNone,NULL); + JSStringRelease(jsstring); + return true; +} + +int example_init(JSContextRef context) { + JSObjectRef global; + ... + jsc_registerFunction(context, global, "fact", wrap_fact); + ... +} + +~~~~ + +When executed, javascript will now have a new command called "fact" that you can use like any other Javascript command. +Although the process of adding a new function to javascript has been illustrated, the procedure is almost identical for Perl and Python. Both require special wrappers to be written and both need additional initialization code. + +## Variable Linking + +Variable linking refers to the problem of mapping a C/C++ global variable to a variable in the scripting language interpreter. For example, suppose you had the following variable: + +~~~~ + +double Foo = 3.5; + +~~~~ + +To provide such access, variables are commonly manipulated using a pair of get/set functions. For example, whenever the value of a variable is read, a "get" function is invoked. Similarly, whenever the value of a variable is changed, a "set" function is called. + +~~~~ + +bool Foo_set(JSContextRef context, JSObjectRef globalobj, JSStringRef propertyName, JSValueRef value, + JSValueRef* exception) +{ + JSValueRef jsresult; + double arg1 = (double)JSValueToNumber(context, value, NULL); + Foo = arg1; + jscresult = JSValueMakeUndefined(context); + return jsresult; +} + +JSValueRef Foo_get(JSContextRef context, JSObjectRef globalobj, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + double result = (double)Foo; + jsresult = JSValueMakeNumber(context, result); + return jsresult; +} + +~~~~ + +In many languages, calls to the get/set functions can be attached to evaluation and assignment operators. Therefore, evaluating a variable such as Foo might implicitly call the get function. Similarly, typing Foo = 4 would call the underlying set function to change the value. + +# A tour of basic C/C++ wrapping + +By default, SWIG tries to build a very natural javascript interface to your C/C++ code. Functions are wrapped as functions, classes are wrapped as classes, and so forth. This section briefly covers the essential aspects of this wrapping. + +## Modules + +The SWIG %module directive specifies the name of the Javascript module. If you specify `%module example`, then everything is wrapped into a Javascript 'example' module. Underneath the covers, this module consists of a cpp source file example.cpp. When choosing a module name, make sure you don't use the same name as a built-in Javascript command or standard module name. + +## Global variables + +C/C++ global variables are fully supported by SWIG. However, the underlying mechanism is somewhat different than you might expect due to the way that javascript works. + +~~~~ + +// SWIG interface file with global variables +%module example +... +%inline %{ +extern double Foo; +extern int gcd(int x, int y); +%} +... + +~~~~ + +Now look at the javascript: + +~~~~ + +print("Global variable Foo=" + example.Foo); +example.Foo = 3.1415926; +print("Variable Foo changed to=" + example.Foo); +print("GCD of x and y is=" + example.gcd(x,y)); + +~~~~ + +## Constants and enums + +C/C++ constants are installed as javascript objects containing the appropriate value. To create a constant, use #define, enum, or the %constant directive. For example: + +~~~~ + +#define ICONST 42 +#define FCONST 2.1828 +%constant int iconst = 37; + +~~~~ + +In javascript they are treated as: + +~~~~ + +print("ICONST = " + example.ICONST + " (should be 42)\n"); +print("FCONST = " + example.FCONST + " (should be 2.1828)\n"); +print("iconst = " + example.iconst + " (should be 37)\n"); + +~~~~ + +For enums, make sure that the definition of the enumeration actually appears in a header file or in the wrapper file somehow---if you just stick an enum in a SWIG interface without also telling the C compiler about it, the wrapper code won't compile. +Enums are treated as constants.So if we have enums in c++ as: + +~~~~ + +void enum_test(color c, Foo::speed s); + +~~~~ + +In javascript they are treated as: + +~~~~ + +example.enum_test(example.RED, example.Foo.IMPULSE); +example.enum_test(example.BLUE, example.Foo.WARP); +example.enum_test(example.GREEN, example.Foo.LUDICROUS); + +~~~~ + +### Inside the class +For class enums as below: + +~~~~ + +class Foo { +public: +Foo() { } +enum speed { IMPULSE, WARP, LUDICROUS }; +} + +~~~~ + +In javascript they are treated as: + +~~~~ + +print(" Foo_IMPULSE =" + example.Foo.IMPULSE); +print(" Foo_WARP =" + example.Foo.WARP); +print(" Foo_LUDICROUS =" + example.Foo.LUDICROUS); + +~~~~ + +## Pointers + +C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Here is a rather simple interface + +~~~~ + +/* File : example.i */ +%module example +%{ +extern void add(int *, int *, int *); +%} + +~~~~ + +When wrapped, you will be able to use the functions in a natural way from javascript. For example: + +~~~~ + +// Call the add() function with some pointers +example.add(a, b, c); + +~~~~ + +// In javascript the code look like as: + +~~~~ + +a = example.new_intp(); +example.intp_assign(a,37); + +~~~~ + +- The first one creates an int-pointer instance. +- The second one assigns it the value 37. + +### C++ classes + +C++ classes are wrapped by javascript classes as well. For example, if you have this class, + +~~~~ + +class Circle +{ +public: + Circle(); + Circle(double r); + double area(); + double radius; +}; + +~~~~ + +you can use it in javascript like this: + +~~~~ + +print("Creating some objects:"); +c = new example.Circle(10); +print("area = " + c.area()); + +~~~~ + +Class data members are accessed in the same manner as C structures. + +Static class members and functions are mapped to javascript in a straight-forward manner: + +~~~~ + +class Spam { +public: + static void foo(); + static int bar; +}; + +~~~~ + +In javascript, the static member can be access in this way: + +~~~~ + +// ----- Access a static member ----- +print("\nA access of static member is" + example.Spam.Foo); // access static member as properties of the class object. + +~~~~ + +## C++ inheritance + +SWIG is fully aware of issues related to C++ inheritance. Therefore, if you have classes like this + +~~~~ + +class A { +public: + void foo(); + virtual void bar(); +}; +class B: public A { +public: + virtual void bar(); +}; + +~~~~ + +Those classes are wrapped into a hierarchy of javascript classes that reflect the same inheritance structure. All of the usual javascript utility functions work normally: + +~~~~ + +var a = new example.A(); +a.foo(); +a.bar(); +var b = new example.B(); +b.foo(); +b.bar(); +print("b.cPtr = " + b.getCPtr()); + +~~~~ + +## C++ overloaded functions + +C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example, if you have two functions like this: + +~~~~ + +void f(int val) { + std::cout << "Called f(int)." << std::endl; +} +void f(int val1, int val2) { + std::cout << "Called f(int, int)." << std::endl; +} +void f(const char* s) { + std::cout << "Called f(const char*)." << std::endl; +} + +~~~~ + +You can use them in javascript in a straightforward manner: + +~~~~ + +example.f(1); +example.f(1, 2); +example.f("bla"); + +~~~~ + +## C++ operators + +Certain C++ overloaded operators can be handled automatically by SWIG. Though, in javascript operator overloading is not possible. Instead one has to make use of the `%rename` feature. + +For example, consider a class like this: + +~~~~ + +/* File : example.h */ +#include +class Complex { +private: + double rpart, ipart; +public: + Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { } + Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { } + Complex &operator=(const Complex &c) { + rpart = c.rpart; + ipart = c.ipart; + return *this; + } + Complex operator+(const Complex &c) const { + return Complex(rpart+c.rpart, ipart+c.ipart); + } + Complex operator-(const Complex &c) const { + return Complex(rpart-c.rpart, ipart-c.ipart); + } + Complex operator*(const Complex &c) const { + return Complex(rpart*c.rpart - ipart*c.ipart, + rpart*c.ipart + c.rpart*ipart); + } + Complex operator-() const { + return Complex(-rpart, -ipart); + } + + double re() const { return rpart; } + double im() const { return ipart; } +}; + +~~~~ + +When wrapped, it works like you expect: + +~~~~ + +a = new example.Complex(2,3); +b = new example.Complex(-5,10); + +print ("a =" + a); +print ("b =" + b); + +c = a.plus(b); + +print("c =" + c); +print("a*b =" + a.times(b)); +print("a-c =" + a.minus(c)); + +e = example.Complex.copy(a.minus(c)); +print("e =" + e); + +// Big expression +f = a.plus(b).times(c.plus(b.times(e))).plus(a.uminus()); +print("f =" + f); + +~~~~ + +One restriction with operator overloading support is that SWIG is not able to fully handle operators that aren't defined as part of the class. For example, if you had code like this + +~~~~ + +class Complex { +... +friend Complex operator+(double, const Complex &c); +... +}; + +~~~~ + +then SWIG ignores it and issues a warning. You can still wrap the operator, but you may have to encapsulate it in a special function. For example: + +%rename(Complex_add_dc) operator+(double, const Complex &); + +There are ways to make this operator appear as part of the class using the %extend directive. + +## C++ namespaces: + +SWIG is aware of C++ namespaces, but namespace names do not appear in the module nor do namespaces result in a module that is broken up into submodules or packages. For example, if you have a file like this, + +~~~~ + +%module example +namespace nspace { +extern int gcd(int x, int y); +extern double Foo; +class Circle +{ +public: + Circle(); + Circle(double r); + double area(); + double radius; + }; +} + +~~~~ + +for namespaces, you use the %feature directive in interface file. %feature attaches a new attribute to any parse tree node that matches given prototype. + +~~~~ + +/* File : example.i */ +%module example +%{ +#include "example.h" +%} +%feature("nspace", 1); +%include "example.h" + +~~~~ + +it works in javascript as follows: + +~~~~ + +print("Global variable Foo=" + example.nspace.Foo); +example.nspace.Foo = 5; +print("Variable Foo changed to " + example.nspace.Foo); +print("GCD of number 6,18 is " + example.nspace.gcd(6,18)); +print("Creating some objects:"); +c = new example.nspace.Circle(10); +print("area = " + c.area()); + +~~~~ + +If your program has more than one namespace, name conflicts (if any) can be resolved using %rename For example: + +~~~~ + +%rename(Bar_spam) Bar::spam; +namespace Foo { + int spam(); +} +namespace Bar { + int spam(); +} + +~~~~ + +If you have more than one namespace and your want to keep their symbols separate, consider wrapping them as separate SWIG modules. For example, make the module name the same as the namespace and create extension modules for each namespace separately. If your program utilizes thousands of small deeply nested namespaces each with identical symbol names, well, then you get what you deserve. +SWIG resolves overloaded functions and methods using a disambiguation scheme that ranks and sorts declarations according to a set of type-precedence rules. The order in which declarations appear in the input does not matter except in situations where ambiguity arises--in this case, the first declaration takes precedence. + +## C++ templates + +C++ templates don't present a huge problem for SWIG. However, in order to create wrappers, you have to tell SWIG to create wrappers for a particular template instantiation. To do this, you use the %template directive. For example: + +~~~~ + +/* File : example.i */ +%module example +%{ +#include "example.h" +%} +/* Let's just grab the original header file here */ +%include "example.h" + +/* Now instantiate some specific template declarations */ +%template(maxint) max; +%template(maxdouble) max; +%template(vecint) vector; +%template(vecdouble) vector; + +~~~~ + +In javascript: + +~~~~ + +//Call some templated functions +print(example.maxint(3,7)); +print(example.maxdouble(3.14,2.18)); + +// Create some class + +iv = new example.vecint(100); +dv = new example.vecdouble(1000); + +for(i=0;i<=100;i++) + iv.setitem(i,2*i); + +for(i=0;i<=1000;i++) + dv.setitem(i, 1.0/(i+1)); + +sum = 0; +for(i=0;i<=100;i++) + sum = sum + iv.getitem(i); + +print(sum); + +sum = 0.0; +for(i=0;i<=1000;i++) + sum = sum + dv.getitem(i); +print(sum); + +~~~~ + +## Exception handling + +The SWIG %exception directive can be used to create a user-definable exception handler for converting exceptions in your C/C++ program into javascript exceptions. The chapter on customization features contains more details, but suppose you have a C++ class like the following: + +Since several methods in this class can throw an exception for an out-of-bounds access, you might want to catch this in the javascript extension by writing the following in an interface file: + +~~~~ + +/* File : example.i */ +%module example +%{ +#include "example.h" +%} +%include "std_string.i" + +/* Let's just grab the original header file here */ +%include "example.h" + +~~~~ + +Actually in JS there is no support for typed exceptions.For now there is support for integer and string +exception. Example for integer exception + +~~~~ + +JSValueRef jsc_gcd(JSContextRef context, JSObjectRef function, JSObjectRef globalobj, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ +int arg1 = (int)JSValueToNumber(context, argv[0], NULL); +int arg2 = (int)JSValueToNumber(context, argv[1], NULL); +*exception = JSValueMakeNumber(context, 13); +int result = (int)gcd(arg1,arg2); +JSValueRef jsresult = JSValueMakeNumber(context, result); + +~~~~ + +and for string exception: + +~~~~ + +JSValueRef wrap_gcd(JSContextRef context, JSObjectRef function, JSObjectRef globalobj, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ +int arg1 = (int)JSValueToNumber(context, argv[0], NULL); +int arg2 = (int)JSValueToNumber(context, argv[1], NULL); +JSStringRef message = JSStringCreateWithUTF8CString("This is a test error."); +*exception = JSValueMakeString(context, message); +JSStringRelease(message); +int result = (int)gcd(arg1,arg2); +JSValueRef jscresult = JSValueMakeNumber(context, result); +return jsresult; +} + +~~~~ + +## How to use generated modules? + +Basically there is no standard extension mechanism in Javascript. We provided a custom interpreter with extension abilities. If JSC is embedded into a custom application, one has to make use of a generated module initializer function that allows easy extension of interpreter. +The basic approach is as follows: + +### Basic Mechanism +- Creating the context +- Calling module initializer +- Evaluate Javascript + +#### Creating the context + +~~~~ + +JSGlobalContextRef context = JSGlobalContextCreate(NULL); +JSObjectRef globalObject = JSContextGetGlobalObject(context); +... + +~~~~ + +### Calling module initializer + +~~~~ + + extern int example_init(JSGlobalContextRef context); + ... + example_init(context); + ... + +~~~~ + +### Evaluate Javascript + +~~~~ + +// Evaluate the javascript +char* scriptContent = jsccreateStringWithContentsOfFile(scriptPath.c_str()); +JSStringRef jsScript; +if(!scriptContent) { + printf("FAIL: runme script could not be loaded.\n"); + failed = 1; + } + else { + JSValueRef ex; + jsScript = JSStringCreateWithUTF8CString(scriptContent); + JSValueRef jsResult = JSEvaluateScript(context, jsScript, 0, 0, 0, &ex); + if (!jsResult && ex) { + jsc_printError(context, ex, scriptPath); + failed = 1; + } + } + if (scriptContent != NULL) { + free(scriptContent); + } + JSStringRelease(jsScript); + JSGlobalContextRelease(context); + globalObject = 0; + for(std::vector::iterator it = loaded_modules.begin(); + it != loaded_modules.end(); ++it) { + HANDLE handle = *it; + dlclose(handle); + } + if (failed) { + printf("FAIL: Some tests failed.\n"); + return 1; + } +} + +~~~~ + +## Typemaps + +A typemap is nothing more than a code generation rule that is attached to a specific C datatype. For example, to convert integers from javascript to C, you might define a typemap like this: + +~~~~ + +%typemap(in) int { + $1 = ($1_ltype)JSValueToNumber(context, $input, NULL); %} + printf("Received an integer : %d\n",$1); +} + +~~~~ + +Typemaps are always associated with some specific aspect of code generation. In this case, the "in" method refers to the conversion of input arguments to C/C++. The datatype int is the datatype to which the typemap will be applied. The supplied C code is used to convert values. In this code a number of special variable prefaced by a $ are used. The $1 variable is placeholder for a local variable of type int. + +## Javascript typemaps + +The previous section illustrated an "in" typemap for converting javascript objects to C. A variety of different typemap methods are defined by the javascript module. For example, to convert a C integer back into a javascript object, you might define an "out" typemap like this: + +~~~~ + +%typemap(out) int { + $result = JSValueMakeNumber(context, $1); +} + +~~~~ + +The Javascript module makes use of Swig's unified template library. + +## Typemap variables + +Within typemap code, a number of special variables prefaced with a $ may appear. A full list of variables can be found in the "Typemaps" chapter. This is a list of the most common variables: + +`$1`: +A C local variable corresponding to the actual type specified in the %typemap directive. For input values, this is a C local variable that's supposed to hold an argument value. For output values, this is the raw result that's supposed to be returned to Javascript. + +`$input`: +A javascript Object * holding a raw javascript object with an argument or variable value. + +`$result`: +A javascript Object * that holds the result to be returned to javascript. + +`$1_name`: +The parameter name that was matched. + +`$1_type`: +The actual C datatype matched by the typemap. + +`$1_ltype`: +An assignable version of the datatype matched by the typemap (a type that can appear on the left-hand-side of a C assignment operation). This type is stripped of qualifiers and may be an altered version of `$1_type`. All arguments and local variables in wrapper functions are declared using this type so that their values can be properly assigned. + +`$symname`: +The javascript name of the wrapper function being created. + +# Javascript: Specification of a Code Generator for JSC + +The module implementation tries to accomplish a separation of logic and code generation by making +use of code templates. In the following, the templates are explained. + +# Top Level structure + +The generated code consists of the following blocks: + +~~~~ + + + + + + + +~~~~ + +- `RUNTIME`: runtime code generated by swig +- `HELPER_FUNCTIONS`: static, from swg-file +- `INCLUDES`: static, module property +- `FUNCTION_WRAPPERS`: dynamically growing, on method declarations +- `INITIALIZER`: dynamically growing, aggregates everything + +## INCLUDES + +~~~~ + +#include + + +~~~~ + +`USER_DEFINED_INCLUDES`: a module property + +## `HELPER_FUNCTIONS` + +A lot of boiler-plate code can be shifted into static helper functions: + +~~~~ + +bool JS_registerClass(JSGlobalContextRef& context, JSObjectRef& parentObject,const char* className, + JSClassDefinition* definition) { + JSStringRef js_className = JSStringCreateWithUTF8CString(className); + JSObjectRef classObject = JSObjectMake(context, JSClassCreate(definition), NULL); + JSObjectSetProperty(context, parentObject,js_className, classObject,kJSPropertyAttributeNone, NULL); + JSStringRelease(js_className); + return true; +} + +bool JS_registerNamespace(JSGlobalContextRef& context,JSObjectRef& namespaceObj,JSObjectRef& parentNamespace,const char* name) +{ + JSStringRef js_name = JSStringCreateWithUTF8CString(name); + JSObjectSetProperty(context, parentNamespace,js_name, namespaceObj,kJSPropertyAttributeNone, NULL); + JSStringRelease(js_name); + return true; +} + +bool JS_registerFunction(JSGlobalContextRef context, JSObjectRef object, const char* functionName, JSObjectCallAsFunctionCallback callback) +{ + JSStringRef js_functionName = JSStringCreateWithUTF8CString(functionName); + JSObjectSetProperty(context,object,js_functionName,JSObjectMakeFunctionWithCallback(context, + js_functionName, callback), kJSPropertyAttributeNone, NULL); + JSStringRelease(js_functionName); + return true; +} +bool JS_veto_set_variable(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + char buffer[256]; + char msg[512]; + int res; + JSStringGetUTF8CString(propertyName, buffer, 256); + res = sprintf(msg, "Tried to write read-only variable: %s.", buffer); + if(res<0) { + SWIG_exception(SWIG_ERROR, "Tried to write read-only variable."); + } else { + SWIG_exception(SWIG_ERROR, msg); + } + return false; +} + +JSValueRef JS_CharPtrToJSValue(JSContextRef context, char* cstr) { + JSValueRef val; + JSStringRef jsstring = JSStringCreateWithUTF8CString((char*) cstr); + val = JSValueMakeString(context, jsstring); + JSStringRelease(jsstring); + return val; +} + +~~~~ + +## `FUNCTION_WRAPPERS` + +There are different types of function wrappers: +- Member Functions +- Getproperty / Setproperty +- Global Functions (global/namespace/class) +- Constructors / Destructors + + +## Member Functions + +~~~~ + +JSValueRef ${functionname}(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + ${LOCALS} + ${CODE} + return jsresult; + + goto fail; + fail: + return NULL; +} + +~~~~ + +- `functionname`: the name of generated wrapper for function +- `LOCALS`: declarations for input arguments +- `CODE`: contains input marshalling, the action, and output marshalling + +## Setproperty + +~~~~ + +bool ${setname}(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + ${LOCALS} + ${CODE} + return jsresult; + + goto fail; + fail: + return NULL; +} + +~~~~ + +- `setname`: the name of the generated wrapper for setproperty. +- `LOCALS`: declarations for input arguments +- `CODE`: contains input marshalling, and the action + +## Getproperty + +~~~~ + +JSValueRef ${getname}(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + ${LOCALS} + ${CODE} + return jsresult; + + goto fail; + fail: + return NULL; +} + +~~~~ + +- `getname`: the name of the generated wrapper for the getproperty +- `LOCALS`: declarations for output arguments +- `CODE`: contains the action, and output marshalling + + +## Global Functions + +~~~~ + +JSStaticValue ${namespace}_values[] = { + ${jsglobalvariables} + { 0, 0, 0, 0 } +}; +JSStaticFunction ${namespace}_functions[] = { + ${jsglobalfunctions} + { 0, 0, 0 } +}; +JSClassDefinition ${namespace}_classDefinition; + +~~~~ + +## Variable declaration + +~~~~ + +{"${propertyname}",${getname}, ${setname}, kJSPropertyAttributeNone} + +~~~~ + +This is used to fill variable definition tables. +`kJSPropertyAttributeNone` is JSC specific and means that the variable has a getter and setter. +Even for read-only variables a setter is used which throws an exception. + +## Constructor + +~~~~ + +JSObjectRef _wrap_create_${classname_mangled}${overloadext}(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + ${LOCALS} + ${CODE} + return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_${type_mangled}, SWIG_POINTER_OWN); + + goto fail; + fail: + return NULL; +} + +~~~~ +- `classname_mangled` is the mangled qualified class name, e.g., `foo::A -> foo_A` +- `LOCALS`: declarations for input arguments +- `CODE`: contains input marshalling, and the action + +## Destructors + +~~~~ + +void _wrap_${classname_mangled}_finalize(JSObjectRef thisObject) +{ + SWIG_PRV_DATA* t = (SWIG_PRV_DATA*)JSObjectGetPrivate(thisObject); + if(t && t->swigCMemOwn) delete (${type}*)(t->swigCObject); + if(t) delete t; +} + +~~~~ + +- `classname_mangled` is the mangled qualified class name, e.g., `foo::A -> foo_A` + +## Initializer + +~~~~ + +bool ${modulename}_initialize(JSGlobalContextRef context) { + SWIG_InitializeModule(0); + + JSObjectRef global_object = JSContextGetGlobalObject(context); + + /* Initialize the base swig type object */ + _SwigObject_objectDefinition.staticFunctions = _SwigObject_functions; + _SwigObject_objectDefinition.staticValues = _SwigObject_values; + _SwigObject_classRef = JSClassCreate(&_SwigObject_objectDefinition); + + /* Create objects for namespaces */ + ${create_namespaces} + + /* Create classes */ + ${initializercode} + + /* Register namespaces */ + ${register_namespaces} + + return true; +} + +~~~~ + +## Class template defintions + +A class is specified by a static part (`*_classDefinition`) and a dynamic part (`*_objectDefinition`). + +~~~~ + +${classname_mangled}_classDefinition.staticFunctions = ${classname_mangled}_staticFunctions; + ${classname_mangled}_classDefinition.staticValues = ${classname_mangled}_staticValues; + ${classname_mangled}_classDefinition.callAsConstructor = _wrap_create_${classname_mangled}; + ${classname_mangled}_objectDefinition.staticValues = ${classname_mangled}_values; + ${classname_mangled}_objectDefinition.staticFunctions = ${classname_mangled}_functions; + ${classname_mangled}_objectDefinition.parentClass = ${base_classname}_classRef; + JSClassRef ${classname_mangled}_classRef = JSClassCreate(&${classname_mangled}_objectDefinition); + SWIGTYPE_${classtype_mangled}->clientdata = ${classname_mangled}_classRef;%} + +~~~~ + +Notes: +- `classname_mangled` is the mangled qualified class name, e.g., `foo::A -> foo_A` + which is retrieved by `Swig_name_mangle(Getattr(n, "name"))` +- ClassDefinitions are built using the staticValues array and the staticFunction array. The staticValues and staticFunctions arrays are the simplest and most efficient means for vending custom properties to the class object. + +## Inheritance + +~~~~ + +{${classname_mangled}_objectDefinition.parentClass = ${base_classname}_classRef}; + +~~~~ + +- `classname_mangled` is the mangled qualified class name, e.g., `foo::A -> foo_A` +- Note: multiple inheritance is not possible; thus we will always take the first parent class + +## Namespaces + +Namespaces are objects without class templates. i.e., instances are created, referenced locally, used as contexts for other registrations, and stored in the according parent contexts. + +~~~~ + + ${namespace}_classDefinition.staticFunctions = ${namespace}_functions; + ${namespace}_classDefinition.staticValues = ${namespace}_values; + JSObjectRef ${namespace}_object = JSObjectMake(context, JSClassCreate(&${namespace}_classDefinition), NULL); + +~~~~ + +## Registration + +The registration part consists of registering classes at contexts (i.e., global or namespace), methods and properties at classes or contexts, and namespaces as objects at parent contexts. + +* Global functions + +~~~~ + +JS_registerFunction(${context}, ${context_object}, "${functionname}", ${functionwrapper} + +~~~~ + +* Classes + +~~~~ + +JS_registerClass(context, ${namespace}_object, "${classname}", &${classname_mangled}_classDefinition) + +~~~~ + +Note: every class template has an associated constructor function wrapper, which is registered here + +* Namespaces + +~~~~ + +${namespace}_classDefinition.staticFunctions = ${namespace}_functions; +${namespace}_classDefinition.staticValues = ${namespace}_values; +JSObjectRef ${namespace}_object = JSObjectMake(context, JSClassCreate(&${namespace}_classDefinition), NULL); + +~~~~ + +Namespaces are registered using: + +~~~~ + +JS_registerNamespace(context, ${namespace}_object, ${parent_namespace}_object, "${namespace}"); + +~~~~ + diff --git a/Doc/Manual/pandoc_template.html b/Doc/Manual/pandoc_template.html new file mode 100644 index 000000000..390bfc51c --- /dev/null +++ b/Doc/Manual/pandoc_template.html @@ -0,0 +1,56 @@ + + + + + + +$for(author-meta)$ + +$endfor$ +$if(date-meta)$ + +$endif$ + $if(title-prefix)$$title-prefix$ - $endif$$if(pagetitle)$$pagetitle$$endif$ +$if(highlighting-css)$ + +$endif$ +$for(css)$ + +$endfor$ +$if(math)$ + $math$ +$endif$ +$for(header-includes)$ + $header-includes$ +$endfor$ + + +$for(include-before)$ +$include-before$ +$endfor$ +$if(title)$ +
    +

    $title$

    +$for(author)$ +

    $author$

    +$endfor$ +$if(date)$ +

    $date$

    +$endif$ +
    +$endif$ +$if(toc)$ +
    +$toc$ +
    +$endif$ +
    +$body$ +
    +$for(include-after)$ +$include-after$ +$endfor$ + + diff --git a/Doc/Manual/style.css b/Doc/Manual/style.css index 02329e56f..7eabf91ae 100644 --- a/Doc/Manual/style.css +++ b/Doc/Manual/style.css @@ -25,7 +25,7 @@ div.indent { margin-right: 4em; } -div.code { +div.code, div:not(.code) pre { border-style: solid; border-width: 1px; padding: 2pt; @@ -82,3 +82,7 @@ div.indent p { margin-right: 0; } +h1 a, h2 a, h3 a, h4 a, h5 a, h6 a { + text-decoration:none; + color: #000000; +} diff --git a/Examples/Makefile.in b/Examples/Makefile.in index e6c0d2f33..80f807631 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -513,6 +513,65 @@ java_clean: rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *@JAVASO@ +################################################################## +##### JAVASCRIPT ###### +################################################################## + +# You need to set this variable to the jscore[or other javascript engine] directories containing the +# files "JavaScript.h" and others +JS_INCLUDE= @JSCOREINC@ + +# Extra JAVASCRIPT specific dynamic linking options +JS_DLNK = @JSCOREDYNAMICLINKING@ +JS_LIBPREFIX = @JSCORELIBRARYPREFIX@ +JSSO =@JSCORESO@ +JSLDSHARED = @JSCORELDSHARED@ +JSCXXSHARED = @JSCORECXXSHARED@ +JSCFLAGS = @JSCORECFLAGS@ +JSCXXFLAGS = @JSCXXFLAGS@ + +# ---------------------------------------------------------------- +# Build a javascript dynamically loadable module (C) +# ---------------------------------------------------------------- + +javascript: $(SRCS) + $(SWIG) -javascript -jsc -debug-templates $(SWIGOPT) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(JSCFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(JS_INCLUDE) + $(JSLDSHARED) $(CCSHARED) $(JSCFLAGS) $(OBJS) $(IOBJS) $(JS_DLNK) $(LIBS) -o $(JS_LIBPREFIX)$(TARGET)$(JSSO) + +# ---------------------------------------------------------------- +# Build a javascript dynamically loadable module (C++) +# ---------------------------------------------------------------- + +javascript_cpp: $(SRCS) + $(SWIG) -javascript -jsc -c++ -debug-templates $(SWIGOPT) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(JSCXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(JS_INCLUDE) + $(JSCXXSHARED) $(CCSHARED) $(OBJS) $(IOBJS) $(JS_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(JS_LIBPREFIX)$(TARGET)$(JSSO) + +# ---------------------------------------------------------------- +# Compile a javascript executable +# ---------------------------------------------------------------- +javascript_exe: $(SRCS) + $(CXX) $(CXXFLAGS) $(JS_INCLUDE) $(JSCXXSRCS) $(LIBS) $(JS_DLNK) -o $(JAVASCRIPT_EXE) + +# ---------------------------------------------------------------- +# Run the Compile a javascript executable +# ---------------------------------------------------------------- + +javascript_run: $(SRCS) + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(JAVASCRIPT_EXE) -l $(JAVASCRIPT_MODULE) $(JS_SCRIPT) + +# ----------------------------------------------------------------- +# Cleaning the javascript examples +# ----------------------------------------------------------------- + +javascript_clean: + rm -f *_wrap* runme + rm -f core @EXTRA_CLEAN@ + rm -f *.@OBJEXT@ *@JSCORESO@ + + + ################################################################## ##### MODULA3 ###### ################################################################## diff --git a/Examples/javascript/class/Makefile b/Examples/javascript/class/Makefile new file mode 100755 index 000000000..ea41e55ce --- /dev/null +++ b/Examples/javascript/class/Makefile @@ -0,0 +1,24 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +SRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx +JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript +JAVASCRIPT_MODULE = example +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i +SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc + +all:: + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: all + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + diff --git a/Examples/javascript/class/example.cpp b/Examples/javascript/class/example.cpp new file mode 100755 index 000000000..e23fa6f73 --- /dev/null +++ b/Examples/javascript/class/example.cpp @@ -0,0 +1,28 @@ +/* File : example.c */ +#include +#include "example.h" +#define M_PI 3.14159265358979323846 + +/* Move the shape to a new location */ +void Shape::move(double dx, double dy) { + x += dx; + y += dy; +} + +int Shape::nshapes = 0; + +double Circle::area(void) { + return M_PI*radius*radius; +} + +double Circle::perimeter(void) { + return 2*M_PI*radius; +} + +double Square::area(void) { + return width*width; +} + +double Square::perimeter(void) { + return 4*width; +} diff --git a/Examples/javascript/class/example.h b/Examples/javascript/class/example.h new file mode 100755 index 000000000..9d19e340a --- /dev/null +++ b/Examples/javascript/class/example.h @@ -0,0 +1,35 @@ +/* File : example.h */ + +class Shape { +public: + Shape() { + nshapes++; + } + virtual ~Shape() { + nshapes--; + }; + double x, y; + void move(double dx, double dy); + virtual double area(void) = 0; + virtual double perimeter(void) = 0; + static void printMe(void); + static int nshapes; +}; + +class Circle : public Shape { +private: + double radius; +public: + Circle(double r) : radius(r) { }; + virtual double area(void); + virtual double perimeter(void); +}; + +class Square : public Shape { +private: + double width; +public: + Square(double w) : width(w) { }; + virtual double area(void); + virtual double perimeter(void); +}; diff --git a/Examples/javascript/class/example.i b/Examples/javascript/class/example.i new file mode 100755 index 000000000..75700b305 --- /dev/null +++ b/Examples/javascript/class/example.i @@ -0,0 +1,10 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +/* Let's just grab the original header file here */ +%include "example.h" + diff --git a/Examples/javascript/class/runme.js b/Examples/javascript/class/runme.js new file mode 100755 index 000000000..922876fc5 --- /dev/null +++ b/Examples/javascript/class/runme.js @@ -0,0 +1,51 @@ +// file: runme.js + +// ----- Object creation ----- + +print("Creating some objects:"); +c = new example.Circle(10); +print("Created circle " + c); +s = new example.Square(10); +print("Created square " + s); + +// ----- Access a static member ----- +print("\nA total of " + example.Shape.nshapes + " shapes were created"); // access static member as properties of the class object + +// ----- Member data access ----- +// Set the location of the object. +// Note: methods in the base class Shape are used since +// x and y are defined there. + +c.x = 20; +c.y = 30; +s.x = -10; +s.y = 5; + +print("\nHere is their current position:"); +print("Circle = (" + c.x + "," + c.y + ")"); +print("Square = (" + s.x + "," + s.y + ")"); + +print("\nHere is their new position:"); +print("Circle = (" + c.x + "," + c.y + ")"); +print("Square = (" + s.x + "," + s.y + ")"); + + +// ----- Call some methods ----- +print("\nHere are some properties of the shapes:"); +print("Circle:"); +print("area = " + c.area() + ""); +print("perimeter = " + c.perimeter() + ""); +print("\n"); +print("Square:"); +print("area = " + s.area() + ""); +print("perimeter = " + s.perimeter() + ""); + +// ----- Delete everything ----- +print("\nGuess I'll clean up now"); +// Note: this invokes the virtual destructor +delete c; +delete s; + +print (example.Shape.nshapes + " shapes remain"); + +print("Goodbye"); diff --git a/Examples/javascript/constant/Makefile b/Examples/javascript/constant/Makefile new file mode 100755 index 000000000..4bc75b1a0 --- /dev/null +++ b/Examples/javascript/constant/Makefile @@ -0,0 +1,24 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +SRCS = +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx +JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript +JAVASCRIPT_MODULE = example +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i +SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc + +all:: + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: all + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + diff --git a/Examples/javascript/constant/example.h b/Examples/javascript/constant/example.h new file mode 100644 index 000000000..2c88ebd1e --- /dev/null +++ b/Examples/javascript/constant/example.h @@ -0,0 +1,8 @@ +#define ICONST 42 +#define FCONST 2.1828 +#define CCONST 'x' +#define CCONST2 '\n' +#define SCONST "Hello World" +#define SCONST2 "\"Hello World\"" +#define EXTERN extern +#define FOO (ICONST + BAR) diff --git a/Examples/javascript/constant/example.i b/Examples/javascript/constant/example.i new file mode 100755 index 000000000..a6d28e7c9 --- /dev/null +++ b/Examples/javascript/constant/example.i @@ -0,0 +1,24 @@ +/* File : example.i */ +%module example + +/* A few preprocessor macros */ + +#define ICONST 42 +#define FCONST 2.1828 +#define CCONST 'x' +#define CCONST2 '\n' +#define SCONST "Hello World" +#define SCONST2 "\"Hello World\"" + +/* This should work just fine */ +#define EXPR ICONST + 3*(FCONST) + +/* This shouldn't do anything */ +#define EXTERN extern + +/* Neither should this (BAR isn't defined) */ +#define FOO (ICONST + BAR) + +/* The following directives also produce constants */ +%constant int iconst = 37; +%constant double fconst = 3.14; diff --git a/Examples/javascript/constant/runme.js b/Examples/javascript/constant/runme.js new file mode 100755 index 000000000..cd4783a27 --- /dev/null +++ b/Examples/javascript/constant/runme.js @@ -0,0 +1,14 @@ +// file: runme.js + +print("ICONST = " + example.ICONST + " (should be 42)\n"); +print("FCONST = " + example.FCONST + " (should be 2.1828)\n"); +print("CCONST = " + example.CCONST + " (should be 'x')\n"); +print("CCONST2 = " + example.CCONST2 + " (this should be on a new line)\n"); +print("SCONST = " + example.SCONST + " (should be 'Hello World')\n"); +print("SCONST2 = " + example.SCONST2 + " (should be '\"Hello World\"')\n"); +print("EXPR = " + example.EXPR + " (should be 48.5484)\n"); +print("iconst = " + example.iconst + " (should be 37)\n"); +print("fconst = " + example.fconst + " (should be 3.14)\n"); + +print("EXTERN = " + example.EXTERN + " (should be undefined)\n"); +print("FOO = " + example.FOO + " (should be undefined)\n"); diff --git a/Examples/javascript/enum/Makefile b/Examples/javascript/enum/Makefile new file mode 100755 index 000000000..ea41e55ce --- /dev/null +++ b/Examples/javascript/enum/Makefile @@ -0,0 +1,24 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +SRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx +JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript +JAVASCRIPT_MODULE = example +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i +SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc + +all:: + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: all + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + diff --git a/Examples/javascript/enum/example.cpp b/Examples/javascript/enum/example.cpp new file mode 100755 index 000000000..6785e57ac --- /dev/null +++ b/Examples/javascript/enum/example.cpp @@ -0,0 +1,37 @@ +/* File : example.c */ + +#include "example.h" +#include + +void Foo::enum_test(speed s) { + if (s == IMPULSE) { + printf("IMPULSE speed\n"); + } else if (s == WARP) { + printf("WARP speed\n"); + } else if (s == LUDICROUS) { + printf("LUDICROUS speed\n"); + } else { + printf("Unknown speed\n"); + } +} + +void enum_test(color c, Foo::speed s) { + if (c == RED) { + printf("color = RED, "); + } else if (c == BLUE) { + printf("color = BLUE, "); + } else if (c == GREEN) { + printf("color = GREEN, "); + } else { + printf("color = Unknown color!, "); + } + if (s == Foo::IMPULSE) { + printf("speed = IMPULSE speed\n"); + } else if (s == Foo::WARP) { + printf("speed = WARP speed\n"); + } else if (s == Foo::LUDICROUS) { + printf("speed = LUDICROUS speed\n"); + } else { + printf("speed = Unknown speed!\n"); + } +} diff --git a/Examples/javascript/enum/example.h b/Examples/javascript/enum/example.h new file mode 100755 index 000000000..9119cd9fc --- /dev/null +++ b/Examples/javascript/enum/example.h @@ -0,0 +1,13 @@ +/* File : example.h */ + +enum color { RED, BLUE, GREEN }; + +class Foo { + public: + Foo() { } + enum speed { IMPULSE=10, WARP=20, LUDICROUS=30 }; + void enum_test(speed s); +}; + +void enum_test(color c, Foo::speed s); + diff --git a/Examples/javascript/enum/example.i b/Examples/javascript/enum/example.i new file mode 100755 index 000000000..23ee8a822 --- /dev/null +++ b/Examples/javascript/enum/example.i @@ -0,0 +1,11 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +/* Let's just grab the original header file here */ + +%include "example.h" + diff --git a/Examples/javascript/enum/runme.js b/Examples/javascript/enum/runme.js new file mode 100755 index 000000000..3f6283639 --- /dev/null +++ b/Examples/javascript/enum/runme.js @@ -0,0 +1,34 @@ +// file: runme.py + +// ----- Object creation ----- + +// Print out the value of some enums +print("*** color ***"); +print(" RED =" + example.RED); +print(" BLUE =" + example.BLUE); +print(" GREEN =" + example.GREEN); + +print("\n*** Foo::speed ***"); +print(" Foo_IMPULSE =" + example.Foo.IMPULSE); +print(" Foo_WARP =" + example.Foo.WARP); +print(" Foo_LUDICROUS =" + example.Foo.LUDICROUS); + +print("\nTesting use of enums with functions\n"); + +example.enum_test(example.RED, example.Foo.IMPULSE); +example.enum_test(example.BLUE, example.Foo.WARP); +example.enum_test(example.GREEN, example.Foo.LUDICROUS); +example.enum_test(1234,5678); + +print("\nTesting use of enum with class method"); +f = new example.Foo(); + +f.enum_test(example.Foo.IMPULSE); +f.enum_test(example.Foo.WARP); +f.enum_test(example.Foo.LUDICROUS); + +// enum value BLUE of enum color is accessed as property of cconst +print("example.BLUE= " + example.BLUE); + +// enum value LUDICROUS of enum Foo::speed is accessed as as property of cconst +print("example.speed.LUDICROUS= " + example.Foo.LUDICROUS); diff --git a/Examples/javascript/exception/Makefile b/Examples/javascript/exception/Makefile new file mode 100755 index 000000000..ea41e55ce --- /dev/null +++ b/Examples/javascript/exception/Makefile @@ -0,0 +1,24 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +SRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx +JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript +JAVASCRIPT_MODULE = example +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i +SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc + +all:: + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: all + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + diff --git a/Examples/javascript/exception/example.cpp b/Examples/javascript/exception/example.cpp new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/Examples/javascript/exception/example.cpp @@ -0,0 +1 @@ + diff --git a/Examples/javascript/exception/example.h b/Examples/javascript/exception/example.h new file mode 100644 index 000000000..7cf917d01 --- /dev/null +++ b/Examples/javascript/exception/example.h @@ -0,0 +1,53 @@ +/* File : example.h */ + +#include +#ifndef SWIG +struct A { +}; +#endif + +class Exc { +public: + Exc(int c, const char *m) { + code = c; + strncpy(msg,m,256); + } + int code; + char msg[256]; +}; + +#if defined(_MSC_VER) + #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow) +#endif + +class Test { +public: + int simple() throw(int) { + throw(37); + return 1; + } + int message() throw(const char *) { + throw("I died."); + return 1; + } + int hosed() throw(Exc) { + throw(Exc(42,"Hosed")); + return 1; + } + int unknown() throw(A*) { + static A a; + throw &a; + return 1; + } + int multi(int x) throw(int, const char *, Exc) { + if (x == 1) throw(37); + if (x == 2) throw("Bleah!"); + if (x == 3) throw(Exc(42,"No-go-diggy-die")); + return 1; + } +}; + +#if defined(_MSC_VER) + #pragma warning(default: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow) +#endif + diff --git a/Examples/javascript/exception/example.i b/Examples/javascript/exception/example.i new file mode 100644 index 000000000..08672c3a8 --- /dev/null +++ b/Examples/javascript/exception/example.i @@ -0,0 +1,12 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +%include "std_string.i" + +/* Let's just grab the original header file here */ +%include "example.h" + diff --git a/Examples/javascript/exception/runme.js b/Examples/javascript/exception/runme.js new file mode 100644 index 000000000..dfa561993 --- /dev/null +++ b/Examples/javascript/exception/runme.js @@ -0,0 +1,54 @@ +//file: runme.js +// Throw a lot of exceptions + +t = new example.Test(); +try{ + t.unknown(); + throw -1; +} catch(error) +{ + if(error == -1) { + print("t.unknown() didn't throw"); + } +} + +try{ + t.simple(); + throw -1; +} +catch(error){ + if(error == -1) { + print("t.simple() did not throw"); + } +} + +try{ + t.message(); + throw -1; +} catch(error){ + if(error == -1) { + print("t.message() did not throw"); + } +} + +try{ + t.hosed(); + throw -1; +} +catch(error){ + if(error == -1) { + print("t.hosed() did not throw"); + } +} + +for (var i=1; i<4; i++) { + try{ + t.multi(i); + throw -1; + } + catch(error){ + if(error == -1) { + print("t.mulit(" + i + ") did not throw"); + } + } +} diff --git a/Examples/javascript/functor/Makefile b/Examples/javascript/functor/Makefile new file mode 100755 index 000000000..ea41e55ce --- /dev/null +++ b/Examples/javascript/functor/Makefile @@ -0,0 +1,24 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +SRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx +JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript +JAVASCRIPT_MODULE = example +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i +SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc + +all:: + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: all + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + diff --git a/Examples/javascript/functor/example.cpp b/Examples/javascript/functor/example.cpp new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/javascript/functor/example.i b/Examples/javascript/functor/example.i new file mode 100644 index 000000000..0450c2124 --- /dev/null +++ b/Examples/javascript/functor/example.i @@ -0,0 +1,25 @@ +/* File : example.i */ +%module example + + +%inline %{ +// From B. Strousjoup, "The C++ Programming Language, Third Edition", p. 514 +template class Sum { + T res; +public: + Sum(T i = 0) : res(i) { } + void operator() (T x) { res += x; } + T result() const { return res; } +}; + +%} + +%rename(call) *::operator(); // the fn call operator + +// Instantiate a few versions +%template(intSum) Sum; +%template(doubleSum) Sum; + + + + diff --git a/Examples/javascript/functor/runme.js b/Examples/javascript/functor/runme.js new file mode 100644 index 000000000..48d332c83 --- /dev/null +++ b/Examples/javascript/functor/runme.js @@ -0,0 +1,16 @@ +// Operator overloading example + + +a = new example.intSum(0); +b = new example.doubleSum(100.0); + +// Use the objects. They should be callable just like a normal +// javascript function. + +for (i=1;i<=100;i++) + a.call(i); // Note: function call + b.call(Math.sqrt(i)); // Note: function call + +print(a.result()); +print(b.result()); + diff --git a/Examples/javascript/namespace/Makefile b/Examples/javascript/namespace/Makefile new file mode 100755 index 000000000..ea41e55ce --- /dev/null +++ b/Examples/javascript/namespace/Makefile @@ -0,0 +1,24 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +SRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx +JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript +JAVASCRIPT_MODULE = example +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i +SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc + +all:: + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: all + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + diff --git a/Examples/javascript/namespace/example.cpp b/Examples/javascript/namespace/example.cpp new file mode 100644 index 000000000..5beeb09fe --- /dev/null +++ b/Examples/javascript/namespace/example.cpp @@ -0,0 +1,36 @@ +/* File : example.c */ + +#include +#include "example.h" + +#define M_PI 3.14159 + + +/* A global variable */ +namespace nspace +{ +double Foo = 3.0; + +/* Compute the greatest common divisor of positive integers */ +int gcd(int x, int y) { + int g; + g = y; + while (x > 0) { + g = x; + x = y % x; + y = g; + } + return g; +} + +Circle::Circle(): radius(1.0) {} + +Circle::Circle(double r): radius(r) { + std::cout << "created Circle with r=" << radius << std::endl; +} + +double Circle::area() { + std::cout << "Circle::area called, r=" << radius << std::endl; + return M_PI*radius*radius; +} +} diff --git a/Examples/javascript/namespace/example.h b/Examples/javascript/namespace/example.h new file mode 100644 index 000000000..7f76c2f07 --- /dev/null +++ b/Examples/javascript/namespace/example.h @@ -0,0 +1,20 @@ + +namespace nspace { + +extern int gcd(int x, int y); +extern double Foo; + +class Circle +{ +public: + Circle(); + + Circle(double r); + + double area(); + + double radius; + +}; + +} diff --git a/Examples/javascript/namespace/example.i b/Examples/javascript/namespace/example.i new file mode 100644 index 000000000..e14b10b44 --- /dev/null +++ b/Examples/javascript/namespace/example.i @@ -0,0 +1,10 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +%feature("nspace", 1); + +%include "example.h" diff --git a/Examples/javascript/namespace/runme.js b/Examples/javascript/namespace/runme.js new file mode 100644 index 000000000..dc49b078e --- /dev/null +++ b/Examples/javascript/namespace/runme.js @@ -0,0 +1,11 @@ + print("Global variable Foo=" + example.nspace.Foo); + example.nspace.Foo = 5; + print("Variable Foo changed to " + example.nspace.Foo); + print("GCD of number 6,18 is " + example.nspace.gcd(6,18)); + +print("Creating some objects:"); +c = new example.nspace.Circle(10); +print("area = " + c.area()); + + + diff --git a/Examples/javascript/operator/Makefile b/Examples/javascript/operator/Makefile new file mode 100755 index 000000000..ea41e55ce --- /dev/null +++ b/Examples/javascript/operator/Makefile @@ -0,0 +1,24 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +SRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx +JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript +JAVASCRIPT_MODULE = example +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i +SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc + +all:: + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: all + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + diff --git a/Examples/javascript/operator/example.cpp b/Examples/javascript/operator/example.cpp new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/javascript/operator/example.h b/Examples/javascript/operator/example.h new file mode 100644 index 000000000..4da6a2307 --- /dev/null +++ b/Examples/javascript/operator/example.h @@ -0,0 +1,36 @@ +/* File : example.h */ +#include + +class Complex { +private: + double rpart, ipart; +public: + Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { } + Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { } + Complex &operator=(const Complex &c) { + rpart = c.rpart; + ipart = c.ipart; + return *this; + } + Complex operator+(const Complex &c) const { + return Complex(rpart+c.rpart, ipart+c.ipart); + } + Complex operator-(const Complex &c) const { + return Complex(rpart-c.rpart, ipart-c.ipart); + } + Complex operator*(const Complex &c) const { + return Complex(rpart*c.rpart - ipart*c.ipart, + rpart*c.ipart + c.rpart*ipart); + } + Complex operator-() const { + return Complex(-rpart, -ipart); + } + + double re() const { return rpart; } + double im() const { return ipart; } +}; + + + + + diff --git a/Examples/javascript/operator/example.i b/Examples/javascript/operator/example.i new file mode 100644 index 000000000..7a1bd45e1 --- /dev/null +++ b/Examples/javascript/operator/example.i @@ -0,0 +1,34 @@ +/* File : example.i */ +%module example +#pragma SWIG nowarn=SWIGWARN_IGNORE_OPERATOR_EQ +%{ +#include "example.h" +%} + +/* This header file is a little tough to handle because it has overloaded + operators and constructors. We're going to try and deal with that here */ + +/* This turns the copy constructor in a function ComplexCopy() that can + be called */ + +%rename(assign) Complex::operator=; +%rename(plus) Complex::operator+; +%rename(minus) Complex::operator-(const Complex &) const; +%rename(uminus) Complex::operator-() const; +%rename(times) Complex::operator*; + +/* Now grab the original header file */ +%include "example.h" + +/* An output method that turns a complex into a short string */ +%extend Complex { + char *toString() { + static char temp[512]; + sprintf(temp,"(%g,%g)", $self->re(), $self->im()); + return temp; + } + static Complex* copy(const Complex& c) { + return new Complex(c); + } +}; + diff --git a/Examples/javascript/operator/runme.js b/Examples/javascript/operator/runme.js new file mode 100644 index 000000000..92b8e3b74 --- /dev/null +++ b/Examples/javascript/operator/runme.js @@ -0,0 +1,25 @@ +// Operator overloading example + +a = new example.Complex(2,3); +b = new example.Complex(-5,10); + +print ("a =" + a); +print ("b =" + b); + +c = a.plus(b); + +print("c =" + c); +print("a*b =" + a.times(b)); +print("a-c =" + a.minus(c)); + +e = example.Complex.copy(a.minus(c)); +print("e =" + e); + +// Big expression +f = a.plus(b).times(c.plus(b.times(e))).plus(a.uminus()); +print("f =" + f); + + + + + diff --git a/Examples/javascript/overload/Makefile b/Examples/javascript/overload/Makefile new file mode 100755 index 000000000..ea41e55ce --- /dev/null +++ b/Examples/javascript/overload/Makefile @@ -0,0 +1,24 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +SRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx +JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript +JAVASCRIPT_MODULE = example +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i +SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc + +all:: + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: all + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + diff --git a/Examples/javascript/overload/example.cpp b/Examples/javascript/overload/example.cpp new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/javascript/overload/example.h b/Examples/javascript/overload/example.h new file mode 100644 index 000000000..2f112f1e1 --- /dev/null +++ b/Examples/javascript/overload/example.h @@ -0,0 +1,28 @@ +#include + +void f() { + std::cout << "Called f()." << std::endl; +} + +void f(int val) { + std::cout << "Called f(int)." << std::endl; +} +void f(int val1, int val2) { + std::cout << "Called f(int, int)." << std::endl; +} + +void f(const char* s) { + std::cout << "Called f(const char*)." << std::endl; +} + +void f(bool val) { + std::cout << "Called f(bool)." << std::endl; +} + +void f(long val) { + std::cout << "Called f(long)." << std::endl; +} + +void f(double val) { + std::cout << "Called f(double)." << std::endl; +} diff --git a/Examples/javascript/overload/example.i b/Examples/javascript/overload/example.i new file mode 100644 index 000000000..c4f652c0a --- /dev/null +++ b/Examples/javascript/overload/example.i @@ -0,0 +1,20 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +/* + Note: overloading is implemented in a sloppy way currently + i.e., only the number of arguments is taken into conideration + for dispatching. + To solve the problem one has to rename such conflicting methods. +*/ + +%rename(f_string) f(const char* s); +%rename(f_bool) f(bool val); +%rename(f_long) f(long val); +%rename(f_double) f(double val); + +%include "example.h" diff --git a/Examples/javascript/overload/runme.js b/Examples/javascript/overload/runme.js new file mode 100644 index 000000000..c6d4ef68d --- /dev/null +++ b/Examples/javascript/overload/runme.js @@ -0,0 +1,7 @@ +example.f(); +example.f(1); +example.f(1, 2); +example.f_string("bla"); +example.f_bool(false); +example.f_long(11111111111); +example.f_double(1.0); diff --git a/Examples/javascript/pointer/Makefile b/Examples/javascript/pointer/Makefile new file mode 100755 index 000000000..ea41e55ce --- /dev/null +++ b/Examples/javascript/pointer/Makefile @@ -0,0 +1,24 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +SRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx +JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript +JAVASCRIPT_MODULE = example +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i +SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc + +all:: + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: all + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + diff --git a/Examples/javascript/pointer/example.cpp b/Examples/javascript/pointer/example.cpp new file mode 100755 index 000000000..8762329fe --- /dev/null +++ b/Examples/javascript/pointer/example.cpp @@ -0,0 +1,16 @@ +/* File : example.c */ + +void add(int *x, int *y, int *result) { + *result = *x + *y; +} + +void subtract(int *x, int *y, int *result) { + *result = *x - *y; +} + +int divide(int n, int d, int *r) { + int q; + q = n/d; + *r = n - q*d; + return q; +} diff --git a/Examples/javascript/pointer/example.i b/Examples/javascript/pointer/example.i new file mode 100755 index 000000000..38c67d7d2 --- /dev/null +++ b/Examples/javascript/pointer/example.i @@ -0,0 +1,30 @@ +/* File : example.i */ +%module example + +%{ +extern void add(int *, int *, int *); +extern void subtract(int *, int *, int *); +extern int divide(int, int, int *); +%} + +/* This example illustrates a couple of different techniques + for manipulating C pointers */ + +/* First we'll use the pointer library */ +extern void add(int *x, int *y, int *result); +%include cpointer.i +%pointer_functions(int, intp); + +/* Next we'll use some typemaps */ + +%include typemaps.i +extern void subtract(int *INPUT, int *INPUT, int *OUTPUT); + +/* Next we'll use typemaps and the %apply directive */ + +%apply int *OUTPUT { int *r }; +extern int divide(int n, int d, int *r); + + + + diff --git a/Examples/javascript/pointer/runme.js b/Examples/javascript/pointer/runme.js new file mode 100755 index 000000000..48f92f11f --- /dev/null +++ b/Examples/javascript/pointer/runme.js @@ -0,0 +1,38 @@ +// file: runme.js + +// First create some objects using the pointer library. +print("Testing the pointer library\n"); +a = example.new_intp(); +b = example.new_intp(); +c = example.new_intp(); + +example.intp_assign(a,37); +example.intp_assign(b,42); + +print(" a = " + example.intp_value(a) + "\n"); +print(" b = " + example.intp_value(b) + "\n"); +print(" c = " + example.intp_value(c) + "\n"); + +//// Call the add() function with some pointers +example.add(a, b, c); + +// +//// Now get the result +r = example.intp_value(c); +print(" 37 + 42 = " + r + "\n"); + +// Clean up the pointers +example.delete_intp(a); +example.delete_intp(b); +example.delete_intp(c); + +//// Now try the typemap library +//// This should be much easier. Now how it is no longer +//// necessary to manufacture pointers. +//"OUTPUT" Mapping is not supported + +//print("Trying the typemap library"); +//r = example.subtract(37,42); +//print("37 - 42 =" + r); + + diff --git a/Examples/javascript/reference/Makefile b/Examples/javascript/reference/Makefile new file mode 100755 index 000000000..ea41e55ce --- /dev/null +++ b/Examples/javascript/reference/Makefile @@ -0,0 +1,24 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +SRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx +JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript +JAVASCRIPT_MODULE = example +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i +SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc + +all:: + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: all + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + diff --git a/Examples/javascript/reference/example.cpp b/Examples/javascript/reference/example.cpp new file mode 100755 index 000000000..8a513bf49 --- /dev/null +++ b/Examples/javascript/reference/example.cpp @@ -0,0 +1,46 @@ +/* File : example.cxx */ + +/* Deal with Microsoft's attempt at deprecating C standard runtime functions */ +#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +# define _CRT_SECURE_NO_DEPRECATE +#endif + +#include "example.h" +#include +#include + +Vector operator+(const Vector &a, const Vector &b) { + Vector r; + r.x = a.x + b.x; + r.y = a.y + b.y; + r.z = a.z + b.z; + return r; +} + +char *Vector::print() { + static char temp[512]; + sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z); + return temp; +} + +VectorArray::VectorArray(int size) { + items = new Vector[size]; + maxsize = size; +} + +VectorArray::~VectorArray() { + delete [] items; +} + +Vector &VectorArray::operator[](int index) { + if ((index < 0) || (index >= maxsize)) { + printf("Panic! Array index out of bounds.\n"); + exit(1); + } + return items[index]; +} + +int VectorArray::size() { + return maxsize; +} + diff --git a/Examples/javascript/reference/example.h b/Examples/javascript/reference/example.h new file mode 100755 index 000000000..4915adb1b --- /dev/null +++ b/Examples/javascript/reference/example.h @@ -0,0 +1,26 @@ +/* File : example.h */ + +class Vector { +private: + double x,y,z; +public: + Vector() : x(0), y(0), z(0) { }; + Vector(double x, double y, double z) : x(x), y(y), z(z) { }; + friend Vector operator+(const Vector &a, const Vector &b); + char *print(); +}; + +class VectorArray { +private: + Vector *items; + int maxsize; +public: + VectorArray(int maxsize); + ~VectorArray(); + Vector &operator[](int); + int size(); +}; + + + + diff --git a/Examples/javascript/reference/example.i b/Examples/javascript/reference/example.i new file mode 100755 index 000000000..1cf19c82c --- /dev/null +++ b/Examples/javascript/reference/example.i @@ -0,0 +1,42 @@ +/* File : example.i */ + +/* This file has a few "typical" uses of C++ references. */ + +%module example + +%{ +#include "example.h" +%} + +class Vector { +public: + Vector(double x, double y, double z); + ~Vector(); + char *print(); +}; + +/* This helper function calls an overloaded operator */ +%inline %{ +Vector addv(Vector &a, Vector &b) { + return a+b; +} +%} + +/* Wrapper around an array of vectors class */ + +class VectorArray { +public: + VectorArray(int maxsize); + ~VectorArray(); + int size(); + + /* This wrapper provides an alternative to the [] operator */ + %extend { + Vector &get(int index) { + return (*$self)[index]; + } + void set(int index, Vector &a) { + (*$self)[index] = a; + } + } +}; diff --git a/Examples/javascript/reference/runme.js b/Examples/javascript/reference/runme.js new file mode 100755 index 000000000..5cf00061e --- /dev/null +++ b/Examples/javascript/reference/runme.js @@ -0,0 +1,67 @@ +// This file illustrates the manipulation of C++ references in Javascript. +// TODO: deleteion of vector objects created here + +// ----- Object creation ----- + +print("Creating some objects:\n"); +a = new example.Vector(3,4,5); +b = new example.Vector(10,11,12); + +print(" created" + a.print()); +print(" created" + b.print()); + +// ----- Call an overloaded operator ----- + +// This calls the wrapper we placed around operator+(const Vector &a, const Vector &) +// It returns a new allocated object. + +print("Adding a+b\n"); +c = example.addv(a, b); +print("a+b = " + c.print()); + + +// TODO: Note: Unless we free the result, a memory leak will occur +//delete_Vector(c); + +// ----- Create a vector array ----- + +// Note: Using the high-level interface here +print("Creating an array of vectors\n"); +va = new example.VectorArray(10); +print("va = " + va + "\n"); + +// ----- Set some values in the array ----- + +// These operators copy the value of a and b to the vector array +va.set(0,a); +va.set(1,b); + +// This will work, but it will cause a memory leak! +va.set(2,example.addv(a,b)); + +// The non-leaky way to do it +//c = addv(a,b); +//va.set(3,c); +//delete_Vector(c); + +// Get some values from the array + +print("Getting some array values\n"); +for (i = 0; i < 5; i++) { + temp = va.get(i); + print(i,temp.print()); +} + +// Watch under resource meter to check on this +print("Making sure we don't leak memory.\n"); +for (i = 0; i < 1000000; i++) { + c = va.get(i % 10); +} +//---------TODO--------- +//----- Clean up ----- +//print("Cleaning up\n"); + +//example.delete_VectorArray(va); +//example.delete_Vector(a); +//example.delete_Vector(b); + diff --git a/Examples/javascript/simple/Makefile b/Examples/javascript/simple/Makefile new file mode 100755 index 000000000..ea41e55ce --- /dev/null +++ b/Examples/javascript/simple/Makefile @@ -0,0 +1,24 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +SRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx +JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript +JAVASCRIPT_MODULE = example +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i +SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc + +all:: + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: all + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + diff --git a/Examples/javascript/simple/example.cpp b/Examples/javascript/simple/example.cpp new file mode 100755 index 000000000..e7d3b0f11 --- /dev/null +++ b/Examples/javascript/simple/example.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include +using namespace std; + +/* File : example.c */ + +/* A global variable */ +double Foo = 3.0; + +/* Compute the greatest common divisor of positive integers */ +int gcd(int x, int y) { + int g; + g = y; + while (x > 0) { + g = x; + x = y % x; + y = g; + } + return g; +} + + + + + + diff --git a/Examples/javascript/simple/example.i b/Examples/javascript/simple/example.i new file mode 100755 index 000000000..7c345964c --- /dev/null +++ b/Examples/javascript/simple/example.i @@ -0,0 +1,15 @@ +/* File : example.i */ +%module example + +%include "std_string.i" + +%inline %{ +extern int gcd(int x, int y); +extern float gcd(float x, float y); +extern char* helloString(char* s); +extern void delete_helloString(char *newstr); +extern std::string helloString(std::string s); +extern void bar(int x, int y = 3, int z = 4); + +extern double Foo; +%} diff --git a/Examples/javascript/simple/runme.js b/Examples/javascript/simple/runme.js new file mode 100755 index 000000000..96c11a5a2 --- /dev/null +++ b/Examples/javascript/simple/runme.js @@ -0,0 +1,26 @@ +/* file: runme.js */ + +/* Call our gcd() function */ + +x = 42; +y = 105; +g = example.gcd(x,y); +print("GCD of x and y is=" + g); + +/* Manipulate the Foo global variable */ + +/* Output its current value */ +print("Global variable Foo=" + example.Foo); + +/* Change its value */ +example.Foo = 3.1415926; + +/* See if the change took effect */ +print("Variable Foo changed to=" + example.Foo); + + + + + + + diff --git a/Examples/javascript/template/Makefile b/Examples/javascript/template/Makefile new file mode 100755 index 000000000..ea41e55ce --- /dev/null +++ b/Examples/javascript/template/Makefile @@ -0,0 +1,24 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +SRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx +JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript +JAVASCRIPT_MODULE = example +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i +SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc + +all:: + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: all + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + diff --git a/Examples/javascript/template/example.cpp b/Examples/javascript/template/example.cpp new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/javascript/template/example.h b/Examples/javascript/template/example.h new file mode 100644 index 000000000..7401df650 --- /dev/null +++ b/Examples/javascript/template/example.h @@ -0,0 +1,32 @@ +/* File : example.h */ + +// Some template definitions + +template T max(T a, T b) { return a>b ? a : b; } + +template class vector { + T *v; + int sz; + public: + vector(int _sz) { + v = new T[_sz]; + sz = _sz; + } + T &get(int index) { + return v[index]; + } + void set(int index, T &val) { + v[index] = val; + } +#ifdef SWIG + %extend { + T getitem(int index) { + return $self->get(index); + } + void setitem(int index, T val) { + $self->set(index,val); + } + } +#endif +}; + diff --git a/Examples/javascript/template/example.i b/Examples/javascript/template/example.i new file mode 100644 index 000000000..8f94c4da1 --- /dev/null +++ b/Examples/javascript/template/example.i @@ -0,0 +1,17 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +/* Let's just grab the original header file here */ +%include "example.h" + +/* Now instantiate some specific template declarations */ + +%template(maxint) max; +%template(maxdouble) max; +%template(vecint) vector; +%template(vecdouble) vector; + diff --git a/Examples/javascript/template/runme.js b/Examples/javascript/template/runme.js new file mode 100644 index 000000000..b2a5264ab --- /dev/null +++ b/Examples/javascript/template/runme.js @@ -0,0 +1,32 @@ +// file: runme.js + +//Call some templated functions +print(example.maxint(3,7)); +print(example.maxdouble(3.14,2.18)); + +// Create some class + +iv = new example.vecint(100); +dv = new example.vecdouble(1000); + +for(i=0;i<=100;i++) + iv.setitem(i,2*i); + +for(i=0;i<=1000;i++) + dv.setitem(i, 1.0/(i+1)); + +sum = 0; +for(i=0;i<=100;i++) + sum = sum + iv.getitem(i); + +print(sum); + +sum = 0.0; +for(i=0;i<=1000;i++) + sum = sum + dv.getitem(i); +print(sum); + +delete iv; +delete dv; + + diff --git a/Examples/javascript/variables/Makefile b/Examples/javascript/variables/Makefile new file mode 100755 index 000000000..e80e370e0 --- /dev/null +++ b/Examples/javascript/variables/Makefile @@ -0,0 +1,24 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +SRCS = example.c +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx +JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript +JAVASCRIPT_MODULE = example +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i +SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc + +all:: + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ +SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: all + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + diff --git a/Examples/javascript/variables/example.c b/Examples/javascript/variables/example.c new file mode 100755 index 000000000..aa4ffe9b3 --- /dev/null +++ b/Examples/javascript/variables/example.c @@ -0,0 +1,91 @@ +/* File : example.c */ + +/* I'm a file containing some C global variables */ + +/* Deal with Microsoft's attempt at deprecating C standard runtime functions */ +#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +# define _CRT_SECURE_NO_DEPRECATE +#endif + +#include +#include +#include "example.h" + +int ivar = 0; +short svar = 0; +long lvar = 0; +unsigned int uivar = 0; +unsigned short usvar = 0; +unsigned long ulvar = 0; +signed char scvar = 0; +unsigned char ucvar = 0; +char cvar = 0; +float fvar = 0; +double dvar = 0; +char *strvar = 0; +const char cstrvar[] = "Goodbye"; +int *iptrvar = 0; +char name[256] = "Dave"; +char path[256] = "/home/beazley"; + + +/* Global variables involving a structure */ +Point *ptptr = 0; +Point pt = { 10, 20 }; + +/* A variable that we will make read-only in the interface */ +int status = 1; + +/* A debugging function to print out their values */ + +void print_vars() { + printf("ivar = %d\n", ivar); + printf("svar = %d\n", svar); + printf("lvar = %ld\n", lvar); + printf("uivar = %u\n", uivar); + printf("usvar = %u\n", usvar); + printf("ulvar = %lu\n", ulvar); + printf("scvar = %d\n", scvar); + printf("ucvar = %u\n", ucvar); + printf("fvar = %g\n", fvar); + 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("iptrvar = %p\n", iptrvar); + printf("name = %s\n", name); + printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); + printf("pt = (%d, %d)\n", pt.x, pt.y); + printf("status = %d\n", status); +} + +/* A function to create an integer (to test iptrvar) */ + +int *new_int(int value) { + int *ip = (int *) malloc(sizeof(int)); + *ip = value; + return ip; +} + +/* A function to create a point */ + +Point *new_Point(int x, int y) { + Point *p = (Point *) malloc(sizeof(Point)); + p->x = x; + p->y = y; + return p; +} + +char * Point_print(Point *p) { + static char buffer[256]; + if (p) { + sprintf(buffer,"(%d,%d)", p->x,p->y); + } else { + sprintf(buffer,"null"); + } + return buffer; +} + +void pt_print() { + printf("(%d, %d)\n", pt.x, pt.y); +} diff --git a/Examples/javascript/variables/example.h b/Examples/javascript/variables/example.h new file mode 100755 index 000000000..0f7e89594 --- /dev/null +++ b/Examples/javascript/variables/example.h @@ -0,0 +1,6 @@ +/* File: example.h */ + +typedef struct { + int x,y; +} Point; + diff --git a/Examples/javascript/variables/example.i b/Examples/javascript/variables/example.i new file mode 100755 index 000000000..591b871ed --- /dev/null +++ b/Examples/javascript/variables/example.i @@ -0,0 +1,49 @@ +/* File : example.i */ +%module example +%{ +#include "example.h" +%} + +/* Some global variable declarations */ +%inline %{ +extern int ivar; +extern short svar; +extern long lvar; +extern unsigned int uivar; +extern unsigned short usvar; +extern unsigned long ulvar; +extern signed char scvar; +extern unsigned char ucvar; +extern char cvar; +extern float fvar; +extern double dvar; +extern char *strvar; +extern const char cstrvar[]; +extern int *iptrvar; +extern char name[256]; + +extern Point *ptptr; +extern Point pt; +%} + + +/* Some read-only variables */ + +%immutable; + +%inline %{ +extern int status; +extern char path[256]; +%} + +%mutable; + +/* Some helper functions to make it easier to test */ +%inline %{ +extern void print_vars(); +extern int *new_int(int value); +extern Point *new_Point(int x, int y); +extern char *Point_print(Point *p); +extern void pt_print(); +%} + diff --git a/Examples/javascript/variables/runme.js b/Examples/javascript/variables/runme.js new file mode 100755 index 000000000..7c4e151de --- /dev/null +++ b/Examples/javascript/variables/runme.js @@ -0,0 +1,68 @@ +// file: runme.js + +// Try to set the values of some global variables +example.ivar = 42; +example.svar = -31000; +example.lvar = 65537; +example.uivar = 123456; +example.usvar = 61000; +example.ulvar = 654321; +example.scvar = -13; +example.ucvar = 251; +example.cvar = "S"; +example.fvar = 3.14159; +example.dvar = 2.1828; +example.strvar = "Hello World"; +example.iptrvar= example.new_int(37); +example.ptptr = example.new_Point(37,42); +example.name = "Bill"; + +// Now print out the values of the variables +print("Variables (values printed from Python)" + "\n"); +print("ivar = " + example.ivar + "\n"); +print("svar = " + example.svar + "\n"); +print("lvar = " + example.lvar + "\n"); +print("uivar = " + example.uivar + "\n"); +print("usvar = " + example.usvar + "\n"); +print("ulvar = " + example.ulvar + "\n"); +print("scvar = " + example.scvar + "\n"); +print("ucvar = " + example.ucvar + "\n"); +print("fvar = " + example.fvar + "\n"); +print("dvar = " + example.dvar + "\n"); +print("cvar = " + example.cvar + "\n"); +print("strvar = " + example.strvar+ "\n"); +print("cstrvar = " + example.cstrvar+ "\n"); +print("iptrvar = " + example.iptrvar+ "\n"); +print("name = " + example.name + "\n"); +print("ptptr = " + example.ptptr + ": " + example.Point_print(example.ptptr) + "\n"); +print("pt = " + example.pt + ": " + example.Point_print(example.pt) + "\n"); + + +print("\nVariables (values printed from C)"); + +example.print_vars(); + +print("\nNow I'm going to try and modify some read only variables"); + +print("Tring to set 'path'"); +try{ + example.path = "Whoa!"; + print("Hey, what's going on?!?! This shouldn't work"); +} +catch(e){ + print("Good."); +} + +print("Trying to set 'status'"); +try{ + example.status = 0; + print("Hey, what's going on?!?! This shouldn't work"); +} catch(e){ + print("Good."); +} + +print("\nI'm going to try and update a structure variable.\n"); +example.pt = example.ptptr; +print("The new value is: "); +example.pt_print(); +print("You should see the value: " + example.Point_print(example.ptptr)); diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 7cc410e7a..268dcee39 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -95,6 +95,7 @@ C_TEST_BROKEN += \ # C++ test cases. (Can be run individually using: make testcase.cpptest) +ifndef SKIP_CPP_CASES CPP_TEST_CASES += \ abstract_access \ abstract_inherit \ @@ -459,6 +460,7 @@ CPP_TEST_CASES += \ voidtest \ wallkw \ wrapmacro +endif # # Put all the heavy STD/STL cases here, where they can be skipped if needed @@ -488,6 +490,7 @@ endif # C test cases. (Can be run individually using: make testcase.ctest) +ifndef SKIP_C_CASES C_TEST_CASES += \ arrays \ char_constant \ @@ -532,9 +535,10 @@ C_TEST_CASES += \ typemap_subst \ union_parameter \ unions - +endif # Multi-module C++ test cases . (Can be run individually using make testcase.multicpptest) +ifndef SKIP_MULTI_CPP_CASES MULTI_CPP_TEST_CASES += \ clientdata_prop \ imports \ @@ -543,6 +547,7 @@ MULTI_CPP_TEST_CASES += \ mod \ template_typedef_import \ multi_import +endif # Custom tests - tests with additional commandline options wallkw.cpptest: SWIGOPT += -Wallkw diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in new file mode 100755 index 000000000..38f350cb0 --- /dev/null +++ b/Examples/test-suite/javascript/Makefile.in @@ -0,0 +1,94 @@ +####################################################################### +# Makefile for javascript test-suite +####################################################################### + +LANGUAGE = javascript +JAVASCRIPT_EXE = ../../../Tools/javascript/javascript +JAVASCRIPT_EXE_SRC = ../../../Tools/javascript/javascript.cxx +SCRIPTSUFFIX = _runme.js +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ +JS_INCLUDE = @JSCOREINC@ +JS_DLNK = @JSCOREDYNAMICLINKING@ +JSCXXFLAGS = @JSCXXFLAGS@ + +C_TEST_CASES = \ + preproc \ + preproc_include + +CPP_TEST_CASES = \ + abstract_access \ + abstract_typedef \ + abstract_typedef2 \ + abstract_virtual \ + array_member \ + arrays_global \ + char_binary \ + class_ignore \ + class_scope_weird \ + complextest \ + constover \ + cpp_enum \ + cpp_namespace \ + cpp_static \ + director_alternating \ + enum_template \ + namespace_virtual_method \ + overload_copy \ + ret_by_value \ + struct_value \ + template_static \ + typedef_class \ + typedef_inherit \ + typedef_scope \ + typemap_arrays \ + typemap_delete \ + typemap_namespace \ + typemap_ns_using \ + using1 \ + using2 + +SKIP_CPP_CASES = @SKIP_CPP_CASES@ +SKIP_C_CASES = @SKIP_C_CASES@ +SKIP_CPP_STD_CASES = @SKIP_CPP_STD_CASES@ +SKIP_MULTI_CPP_CASES = @SKIP_MULTI_CPP_CASES@ + +include $(srcdir)/../common.mk + +# Overridden variables here + +# Custom tests - tests with additional commandline options + +javascript_exe: + $(CXX) $(JSCXXFLAGS) $(JS_INCLUDE) $(JAVASCRIPT_EXE_SRC) $(LIBS) $(JS_DLNK) -o $(JAVASCRIPT_EXE) + +# Rules for the different types of tests +%.cpptest: javascript_exe + $(setup) + +$(swig_and_compile_cpp) + $(run_testcase) + +%.ctest: javascript_exe + $(setup) + +$(swig_and_compile_c) + $(run_testcase) + +%.multicpptest: javascript_exe + $(setup) + +$(swig_and_compile_multi_cpp) + $(run_testcase) + +# Runs the testcase. A testcase is only run if +# a file is found which has _runme.js appended after the testcase name. +run_testcase = \ + if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(JAVASCRIPT_EXE) -l $* $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + fi + +# Clean +%.clean: + + +clean: + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile javascript_clean diff --git a/Examples/test-suite/javascript/README b/Examples/test-suite/javascript/README new file mode 100755 index 000000000..acb2f7291 --- /dev/null +++ b/Examples/test-suite/javascript/README @@ -0,0 +1,4 @@ +See ../README for common README file. + +Any testcases which have _runme.js appended after the testcase name will be detected and run. + diff --git a/Examples/test-suite/javascript/abstract_access_runme.js b/Examples/test-suite/javascript/abstract_access_runme.js new file mode 100644 index 000000000..356d07ea7 --- /dev/null +++ b/Examples/test-suite/javascript/abstract_access_runme.js @@ -0,0 +1,5 @@ +var d = new abstract_access.D() +if (d.do_x() != 1) { + throw "Error"; +} + diff --git a/Examples/test-suite/javascript/abstract_typedef2_runme.js b/Examples/test-suite/javascript/abstract_typedef2_runme.js new file mode 100644 index 000000000..8adc2e05b --- /dev/null +++ b/Examples/test-suite/javascript/abstract_typedef2_runme.js @@ -0,0 +1,4 @@ +var a = new abstract_typedef2.A_UF(); + +if (a == undefined) + throw "Error"; diff --git a/Examples/test-suite/javascript/abstract_typedef_runme.js b/Examples/test-suite/javascript/abstract_typedef_runme.js new file mode 100644 index 000000000..106baea65 --- /dev/null +++ b/Examples/test-suite/javascript/abstract_typedef_runme.js @@ -0,0 +1,6 @@ +var e = new abstract_typedef.Engine(); +var a = new abstract_typedef.A() + +if (a.write(e) != 1) { + throw "Error"; +} diff --git a/Examples/test-suite/javascript/abstract_virtual_runme.js b/Examples/test-suite/javascript/abstract_virtual_runme.js new file mode 100644 index 000000000..c15abb5f6 --- /dev/null +++ b/Examples/test-suite/javascript/abstract_virtual_runme.js @@ -0,0 +1,9 @@ +d = new abstract_virtual.D() + +if (d == undefined) + throw "Error"; + +e = new abstract_virtual.E() + +if (e == undefined) + throw "Error"; diff --git a/Examples/test-suite/javascript/array_member_runme.js b/Examples/test-suite/javascript/array_member_runme.js new file mode 100644 index 000000000..dee4c2ca9 --- /dev/null +++ b/Examples/test-suite/javascript/array_member_runme.js @@ -0,0 +1,20 @@ +var f = new array_member.Foo(); +f.data = array_member.global_data; + +for (var i=0; i<8; i++) { + if (array_member.get_value(f.data,i) != array_member.get_value(array_member.global_data,i)) { + throw "Bad array assignment (1)"; + } +} + +for (var i=0; i<8; i++) { + array_member.set_value(f.data,i,-i); +} + +array_member.global_data = f.data; + +for (var i=0; i<8; i++){ + if (array_member.get_value(f.data,i) != array_member.get_value(array_member.global_data,i)) { + throw "Bad array assignment (2)"; + } +} diff --git a/Examples/test-suite/javascript/arrays_global_runme.js b/Examples/test-suite/javascript/arrays_global_runme.js new file mode 100644 index 000000000..9668826f3 --- /dev/null +++ b/Examples/test-suite/javascript/arrays_global_runme.js @@ -0,0 +1,16 @@ +arrays_global.array_i = arrays_global.array_const_i; + +arrays_global.BeginString_FIX44a; +arrays_global.BeginString_FIX44b; +arrays_global.BeginString_FIX44c; +arrays_global.BeginString_FIX44d; +arrays_global.BeginString_FIX44d; +arrays_global.BeginString_FIX44b = "12"+'\0'+"45"; +arrays_global.BeginString_FIX44b; +arrays_global.BeginString_FIX44d; +arrays_global.BeginString_FIX44e; +arrays_global.BeginString_FIX44f; + +arrays_global.test_a("hello","hi","chello","chi"); + +arrays_global.test_b("1234567","hi"); diff --git a/Examples/test-suite/javascript/char_binary_runme.js b/Examples/test-suite/javascript/char_binary_runme.js new file mode 100644 index 000000000..7cd09bd5c --- /dev/null +++ b/Examples/test-suite/javascript/char_binary_runme.js @@ -0,0 +1,36 @@ +var t = new char_binary.Test(); +if (t.strlen('hile') != 4) { + print(t.strlen('hile')); + throw("bad multi-arg typemap 1"); +} + +if (t.strlen('hil\0') != 4) { + throw("bad multi-arg typemap 2"); +} + +/* + * creating a raw char* + */ +var pc = char_binary.new_pchar(5); +char_binary.pchar_setitem(pc, 0, 'h'); +char_binary.pchar_setitem(pc, 1, 'o'); +char_binary.pchar_setitem(pc, 2, 'l'); +char_binary.pchar_setitem(pc, 3, 'a'); +char_binary.pchar_setitem(pc, 4, 0); + + +if (t.strlen(pc) != 4) { + throw("bad multi-arg typemap (3)"); +} + +char_binary.var_pchar = pc; +if (char_binary.var_pchar != "hola") { + print(char_binary.var_pchar); + throw("bad pointer case (1)"); +} + +char_binary.var_namet = pc; +if (char_binary.var_namet != "hola") { + throw("bad pointer case (2)"); +} +char_binary.delete_pchar(pc); diff --git a/Examples/test-suite/javascript/class_ignore_runme.js b/Examples/test-suite/javascript/class_ignore_runme.js new file mode 100644 index 000000000..00bb2591e --- /dev/null +++ b/Examples/test-suite/javascript/class_ignore_runme.js @@ -0,0 +1,5 @@ + +a = new class_ignore.Bar(); + +if (class_ignore.do_blah(a) != "Bar::blah") + throw "Error"; diff --git a/Examples/test-suite/javascript/class_scope_weird_runme.js b/Examples/test-suite/javascript/class_scope_weird_runme.js new file mode 100644 index 000000000..c442cc7f6 --- /dev/null +++ b/Examples/test-suite/javascript/class_scope_weird_runme.js @@ -0,0 +1,5 @@ + +f = new class_scope_weird.Foo(); +g = new class_scope_weird.Foo(3); +if (f.bar(3) != 3) + throw RuntimeError; diff --git a/Examples/test-suite/javascript/complextest_runme.js b/Examples/test-suite/javascript/complextest_runme.js new file mode 100644 index 000000000..9d3cf4264 --- /dev/null +++ b/Examples/test-suite/javascript/complextest_runme.js @@ -0,0 +1,21 @@ + +a = [-1,2]; + +expected = [-1, -2]; + +a_c = complextest.Conj(a); +if (a_c.toString() != expected.toString()) + throw "Error in Conj(a)"; + +a_c_f = complextest.Conjf(a); +if (a_c_f.toString() != expected.toString()) + throw "Error in Conjf(a)"; + +v = new complextest.VectorStdCplx(); +v.add([1,2]); +v.add([2,3]); +v.add([4,3]); +v.add(1); + +// TODO: how to check validity? +complextest.Copy_h(v); diff --git a/Examples/test-suite/javascript/constover_runme.js b/Examples/test-suite/javascript/constover_runme.js new file mode 100644 index 000000000..f131ef444 --- /dev/null +++ b/Examples/test-suite/javascript/constover_runme.js @@ -0,0 +1,31 @@ +p = constover.test("test"); +if (p != "test") { + throw "test failed!"; +} + +p = constover.test_pconst("test"); +if (p != "test_pconst") { + throw "test_pconst failed!"; +} + +f = new constover.Foo(); + +p = f.test("test"); +if (p != "test") { + throw "member-test failed!"; +} + +p = f.test_pconst("test"); +if (p != "test_pconst") { + throw "member-test_pconst failed!"; +} + +p = f.test_constm("test"); +if (p != "test_constmethod") { + throw "member-test_constm failed!"; +} + +p = f.test_pconstm("test"); +if (p != "test_pconstmethod") { + throw "member-test_pconstm failed!"; +} diff --git a/Examples/test-suite/javascript/cpp_enum_runme.js b/Examples/test-suite/javascript/cpp_enum_runme.js new file mode 100644 index 000000000..f5a9e3595 --- /dev/null +++ b/Examples/test-suite/javascript/cpp_enum_runme.js @@ -0,0 +1,26 @@ +var f = new cpp_enum.Foo() + +if(f.hola != cpp_enum.Hello){ + print(f.hola); + throw "Error"; +} + +f.hola = cpp_enum.Foo.Hi +if(f.hola != cpp_enum.Foo.Hi){ + print(f.hola); + throw "Error"; +} + +f.hola = cpp_enum.Hello + +if(f.hola != cpp_enum.Hello){ + print(f.hola); + throw "Error"; +} + +cpp_enum.Foo.hi = cpp_enum.Hello +if(cpp_enum.Foo.hi != cpp_enum.Hello){ + print(cpp_enum.Foo.hi); + throw "Error"; +} + diff --git a/Examples/test-suite/javascript/cpp_namespace_runme.js b/Examples/test-suite/javascript/cpp_namespace_runme.js new file mode 100644 index 000000000..5795536bd --- /dev/null +++ b/Examples/test-suite/javascript/cpp_namespace_runme.js @@ -0,0 +1,45 @@ +var n = cpp_namespace.fact(4); +if (n != 24){ + throw ("Bad return value error!"); +} +if (cpp_namespace.Foo != 42){ + throw ("Bad variable value error!"); +} + +t = new cpp_namespace.Test(); +if (t.method() != "Test::method"){ + throw ("Bad method return value error!"); +} +if (cpp_namespace.do_method(t) != "Test::method"){ + throw ("Bad return value error!"); +} + +if (cpp_namespace.do_method2(t) != "Test::method"){ + throw ("Bad return value error!"); +} +cpp_namespace.weird("hello", 4); +delete t; + +t2 = new cpp_namespace.Test2(); +t3 = new cpp_namespace.Test3(); +t4 = new cpp_namespace.Test4(); +t5 = new cpp_namespace.Test5(); +if (cpp_namespace.foo3(42) != 42){ + throw ("Bad return value error!"); +} + +if (cpp_namespace.do_method3(t2,40) != "Test2::method"){ + throw ("Bad return value error!"); +} + +if (cpp_namespace.do_method3(t3,40) != "Test3::method"){ + throw ("Bad return value error!"); +} + +if (cpp_namespace.do_method3(t4,40) != "Test4::method"){ + throw ("Bad return value error!"); +} + +if (cpp_namespace.do_method3(t5,40) != "Test5::method"){ + throw ("Bad return value error!"); +} diff --git a/Examples/test-suite/javascript/cpp_static_runme.js b/Examples/test-suite/javascript/cpp_static_runme.js new file mode 100644 index 000000000..0ff28b4ee --- /dev/null +++ b/Examples/test-suite/javascript/cpp_static_runme.js @@ -0,0 +1,7 @@ +cpp_static.StaticFunctionTest.static_func(); +cpp_static.StaticFunctionTest.static_func_2(1); +cpp_static.StaticFunctionTest.static_func_3(1,2); +cpp_static.StaticMemberTest.static_int = 10; +if (cpp_static.StaticMemberTest.static_int != 10) +throw "error"; + diff --git a/Examples/test-suite/javascript/director_alternating_runme.js b/Examples/test-suite/javascript/director_alternating_runme.js new file mode 100644 index 000000000..3c2c883a1 --- /dev/null +++ b/Examples/test-suite/javascript/director_alternating_runme.js @@ -0,0 +1,4 @@ + +id = director_alternating.getBar().id(); +if (id != director_alternating.idFromGetBar()) + throw ("Error, Got wrong id: " + str(id)); diff --git a/Examples/test-suite/javascript/enum_template_runme.js b/Examples/test-suite/javascript/enum_template_runme.js new file mode 100644 index 000000000..54195c78b --- /dev/null +++ b/Examples/test-suite/javascript/enum_template_runme.js @@ -0,0 +1,6 @@ +if (enum_template.MakeETest() != 1) + throw "RuntimeError"; + +if (enum_template.TakeETest(0) != null) + throw "RuntimeError"; + diff --git a/Examples/test-suite/javascript/namespace_virtual_method_runme.js b/Examples/test-suite/javascript/namespace_virtual_method_runme.js new file mode 100644 index 000000000..bb187b993 --- /dev/null +++ b/Examples/test-suite/javascript/namespace_virtual_method_runme.js @@ -0,0 +1,2 @@ + +x = new namespace_virtual_method.Spam(); diff --git a/Examples/test-suite/javascript/overload_copy_runme.js b/Examples/test-suite/javascript/overload_copy_runme.js new file mode 100644 index 000000000..88fab3720 --- /dev/null +++ b/Examples/test-suite/javascript/overload_copy_runme.js @@ -0,0 +1,3 @@ + +f = new overload_copy.Foo(); +g = new overload_copy.Foo(f); diff --git a/Examples/test-suite/javascript/preproc_include_runme.js b/Examples/test-suite/javascript/preproc_include_runme.js new file mode 100644 index 000000000..d52ef97c1 --- /dev/null +++ b/Examples/test-suite/javascript/preproc_include_runme.js @@ -0,0 +1,22 @@ + +if (preproc_include.multiply10(10) != 100) + throw "RuntimeError"; + +if (preproc_include.multiply20(10) != 200) + throw "RuntimeError"; + +if (preproc_include.multiply30(10) != 300) + throw "RuntimeError"; + +if (preproc_include.multiply40(10) != 400) + throw "RuntimeError"; + +if (preproc_include.multiply50(10) != 500) + throw "RuntimeError"; + +if (preproc_include.multiply60(10) != 600) + throw "RuntimeError"; + +if (preproc_include.multiply70(10) != 700) + throw "RuntimeError"; + diff --git a/Examples/test-suite/javascript/preproc_runme.js b/Examples/test-suite/javascript/preproc_runme.js new file mode 100644 index 000000000..b708385da --- /dev/null +++ b/Examples/test-suite/javascript/preproc_runme.js @@ -0,0 +1,13 @@ + +if (preproc.endif != 1) + throw "RuntimeError"; + +if (preproc.define != 1) + throw "RuntimeError"; + +if (preproc.defined != 1) + throw "RuntimeError"; + +if (2*preproc.one != preproc.two) + throw "RuntimeError"; + diff --git a/Examples/test-suite/javascript/ret_by_value_runme.js b/Examples/test-suite/javascript/ret_by_value_runme.js new file mode 100644 index 000000000..720cd398f --- /dev/null +++ b/Examples/test-suite/javascript/ret_by_value_runme.js @@ -0,0 +1,7 @@ + +a = ret_by_value.get_test(); +if (a.myInt != 100) + throw "RuntimeError"; + +if (a.myShort != 200) + throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/struct_value_runme.js b/Examples/test-suite/javascript/struct_value_runme.js new file mode 100644 index 000000000..314551688 --- /dev/null +++ b/Examples/test-suite/javascript/struct_value_runme.js @@ -0,0 +1,10 @@ + +b = new struct_value.Bar(); + +b.a.x = 3; +if (b.a.x != 3) +throw "RuntimeError"; + +b.b.x = 3; +if (b.b.x != 3) +throw "RuntimeError" diff --git a/Examples/test-suite/javascript/template_static_runme.js b/Examples/test-suite/javascript/template_static_runme.js new file mode 100644 index 000000000..338e2c55c --- /dev/null +++ b/Examples/test-suite/javascript/template_static_runme.js @@ -0,0 +1,2 @@ + +template_static.Foo.bar_double(1); diff --git a/Examples/test-suite/javascript/typedef_class_runme.js b/Examples/test-suite/javascript/typedef_class_runme.js new file mode 100644 index 000000000..accefb499 --- /dev/null +++ b/Examples/test-suite/javascript/typedef_class_runme.js @@ -0,0 +1,5 @@ +a = new typedef_class.RealA(); +a.a = 3; + +b = new typedef_class.B(); +b.testA(a); diff --git a/Examples/test-suite/javascript/typedef_inherit_runme.js b/Examples/test-suite/javascript/typedef_inherit_runme.js new file mode 100644 index 000000000..f16c1787e --- /dev/null +++ b/Examples/test-suite/javascript/typedef_inherit_runme.js @@ -0,0 +1,22 @@ + +a = new typedef_inherit.Foo(); +b = new typedef_inherit.Bar(); + +x = typedef_inherit.do_blah(a); +if (x != "Foo::blah") + print("Whoa! Bad return" + x); + +x = typedef_inherit.do_blah(b); +if (x != "Bar::blah") + print("Whoa! Bad return" + x); + +c = new typedef_inherit.Spam(); +d = new typedef_inherit.Grok(); + +x = typedef_inherit.do_blah2(c); +if (x != "Spam::blah") + print("Whoa! Bad return" + x); + +x = typedef_inherit.do_blah2(d); +if (x != "Grok::blah") + print ("Whoa! Bad return" + x); diff --git a/Examples/test-suite/javascript/typedef_scope_runme.js b/Examples/test-suite/javascript/typedef_scope_runme.js new file mode 100644 index 000000000..8a08ffb9b --- /dev/null +++ b/Examples/test-suite/javascript/typedef_scope_runme.js @@ -0,0 +1,11 @@ + +b = new typedef_scope.Bar(); +x = b.test1(42,"hello"); +if (x != 42) + print("Failed!!"); + +x = b.test2(42,"hello"); +if (x != "hello") + print("Failed!!"); + + diff --git a/Examples/test-suite/javascript/typemap_arrays_runme.js b/Examples/test-suite/javascript/typemap_arrays_runme.js new file mode 100644 index 000000000..2126ed15f --- /dev/null +++ b/Examples/test-suite/javascript/typemap_arrays_runme.js @@ -0,0 +1,4 @@ + +if (typemap_arrays.sumA(null) != 60) + throw "RuntimeError, Sum is wrong"; + diff --git a/Examples/test-suite/javascript/typemap_delete_runme.js b/Examples/test-suite/javascript/typemap_delete_runme.js new file mode 100644 index 000000000..d58684df4 --- /dev/null +++ b/Examples/test-suite/javascript/typemap_delete_runme.js @@ -0,0 +1,4 @@ + +r = new typemap_delete.Rect(123); +if (r.val != 123) + throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/typemap_namespace_runme.js b/Examples/test-suite/javascript/typemap_namespace_runme.js new file mode 100644 index 000000000..d679f3b0b --- /dev/null +++ b/Examples/test-suite/javascript/typemap_namespace_runme.js @@ -0,0 +1,6 @@ + +if (typemap_namespace.test1("hello") != "hello") + throw "RuntimeError"; + +if (typemap_namespace.test2("hello") != "hello") + throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/typemap_ns_using_runme.js b/Examples/test-suite/javascript/typemap_ns_using_runme.js new file mode 100644 index 000000000..d05f7f0c1 --- /dev/null +++ b/Examples/test-suite/javascript/typemap_ns_using_runme.js @@ -0,0 +1,3 @@ + +if (typemap_ns_using.spam(37) != 37) + throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/using1_runme.js b/Examples/test-suite/javascript/using1_runme.js new file mode 100644 index 000000000..cb54a62fa --- /dev/null +++ b/Examples/test-suite/javascript/using1_runme.js @@ -0,0 +1,4 @@ + + +if (using1.spam(37) != 37) + throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/using2_runme.js b/Examples/test-suite/javascript/using2_runme.js new file mode 100644 index 000000000..948f58ead --- /dev/null +++ b/Examples/test-suite/javascript/using2_runme.js @@ -0,0 +1,3 @@ + +if (using2.spam(37) != 37) + throw "RuntimeError"; diff --git a/Lib/javascript/jsc/ccomplex.i b/Lib/javascript/jsc/ccomplex.i new file mode 100644 index 000000000..8eda920bb --- /dev/null +++ b/Lib/javascript/jsc/ccomplex.i @@ -0,0 +1,26 @@ +/* ----------------------------------------------------------------------------- + * ccomplex.i + * + * C complex typemaps + * ISO C99: 7.3 Complex arithmetic + * ----------------------------------------------------------------------------- */ + + +%include + +%{ +#include +%} + + +/* C complex constructor */ +#define CCplxConst(r, i) ((r) + I*(i)) + +%swig_cplxflt_convn(float complex, CCplxConst, creal, cimag); +%swig_cplxdbl_convn(double complex, CCplxConst, creal, cimag); +%swig_cplxdbl_convn(complex, CCplxConst, creal, cimag); + +/* declaring the typemaps */ +%typemaps_primitive(SWIG_TYPECHECK_CPLXFLT, float complex); +%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, double complex); +%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, complex); diff --git a/Lib/javascript/jsc/complex.i b/Lib/javascript/jsc/complex.i new file mode 100644 index 000000000..4c3b3c5e2 --- /dev/null +++ b/Lib/javascript/jsc/complex.i @@ -0,0 +1,6 @@ +#ifdef __cplusplus +%include +#else +%include +#endif + diff --git a/Lib/javascript/jsc/javascript.swg b/Lib/javascript/jsc/javascript.swg new file mode 100644 index 000000000..3a83b6495 --- /dev/null +++ b/Lib/javascript/jsc/javascript.swg @@ -0,0 +1,19 @@ +/* ----------------------------------------------------------------------------- + * javascript.swg + * + * Javascript typemaps + * ----------------------------------------------------------------------------- */ + +%include + +%include + +%include + +%include + +%include + +%include + +%include diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg new file mode 100644 index 000000000..dfa51e143 --- /dev/null +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -0,0 +1,292 @@ +/********************************************************************* + *getproperty: This template gives name to generated wrapper for the getproperty + *{LOCALS}: declarations for input arguments + *{CODE}: contains input marshalling, and the action +*********************************************************************/ + +%fragment ("JS_getproperty", "templates") +%{ +JSValueRef ${getname}(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + ${LOCALS} + ${CODE} + return jsresult; + + goto fail; + fail: + return NULL; +} +%} + +/********************************************************************** + *setproperty: This template gives name to generated wrapper for the setproperty + *{LOCALS}: declarations for input arguments + *{CODE}: contains input marshalling, and the action +**********************************************************************/ + +%fragment ("JS_setproperty", "templates") +%{ +bool ${setname}(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + ${LOCALS} + ${CODE} + + return true; + + goto fail; + fail: + return false; +} +%} + +/************************************************************************************ + *functionwrapper: This template gives name to generated wrapper for the function + *{LOCALS}: declarations for input arguments + *{CODE} contains input marshalling, and the action +************************************************************************************/ +%fragment ("JS_functionwrapper", "templates") +%{ +JSValueRef ${functionname}(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + ${LOCALS} + ${CODE} + return jsresult; + + goto fail; + fail: + return NULL; +} +%} + +/************************************************************************************** +function_dispatch_case: This template is used for the function which is overloaded +***************************************************************************************/ + +%fragment ("JS_function_dispatch_case", "templates") +%{if(argc == ${argcount}) { + jsresult = ${functionwrapper}(context, function, thisObject, argc, argv, exception); + } else %} + +%fragment ("JS_function_dispatch_case_default", "templates") +%{ + { + // TODO: throw JS exception + throw "Invalid function arguments."; + } +%} + +/* Added template for function declaration */ + +%fragment ("JS_variabledecl", "templates") +%{{"${propertyname}",${getname}, ${setname},kJSPropertyAttributeNone},%} + + +/* Added template for function declaration */ + +%fragment ("JS_functiondecl", "templates") +%{{"${functionname}",${functionwrapper}, kJSPropertyAttributeNone},%} + +%fragment ("JS_globaldefn", "templates") +%{ +JSStaticValue ${namespace}_values[] = { + ${jsglobalvariables} + { 0, 0, 0, 0 } +}; + +JSStaticFunction ${namespace}_functions[] = { + ${jsglobalfunctions} + { 0, 0, 0 } +}; + +JSClassDefinition ${namespace}_classDefinition; +%} + +/****************************************************************************************** + * class_definition: + * This code template is used for wrapper of classes definition. + * ${classname_mangled}:the mangled name of the qualified class name, e.g., foo::A -> foo_A + *****************************************************************************************/ + +%fragment ("JS_class_definition", "templates") +%{ +JSClassDefinition ${classname_mangled}_classDefinition; + +JSClassDefinition ${classname_mangled}_objectDefinition; + +JSClassRef ${classname_mangled}_classRef; +%} + +/********************************************************************* + * class_table: + * This code template is used to add the wrapper for class declaration + * ${classname_mangled}: The mangled name of the qualified class name, e.g., foo::A -> foo_A +***********************************************************************/ + +%fragment ("JS_class_tables", "templates") +%{ +JSStaticValue ${classname_mangled}_staticValues[] = { + ${jsstaticclassvariables} + { 0, 0, 0, 0 } +}; + +JSStaticFunction ${classname_mangled}_staticFunctions[] = { + ${jsstaticclassfunctions} + { 0, 0, 0 } +}; + +JSStaticValue ${classname_mangled}_values[] = { + ${jsclassvariables} + { 0, 0, 0, 0 } +}; + +JSStaticFunction ${classname_mangled}_functions[] = { + ${jsclassfunctions} + { 0, 0, 0 } +}; +%} + +/********************************************************************* + * destructordefn: + * This code template is used to adds the destructor wrapper function + * ${classname_mangled}: The mangled name of the qualified class name, e.g., foo::A -> foo_A +***********************************************************************/ + +%fragment ("JS_destructordefn", "templates") +%{ +void _wrap_${classname_mangled}_finalize(JSObjectRef thisObject) +{ + SWIG_PRV_DATA* t = (SWIG_PRV_DATA*)JSObjectGetPrivate(thisObject); + if(t && t->swigCMemOwn) free ((${type}*)t->swigCObject); + if(t) free(t); +} +%} + +/********************************************************************* + * constructor_definition: + * This code template is used to adds the main constructor wrapper function + * ${classname_mangled}: The mangled name of the qualified class name, e.g., foo::A -> foo_A +***********************************************************************/ + + +%fragment ("JS_mainctordefn", "templates") +%{ +JSObjectRef _wrap_create_${classname_mangled}(JSContextRef context, JSObjectRef ctorObject, + size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + JSObjectRef thisObject; + + ${DISPATCH_CASES} + { + // TODO: handle illegal arguments + SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for contruction of ${classname_mangled}"); + } + + return thisObject; + + fail: + return NULL; +} +%} + +/************************************************************************************** +ctor_dispatch_case: This template is used for the constructor which is overloaded +***************************************************************************************/ + +%fragment ("JS_ctor_dispatch_case", "templates") +%{if(argc == ${argcount}) { + thisObject = _wrap_create_${classname_mangled}${overloadext}(context, NULL, argc, argv, exception); + } else %} + + +%fragment ("JS_ctordefn", "templates") +%{ +JSObjectRef _wrap_create_${classname_mangled}${overloadext}(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + ${LOCALS} + ${CODE} + + return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_${type_mangled}, SWIG_POINTER_OWN); + + goto fail; + fail: + return NULL; +} +%} +/********************************************************************** +initializer:This template is dynamic growing and aggregates everything +**********************************************************************/ + +%fragment ("JS_initializer", "templates") %{ +#ifdef __cplusplus +extern "C" { +#endif + +bool ${modulename}_initialize(JSGlobalContextRef context) { + SWIG_InitializeModule(0); + + JSObjectRef global_object = JSContextGetGlobalObject(context); + + /* Initialize the base swig type object */ + _SwigObject_objectDefinition.staticFunctions = _SwigObject_functions; + _SwigObject_objectDefinition.staticValues = _SwigObject_values; + _SwigObject_classRef = JSClassCreate(&_SwigObject_objectDefinition); + + /* Create objects for namespaces */ + ${create_namespaces} + + /* Create classes */ + ${initializercode} + + /* Register namespaces */ + ${register_namespaces} + + return true; +} + +#ifdef __cplusplus +} +#endif + +%} + +/***************************************************************************************** + *create_class_template: + *This template is used to add a Static references to class templates. + *${classname_mangled}: The mangled name of the qualified class name, e.g., foo::A -> foo_A +*****************************************************************************************/ + +%fragment ("JS_create_class_template", "templates") +%{ ${classname_mangled}_classDefinition.staticFunctions = ${classname_mangled}_staticFunctions; + ${classname_mangled}_classDefinition.staticValues = ${classname_mangled}_staticValues; + ${classname_mangled}_classDefinition.callAsConstructor = _wrap_create_${classname_mangled}; + ${classname_mangled}_objectDefinition.staticValues = ${classname_mangled}_values; + ${classname_mangled}_objectDefinition.staticFunctions = ${classname_mangled}_functions; + ${classname_mangled}_objectDefinition.parentClass = ${base_classname}_classRef; + JSClassRef ${classname_mangled}_classRef = JSClassCreate(&${classname_mangled}_objectDefinition); + SWIGTYPE_${classtype_mangled}->clientdata = ${classname_mangled}_classRef;%} + +/***************************************************************************************** + *register_class: + *This template is used to adds a class registration statement to initializer function + *${classname_mangled}: The mangled name of the qualified class name, e.g., foo::A -> foo_A +*****************************************************************************************/ + +%fragment ("JS_register_class", "templates") +%{JS_registerClass(context, ${namespace_mangled}_object, "${classname}", &${classname_mangled}_classDefinition);%} + +/* register global function */ +%fragment ("JS_register_global_function", "templates") +%{JS_registerFunction(${context}, ${context_object}, "${functionname}", ${functionwrapper});%} + + +/* create and register namespaces */ + +%fragment ("JS_create_namespace", "templates") +%{ ${namespace}_classDefinition.staticFunctions = ${namespace}_functions; + ${namespace}_classDefinition.staticValues = ${namespace}_values; + JSObjectRef ${namespace}_object = JSObjectMake(context, JSClassCreate(&${namespace}_classDefinition), NULL); +%} + +%fragment ("JS_register_namespace", "templates") +%{ +JS_registerNamespace(context, ${namespace_mangled}_object, ${parent_namespace}_object, "${namespace}"); %} diff --git a/Lib/javascript/jsc/javascriptcomplex.swg b/Lib/javascript/jsc/javascriptcomplex.swg new file mode 100644 index 000000000..7d165dce4 --- /dev/null +++ b/Lib/javascript/jsc/javascriptcomplex.swg @@ -0,0 +1,146 @@ +/* + Defines the As/From converters for double/float complex, you need to + provide complex Type, the Name you want to use in the converters, + the complex Constructor method, and the Real and Imag complex + accessor methods. + + See the std_complex.i and ccomplex.i for concret examples. +*/ + +/* the common from converter */ +%define %swig_fromcplx_conv(Type, Real, Imag) +%fragment(SWIG_From_frag(Type),"header", + fragment=SWIG_From_frag(double)) +{ +SWIGINTERNINLINE JSObjectRef +SWIG_From_dec(Type)(%ifcplusplus(const Type&, Type) c) +{ + JSValueRef vals[2]; + vals[0] = SWIG_From(double)(Real(c)); + vals[1] = SWIG_From(double)(Imag(c)); + return JSObjectMakeArray(context, 2, vals, NULL); +} +} +%enddef + +/* the double case */ +%define %swig_cplxdbl_conv(Type, Constructor, Real, Imag) +%fragment(SWIG_AsVal_frag(Type),"header", + fragment=SWIG_AsVal_frag(double)) +{ +SWIGINTERN int +SWIG_AsVal_dec(Type) (JSValueRef o, Type* val) +{ + if (JSValueIsObject(context, o)) { + JSObjectRef array; + JSValueRef exception, js_re, js_im; + double re, im; + int res; + + exception = 0; + res = 0; + + array = JSValueToObject(context, o, &exception); + if(exception != 0) + return SWIG_TypeError; + + js_re = JSObjectGetPropertyAtIndex(context, array, 0, &exception); + if(exception != 0) + return SWIG_TypeError; + + js_im = JSObjectGetPropertyAtIndex(context, array, 1, &exception); + if(exception != 0) + return SWIG_TypeError; + + res = SWIG_AsVal(double)(js_re, &re); + if(!SWIG_IsOK(res)) { + return SWIG_TypeError; + } + + res = SWIG_AsVal(double)(js_im, &im); + if(!SWIG_IsOK(res)) { + return SWIG_TypeError; + } + + if (val) *val = Constructor(re, im); + return SWIG_OK; + } else { + double d; + int res = SWIG_AddCast(SWIG_AsVal(double)(o, &d)); + if (SWIG_IsOK(res)) { + if (val) *val = Constructor(d, 0.0); + return res; + } + } + return SWIG_TypeError; +} +} +%swig_fromcplx_conv(Type, Real, Imag); +%enddef + +/* the float case */ +%define %swig_cplxflt_conv(Type, Constructor, Real, Imag) +%fragment(SWIG_AsVal_frag(Type),"header", + fragment=SWIG_AsVal_frag(float)) { +SWIGINTERN int +SWIG_AsVal_dec(Type)(JSValueRef o, Type *val) +{ + if (JSValueIsObject(context, o)) { + JSObjectRef array; + JSValueRef exception, js_re, js_im; + double re, im; + int res; + + exception = 0; + res = 0; + + array = JSValueToObject(context, o, &exception); + if(exception != 0) + return SWIG_TypeError; + + js_re = JSObjectGetPropertyAtIndex(context, array, 0, &exception); + if(exception != 0) + return SWIG_TypeError; + + js_im = JSObjectGetPropertyAtIndex(context, array, 1, &exception); + if(exception != 0) + return SWIG_TypeError; + + res = SWIG_AsVal(double)(js_re, &re); + if(!SWIG_IsOK(res)) { + return SWIG_TypeError; + } + + res = SWIG_AsVal(double)(js_im, &im); + if(!SWIG_IsOK(res)) { + return SWIG_TypeError; + } + + if ((-FLT_MAX <= re && re <= FLT_MAX) && (-FLT_MAX <= im && im <= FLT_MAX)) { + if (val) *val = Constructor(%numeric_cast(re, float), + %numeric_cast(im, float)); + return SWIG_OK; + } else { + return SWIG_OverflowError; + } + } else { + float re; + int res = SWIG_AddCast(SWIG_AsVal(float)(o, &re)); + if (SWIG_IsOK(res)) { + if (val) *val = Constructor(re, 0.0); + return res; + } + } + return SWIG_TypeError; +} +} + +%swig_fromcplx_conv(Type, Real, Imag); +%enddef + +#define %swig_cplxflt_convn(Type, Constructor, Real, Imag) \ +%swig_cplxflt_conv(Type, Constructor, Real, Imag) + + +#define %swig_cplxdbl_convn(Type, Constructor, Real, Imag) \ +%swig_cplxdbl_conv(Type, Constructor, Real, Imag) diff --git a/Lib/javascript/jsc/javascriptfragments.swg b/Lib/javascript/jsc/javascriptfragments.swg new file mode 100644 index 000000000..e69de29bb diff --git a/Lib/javascript/jsc/javascripthelpers.swg b/Lib/javascript/jsc/javascripthelpers.swg new file mode 100644 index 000000000..820075ca6 --- /dev/null +++ b/Lib/javascript/jsc/javascripthelpers.swg @@ -0,0 +1,69 @@ +%insert(wrapper) %{ + +bool JS_registerClass(JSGlobalContextRef context, JSObjectRef parentObject, + const char* className, + JSClassDefinition* definition) { + + JSStringRef js_className = JSStringCreateWithUTF8CString(className); + JSObjectRef classObject = JSObjectMake(context, JSClassCreate(definition), NULL); + JSObjectSetProperty(context, parentObject, + js_className, classObject, + kJSPropertyAttributeNone, NULL); + JSStringRelease(js_className); + + return true; +} + +bool JS_registerNamespace(JSGlobalContextRef context, + JSObjectRef namespaceObj, JSObjectRef parentNamespace, + const char* name) +{ + JSStringRef js_name = JSStringCreateWithUTF8CString(name); + JSObjectSetProperty(context, parentNamespace, + js_name, namespaceObj, + kJSPropertyAttributeNone, NULL); + JSStringRelease(js_name); + + return true; +} + + +bool JS_registerFunction(JSGlobalContextRef context, JSObjectRef object, + const char* functionName, JSObjectCallAsFunctionCallback callback) +{ + JSStringRef js_functionName = JSStringCreateWithUTF8CString(functionName); + JSObjectSetProperty(context, object, js_functionName, + JSObjectMakeFunctionWithCallback(context, js_functionName, callback), + kJSPropertyAttributeNone, NULL); + JSStringRelease(js_functionName); + return true; +} + +bool JS_veto_set_variable(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + char buffer[256]; + char msg[512]; + int res; + + JSStringGetUTF8CString(propertyName, buffer, 256); + res = sprintf(msg, "Tried to write read-only variable: %s.", buffer); + + if(res<0) { + SWIG_exception(SWIG_ERROR, "Tried to write read-only variable."); + } else { + SWIG_exception(SWIG_ERROR, msg); + } + + return false; +} + +JSValueRef JS_CharPtrToJSValue(JSContextRef context, char* cstr) { + JSValueRef val; + + JSStringRef jsstring = JSStringCreateWithUTF8CString((char*) cstr); + val = JSValueMakeString(context, jsstring); + JSStringRelease(jsstring); + + return val; +} +%} diff --git a/Lib/javascript/jsc/javascriptinit.swg b/Lib/javascript/jsc/javascriptinit.swg new file mode 100644 index 000000000..69bc3a9b1 --- /dev/null +++ b/Lib/javascript/jsc/javascriptinit.swg @@ -0,0 +1,15 @@ +%insert(init) %{ +SWIGRUNTIME void +SWIG_JSC_SetModule(swig_module_info *swig_module) {} + +SWIGRUNTIME swig_module_info * +SWIG_JSC_GetModule(void) { + return 0; +} + +#define SWIG_GetModule(clientdata) SWIG_JSC_GetModule() +#define SWIG_SetModule(clientdata, pointer) SWIG_JSC_SetModule(pointer) + +%} + +%insert(init) "swiginit.swg" diff --git a/Lib/javascript/jsc/javascriptkw.swg b/Lib/javascript/jsc/javascriptkw.swg new file mode 100644 index 000000000..c3c118391 --- /dev/null +++ b/Lib/javascript/jsc/javascriptkw.swg @@ -0,0 +1,40 @@ +#ifndef JAVASCRIPT_JAVASCRIPTKW_SWG_ +#define JAVASCRIPT_JAVASCRIPTKW_SWG_ + +/* Warnings for Java keywords */ +#define JAVASCRIPTKW(x) %keywordwarn("'" `x` "' is a javascript keyword, renaming to '_"`x`"'",rename="_%s") `x` + +/* Taken from https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Reserved_Words */ + +JAVASCRIPTKW(break); +JAVASCRIPTKW(case); +JAVASCRIPTKW(catch); +JAVASCRIPTKW(continue); +JAVASCRIPTKW(default); +JAVASCRIPTKW(delete); +JAVASCRIPTKW(do); +JAVASCRIPTKW(else); +JAVASCRIPTKW(finally); +JAVASCRIPTKW(for); +JAVASCRIPTKW(function); +JAVASCRIPTKW(if); +JAVASCRIPTKW(in); +JAVASCRIPTKW(instanceof); +JAVASCRIPTKW(new); +JAVASCRIPTKW(return); +JAVASCRIPTKW(switch); +JAVASCRIPTKW(this); +JAVASCRIPTKW(throw); +JAVASCRIPTKW(try); +JAVASCRIPTKW(typeof); +JAVASCRIPTKW(var); +JAVASCRIPTKW(void); +JAVASCRIPTKW(while); +JAVASCRIPTKW(with); + +/* others bad names if any*/ +// for example %namewarn("321:clone() is a javascript bad method name") *::clone(); + +#undef JAVASCRIPTKW + +#endif //JAVASCRIPT_JAVASCRIPTKW_SWG_ diff --git a/Lib/javascript/jsc/javascriptprimitives.swg b/Lib/javascript/jsc/javascriptprimitives.swg new file mode 100644 index 000000000..f61e83272 --- /dev/null +++ b/Lib/javascript/jsc/javascriptprimitives.swg @@ -0,0 +1,104 @@ +%fragment(SWIG_From_frag(bool),"header") { +SWIGINTERNINLINE +JSValueRef SWIG_From_dec(bool)(bool value) +{ + return JSValueMakeBoolean(context, value); +} +} + +%fragment(SWIG_AsVal_frag(bool),"header", + fragment=SWIG_AsVal_frag(long)) { +SWIGINTERN +int SWIG_AsVal_dec(bool)(JSValueRef obj, bool *val) +{ + if(!JSValueIsBoolean(context, obj)) { + return SWIG_ERROR; + } + if (val) *val = JSValueToBoolean(context, obj); + return SWIG_OK; +} +} + +%fragment(SWIG_From_frag(int),"header") { +SWIGINTERNINLINE JSValueRef + SWIG_From_dec(int)(int value) +{ + return JSValueMakeNumber(context, value); +} +} + +%fragment(SWIG_From_frag(long),"header") { +SWIGINTERNINLINE JSValueRef + SWIG_From_dec(long)(long value) +{ + return JSValueMakeNumber(context, value); +} +} + +%fragment(SWIG_AsVal_frag(long),"header", + fragment="SWIG_CanCastAsInteger") { +SWIGINTERN int +SWIG_AsVal_dec(long)(JSValueRef obj, long* val) +{ + if (!JSValueIsNumber(context, obj)) { + return SWIG_TypeError; + } + if(val) *val = (long) JSValueToNumber(context, obj, NULL); + + return SWIG_OK; +} +} + +/* unsigned long */ + +%fragment(SWIG_From_frag(unsigned long),"header", + fragment=SWIG_From_frag(long)) { +SWIGINTERNINLINE JSValueRef +SWIG_From_dec(unsigned long)(unsigned long value) +{ + return (value > LONG_MAX) ? + JSValueMakeNumber(context, value) : JSValueMakeNumber(context, %numeric_cast(value,long)); +} +} + +%fragment(SWIG_AsVal_frag(unsigned long),"header", + fragment="SWIG_CanCastAsInteger") { +SWIGINTERN int +SWIG_AsVal_dec(unsigned long)(JSValueRef obj, unsigned long *val) +{ + if(!JSValueIsNumber(context, obj)) { + return SWIG_TypeError; + } + + long longVal = (long) JSValueToNumber(context, obj, NULL); + + if(longVal < 0) { + return SWIG_OverflowError; + } + + if(val) *val = longVal; + + return SWIG_OK; +} +} + +%fragment(SWIG_From_frag(double),"header") { +SWIGINTERN JSValueRef +SWIG_From_dec(double) (double val) +{ + return JSValueMakeNumber(context, val); +} +} + +%fragment(SWIG_AsVal_frag(double),"header") { +SWIGINTERN int +SWIG_AsVal_dec(double)(JSValueRef obj, double *val) +{ + if(!JSValueIsNumber(context, obj)) { + return SWIG_TypeError; + } + if(val) *val = JSValueToNumber(context, obj, NULL); + + return SWIG_OK; +} +} diff --git a/Lib/javascript/jsc/javascriptruntime.swg b/Lib/javascript/jsc/javascriptruntime.swg new file mode 100644 index 000000000..1eddf93f1 --- /dev/null +++ b/Lib/javascript/jsc/javascriptruntime.swg @@ -0,0 +1,175 @@ +/* ----------------------------------------------------------------------------- + * javascriptruntime.swg + * + * Javascript support code + * ----------------------------------------------------------------------------- */ + +%insert(runtime) %{ +#include +#include +#include +#include +#include +#include +%} + +%insert(runtime) "swigrun.swg"; /* SWIG API */ +%insert(runtime) "swigerrors.swg"; /* SWIG errors */ + +%insert(runtime) %{ +#define SWIG_Error(code, msg) SWIG_JSC_exception(context, exception, code, msg) +#define SWIG_exception(code, msg) SWIG_JSC_exception(context, exception, code, msg) +#define SWIG_fail goto fail + +#define SWIG_JSC_FROM_DECL_ARGS(arg1) (JSContextRef context, arg1) +#define SWIG_JSC_FROM_CALL_ARGS(arg1) (context, arg1) +#define SWIG_JSC_AS_DECL_ARGS(arg1, arg2) (JSContextRef context, arg1, arg2) +#define SWIG_JSC_AS_CALL_ARGS(arg1, arg2) (context, arg1, arg2) +%} + +%insert(runtime) %{ +typedef struct { + bool swigCMemOwn; + void *swigCObject; + swig_type_info *info; +}SWIG_PRV_DATA; +%} + +%insert(runtime) %{ + +void SWIG_Javascript_Raise(JSContextRef context, JSValueRef *exception, const char* type) { + JSStringRef message = JSStringCreateWithUTF8CString(type); + *exception = JSValueMakeString(context, message); + JSStringRelease(message); +} + +void SWIG_JSC_exception(JSContextRef context, JSValueRef *exception, int code, const char* msg) { + SWIG_Javascript_Raise(context, exception, msg); +} + +%} + +%insert(runtime) %{ + +JSValueRef _wrap_SwigObject_disown(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + JSValueRef jsresult; + + JSObjectRef obj = JSValueToObject(context, thisObject, NULL); + SWIG_PRV_DATA *cdata = (SWIG_PRV_DATA *) JSObjectGetPrivate(obj); + + cdata->swigCMemOwn = false; + + jsresult = JSValueMakeUndefined(context); + return jsresult; +} + +JSValueRef _wrap_SwigObject_getCPtr(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + JSValueRef jsresult; + long result; + + JSObjectRef obj = JSValueToObject(context, thisObject, NULL); + SWIG_PRV_DATA *cdata = (SWIG_PRV_DATA*) JSObjectGetPrivate(obj); + + result = (long) cdata->swigCObject; + jsresult = JSValueMakeNumber(context, result); + + return jsresult; +} + +JSStaticValue _SwigObject_values[] = { + { + 0, 0, 0, 0 + } +}; + +JSStaticFunction _SwigObject_functions[] = { + { + "disown",_wrap_SwigObject_disown, kJSPropertyAttributeNone + },{ + "getCPtr",_wrap_SwigObject_getCPtr, kJSPropertyAttributeNone + }, + { + 0, 0, 0 + } +}; + +JSClassDefinition _SwigObject_objectDefinition; + +JSClassRef _SwigObject_classRef; + +%} + + +%insert(runtime) %{ +int SWIG_JSC_ConvertInstancePtr(JSContextRef context, JSObjectRef objRef, void** ptr, swig_type_info *info, int flags) { + SWIG_PRV_DATA *cdata = (SWIG_PRV_DATA *) JSObjectGetPrivate(objRef); + if(cdata == NULL) { + return SWIG_ERROR; + } + if(cdata->info != info) { + bool type_valid = false; + swig_cast_info *t = info->cast; + while(t != NULL) { + if(t->type == cdata->info) { + type_valid = true; + break; + } + t = t->next; + } + if(!type_valid) { + return SWIG_TypeError; + } + } + + *ptr = cdata->swigCObject; + + if(flags & SWIG_POINTER_DISOWN) { + cdata->swigCMemOwn = false; + } + + return SWIG_OK; +} + +int SWIG_JSC_ConvertPtr(JSContextRef context, JSValueRef valRef, void** ptr, swig_type_info *info, int flags) { + if(!JSValueIsObject(context, valRef)) { + return SWIG_TypeError; + } + + JSObjectRef objRef = JSValueToObject(context, valRef, NULL); + if(objRef == NULL) { + return SWIG_ERROR; + } + + return SWIG_JSC_ConvertInstancePtr(context, objRef, ptr, info, flags); +} + +JSObjectRef SWIG_JSC_NewPointerObj(JSContextRef context, void *ptr, swig_type_info *info, int flags) { + + JSClassRef classRef; + if(info->clientdata == NULL) { + classRef = _SwigObject_classRef; + } else { + classRef = (JSClassRef) info->clientdata; + } + + JSObjectRef result = JSObjectMake(context, classRef, NULL); + + SWIG_PRV_DATA* cdata = (SWIG_PRV_DATA*) malloc(sizeof(SWIG_PRV_DATA)); + cdata->swigCObject = ptr; + cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; + cdata->info = info; + + JSObjectSetPrivate(result, cdata); + + return result; +} + +#define SWIG_ConvertPtr(obj, ptr, info, flags) SWIG_JSC_ConvertPtr(context, obj, ptr, info, flags) +#define SWIG_NewPointerObj(ptr, info, flags) SWIG_JSC_NewPointerObj(context, ptr, info, flags) + +#define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_JSC_ConvertInstancePtr(context, obj, pptr, type, flags) +#define SWIG_NewInstanceObj(thisvalue, type, flags) SWIG_JSC_NewPointerObj(context, thisvalue, type, flags) + +%} diff --git a/Lib/javascript/jsc/javascriptstrings.swg b/Lib/javascript/jsc/javascriptstrings.swg new file mode 100644 index 000000000..f97e84cd0 --- /dev/null +++ b/Lib/javascript/jsc/javascriptstrings.swg @@ -0,0 +1,171 @@ +/* ------------------------------------------------------------ + * utility methods for char strings + * ------------------------------------------------------------ */ +%fragment("SWIG_AsCharPtrAndSize","header",fragment="SWIG_pchar_descriptor") { +SWIGINTERN int +SWIG_JSC_AsCharPtrAndSize(JSContextRef context, JSValueRef valRef, char** cptr, size_t* psize, int *alloc) +{ + if(JSValueIsString(context, valRef)) { + JSStringRef js_str = JSValueToStringCopy(context, valRef, NULL); + size_t len = JSStringGetMaximumUTF8CStringSize(js_str); + size_t abs_len = JSStringGetLength(js_str); + char* cstr = (char*) malloc(len * sizeof(char)); + JSStringGetUTF8CString(js_str, cstr, len); + + if(alloc) *alloc = SWIG_NEWOBJ; + if(psize) *psize = abs_len + 1; + if(cptr) *cptr = cstr; + + return SWIG_OK; + } else { + if(JSValueIsObject(context, valRef)) { + JSObjectRef obj = JSValueToObject(context, valRef, NULL); + // try if the object is a wrapped char[] + swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); + if (pchar_descriptor) { + void* vptr = 0; + if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { + if (cptr) *cptr = (char *) vptr; + if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; + if (alloc) *alloc = SWIG_OLDOBJ; + return SWIG_OK; + } + } + return SWIG_TypeError; + } else { + return SWIG_TypeError; + } + } +} +} + +%fragment("SWIG_FromCharPtrAndSize","header",fragment="SWIG_pchar_descriptor") { +SWIGINTERNINLINE JSValueRef +SWIG_JSC_FromCharPtrAndSize(JSContextRef context, const char* carray, size_t size) +{ + if (carray) { + if (size > INT_MAX) { + // TODO: handle extra long strings + //swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); + //return pchar_descriptor ? + // SWIG_InternalNewPointerObj(%const_cast(carray,char *), pchar_descriptor, 0) : SWIG_Py_Void(); + return JSValueMakeUndefined(context); + } else { + JSStringRef jsstring = JSStringCreateWithUTF8CString(carray); + JSValueRef result = JSValueMakeString(context, jsstring); + JSStringRelease(jsstring); + return result; + } + } else { + return JSValueMakeUndefined(context); + } +} +} + +%define %_typemap2_string(StringCode, CharCode, + Char, CharName, + SWIG_AsCharPtrAndSize, + SWIG_FromCharPtrAndSize, + SWIG_CharPtrLen, + SWIG_NewCopyCharArray, + SWIG_DeleteCharArray, + FragLimits, CHAR_MIN, CHAR_MAX) + +%fragment("SWIG_From"#CharName"Ptr","header",fragment=#SWIG_FromCharPtrAndSize) { +SWIGINTERNINLINE SWIG_Object +SWIG_JSC_From##CharName##Ptr(JSContextRef context, const Char *cptr) +{ + return SWIG_JSC_FromCharPtrAndSize(context, cptr, (cptr ? SWIG_CharPtrLen(cptr) : 0)); +} +} + +%fragment("SWIG_From"#CharName"Array","header",fragment=#SWIG_FromCharPtrAndSize) { +SWIGINTERNINLINE SWIG_Object +SWIG_JSC_From##CharName##Array(JSContextRef context, const Char *cptr, size_t size) +{ + return SWIG_JSC_FromCharPtrAndSize(context, cptr, size); +} +} + +%fragment("SWIG_As" #CharName "Ptr","header",fragment=#SWIG_AsCharPtrAndSize) { +%define_as(SWIG_As##CharName##Ptr(obj, val, alloc), SWIG_JSC_AsCharPtrAndSize(context, obj, val, NULL, alloc)) +} + +%fragment("SWIG_As" #CharName "Array","header",fragment=#SWIG_AsCharPtrAndSize) { +SWIGINTERN int +SWIG_JSC_As##CharName##Array(JSContextRef context, SWIG_Object obj, Char *val, size_t size) +{ + Char* cptr = 0; size_t csize = 0; int alloc = SWIG_OLDOBJ; + int res = SWIG_JSC_AsCharPtrAndSize(context, obj, &cptr, &csize, &alloc); + if (SWIG_IsOK(res)) { + if ((csize == size + 1) && cptr && !(cptr[csize-1])) --csize; + if (csize <= size) { + if (val) { + if (csize) memcpy(val, cptr, csize*sizeof(Char)); + if (csize < size) memset(val + csize, 0, (size - csize)*sizeof(Char)); + } + if (alloc == SWIG_NEWOBJ) { + SWIG_DeleteCharArray(cptr); + res = SWIG_DelNewMask(res); + } + return res; + } + if (alloc == SWIG_NEWOBJ) SWIG_DeleteCharArray(cptr); + } + return SWIG_TypeError; +} + +#define SWIG_As##CharName##Array(obj, val, size) SWIG_JSC_As##CharName##Array(context, obj, val, size) +} + +/* Char */ + +%fragment(SWIG_From_frag(Char),"header",fragment=#SWIG_FromCharPtrAndSize) { +SWIGINTERNINLINE SWIG_Object +SWIG_From_dec(Char)(Char c) +{ + return SWIG_JSC_FromCharPtrAndSize(context, &c,1); +} +} + +%fragment(SWIG_AsVal_frag(Char),"header", + fragment="SWIG_As"#CharName"Array", + fragment=FragLimits, + fragment=SWIG_AsVal_frag(long)) { +SWIGINTERN int +SWIG_AsVal_dec(Char)(SWIG_Object obj, Char *val) +{ + int res = SWIG_As##CharName##Array(obj, val, 1); + if (!SWIG_IsOK(res)) { + long v; + res = SWIG_AddCast(SWIG_AsVal(long)(obj, &v)); + if (SWIG_IsOK(res)) { + if ((CHAR_MIN <= v) && (v <= CHAR_MAX)) { + if (val) *val = %numeric_cast(v, Char); + } else { + res = SWIG_OverflowError; + } + } + } + return res; +} +} + +%_typemap_string(StringCode, + Char, + SWIG_AsCharPtrAndSize, + SWIG_FromCharPtrAndSize, + SWIG_CharPtrLen, + SWIG_As##CharName##Ptr, + SWIG_From##CharName##Ptr, + SWIG_As##CharName##Array, + SWIG_NewCopyCharArray, + SWIG_DeleteCharArray) + +%enddef + +%insert(runtime) %{ +#define SWIG_AsCharPtrAndSize(val, cptr, psize, alloc) SWIG_JSC_AsCharPtrAndSize(context, val, cptr, psize, alloc) +#define SWIG_FromCharPtrAndSize(cptr, size) SWIG_JSC_FromCharPtrAndSize(context, cptr, size) +#define SWIG_FromCharPtr(cptr) SWIG_JSC_FromCharPtr(context, cptr) +%} diff --git a/Lib/javascript/jsc/javascripttypemaps.swg b/Lib/javascript/jsc/javascripttypemaps.swg new file mode 100644 index 000000000..e8711cfc5 --- /dev/null +++ b/Lib/javascript/jsc/javascripttypemaps.swg @@ -0,0 +1,26 @@ + +#define SWIG_FROM_DECL_ARGS SWIG_JSC_FROM_DECL_ARGS +#define SWIG_FROM_CALL_ARGS SWIG_JSC_FROM_CALL_ARGS +#define SWIG_AS_DECL_ARGS SWIG_JSC_AS_DECL_ARGS +#define SWIG_AS_CALL_ARGS SWIG_JSC_AS_CALL_ARGS +#define SWIG_Object JSValueRef +#define VOID_Object JSValueMakeUndefined(context) +#define SWIG_AppendOutput(result, obj) +#define SWIG_SetConstant(name, obj) +#define SWIG_Raise(obj, type, desc) SWIG_Javascript_Raise(context, exception, type) + +%include + +/* Include fundamental fragemt definitions */ +%include + +/* Python fragments for fundamental types */ +%include + +/* override some of the macros in global valtypes.swg */ +%include + +%include + +/* Include the unified typemap library */ +%include diff --git a/Lib/javascript/jsc/javascriptvaltypes.swg b/Lib/javascript/jsc/javascriptvaltypes.swg new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/Lib/javascript/jsc/javascriptvaltypes.swg @@ -0,0 +1 @@ + diff --git a/Lib/javascript/jsc/std_common.i b/Lib/javascript/jsc/std_common.i new file mode 100755 index 000000000..cee11e8ca --- /dev/null +++ b/Lib/javascript/jsc/std_common.i @@ -0,0 +1,5 @@ +%include + +%apply size_t { std::size_t }; +%apply const size_t& { const std::size_t& }; + diff --git a/Lib/javascript/jsc/std_complex.i b/Lib/javascript/jsc/std_complex.i new file mode 100644 index 000000000..088a4fe7b --- /dev/null +++ b/Lib/javascript/jsc/std_complex.i @@ -0,0 +1,19 @@ +/* + * STD C++ complex typemaps + */ + +%include + +%{ +#include +%} + +/* defining the complex as/from converters */ + +%swig_cplxdbl_convn(std::complex, std::complex, std::real, std::imag) +%swig_cplxflt_convn(std::complex, std::complex, std::real, std::imag) + +/* defining the typemaps */ + +%typemaps_primitive(%checkcode(CPLXDBL), std::complex); +%typemaps_primitive(%checkcode(CPLXFLT), std::complex); diff --git a/Lib/javascript/jsc/std_except.i b/Lib/javascript/jsc/std_except.i new file mode 100644 index 000000000..af98428f6 --- /dev/null +++ b/Lib/javascript/jsc/std_except.i @@ -0,0 +1 @@ +%include diff --git a/Lib/javascript/jsc/std_map.i b/Lib/javascript/jsc/std_map.i new file mode 100755 index 000000000..e7812f38a --- /dev/null +++ b/Lib/javascript/jsc/std_map.i @@ -0,0 +1,74 @@ +/* ----------------------------------------------------------------------------- + * std_map.i + * + * SWIG typemaps for std::map + * ----------------------------------------------------------------------------- */ + +%include + +// ------------------------------------------------------------------------ +// std::map +// ------------------------------------------------------------------------ + +%{ +#include +#include +#include +%} + +// exported class + +namespace std { + + template class map { + // add typemaps here + public: + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef K key_type; + typedef T mapped_type; + map(); + map(const map &); + + unsigned int size() const; + bool empty() const; + void clear(); + %extend { + const T& get(const K& key) throw (std::out_of_range) { + std::map::iterator i = self->find(key); + if (i != self->end()) + return i->second; + else + throw std::out_of_range("key not found"); + } + void set(const K& key, const T& x) { + (*self)[key] = x; + } + void del(const K& key) throw (std::out_of_range) { + std::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 K& key) { + std::map::iterator i = self->find(key); + return i != self->end(); + } + } + }; + +// Legacy macros (deprecated) +%define specialize_std_map_on_key(K,CHECK,CONVERT_FROM,CONVERT_TO) +#warning "specialize_std_map_on_key ignored - macro is deprecated and no longer necessary" +%enddef + +%define specialize_std_map_on_value(T,CHECK,CONVERT_FROM,CONVERT_TO) +#warning "specialize_std_map_on_value ignored - macro is deprecated and no longer necessary" +%enddef + +%define specialize_std_map_on_both(K,CHECK_K,CONVERT_K_FROM,CONVERT_K_TO, T,CHECK_T,CONVERT_T_FROM,CONVERT_T_TO) +#warning "specialize_std_map_on_both ignored - macro is deprecated and no longer necessary" +%enddef + +} diff --git a/Lib/javascript/jsc/std_pair.i b/Lib/javascript/jsc/std_pair.i new file mode 100755 index 000000000..fe45ee676 --- /dev/null +++ b/Lib/javascript/jsc/std_pair.i @@ -0,0 +1,34 @@ +/* ----------------------------------------------------------------------------- + * std_pair.i + * + * SWIG typemaps for std::pair + * ----------------------------------------------------------------------------- */ + +%include +%include + +// ------------------------------------------------------------------------ +// std::pair +// ------------------------------------------------------------------------ + +%{ +#include +%} + +namespace std { + + template struct pair { + + pair(); + pair(T first, U second); + pair(const pair& p); + + template pair(const pair &p); + + T first; + U second; + }; + + // add specializations here + +} diff --git a/Lib/javascript/jsc/std_string.i b/Lib/javascript/jsc/std_string.i new file mode 100755 index 000000000..9fbee75ef --- /dev/null +++ b/Lib/javascript/jsc/std_string.i @@ -0,0 +1,71 @@ +/* ----------------------------------------------------------------------------- + * std_string.i + * + * Typemaps for std::string and const std::string& + * These are mapped to a JSCore String and are passed around by value. + * + * To use non-const std::string references use the following %apply. Note + * that they are passed by value. + * %apply const std::string & {std::string &}; + * ----------------------------------------------------------------------------- */ + +%{ +#include +%} + +namespace std { + +%naturalvar string; + +class string; + +// string + +%typemap(in) string +%{ if (!$input) { + // TODO: Throw exception? + return NULL; + } + JSStringRef $1_str = JSValueToStringCopy(context, $input, NULL); + size_t $1_strsize = JSStringGetMaximumUTF8CStringSize($1_str); + char* $1_cstr = (char *)malloc($1_strsize * sizeof(char)); + JSStringGetUTF8CString($1_str, $1_cstr, $1_strsize); + $1 = std::string($1_cstr); +%} + +%typemap(out) string %{ + JSStringRef jsstring = JSStringCreateWithUTF8CString($1.c_str()); + $result = JSValueMakeString(context, jsstring); + JSStringRelease(jsstring); +%} + +%typemap(freearg) string //TODO: Not working: A memory leak +%{ free($1_cstr); %} + +//%typemap(typecheck) string = char *; + +// const string & +%typemap(in) const string & +%{ if (!$input) { + // TODO: Throw exception? + return NULL; + } + JSStringRef $1_str = JSValueToStringCopy(context, $input, NULL); + size_t $1_strsize = JSStringGetMaximumUTF8CStringSize($1_str); + char* $1_cstr = (char *)malloc($1_strsize * sizeof(char)); + JSStringGetUTF8CString($1_str, $1_cstr, $1_strsize); + $1 = new std::string($1_cstr); +%} + +%typemap(out) const string & %{ + JSStringRef jsstring = JSStringCreateWithUTF8CString($1.c_str()); + $result = JSValueMakeString(context, jsstring); + JSStringRelease(jsstring); +%} + +%typemap(freearg) const string & //TODO: Not working: A memory leak +%{ free($1_cstr); %} + +//%typemap(typecheck) const string & = char *; + +} diff --git a/Lib/javascript/jsc/std_vector.i b/Lib/javascript/jsc/std_vector.i new file mode 100755 index 000000000..3f29b19c7 --- /dev/null +++ b/Lib/javascript/jsc/std_vector.i @@ -0,0 +1,85 @@ +/* ----------------------------------------------------------------------------- + * std_vector.i + * ----------------------------------------------------------------------------- */ + +%include + +%{ +#include +#include +%} + +namespace std { + + template class vector { + public: + typedef size_t size_type; + typedef T value_type; + typedef const value_type& const_reference; + vector(); + vector(size_type n); + size_type size() const; + size_type capacity() const; + void reserve(size_type n); + %rename(isEmpty) empty; + bool empty() const; + void clear(); + %rename(add) push_back; + void push_back(const value_type& x); + %extend { + const_reference get(int i) throw (std::out_of_range) { + int size = int(self->size()); + if (i>=0 && isize()); + if (i>=0 && i class vector { + public: + typedef size_t size_type; + typedef bool value_type; + typedef bool const_reference; + vector(); + vector(size_type n); + size_type size() const; + size_type capacity() const; + void reserve(size_type n); + %rename(isEmpty) empty; + bool empty() const; + void clear(); + %rename(add) push_back; + void push_back(const value_type& x); + %extend { + const_reference get(int i) throw (std::out_of_range) { + int size = int(self->size()); + if (i>=0 && isize()); + if (i>=0 && i +%include +%include +%include +%include + diff --git a/Lib/typemaps/strings.swg b/Lib/typemaps/strings.swg index 55e9d2bb5..eea913b60 100644 --- a/Lib/typemaps/strings.swg +++ b/Lib/typemaps/strings.swg @@ -493,7 +493,7 @@ * --- String fragment methods --- * ------------------------------------------------------------ */ - +#ifndef %_typemap2_string %define %_typemap2_string(StringCode, CharCode, Char, CharName, SWIG_AsCharPtrAndSize, @@ -593,7 +593,7 @@ SWIG_AsVal_dec(Char)(SWIG_Object obj, Char *val) SWIG_DeleteCharArray) %enddef - +#endif /* ------------------------------------------------------------ * String typemaps and fragments, with default allocators diff --git a/Makefile.in b/Makefile.in index 644275773..adc971455 100644 --- a/Makefile.in +++ b/Makefile.in @@ -77,6 +77,7 @@ skip-uffi = test -n "@SKIP_UFFI@" skip-r = test -n "@SKIP_R@" skip-go = test -n "@SKIP_GO@" skip-d = test -n "@SKIP_D@" +skip-javascript = test -n "@SKIP_JAVASCRIPT@" # Additional dependencies for some tests skip-gcj = test -n "@SKIP_GCJ@" @@ -119,6 +120,7 @@ check-aliveness: @$(skip-r) || ./$(TARGET) -r -help @$(skip-go) || ./$(TARGET) -go -help @$(skip-d) || ./$(TARGET) -d -help + @$(skip-javascript)|| ./$(TARGET) -d -help check-ccache: test -z "$(ENABLE_CCACHE)" || (cd $(CCACHE) && $(MAKE) check) @@ -147,7 +149,8 @@ check-examples: \ check-cffi-examples \ check-r-examples \ check-go-examples \ - check-d-examples + check-d-examples \ + check-javascript-examples tcl_examples :=$(shell sed '/^\#/d' $(srcdir)/Examples/tcl/check.list) perl5_examples :=$(shell sed '/^\#/d' $(srcdir)/Examples/perl5/check.list) @@ -172,6 +175,7 @@ cffi_examples := r_examples :=$(shell sed '/^\#/d' $(srcdir)/Examples/r/check.list) go_examples :=$(shell sed '/^\#/d' $(srcdir)/Examples/go/check.list) d_examples :=$(shell sed '/^\#/d' $(srcdir)/Examples/d/check.list) +javascript_examples:= # all examples check-%-examples : @@ -225,7 +229,8 @@ check-test-suite: \ check-chicken-test-suite \ check-r-test-suite \ check-go-test-suite \ - check-d-test-suite + check-d-test-suite \ + check-javascript-test-suite check-%-test-suite: @if test -z "$(skip-$*)"; then \ @@ -278,7 +283,8 @@ all-test-suite: \ all-chicken-test-suite \ all-r-test-suite \ all-go-test-suite \ - all-d-test-suite + all-d-test-suite \ + all-javascript-test-suite all-%-test-suite: @$(MAKE) -k -s check-$*-test-suite ACTION=all @@ -307,7 +313,8 @@ broken-test-suite: \ broken-chicken-test-suite \ broken-r-test-suite \ broken-go-test-suite \ - broken-d-test-suite + broken-d-test-suite \ + broken-javascript-test-suite broken-%-test-suite: @$(MAKE) -k -s check-$*-test-suite ACTION=broken @@ -424,7 +431,7 @@ install-main: @$(INSTALL_PROGRAM) $(TARGET) $(DESTDIR)$(BIN_DIR)/`echo $(TARGET_NOEXE) | sed '$(transform)'`@EXEEXT@ lib-languages = gcj typemaps tcl perl5 python guile java mzscheme ruby php ocaml octave \ - pike chicken csharp modula3 allegrocl clisp lua cffi uffi r go d + pike chicken csharp modula3 allegrocl clisp lua cffi uffi r go d javascript javascript/jsc lib-modules = std diff --git a/Source/DOH/fio.c b/Source/DOH/fio.c index 2ef605c32..4e91a1b51 100644 --- a/Source/DOH/fio.c +++ b/Source/DOH/fio.c @@ -490,6 +490,7 @@ int DohCopyto(DOH *in, DOH *out) { return nbytes; } } + return nbytes; } @@ -588,4 +589,5 @@ DOH *DohReadline(DOH *in) { Putc(c, s); n++; } + return s; } diff --git a/Source/Makefile.am b/Source/Makefile.am index 85530fd45..420fd6d3f 100644 --- a/Source/Makefile.am +++ b/Source/Makefile.am @@ -50,7 +50,6 @@ eswig_SOURCES = CParse/cscanner.c \ Modules/java.cxx \ Modules/lang.cxx \ Modules/javascript.cxx \ - Modules/javascript_emitter.cxx \ Modules/javascript_v8.cxx \ Modules/lua.cxx \ Modules/main.cxx \ diff --git a/Source/Modules/emit.cxx b/Source/Modules/emit.cxx index efcf9a352..7d7f66eaf 100644 --- a/Source/Modules/emit.cxx +++ b/Source/Modules/emit.cxx @@ -470,6 +470,7 @@ String *emit_action(Node *n) { if (catchlist) { int unknown_catch = 0; + int has_varargs = 0; Printf(eaction, "}\n"); for (Parm *ep = catchlist; ep; ep = nextSibling(ep)) { String *em = Swig_typemap_lookup("throws", ep, "_e", 0); @@ -480,6 +481,7 @@ String *emit_action(Node *n) { Printf(eaction, "catch(%s) {", SwigType_str(et, "_e")); } else if (SwigType_isvarargs(etr)) { Printf(eaction, "catch(...) {"); + has_varargs = 1; } else { Printf(eaction, "catch(%s) {", SwigType_str(et, "&_e")); } @@ -490,8 +492,8 @@ String *emit_action(Node *n) { unknown_catch = 1; } } - if (unknown_catch) { - Printf(eaction, "catch(...) { throw; }\n"); + if (unknown_catch && !has_varargs) { + Printf(eaction, "catch(...) { throw; }\n"); } } diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 64d943453..009bcc400 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -4,38 +4,1328 @@ #include #include -#include "javascript_emitter.h" +/** + * A class that wraps a code snippet used as template for code generation. + */ +class Template { -extern JSEmitter* create_v8_emitter(); +public: + Template(const String *code); + + Template(const String *code, const String *templateName, bool debug = false); + + ~Template(); + + String *str(); + + Template & replace(const String *pattern, const String *repl); + +private: + String *code; + String *templateName; + bool debug; +}; + +class JSEmitter { + +public: + + enum JSEmitterType { + JavascriptCore, + V8, + QtScript + }; + + JSEmitter(); + + virtual ~ JSEmitter(); + + /** + * Opens output files and temporary output DOHs. + */ + virtual int initialize(Node *n) = 0; + + /** + * Writes all collected code into the output file(s). + */ + virtual int dump(Node *n) = 0; + + /** + * Cleans up all open output DOHs. + */ + virtual int close() = 0; + + /** + * Switches the context for code generation. + * + * Classes, global variables and global functions may need to + * be registered in certain static tables. + * This method should be used to switch output DOHs correspondingly. + */ + virtual int switchNamespace(Node *) { + return SWIG_OK; + }; + + /** + * Invoked at the beginning of the classHandler. + */ + virtual int enterClass(Node *) { + return SWIG_OK; + }; + + /** + * Invoked at the end of the classHandler. + */ + virtual int exitClass(Node *) { + return SWIG_OK; + }; + + /** + * Invoked at the beginning of the variableHandler. + */ + virtual int enterVariable(Node *) { + return SWIG_OK; + }; + + /** + * Invoked at the end of the variableHandler. + */ + virtual int exitVariable(Node *) { + return SWIG_OK; + }; + + /** + * Invoked at the beginning of the functionHandler. + */ + virtual int enterFunction(Node *) { + return SWIG_OK; + }; + + /** + * Invoked at the end of the functionHandler. + */ + virtual int exitFunction(Node *) { + return SWIG_OK; + }; + + /** + * Invoked by functionWrapper callback after call to Language::functionWrapper. + */ + virtual int emitWrapperFunction(Node *n); + + /** + * Invoked from constantWrapper after call to Language::constantWrapper. + **/ + virtual int emitConstant(Node *n) = 0; + + /** + * Registers a given code snippet for a given key name. + * + * This method is called by the fragmentDirective handler + * of the JAVASCRIPT language module. + **/ + int registerTemplate(const String *name, const String *code); + + /** + * Retrieve the code template registered for a given name. + */ + Template getTemplate(const String *name); + + void enableDebug(); + + void setStaticFlag(bool is_static = false); + +protected: + + virtual int emitCtor(Node *n) = 0; + + virtual int emitDtor(Node *n) = 0; + + virtual int emitFunction(Node *n, bool is_member) = 0; + + virtual int emitGetter(Node *n, bool is_member) = 0; + + virtual int emitSetter(Node *n, bool is_member) = 0; + + bool isSetterMethod(Node *n); + + Node *getBaseClass(Node *n); + + const String *typemapLookup(Node *n, const_String_or_char_ptr tmap_method, SwigType *type, int warning, Node *typemap_attributes = 0); + + void enableDebugTemplates(); + +protected: + + // empty string used at different places in the code + String *empty_string; + + Hash *templates; + + Wrapper *current_wrapper; + + bool is_static; + + bool debug; +}; + +class JSCEmitter:public JSEmitter { + +private: + + enum MarshallingMode { + Setter, + Getter, + Ctor, + Function + }; + +public: + + JSCEmitter(); + + virtual ~ JSCEmitter(); + + virtual int initialize(Node *n); + + virtual int dump(Node *n); + + virtual int close(); + + +protected: + + virtual int emitCtor(Node *n); + + virtual int emitDtor(Node *n); + + virtual int enterVariable(Node *n); + + virtual int exitVariable(Node *n); + + virtual int enterFunction(Node *n); + + virtual int exitFunction(Node *n); + + virtual int enterClass(Node *n); + + virtual int exitClass(Node *n); + + virtual int emitFunction(Node *n, bool is_member); + + virtual int emitFunctionDispatcher(Node *n, bool is_member); + + virtual int emitGetter(Node *n, bool is_member); + + virtual int emitSetter(Node *n, bool is_member); + + void marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static = false); + + void marshalOutput(Node *n, String *actioncode, Wrapper *wrapper); + + Parm *skipIgnoredArgs(Parm *p); + + virtual int switchNamespace(Node *n); + + virtual int createNamespace(String *scope); + + virtual Hash *createNamespaceEntry(const char *name, const char *parent); + + virtual int emitNamespaces(); + + virtual int emitConstant(Node *n); + +private: + + File *f_wrap_cpp; + File *f_runtime; + File *f_header; + File *f_wrappers; + File *f_init; + + String *NULL_STR; + String *VETO_SET; + const char *GLOBAL_STR; + + // contains context specific structs + // to allow generation different class definition tables + // which are switched on namespace change + Hash *namespaces; + Hash *current_namespace; + + // dynamically filled code parts + + String *create_namespaces_code; + String *register_namespaces_code; + + String *current_class_functions; + String *class_variables_code; + String *class_static_functions_code; + String *class_static_variables_code; + + String *ctor_wrappers; + String *ctor_dispatcher_code; + + String *initializer_code; + String *function_dispatcher_code; + + // state variables + String *current_propertyname; + String *current_getter; + String *current_setter; + bool is_immutable; + + String *current_classname; + String *current_classname_mangled; + String *current_classtype; + String *current_classtype_mangled; + String *current_functionwrapper; + String *current_functionname; +}; + +/* ----------------------------------------------------------------------------- + * JSEmitter() + * ----------------------------------------------------------------------------- */ + +JSEmitter::JSEmitter() +: empty_string(NewString("")), current_wrapper(NULL), is_static(false), debug(false) { + templates = NewHash(); +} + +/* ----------------------------------------------------------------------------- + * ~JSEmitter() + * ----------------------------------------------------------------------------- */ + +JSEmitter::~JSEmitter() { + Delete(empty_string); + Delete(templates); +} + +/* ----------------------------------------------------------------------------- + * JSEmitter::RegisterTemplate() : Registers a code template + * ----------------------------------------------------------------------------- */ + +int JSEmitter::registerTemplate(const String *name, const String *code) { + return Setattr(templates, name, code); +} + +/* ----------------------------------------------------------------------------- + * JSEmitter::GetTemplate() : Retrieves a registered a code template + * ----------------------------------------------------------------------------- */ + +Template JSEmitter::getTemplate(const String *name) { + String *templ = Getattr(templates, name); + + if (!templ) { + Printf(stderr, "Could not find template %s\n.", name); + SWIG_exit(EXIT_FAILURE); + } + + Template t(templ, name, debug); + + return t; +} + +void JSEmitter::enableDebug() { + debug = true; +} + +void JSEmitter::setStaticFlag(bool _is_static) { + is_static = _is_static; +} + +/* ----------------------------------------------------------------------------- + * JSEmitter::typemapLookup() + * + * n - for input only and must contain info for Getfile(n) and Getline(n) to work + * tmap_method - typemap method name + * type - typemap type to lookup + * warning - warning number to issue if no typemaps found + * typemap_attributes - the typemap attributes are attached to this node and will + * also be used for temporary storage if non null + * return is never NULL, unlike Swig_typemap_lookup() + * ----------------------------------------------------------------------------- */ + +const String *JSEmitter::typemapLookup(Node *n, const_String_or_char_ptr tmap_method, SwigType *type, int warning, Node *typemap_attributes) { + Node *node = !typemap_attributes ? NewHash() : typemap_attributes; + Setattr(node, "type", type); + Setfile(node, Getfile(n)); + Setline(node, Getline(n)); + const String *tm = Swig_typemap_lookup(tmap_method, node, "", 0); + if (!tm) { + tm = empty_string; + if (warning != WARN_NONE) { + Swig_warning(warning, Getfile(n), Getline(n), "No %s typemap defined for %s\n", tmap_method, SwigType_str(type, 0)); + } + } + if (!typemap_attributes) { + Delete(node); + } + return tm; +} + +/* ----------------------------------------------------------------------------- + * JSEmitter::getBaseClass() : the node of the base class or NULL + * ----------------------------------------------------------------------------- */ + +Node *JSEmitter::getBaseClass(Node *n) { + // retrieve the first base class that is not %ignored + List *baselist = Getattr(n, "bases"); + if (baselist) { + Iterator base = First(baselist); + while (base.item && GetFlag(base.item, "feature:ignore")) { + base = Next(base); + } + + return base.item; + } + + return NULL; +} + + /* ----------------------------------------------------------------------------- + * JSEmitter::emitWrapperFunction() : dispatches emitter functions + * ----------------------------------------------------------------------------- */ + +int JSEmitter::emitWrapperFunction(Node *n) { + int ret = SWIG_OK; + + current_wrapper = NewWrapper(); + Setattr(n, "wrap:name", Getattr(n, "sym:name")); + + String *kind = Getattr(n, "kind"); + + if (kind) { + bool is_member = GetFlag(n, "ismember"); + if (Cmp(kind, "function") == 0) { + ret = emitFunction(n, is_member); + + } else if (Cmp(kind, "variable") == 0) { + if (isSetterMethod(n)) { + ret = emitSetter(n, is_member); + + } else { + ret = emitGetter(n, is_member); + + } + } else { + Printf(stderr, "Warning: unsupported wrapper function type\n"); + Swig_print_node(n); + + ret = SWIG_ERROR; + } + } else { + String *view = Getattr(n, "view"); + + if (Cmp(view, "constructorHandler") == 0) { + ret = emitCtor(n); + + } else if (Cmp(view, "destructorHandler") == 0) { + ret = emitDtor(n); + + } else { + Printf(stderr, "Warning: unsupported wrapper function type"); + Swig_print_node(n); + ret = SWIG_ERROR; + } + } + + DelWrapper(current_wrapper); + current_wrapper = 0; + + return ret; +} + +/* ----------------------------------------------------------------------------- + * __swigjs_str_ends_with() : c string helper to check suffix match + * ----------------------------------------------------------------------------- */ + +int __swigjs_str_ends_with(const char *str, const char *suffix) { + + if (str == NULL || suffix == NULL) + return 0; + + size_t str_len = strlen(str); + size_t suffix_len = strlen(suffix); + + if (suffix_len > str_len) + return 0; + + return 0 == strncmp(str + str_len - suffix_len, suffix, suffix_len); +} + + +/* ----------------------------------------------------------------------------- + * JSEmitter::isSetterMethod() : helper to check if a method is a setter function + * ----------------------------------------------------------------------------- */ + +bool JSEmitter::isSetterMethod(Node *n) { + String *symname = Getattr(n, "sym:name"); + return (__swigjs_str_ends_with((char *) Data(symname), "_set") != 0); +} + +/* ----------------------------------------------------------------------------- + * Template::Template() : creates a Template class for given template code + * ----------------------------------------------------------------------------- */ + +Template::Template(const String *code_) { + + if (!code_) { + Printf(stdout, "Template code was null. Illegal input for template."); + SWIG_exit(EXIT_FAILURE); + } + debug = false; + code = NewString(code_); + templateName = NewString(""); +} + +Template::Template(const String *code_, const String *templateName_, bool debug_) { + + if (!code_) { + Printf(stdout, "Template code was null. Illegal input for template."); + SWIG_exit(EXIT_FAILURE); + } + + code = NewString(code_); + templateName = NewString(templateName_); + debug = debug_; +} + + +/* ----------------------------------------------------------------------------- + * Template::~Template() : cleans up of Template. + * ----------------------------------------------------------------------------- */ + +Template::~Template() { + Delete(code); + Delete(templateName); +} + +/* ----------------------------------------------------------------------------- + * String* Template::str() : retrieves the current content of the template. + * ----------------------------------------------------------------------------- */ + +String *Template::str() { + if (debug) { + String *pre_code = NewString(""); + String *post_code = NewString(""); + String *debug_code = NewString(""); + Printf(pre_code, "//begin fragment(\"%s\")\n", templateName); + Printf(post_code, "//end fragment(\"%s\")\n", templateName); + Printf(debug_code, "%s\n%s\n%s", pre_code, code, post_code); + + Delete(code); + Delete(pre_code); + Delete(post_code); + + code = debug_code; + } + return code; +} + +/* ----------------------------------------------------------------------------- + * Template& Template::replace(const String* pattern, const String* repl) : + * + * replaces all occurances of a given pattern with a given replacement. + * + * - pattern: the pattern to be replaced + * - repl: the replacement string + * - returns a reference to the Template to allow chaining of methods. + * ----------------------------------------------------------------------------- */ + +Template & Template::replace(const String *pattern, const String *repl) { + ::Replaceall(code, pattern, repl); + return *this; +} + +JSCEmitter::JSCEmitter() +: +JSEmitter(), NULL_STR(NewString("NULL")), current_classname(NULL), f_header(NULL), current_classtype(NULL), f_runtime(NULL), current_class_functions(NULL), +f_wrappers(NULL), current_getter(NULL), is_immutable(NULL), create_namespaces_code(NULL), current_classname_mangled(NULL), initializer_code(NULL), +register_namespaces_code(NULL), f_wrap_cpp(NULL), current_setter(NULL), ctor_dispatcher_code(NULL), current_functionwrapper(NULL), +class_static_functions_code(NULL), namespaces(NULL), function_dispatcher_code(NULL), namespaces(NULL), GLOBAL_STR(NULL), current_propertyname(NULL), +current_namespace(NULL), ctor_wrappers(NULL), class_static_variables_code(NULL), class_variables_code(NULL), f_init(NULL), current_functionname(NULL), +current_classtype_mangled(NULL), VETO_SET(NewString("JS_veto_set_variable")) { +} + +JSCEmitter::~JSCEmitter() { + Delete(NULL_STR); + Delete(VETO_SET); +} + +/* --------------------------------------------------------------------- + * skipIgnoredArgs() + * --------------------------------------------------------------------- */ + +Parm *JSCEmitter::skipIgnoredArgs(Parm *p) { + while (checkAttribute(p, "tmap:in:numinputs", "0")) { + p = Getattr(p, "tmap:in:next"); + } + return p; +} + +/* --------------------------------------------------------------------- + * marshalInputArgs() + * + * Process all of the arguments passed into the argv array + * and convert them into C/C++ function arguments using the + * supplied typemaps. + * --------------------------------------------------------------------- */ + +void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) { + String *tm; + Parm *p; + + int startIdx = 0; + if (is_member && !is_static) + startIdx = 1; + + + int i = 0; + for (p = parms; p; p = nextSibling(p), i++) { + SwigType *pt = Getattr(p, "type"); + String *arg = NewString(""); + + switch (mode) { + case Getter: + case Function: + if (is_member && !is_static && i == 0) { + Printv(arg, "thisObject", 0); + } else { + Printf(arg, "argv[%d]", i - startIdx); + } + + break; + case Setter: + if (is_member && !is_static && i == 0) { + Printv(arg, "thisObject", 0); + } else { + Printv(arg, "value", 0); + } + break; + case Ctor: + Printf(arg, "argv[%d]", i); + break; + default: + throw "Illegal state."; + } + + tm = Getattr(p, "tmap:in"); // Get typemap for this argument + if (tm != NULL) { + Replaceall(tm, "$input", arg); + Setattr(p, "emit:input", arg); + + if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) { + Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); + } else { + Replaceall(tm, "$disown", "0"); + } + Replaceall(tm, "$symname", Getattr(n, "sym:name")); + + Printf(wrapper->code, "%s\n", tm); + } else { + Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0)); + } + Delete(arg); + } +} + +/* --------------------------------------------------------------------- +* marshalOutput() +* +* Process the return value of the C/C++ function call +* and convert them into the Javascript types using the +* supplied typemaps. +* --------------------------------------------------------------------- */ + +void JSCEmitter::marshalOutput(Node *n, String *actioncode, Wrapper *wrapper) { + SwigType *type = Getattr(n, "type"); + Setattr(n, "type", type); + String *tm; + + // HACK: output types are not registered as swig_types automatically + if (SwigType_ispointer(type)) { + SwigType_remember_clientdata(type, NewString("0")); + } + + if ((tm = Swig_typemap_lookup_out("out", n, "result", wrapper, actioncode))) { + Replaceall(tm, "$result", "jsresult"); + // TODO: May not be the correct way + Replaceall(tm, "$objecttype", Swig_scopename_last(SwigType_str(SwigType_strip_qualifiers(type), 0))); + + if (GetFlag(n, "feature:new")) { + Replaceall(tm, "$owner", "SWIG_POINTER_OWN"); + } else { + Replaceall(tm, "$owner", "0"); + } + + Printf(wrapper->code, "%s", tm); + if (Len(tm)) + Printf(wrapper->code, "\n"); + } else { + Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(type, 0), Getattr(n, "name")); + } + emit_return_variable(n, type, wrapper); +} + +int JSCEmitter::initialize(Node *n) { + + /* Get the output file name */ + String *outfile = Getattr(n, "outfile"); + + /* Initialize I/O */ + f_wrap_cpp = NewFile(outfile, "w", SWIG_output_files()); + if (!f_wrap_cpp) { + FileErrorDisplay(outfile); + SWIG_exit(EXIT_FAILURE); + } + + /* Initialization of members */ + f_runtime = NewString(""); + f_init = NewString(""); + f_header = NewString(""); + f_wrappers = NewString(""); + + create_namespaces_code = NewString(""); + register_namespaces_code = NewString(""); + initializer_code = NewString(""); + + namespaces = NewHash(); + Hash *global_namespace = createNamespaceEntry(Char(Getattr(n, "name")), "global"); + Setattr(namespaces, "::", global_namespace); + current_namespace = global_namespace; + + /* Register file targets with the SWIG file handler */ + Swig_register_filebyname("begin", f_wrap_cpp); + Swig_register_filebyname("header", f_header); + Swig_register_filebyname("wrapper", f_wrappers); + Swig_register_filebyname("runtime", f_runtime); + Swig_register_filebyname("init", f_init); + + return SWIG_OK; +} + +int JSCEmitter::dump(Node *n) { + /* Get the module name */ + String *module = Getattr(n, "name"); + + // write the swig banner + Swig_banner(f_wrap_cpp); + + SwigType_emit_type_table(f_runtime, f_wrappers); + + Printv(f_wrap_cpp, f_runtime, "\n", 0); + Printv(f_wrap_cpp, f_header, "\n", 0); + Printv(f_wrap_cpp, f_wrappers, "\n", 0); + + + emitNamespaces(); + + // compose the initializer function using a template + Template initializer(getTemplate("JS_initializer")); + initializer.replace("${modulename}", module) + .replace("${initializercode}", initializer_code) + .replace("${create_namespaces}", create_namespaces_code) + .replace("${register_namespaces}", register_namespaces_code); + Wrapper_pretty_print(initializer.str(), f_init); + + Printv(f_wrap_cpp, f_init, "\n", 0); + + return SWIG_OK; +} + + +int JSCEmitter::close() { + /* strings */ + Delete(f_runtime); + Delete(f_header); + Delete(f_wrappers); + Delete(f_init); + + Delete(create_namespaces_code); + Delete(register_namespaces_code); + Delete(initializer_code); + + Delete(namespaces); + + /* files */ + ::Close(f_wrap_cpp); + Delete(f_wrap_cpp); + + return SWIG_OK; +} + +int JSCEmitter::enterFunction(Node *n) { + + bool is_overloaded = GetFlag(n, "sym:overloaded"); + + current_functionname = Getattr(n, "sym:name"); + + if (is_overloaded && function_dispatcher_code == 0) { + function_dispatcher_code = NewString(""); + } + + return SWIG_OK; +} + +int JSCEmitter::exitFunction(Node *n) { + Template t_function = getTemplate("JS_functiondecl"); + + String *functionname = current_functionname; + String *functionwrapper = current_functionwrapper; + + bool is_member = GetFlag(n, "ismember"); + + // handle overloaded functions + // Note: wrappers for overloaded functions are currently + // not made available (e.g., foo_double, foo_int) + // maybe this could be enabled by an extra feature flag + bool is_overloaded = GetFlag(n, "sym:overloaded"); + + if (is_overloaded) { + if (!Getattr(n, "sym:nextSibling")) { + + functionwrapper = Swig_name_wrapper(Getattr(n, "name")); + // note: set this attribute to transfer ownership + Setattr(n, "wrap:dispatcher", functionwrapper); + + // create dispatcher + emitFunctionDispatcher(n, is_member); + + Delete(function_dispatcher_code); + function_dispatcher_code = 0; + + } else { + + //don't register wrappers of overloaded functions in function tables + return SWIG_OK; + } + } + + t_function.replace("${functionname}", functionname) + .replace("${functionwrapper}", functionwrapper); + + if (is_member) { + + if (Equal(Getattr(n, "storage"), "static")) { + Printv(class_static_functions_code, t_function.str(), 0); + + } else { + Printv(current_class_functions, t_function.str(), 0); + } + + } else { + Printv(Getattr(current_namespace, "functions"), t_function.str(), 0); + } + + return SWIG_OK; +} + +int JSCEmitter::enterVariable(Node *n) { + current_getter = NULL_STR; + current_setter = VETO_SET; + current_propertyname = Swig_scopename_last(Getattr(n, "name")); + is_immutable = GetFlag(n, "wrap:immutable"); + + return SWIG_OK; +} + + +int JSCEmitter::exitVariable(Node *n) { + Template t_variable(getTemplate("JS_variabledecl")); + t_variable.replace("${setname}", current_setter) + .replace("${getname}", current_getter) + .replace("${propertyname}", current_propertyname); + + if (GetFlag(n, "ismember")) { + if (Equal(Getattr(n, "storage"), "static") || (Equal(Getattr(n, "nodeType"), "enumitem"))) { + + Printv(class_static_variables_code, t_variable.str(), 0); + + } else { + Printv(class_variables_code, t_variable.str(), 0); + } + } else { + Printv(Getattr(current_namespace, "values"), t_variable.str(), 0); + } + + return SWIG_OK; +} + +int JSCEmitter::enterClass(Node *n) { + + current_classname = Getattr(n, "sym:name"); + current_classname_mangled = SwigType_manglestr(Getattr(n, "name")); + current_classtype = NewString(Getattr(n, "classtype")); + + String *type = SwigType_manglestr(Getattr(n, "classtypeobj")); + current_classtype_mangled = NewString(""); + Printf(current_classtype_mangled, "p%s", type); + Delete(type); + + Template t_class_defn = getTemplate("JS_class_definition"); + t_class_defn.replace("${classname_mangled}", current_classname_mangled); + Wrapper_pretty_print(t_class_defn.str(), f_wrappers); + + class_variables_code = NewString(""); + current_class_functions = NewString(""); + class_static_variables_code = NewString(""); + class_static_functions_code = NewString(""); + ctor_wrappers = NewString(""); + ctor_dispatcher_code = NewString(""); + + return SWIG_OK; +} + +int JSCEmitter::exitClass(Node *n) { + + String *mangled_name = SwigType_manglestr(Getattr(n, "name")); + + Template t_class_tables(getTemplate("JS_class_tables")); + t_class_tables.replace("${classname_mangled}", mangled_name) + .replace("${jsclassvariables}", class_variables_code) + .replace("${jsclassfunctions}", current_class_functions) + .replace("${jsstaticclassfunctions}", class_static_functions_code) + .replace("${jsstaticclassvariables}", class_static_variables_code); + Wrapper_pretty_print(t_class_tables.str(), f_wrappers); + + /* adds the ctor wrappers at this position */ + // Note: this is necessary to avoid extra forward declarations. + Printv(f_wrappers, ctor_wrappers, 0); + + /* adds the main constructor wrapper function */ + Template t_mainctor(getTemplate("JS_mainctordefn")); + t_mainctor.replace("${classname_mangled}", mangled_name) + .replace("${DISPATCH_CASES}", ctor_dispatcher_code); + Wrapper_pretty_print(t_mainctor.str(), f_wrappers); + + /* adds a class template statement to initializer function */ + Template t_classtemplate(getTemplate("JS_create_class_template")); + + /* prepare registration of base class */ + String *base_name_mangled = NewString("_SwigObject"); + Node *base_class = getBaseClass(n); + if (base_class != NULL) { + Delete(base_name_mangled); + base_name_mangled = SwigType_manglestr(Getattr(base_class, "name")); + } + + t_classtemplate.replace("${classname_mangled}", mangled_name) + .replace("${classtype_mangled}", current_classtype_mangled) + .replace("${base_classname}", base_name_mangled); + Wrapper_pretty_print(t_classtemplate.str(), initializer_code); + +/* + String *clientdata = NewString(""); + Printv(clientdata, mangled_name, "_classRef", 0); + SwigType_remember_clientdata(current_classtype_mangled, clientdata); +*/ + + SwigType_remember_clientdata(current_classtype_mangled, NewString("0")); + + /* adds a class registration statement to initializer function */ + Template t_registerclass(getTemplate("JS_register_class")); + t_registerclass.replace("${classname}", current_classname) + .replace("${classname_mangled}", current_classname_mangled) + .replace("${namespace_mangled}", Getattr(current_namespace, "name_mangled")); + + Wrapper_pretty_print(t_registerclass.str(), initializer_code); + + /* clean up all DOHs */ + Delete(class_variables_code); + Delete(current_class_functions); + Delete(class_static_variables_code); + Delete(class_static_functions_code); + Delete(ctor_wrappers); + Delete(mangled_name); + Delete(ctor_dispatcher_code); + class_variables_code = 0; + current_class_functions = 0; + class_static_variables_code = 0; + class_static_functions_code = 0; + ctor_wrappers = 0; + ctor_dispatcher_code = 0; + + Delete(current_classname); + Delete(current_classname_mangled); + Delete(current_classtype); + Delete(current_classtype_mangled); + + return SWIG_OK; +} + +int JSCEmitter::emitCtor(Node *n) { + + Template t_ctor(getTemplate("JS_ctordefn")); + String *mangled_name = SwigType_manglestr(Getattr(n, "name")); + + String *name = (Getattr(n, "wrap:name")); + String *overname = Getattr(n, "sym:overname"); + String *wrap_name = Swig_name_wrapper(name); + Setattr(n, "wrap:name", wrap_name); + + ParmList *params = Getattr(n, "parms"); + emit_parameter_variables(params, current_wrapper); + emit_attach_parmmaps(params, current_wrapper); + + Printf(current_wrapper->locals, "%sresult;", SwigType_str(Getattr(n, "type"), 0)); + + int num_args = emit_num_arguments(params); + String *action = emit_action(n); + marshalInputArgs(n, params, current_wrapper, Ctor, true); + + Printv(current_wrapper->code, action, "\n", 0); + t_ctor.replace("${classname_mangled}", mangled_name) + .replace("${overloadext}", overname) + .replace("${LOCALS}", current_wrapper->locals) + .replace("${CODE}", current_wrapper->code) + .replace("${type_mangled}", current_classtype_mangled); + + Wrapper_pretty_print(t_ctor.str(), ctor_wrappers); + + String *argcount = NewString(""); + Printf(argcount, "%d", num_args); + + Template t_ctor_case(getTemplate("JS_ctor_dispatch_case")); + t_ctor_case.replace("${classname_mangled}", mangled_name) + .replace("${overloadext}", overname) + .replace("${argcount}", argcount); + Printv(ctor_dispatcher_code, t_ctor_case.str(), 0); + Delete(argcount); + + return SWIG_OK; + +} + +int JSCEmitter::emitDtor(Node *) { + + Template t_dtor = getTemplate("JS_destructordefn"); + t_dtor.replace("${classname_mangled}", current_classname_mangled) + .replace("${type}", current_classtype); + Wrapper_pretty_print(t_dtor.str(), f_wrappers); + + return SWIG_OK; +} + +int JSCEmitter::emitGetter(Node *n, bool is_member) { + Template t_getter(getTemplate("JS_getproperty")); + bool is_static = Equal(Getattr(n, "storage"), "static"); + + String *name = Getattr(n, "wrap:name"); + String *wrap_name = Swig_name_wrapper(name); + current_getter = wrap_name; + Setattr(n, "wrap:name", wrap_name); + + ParmList *params = Getattr(n, "parms"); + emit_parameter_variables(params, current_wrapper); + emit_attach_parmmaps(params, current_wrapper); + Wrapper_add_local(current_wrapper, "jsresult", "JSValueRef jsresult"); + + String *action = emit_action(n); + marshalInputArgs(n, params, current_wrapper, Getter, is_member, is_static); + marshalOutput(n, action, current_wrapper); + + t_getter.replace("${getname}", wrap_name) + .replace("${LOCALS}", current_wrapper->locals) + .replace("${CODE}", current_wrapper->code); + + Wrapper_pretty_print(t_getter.str(), f_wrappers); + + return SWIG_OK; +} + +int JSCEmitter::emitSetter(Node *n, bool is_member) { + + // skip variable that are immutable + if (is_immutable) + return SWIG_OK; + + Template t_setter(getTemplate("JS_setproperty")); + bool is_static = Equal(Getattr(n, "storage"), "static"); + + String *name = Getattr(n, "wrap:name"); + String *wrap_name = Swig_name_wrapper(name); + current_setter = wrap_name; + Setattr(n, "wrap:name", wrap_name); + + ParmList *params = Getattr(n, "parms"); + emit_parameter_variables(params, current_wrapper); + emit_attach_parmmaps(params, current_wrapper); + + String *action = emit_action(n); + marshalInputArgs(n, params, current_wrapper, Setter, is_member, is_static); + Append(current_wrapper->code, action); + + t_setter.replace("${setname}", wrap_name) + .replace("${LOCALS}", current_wrapper->locals) + .replace("${CODE}", current_wrapper->code); + + Wrapper_pretty_print(t_setter.str(), f_wrappers); + + return SWIG_OK; +} + +/* ----------------------------------------------------------------------------- + * swig::JSEmitter::emitConstant() : triggers code generation for constants + * ----------------------------------------------------------------------------- */ + +int JSCEmitter::emitConstant(Node *n) { + + // call the variable methods as a constants are + // registred in same way + enterVariable(n); + + current_wrapper = NewWrapper(); + + String *action = NewString(""); + + String *name = Getattr(n, "name"); + String *wrap_name = Swig_name_wrapper(name); + String *value = Getattr(n, "rawval"); + if (value == NULL) { + value = Getattr(n, "rawvalue"); + } + if (value == NULL) { + value = Getattr(n, "value"); + } + + Template t_getter(getTemplate("JS_getproperty")); + + current_getter = wrap_name; + Setattr(n, "wrap:name", wrap_name); + + Printf(action, "result = %s;\n", value); + Setattr(n, "wrap:action", action); + + Wrapper_add_local(current_wrapper, "jsresult", "JSValueRef jsresult"); + marshalOutput(n, action, current_wrapper); + + t_getter.replace("${getname}", wrap_name) + .replace("${LOCALS}", current_wrapper->locals) + .replace("${CODE}", current_wrapper->code); + + Wrapper_pretty_print(t_getter.str(), f_wrappers); + + DelWrapper(current_wrapper); + current_wrapper = 0; + + exitVariable(n); + + return SWIG_OK; +} + +int JSCEmitter::emitFunction(Node *n, bool is_member) { + Template t_function(getTemplate("JS_functionwrapper")); + + // Note: there is an inconsistency in SWIG with static member functions + // that do not have storage:static + // in these cases the context (staticmemberfunctionHandler) is + // exploited and a flag is set temporarily + // TODO: this could be done in general with is_member and is_static + bool is_static = JSEmitter::is_static || Equal(Getattr(n, "storage"), "static"); + + bool is_overloaded = GetFlag(n, "sym:overloaded"); + String *name = Getattr(n, "sym:name"); + String *wrap_name = Swig_name_wrapper(name); + + if (is_overloaded) { + Append(wrap_name, Getattr(n, "sym:overname")); + } + + current_functionwrapper = wrap_name; + Setattr(n, "wrap:name", wrap_name); + + ParmList *params = Getattr(n, "parms"); + emit_parameter_variables(params, current_wrapper); + emit_attach_parmmaps(params, current_wrapper); + Wrapper_add_local(current_wrapper, "jsresult", "JSValueRef jsresult"); + + String *action = emit_action(n); + marshalInputArgs(n, params, current_wrapper, Function, is_member, is_static); + marshalOutput(n, action, current_wrapper); + + t_function.replace("${functionname}", wrap_name) + .replace("${LOCALS}", current_wrapper->locals) + .replace("${CODE}", current_wrapper->code); + Wrapper_pretty_print(t_function.str(), f_wrappers); + + if (is_overloaded) { + Template t_dispatch_case = getTemplate("JS_function_dispatch_case"); + + int argc = emit_num_arguments(params); + String *argcount = NewString(""); + Printf(argcount, "%d", argc); + + t_dispatch_case.replace("${functionwrapper}", wrap_name) + .replace("${argcount}", argcount); + + Printv(function_dispatcher_code, t_dispatch_case.str(), 0); + + Delete(argcount); + } + + return SWIG_OK; +} + +int JSCEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { + + Template t_function(getTemplate("JS_functionwrapper")); + + Wrapper *wrapper = NewWrapper(); + String *wrap_name = Swig_name_wrapper(Getattr(n, "name")); + Setattr(n, "wrap:name", wrap_name); + + Wrapper_add_local(wrapper, "jsresult", "JSValueRef jsresult"); + + Append(wrapper->code, function_dispatcher_code); + Append(wrapper->code, getTemplate("JS_function_dispatch_case_default").str()); + + t_function.replace("${functionname}", wrap_name) + .replace("${LOCALS}", wrapper->locals) + .replace("${CODE}", wrapper->code); + + Wrapper_pretty_print(t_function.str(), f_wrappers); + + DelWrapper(wrapper); + + return SWIG_OK; +} + +int JSCEmitter::switchNamespace(Node *n) { + if (!GetFlag(n, "feature:nspace")) { + current_namespace = Getattr(namespaces, "::"); + + } else { + + String *scope = Swig_scopename_prefix(Getattr(n, "name")); + + if (scope) { + // if the scope is not yet registered + // create all scopes/namespaces recursively + if (!Getattr(namespaces, scope)) { + createNamespace(scope); + } + + current_namespace = Getattr(namespaces, scope); + + } else { + current_namespace = Getattr(namespaces, "::"); + } + } + + return SWIG_OK; +} + +int JSCEmitter::createNamespace(String *scope) { + + String *parent_scope = Swig_scopename_prefix(scope); + + Hash *parent_namespace; + + if (parent_scope == 0) { + parent_namespace = Getattr(namespaces, "::"); + } else if (!Getattr(namespaces, parent_scope)) { + createNamespace(parent_scope); + parent_namespace = Getattr(namespaces, parent_scope); + } else { + parent_namespace = Getattr(namespaces, parent_scope); + } + + assert(parent_namespace != 0); + + Hash *new_namespace = createNamespaceEntry(Char(scope), Char(Getattr(parent_namespace, "name"))); + Setattr(namespaces, scope, new_namespace); + + Delete(parent_scope); + + return SWIG_OK; +} + +Hash *JSCEmitter::createNamespaceEntry(const char *name, const char *parent) { + Hash *entry = NewHash(); + String *_name = NewString(name); + Setattr(entry, "name", Swig_scopename_last(_name)); + Setattr(entry, "name_mangled", Swig_name_mangle(_name)); + Setattr(entry, "parent", NewString(parent)); + Setattr(entry, "functions", NewString("")); + Setattr(entry, "values", NewString("")); + + Delete(_name); + + return entry; +} + +int JSCEmitter::emitNamespaces() { + Iterator it; + for (it = First(namespaces); it.item; it = Next(it)) { + Hash *entry = it.item; + + String *name = Getattr(entry, "name"); + String *parent = Getattr(entry, "parent"); + String *functions = Getattr(entry, "functions"); + String *variables = Getattr(entry, "values"); + String *name_mangled = Getattr(entry, "name_mangled"); + String *parent_mangled = Swig_name_mangle(parent); + + Template namespace_definition(getTemplate("JS_globaldefn")); + namespace_definition.replace("${jsglobalvariables}", variables) + .replace("${jsglobalfunctions}", functions) + .replace("${namespace}", name_mangled); + Wrapper_pretty_print(namespace_definition.str(), f_wrap_cpp); + + Template t_createNamespace(getTemplate("JS_create_namespace")); + t_createNamespace.replace("${namespace}", name_mangled); + Printv(create_namespaces_code, t_createNamespace.str(), 0); + + Template t_registerNamespace(getTemplate("JS_register_namespace")); + t_registerNamespace.replace("${namespace_mangled}", name_mangled) + .replace("${namespace}", name) + .replace("${parent_namespace}", parent_mangled); + Printv(register_namespaces_code, t_registerNamespace.str(), 0); + } + + return SWIG_OK; +} + +JSEmitter *swig_javascript_create_JSC_emitter() { + return new JSCEmitter(); +} + +extern JSEmitter *swig_javascript_create_JSC_emitter(); /* ******************************************************************** * JAVASCRIPT * ********************************************************************/ -class JAVASCRIPT : public Language { +class JAVASCRIPT:public Language { public: - JAVASCRIPT() {} - ~JAVASCRIPT() {} - - virtual int functionHandler(Node *n); - virtual int globalfunctionHandler(Node *n); - virtual int variableHandler(Node *n); - virtual int globalvariableHandler(Node *n); - virtual int classHandler(Node *n); - virtual int functionWrapper(Node *n); + JAVASCRIPT() { + emitter = NULL; + } ~JAVASCRIPT() { + } + virtual int functionHandler(Node *n); + virtual int globalfunctionHandler(Node *n); + virtual int variableHandler(Node *n); + virtual int globalvariableHandler(Node *n); + virtual int staticmemberfunctionHandler(Node *n); + virtual int classHandler(Node *n); + virtual int functionWrapper(Node *n); + virtual int constantWrapper(Node *n); /** * Registers all %fragments assigned to section "templates" with the Emitter. **/ - virtual int fragmentDirective(Node *n); + virtual int fragmentDirective(Node *n); - virtual void main(int argc, char *argv[]); - virtual int top(Node *n); + virtual int constantDirective(Node *n); + + virtual void main(int argc, char *argv[]); + virtual int top(Node *n); private: - JSEmitter* emitter; + JSEmitter * emitter; }; /* --------------------------------------------------------------------- @@ -45,12 +1335,13 @@ private: * --------------------------------------------------------------------- */ int JAVASCRIPT::functionWrapper(Node *n) { - - Language::functionWrapper(n); - - emitter->EmitWrapperFunction(n); - - return SWIG_OK; + + // note: the default implementation only prints a message + // Language::functionWrapper(n); + + emitter->emitWrapperFunction(n); + + return SWIG_OK; } /* --------------------------------------------------------------------- @@ -58,16 +1349,18 @@ int JAVASCRIPT::functionWrapper(Node *n) { * * Function handler for generating wrappers for functions * --------------------------------------------------------------------- */ - int JAVASCRIPT::functionHandler(Node *n) { - - emitter->EnterFunction(n); - - Language::functionHandler(n); - - emitter->ExitFunction(n); - - return SWIG_OK; + + if (GetFlag(n, "isextension") == 1) + SetFlag(n, "ismember"); + + emitter->enterFunction(n); + + Language::functionHandler(n); + + emitter->exitFunction(n); + + return SWIG_OK; } /* --------------------------------------------------------------------- @@ -77,12 +1370,21 @@ int JAVASCRIPT::functionHandler(Node *n) { * --------------------------------------------------------------------- */ int JAVASCRIPT::globalfunctionHandler(Node *n) { - emitter->SwitchContext(n); - - Language::globalfunctionHandler(n); - return SWIG_OK; + emitter->switchNamespace(n); + + Language::globalfunctionHandler(n); + return SWIG_OK; } +int JAVASCRIPT::staticmemberfunctionHandler(Node *n) { + // workaround: storage=static is not set for static member functions + emitter->setStaticFlag(true); + Language::staticmemberfunctionHandler(n); + emitter->setStaticFlag(false); + return SWIG_OK; +} + + /* --------------------------------------------------------------------- * variableHandler() * @@ -90,14 +1392,19 @@ int JAVASCRIPT::globalfunctionHandler(Node *n) { * --------------------------------------------------------------------- */ int JAVASCRIPT::variableHandler(Node *n) { - - emitter->EnterVariable(n); - - Language::variableHandler(n); - - emitter->ExitVariable(n); - return SWIG_OK; + if (!is_assignable(n) + // HACK: don't know why this is assignable? But does not compile + || Equal(Getattr(n, "type"), "a().char")) { + SetFlag(n, "wrap:immutable"); + } + emitter->enterVariable(n); + + Language::variableHandler(n); + + emitter->exitVariable(n); + + return SWIG_OK; } /* --------------------------------------------------------------------- @@ -108,10 +1415,30 @@ int JAVASCRIPT::variableHandler(Node *n) { int JAVASCRIPT::globalvariableHandler(Node *n) { - emitter->SwitchContext(n); + emitter->switchNamespace(n); - Language::globalvariableHandler(n); + Language::globalvariableHandler(n); + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * constantHandler() + * + * Function handler for generating wrappers for constants + * --------------------------------------------------------------------- */ + + +int JAVASCRIPT::constantWrapper(Node *n) { + + // TODO: handle callback declarations + //Note: callbacks trigger this wrapper handler + if (Equal(Getattr(n, "kind"), "function")) { return SWIG_OK; + } + //Language::constantWrapper(n); + emitter->emitConstant(n); + + return SWIG_OK; } /* --------------------------------------------------------------------- @@ -121,28 +1448,35 @@ int JAVASCRIPT::globalvariableHandler(Node *n) { * --------------------------------------------------------------------- */ int JAVASCRIPT::classHandler(Node *n) { - emitter->SwitchContext(n); + emitter->switchNamespace(n); - emitter->EnterClass(n); - Language::classHandler(n); - emitter->ExitClass(n); + emitter->enterClass(n); + Language::classHandler(n); + emitter->exitClass(n); - return SWIG_OK; + return SWIG_OK; } int JAVASCRIPT::fragmentDirective(Node *n) { - - // catch all fragment directives that have "templates" as location - // and register them at the emitter. - String *section = Getattr(n, "section"); - - if(Cmp(section, "templates") == 0) { - emitter->RegisterTemplate(Getattr(n, "value"), Getattr(n, "code")); - } else { - Swig_fragment_register(n); - } - - return SWIG_OK; + + // catch all fragment directives that have "templates" as location + // and register them at the emitter. + String *section = Getattr(n, "section"); + + if (Cmp(section, "templates") == 0) { + emitter->registerTemplate(Getattr(n, "value"), Getattr(n, "code")); + } else { + Swig_fragment_register(n); + } + + return SWIG_OK; +} + +int JAVASCRIPT::constantDirective(Node *n) { + + Language::constantDirective(n); + + return SWIG_OK; } /* --------------------------------------------------------------------- @@ -153,17 +1487,17 @@ int JAVASCRIPT::fragmentDirective(Node *n) { * --------------------------------------------------------------------- */ int JAVASCRIPT::top(Node *n) { - - emitter->Initialize(n); - - Language::top(n); - - emitter->Dump(n); - emitter->Close(); - - delete emitter; - - return SWIG_OK; + + emitter->initialize(n); + + Language::top(n); + + emitter->dump(n); + emitter->close(); + + delete emitter; + + return SWIG_OK; } /* --------------------------------------------------------------------- @@ -174,65 +1508,70 @@ int JAVASCRIPT::top(Node *n) { void JAVASCRIPT::main(int argc, char *argv[]) { - const char* lib_dir; + // Set javascript subdirectory in SWIG library + SWIG_library_directory("javascript"); - // Set javascript subdirectory in SWIG library - SWIG_library_directory("javascript"); - - int mode = -1; - - for (int i = 1; i < argc; i++) { - if (argv[i]) { - if (strcmp(argv[i], "-v8") == 0) { - Swig_mark_arg(i); - mode = JSEmitter::V8; - SWIG_library_directory("javascript/v8"); - } else if (strcmp(argv[i], "-jsc") == 0) { - Swig_mark_arg(i); - mode = JSEmitter::JavascriptCore; - SWIG_library_directory("javascript/jsc"); - } else if (strcmp(argv[i], "-qt") == 0) { - Swig_mark_arg(i); - mode = JSEmitter::QtScript; - SWIG_library_directory("javascript/qt"); - } - } + int mode = -1; + + bool debug_templates = false; + for (int i = 1; i < argc; i++) { + if (argv[i]) { + if (strcmp(argv[i], "-v8") == 0) { + Swig_mark_arg(i); + mode = JSEmitter::V8; + SWIG_library_directory("javascript/v8"); + } else if (strcmp(argv[i], "-jsc") == 0) { + Swig_mark_arg(i); + mode = JSEmitter::JavascriptCore; + SWIG_library_directory("javascript/jsc"); + } else if (strcmp(argv[i], "-qt") == 0) { + Swig_mark_arg(i); + mode = JSEmitter::QtScript; + SWIG_library_directory("javascript/qt"); + } else if (strcmp(argv[i], "-debug-templates") == 0) { + Swig_mark_arg(i); + debug_templates = true; + } } - - switch(mode) { - case JSEmitter::V8: - { - emitter = create_v8_emitter(); - break; - } - case JSEmitter::JavascriptCore: - { - // TODO: emitter = create_jsc_emitter(); - break; - } - case JSEmitter::QtScript: - { - // TODO: emitter = create_qtscript_emitter(); - break; - } - default: - { - Printf(stderr, "Unknown emitter type."); - SWIG_exit(-1); - } - } - - - // Add a symbol to the parser for conditional compilation - Preprocessor_define("SWIGJAVASCRIPT 1", 0); + } - // Add typemap definitions - SWIG_typemap_lang("javascript"); + switch (mode) { + case JSEmitter::V8: + { + // TODO: emitter = create_v8_emitter(); + break; + } + case JSEmitter::JavascriptCore: + { + emitter = swig_javascript_create_JSC_emitter(); + break; + } + case JSEmitter::QtScript: + { + // TODO: emitter = create_qtscript_emitter(); + break; + } + default: + { + Printf(stderr, "Unknown emitter type."); + SWIG_exit(-1); + break; + } + } - // Set configuration file - SWIG_config_file("javascript.swg"); + if (debug_templates) { + emitter->enableDebug(); + } + // Add a symbol to the parser for conditional compilation + Preprocessor_define("SWIGJAVASCRIPT 1", 0); - allow_overloading(); + // Add typemap definitions + SWIG_typemap_lang("javascript"); + + // Set configuration file + SWIG_config_file("javascript.swg"); + + allow_overloading(); } /* ----------------------------------------------------------------------------- diff --git a/Tools/javascript/javascript.cxx b/Tools/javascript/javascript.cxx new file mode 100644 index 000000000..9e7dd2809 --- /dev/null +++ b/Tools/javascript/javascript.cxx @@ -0,0 +1,217 @@ + +#include +#include +#include + +#include +#include +#include + +#include + +#include + +using namespace std; + +static JSValueRef jsc_printstring(JSContextRef context,JSObjectRef object, JSObjectRef globalobj, size_t argc, const JSValueRef args[], JSValueRef* ex); +static char* jsccreateStringWithContentsOfFile(const char* fileName); +bool jsc_registerFunction(JSGlobalContextRef context, JSObjectRef object, const char* FunctionName,JSObjectCallAsFunctionCallback cbFunction); + +typedef void* HANDLE; +typedef int (*JSCIntializer)(JSGlobalContextRef context); + +void jsc_printError(JSContextRef, JSValueRef, const std::string&); + +void print_usage() { + std::cout << "javascript [-l module] " << std::endl; +} + +int main(int argc, char* argv[]) { + + std::string scriptPath; + + std::vector module_names; + + std::vector loaded_modules; + std::vector module_initializers; + + for (int idx = 1; idx < argc; ++idx) { + if(strcmp(argv[idx], "-l") == 0) { + idx++; + if(idx > argc) { + print_usage(); + exit(-1); + } + std::string module_name(argv[idx]); + module_names.push_back(module_name); + } else { + scriptPath = argv[idx]; + } + } + + for(std::vector::iterator it = module_names.begin(); + it != module_names.end(); ++it) { + std::string module_name = *it; + std::string lib_name = std::string("lib").append(module_name).append(".so"); + + HANDLE handle = dlopen(lib_name.c_str(), RTLD_LAZY); + if(handle == 0) { + std::cout << "Could not load library " << lib_name << ":" + << std::endl << dlerror() << std::endl; + continue; + } + + std::string symname; + symname.append(module_name).append("_initialize"); + + JSCIntializer init_function = reinterpret_cast((long) dlsym(handle, symname.c_str())); + if(init_function == 0) { + std::cout << "Could not find initializer function in module " << module_name << std::endl; + dlclose(handle); + continue; + } + + loaded_modules.push_back(handle); + module_initializers.push_back(init_function); + } + + static int failed; + + JSGlobalContextRef context = JSGlobalContextCreate(NULL); + JSObjectRef globalObject = JSContextGetGlobalObject(context); + + jsc_registerFunction(context, globalObject, "print", jsc_printstring); // Utility print function + + // Call module initializers + for(std::vector::iterator it = module_initializers.begin(); + it != module_initializers.end(); ++it) { + JSCIntializer init_function = *it; + init_function(context); + } + + // Evaluate the javascript + char* scriptContent = jsccreateStringWithContentsOfFile(scriptPath.c_str()); + JSStringRef jsScript; + + if(!scriptContent) { + printf("FAIL: runme script could not be loaded.\n"); + failed = 1; + } + else { + JSValueRef ex; + jsScript = JSStringCreateWithUTF8CString(scriptContent); + JSValueRef jsResult = JSEvaluateScript(context, jsScript, 0, 0, 0, &ex); + + if (!jsResult && ex) { + jsc_printError(context, ex, scriptPath); + failed = 1; + } + } + + if (scriptContent != NULL) { + free(scriptContent); + } + + JSStringRelease(jsScript); + + JSGlobalContextRelease(context); + globalObject = 0; + + for(std::vector::iterator it = loaded_modules.begin(); + it != loaded_modules.end(); ++it) { + HANDLE handle = *it; + dlclose(handle); + } + + if (failed) { + printf("FAIL: Some tests failed.\n"); + return 1; + } +} + +static JSValueRef jsc_printstring(JSContextRef context,JSObjectRef object, JSObjectRef globalobj, size_t argc, const JSValueRef args[], JSValueRef* ex) +{ + if (argc > 0) + { + JSStringRef string = JSValueToStringCopy(context, args[0], NULL); + size_t numChars = JSStringGetMaximumUTF8CStringSize(string); + char *stringUTF8 = new char[numChars]; + JSStringGetUTF8CString(string, stringUTF8, numChars); + printf("%s\n", stringUTF8); + + delete[] stringUTF8; + } + + return JSValueMakeUndefined(context); +} + +static char* jsccreateStringWithContentsOfFile(const char* fileName) +{ + char* buffer; + + size_t buffer_size = 0; + size_t buffer_capacity = 1024; + buffer = (char*)malloc(buffer_capacity); + + FILE* f = fopen(fileName, "r"); + if (!f) + { + fprintf(stderr, "Could not open file: %s\n", fileName); + return 0; + } + + while (!feof(f) && !ferror(f)) + { + buffer_size += fread(buffer + buffer_size, 1, buffer_capacity - buffer_size, f); + if (buffer_size == buffer_capacity) + { + // guarantees space for trailing '\0' + buffer_capacity *= 2; + buffer = (char*)realloc(buffer, buffer_capacity); + } + } + fclose(f); + buffer[buffer_size] = '\0'; + + return buffer; +} + +bool jsc_registerFunction(JSGlobalContextRef context, JSObjectRef object, + const char* functionName, JSObjectCallAsFunctionCallback callback) +{ + JSStringRef js_functionName = JSStringCreateWithUTF8CString(functionName); + JSObjectSetProperty(context, object, js_functionName, + JSObjectMakeFunctionWithCallback(context, js_functionName, callback), + kJSPropertyAttributeNone, NULL); + JSStringRelease(js_functionName); + return true; +} + +void jsc_printError(JSContextRef ctx, JSValueRef err, const std::string& sourceUrl) +{ + char *buffer; + + JSStringRef string = JSValueToStringCopy(ctx, err, 0); + size_t length = JSStringGetLength(string); + + buffer = (char*) malloc(length+1); + JSStringGetUTF8CString(string, buffer, length+1); + std::string errMsg(buffer); + JSStringRelease(string); + free(buffer); + + JSObjectRef errObj = JSValueToObject(ctx, err, 0); + + if(errObj == 0) { + return; + } + // Note: usually you would also retrieve the property "sourceURL" + // though, it happened that this was always "" + JSStringRef lineKey = JSStringCreateWithUTF8CString("line"); + JSValueRef jsLine = JSObjectGetProperty(ctx, errObj, lineKey, 0); + int line = (int) JSValueToNumber(ctx, jsLine, 0); + JSStringRelease(lineKey); + + std::cerr << sourceUrl << ":" << line << ":" << errMsg << std::endl; + +} diff --git a/Tools/swigprinters.gdb b/Tools/swigprinters.gdb new file mode 100644 index 000000000..661aa3ea1 --- /dev/null +++ b/Tools/swigprinters.gdb @@ -0,0 +1,24 @@ +python +import sys +import os + +try: + global SWIG_PRINTER_DIR + sys.path.insert(0, SWIG_PRINTER_DIR) +except NameError: + raise RuntimeError(""" +--------------------------------------------------------- +Change ~/.gdbinit to be able to use swig pretty printers: +> set python SWIG_PRINTER_DIR = /Tools +> source /Tools/swigprinters.gdb +--------------------------------------------------------- +""") + +from swigprinters import register_swig_printers, enableGdbPrintWorkaround, \ + setChildrenRecursionLevel + +#enableGdbPrintWorkaround() +#setChildrenRecursionLevel(2) +register_swig_printers (None) + +end diff --git a/Tools/swigprinters.py b/Tools/swigprinters.py new file mode 100755 index 000000000..741565997 --- /dev/null +++ b/Tools/swigprinters.py @@ -0,0 +1,574 @@ +import gdb +import gdb.types +import itertools +import re + +log_file = None +GDB_FLATTENED_CHILDREN_WORKAROUND = False +CHILDREN_MAX_RECURSION_LEVEL = 0 + +# workaround: don't cast the following DOHs to it's actual type +# to avoid infinite pretty-print loops +cast_black_list = { + 'Hash': set(['parentNode', 'symtab', 'csymtab', 'sym:symtab', 'inherit', 'nextSibling', 'previousSibling']) +} + +def print_(msg): + global log_file; + + if True: + if log_file == None: + log_file = open('swig_gdb.log', 'w') + log_file.write(msg) + + print(msg) + +class SwigStringPrinter: + """ + Pretty print Swig String* types. + """ + + def __init__ (self, typename, val): + self.typename = typename + self.val = val + + try: + self.t_swigstr_ptr = gdb.lookup_type("struct String").pointer() + self.t_doh_base_ptr = gdb.lookup_type("DohBase").pointer() + except Exception as err: + print_("SwigStringPrinter: Could not retrieve gdb types.\n %s.\n"%(str(err))) + + def display_hint(self): + return 'string' + + def to_string(self): + ret = "" + + # Conversion taken from Swig Internals manual: + # http://peregrine.hpc.uwm.edu/Head-node-docs/swig/2.0.4/Devel/internals.html#7 + # (*(struct String *)(((DohBase *)s)->data)).str + + dohbase = None; + str_data = None; + char_ptr = None; + + try: + dohbase = self.val.reinterpret_cast(self.t_doh_base_ptr).dereference() + except Exception as err: + print_("SwigStringPrinter: Could not dereference DOHBase*\n"); + return ""; + + try: + str_data = dohbase['data'].reinterpret_cast(self.t_swigstr_ptr).dereference() + except Exception as err: + print_("SwigStringPrinter: Could not dereference struct String*\n"); + return ""; + + try: + char_ptr = str_data['str'] + except Exception as err: + print_("SwigStringPrinter: Could not access field (struct String).str\n"); + return ""; + + if char_ptr.is_lazy is True: + char_ptr.fetch_lazy () + + try: + ret = char_ptr.string() + except Exception as err: + print_("SwigStringPrinter: Could not convert const char* to string\n"); + return ""; + + return ret + +class SwigIterator: + + def __init__(self): + + self.t_doh_base_ptr = gdb.lookup_type("DohBase").pointer() + self.t_string_ptr = gdb.lookup_type("String").pointer() + self.t_node_ptr = gdb.lookup_type("Node").pointer() + self.t_hash_ptr = gdb.lookup_type("Hash").pointer() + self.t_file_ptr = gdb.lookup_type("File").pointer() + self.t_void_ptr = gdb.lookup_type("void").pointer() + + def cast_doh(self, doh, name = None): + + if doh == 0: + return doh + + doh = doh.reinterpret_cast(self.t_doh_base_ptr); + + val_base = doh.dereference() + val_type = val_base['type'].dereference() + val_typestr = val_type['objname'].string() + + if not name == None and val_typestr in cast_black_list: + blacklist = cast_black_list[val_typestr] + if name in blacklist: + return doh + + if "String" == val_typestr: + doh = doh.reinterpret_cast(self.t_string_ptr) + elif "File" == val_typestr: + doh = doh.reinterpret_cast(self.t_file_ptr) + # BUG: GDB Pyhton can not handle cyclic references yet + # so these casts are deactivated + elif "Hash" == val_typestr: + doh = doh.reinterpret_cast(self.t_hash_ptr) + elif "Node" == val_typestr: + doh = doh.reinterpret_cast(self.t_node_ptr) + + return doh + +class SwigListIterator(SwigIterator): + + def __init__(self, val): + SwigIterator.__init__(self); + + try: + self.valid = False + + self.val = val.reinterpret_cast(self.t_doh_base_ptr) + val_base = self.val.dereference() + val_type = val_base['type'].dereference() + val_typestr = val_type['objname'].string() + #print_("SwigListIterator: constructing iterator for value of type %s"%val_typestr) + + self.t_struct_list_ptr = gdb.lookup_type("struct List").pointer() + + doh_base = self.val.dereference() + self.l = doh_base['data'].reinterpret_cast(self.t_struct_list_ptr).dereference() + + self.address = 0 + self._index = 0 + self.key = 0 + self.item = 0 + + self.address = self.val.dereference().address + + self.is_first = True + self.valid = True + + except Exception as err: + print_("SwigListIterator: Construction failed.\n %s.\n"%(str(err))) + + def __iter__(self): + return self + + def List_first(self): + + self.object = None; + self._index = 0 + self.key = 0 + self.nitems = int(self.l['nitems']) + self.items = self.l['items'] + + if self.nitems > 0: + self.item = self.items[0] + else: + self.stop() + + def List_next(self): + self._index = self._index + 1 + if self._index >= self.nitems: + self.stop() + else: + self.item = self.items[self._index] + + def next(self): + + if not self.valid: + self.stop() + + if self.is_first: + self.is_first = False + try: + self.List_first() + except StopIteration: + raise StopIteration + except Exception as err: + print_("Error during iteration to first node: \n %s \n" %(str(err))) + self.stop() + else: + try: + self.List_next() + except StopIteration: + raise StopIteration + except Exception as err: + print_("Error during iteration to first node: \n %s \n" %(str(err))) + self.stop() + + key_str = "[%d]"%self._index + item = 0 + + try: + item = self.cast_doh(self.item) + except Exception as err: + print_("SwigListIterator(%s): Exception during casting of value doh:\n %s\n" % (str(self.address), str(err)) ) + self.stop() + + return (key_str, item) + + def stop(self): + self.is_first = True + self.item = 0 + self.key = 0 + raise StopIteration + +class SwigHashIterator(SwigIterator): + + def __init__(self, val): + SwigIterator.__init__(self); + + try: + self.valid = False + + self.val = val.reinterpret_cast(self.t_doh_base_ptr) + + self.t_struct_hash_ptr = gdb.lookup_type("struct Hash").pointer() + self.t_struct_hash_node_ptr = gdb.lookup_type("struct HashNode").pointer() + + doh_base = self.val.dereference() + hash_ = doh_base['data'].reinterpret_cast(self.t_struct_hash_ptr).dereference() + self.hashtable = hash_['hashtable'] + self.hashsize = int(hash_['hashsize']) + self.nitems = int(hash_['nitems']) + + self.next_ = 0 + self.address = 0 + self.pos = 0; + self._current = 0 + self.item = 0 + self.key = 0 + self._index = 0 + + self.address = self.val.dereference().address + + self.is_first = True + self.valid = True + + except Exception as err: + print_("SwigHashIterator: Construction failed.\n %s.\n"%(str(err))) + + def __iter__(self): + return self + + def Hash_firstiter(self): + self._current = 0; + self.item = 0; + self.key = 0; + self._index = 0; + + while (self._index < self.hashsize) and (self.hashtable[self._index] == 0): + self._index = self._index+1; + + if self._index >= self.hashsize: + self.stop(); + + self._current = self.hashtable[self._index] + self._current = self._current.reinterpret_cast(self.t_struct_hash_node_ptr); + self.item = self._current['object']; + self.key = self._current['key']; + + self._current = self._current['next']; + + + def Hash_nextiter(self): + if self._current == 0: + self._index = self._index + 1 + while (self._index < self.hashsize) and (self.hashtable[self._index] == 0): + self._index = self._index + 1 + + if self._index >= self.hashsize: + self.item = 0; + self.key = 0; + self._current = 0; + self.stop() + + self._current = self.hashtable[self._index]; + + self._current = self._current.reinterpret_cast(self.t_struct_hash_node_ptr); + self.key = self._current['key']; + self.item = self._current['object']; + + self._current = self._current['next']; + + + def next(self): + + if not self.valid: + self.stop() + + if self.is_first: + self.is_first = False + try: + self.Hash_firstiter() + except StopIteration: + raise StopIteration + except Exception as err: + print_("Error during iteration to first node: \n %s \n" %(str(err))) + self.stop() + else: + try: + self.Hash_nextiter() + except StopIteration: + raise StopIteration + except Exception as err: + print_("Error during iteration to first node: \n %s \n" %(str(err))) + self.stop() + + key_str = "" + item = 0 + try: + string_printer = SwigStringPrinter("String *", self.key) + key_str = string_printer.to_string() + except Exception as err: + print_("SwigHashIterator(%s): Exception during extracting key string:\n %s\n" % (str(self.address), str(err)) ) + self.stop() + + try: + item = self.cast_doh(self.item, key_str) + + except Exception as err: + print_("SwigHashIterator(%s): Exception during casting of value doh:\n %s\n" % (str(self.address), str(err)) ) + self.stop() + + return (key_str, item) + + def stop(self): + self.is_first = True + raise StopIteration + +class AlternateKeyValueIterator(): + + def __init__(self, iterable): + self.it = iterable.__iter__() + self._next = None + self.count = -1 + + def __iter__(self): + return self + + def next(self): + if self._next == None: + key, value = self.it.next() + self._next = value + self.count = self.count + 1 + return ("[%d]"%self.count, key) + else: + value = self._next + self._next = None + return ("[%d]"%self.count, value) + +class NopIterator: + + def __init__(self): + pass + + def __iter__(self): + return self + + def next(self): + raise StopIteration + +class SwigListPrinter: + """ + Pretty print Swig List* types (also ParmList*). + """ + + def __init__ (self, typename, val): + + self.typename = typename + self.val = val + + it = SwigListIterator(val) + self.valid = it.valid + self.address = it.address + + + def display_hint(self): + return 'array' + + def to_string(self): + return "%s(%s)" % (str(self.typename), str(self.address)) + + def children(self): + + if not self.valid: + print_("SwigListPrinter: Invalid state.\n") + return NopIterator() + + try: + it = SwigListIterator(self.val) + return it + except Exception as err: + print_("SwigListPrinter: Error during creation of children iterator. \n %s \n" %(str(err))) + raise err + +class SwigHashPrinter: + """ + Pretty print Swig Hash* types (also Node*). + """ + + def __init__ (self, typename, val): + + self.typename = typename + self.val = val + it = SwigHashIterator(val) + self.valid = it.valid + self.address = it.address + self.level = 0; + + def display_hint(self): + return 'map' + + def to_string(self): + return "%s(%s)" % (str(self.typename), str(self.address)) + + def children(self): + global GDB_FLATTENED_CHILDREN_WORKAROUND + global CHILDREN_MAX_RECURSION_LEVEL + + if not self.valid: + print_("SwigHashPrinter: Invalid state.\n") + return NopIterator() + + if self.level > CHILDREN_MAX_RECURSION_LEVEL: + return NopIterator() + + try: + it = SwigHashIterator(self.val) + if GDB_FLATTENED_CHILDREN_WORKAROUND: + return AlternateKeyValueIterator(it) + return it + except Exception as err: + print_("SwigHashPrinter: Error during creation of children iterator. \n %s \n" %(str(err))) + raise err + +class SwigSimplePrinter: + def __init__ (self, typename, val): + self.typename = typename + self.val = val + + def display_hint(self): + return "string" + + def to_string(self): + return "%s(%s)"%(self.typename, str(self.val.address)) + +class SwigDelegatingPrinter: + + def __init__ (self, typename, val): + t_doh_base_ptr = gdb.lookup_type("DohBase").pointer() + val_base = val.reinterpret_cast(t_doh_base_ptr).dereference() + val_type = val_base['type'].dereference() + val_typestr = val_type['objname'].string() + self.has_children = False + + if val_typestr == "Hash": + self.delegate = SwigHashPrinter(typename, val) + self.has_children = True + elif val_typestr == "List": + self.delegate = SwigListPrinter(typename, val) + self.has_children = True + elif val_typestr == "String": + self.delegate = SwigStringPrinter(typename, val) + else: + self.delegate = SwigSimplePrinter(typename, val) + + def display_hint(self): + return self.delegate.display_hint() + + def to_string(self): + return self.delegate.to_string() + + def children(self): + if not self.has_children: + return NopIterator() + + return self.delegate.children() + +class RxPrinter(object): + def __init__(self, name, function): + super(RxPrinter, self).__init__() + self.name = name + self.function = function + self.enabled = True + + def invoke(self, value): + if not self.enabled: + return None + return self.function(self.name, value) + +# A pretty-printer that conforms to the "PrettyPrinter" protocol from +# gdb.printing. It can also be used directly as an old-style printer. +class Printer(object): + def __init__(self, name): + super(Printer, self).__init__() + self.name = name + self.subprinters = [] + self.lookup = {} + self.enabled = True + self.compiled_rx = re.compile('^([a-zA-Z0-9_: *]+)$') + + def add(self, name, function): + if not self.compiled_rx.match(name): + raise ValueError, 'error: "%s" does not match' % name + + printer = RxPrinter(name, function) + self.subprinters.append(printer) + self.lookup[name] = printer + print('Added pretty printer for %s. ' % (name)) + + def __call__(self, val): + typename = str(val.type) + if typename in self.lookup: + ret = self.lookup[typename].invoke(val) + return ret + + # Cannot find a pretty printer. Return None. + return None + +swig_printer = None + +def register_swig_printers(obj): + global swig_printer + + if obj is None: + obj = gdb + + obj.pretty_printers.append(swig_printer) + +def build_swig_printer(): + global swig_printer + + swig_printer = Printer("swig") + swig_printer.add('String *', SwigStringPrinter) + swig_printer.add('const String *', SwigStringPrinter) + swig_printer.add('SwigType *', SwigStringPrinter) + swig_printer.add('Hash *', SwigHashPrinter) + swig_printer.add('const Hash *', SwigHashPrinter) + swig_printer.add('Node *', SwigHashPrinter) + swig_printer.add('const Node *', SwigHashPrinter) + swig_printer.add('Parm *', SwigHashPrinter) + swig_printer.add('const Parm *', SwigHashPrinter) + swig_printer.add('List *', SwigListPrinter) + swig_printer.add('const List *', SwigListPrinter) + swig_printer.add('ParmList *', SwigDelegatingPrinter) + swig_printer.add('const ParmList *', SwigDelegatingPrinter) + swig_printer.add('File *', SwigDelegatingPrinter) + #swig_printer.add('DOH *', SwigDelegatingPrinter) + #swig_printer.add('const DOH *', SwigDelegatingPrinter) + + print_("Loaded swig printers\n"); + +def enableGdbPrintWorkaround(): + global GDB_FLATTENED_CHILDREN_WORKAROUND + GDB_FLATTENED_CHILDREN_WORKAROUND = True + +def setChildrenRecursionLevel(level): + global CHILDREN_MAX_RECURSION_LEVEL + CHILDREN_MAX_RECURSION_LEVEL = level + +build_swig_printer() diff --git a/configure.in b/configure.in index 77791bd02..92955c4c0 100644 --- a/configure.in +++ b/configure.in @@ -1077,6 +1077,140 @@ AC_SUBST(JAVALDSHARED) AC_SUBST(JAVACXXSHARED) AC_SUBST(JAVACFLAGS) +#---------------------------------------------------------------- +# Look for JAVASCRIPT [JavaScriptCore Headers and Library] +#---------------------------------------------------------------- +AC_ARG_WITH(javascript, AS_HELP_STRING([--without-javascript], [Disable JAVASCRIPT]), [with_javascript="$withval"], [with_javascript=yes]) + +# First, check for "--without-javascript" or "--with-javascript=no". +if test x"${with_javascript}" = xno -o x"${with_alllang}" = xno ; then +AC_MSG_NOTICE([Disabling Javascript]) +JAVASCRIPT= +else + +# check for include files +AC_MSG_CHECKING(for include file JavaScriptCore/JavaScript.h) +AC_ARG_WITH(javascriptincl, [ --with-javascript=path Set location of Javascript include directory], [JSCOREINCDIR="$withval"], [JSCOREINCDIR=]) + +if test -z "$JSCOREINCDIR"; then + JSCOREINCDIR="/usr/include/ /usr/local/include/" + + # Add in default directory for JavaScriptCore headers for Linux and MacOSX + case $host in + *-*-linux*) JSCOREINCDIR="/usr/include/webkit-1.0/ /usr/include/webkitgtk-1.0/ /usr/local/include/webkit-1.0/JavaScriptCore/ $JSCOREINCDIR";; + *-*-darwin*) JSCOREINCDIR="/System/Library/Frameworks/JavaScriptCore.framework/Headers/ $JSCOREINCDIR";; + *);; + esac +fi + +for d in $JSCOREINCDIR ; do + if test -r "$d/JavaScriptCore/JavaScript.h" || test -r "$d/JavaScript.h" ; then + AC_MSG_RESULT($d) + JSCOREINCDIR=$d + JSCOREINC=-I\"$d\" + break + fi +done + +if test "$JSCOREINC" = "" ; then + AC_MSG_RESULT(not found) +fi + + +# check for JavaScriptCore, Webkit libraries +AC_ARG_WITH(jscorelib,[ --with-jscorelib =path Set location of JavaScriptCore (Webkit) library directory],[ + JSCORELIB="-L$withval"], [JSCORELIB=]) +AC_MSG_CHECKING(for JavaScriptCore(Webkit) library) + +if test -z "$JSCORELIB"; then +dirs="/usr/lib/ /usr/local/lib/" +for i in $dirs ; do + + if test -r $i/libwebkit-1.0.la; then + AC_MSG_RESULT($i) + JSCORELIB="-L$i -lwebkit-1.0" + break + fi + + if test -r $i/libjavascriptcoregtk-1.0.so; then + AC_MSG_RESULT($i) + JSCORELIB="-L$i -ljavascriptcoregtk-1.0" + break + fi + + if test -r $i/libwebkitgtk-1.0.so; then + AC_MSG_RESULT($i) + JSCORELIB="-L$i -lwebkitgtk-1.0" + break + fi +done + +if test -z "$JSCORELIB"; then + AC_MSG_RESULT(not found) +fi + +else +AC_MSG_RESULT($JSCORELIB) +fi + + +# linking options +case $host in +*-*-darwin*) + JSCOREDYNAMICLINKING="-framework JavaScriptCore" + JSCORECFLAGS="" + ;; +*-*-linux*) + JSCOREDYNAMICLINKING="$JSCORELIB" + JSCORECFLAGS="" + ;; +*) + JSCOREDYNAMICLINKING="" + JSCORECFLAGS="" + ;; +esac + +# JSCORELIBRARYPREFIX +case $host in +*-*-cygwin* | *-*-mingw*) JSCORELIBRARYPREFIX="";; +*) JSCORELIBRARYPREFIX="lib";; +esac + +if "$JS_NO_WARNINGS" == "1"; then +case $host in +*-*-darwin* | *-*-linux* | *-*-cygwin* | *-*-mingw*) + echo "HHHHHHHHHHHHHHHHHHHHHHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + JSCXXFLAGS="`echo $CXXFLAGS | sed 's/-Wall//g'`" + ;; +*) + JSCXXFLAGS="$CXXFLAGS" +esac +fi + +# library output +case $host in +*-*-darwin*) + JSCORESO=".dylib" + JSCORELDSHARED='$(CC) -dynamiclib' + JSCORECXXSHARED='$(CXX) -dynamiclib' + ;; +*) + JSCORESO=$SO + JSCORELDSHARED='$(LDSHARED)' + JSCORECXXSHARED='$(CXXSHARED)' + ;; +esac +fi + +AC_SUBST(JSCOREINC) +AC_SUBST(JSCOREDYNAMICLINKING) +AC_SUBST(JSCORELIBRARYPREFIX) +AC_SUBST(JSCORECFLAGS) +AC_SUBST(JSCORESO) +AC_SUBST(JSCORELDSHARED) +AC_SUBST(JSCORECXXSHARED) +AC_SUBST(JSCXXFLAGS) + #---------------------------------------------------------------- # Look for gcj #---------------------------------------------------------------- @@ -2237,6 +2371,20 @@ if test -z "$JAVA" || test -z "$JAVAC" || test -z "$JAVAINC" ; then fi AC_SUBST(SKIP_JAVA) +SKIP_JAVASCRIPT= +if test -z "$JSCOREINC"; then + # Add in default directory for JavaScriptCore headers for Linux and MacOSX + case $host in + *-*-linux*) if test -z "$JSCORELIB"; then + SKIP_JAVASCRIPT="1" + fi + ;; + *-*-darwin*)SKIP_JAVASCRIPT="1" + ;; + *);; + esac +fi +AC_SUBST(SKIP_JAVASCRIPT) SKIP_GUILE= if test -z "$GUILEINCLUDE" || test -z "$GUILELIB" || test -z "$GUILE_GH_INTERFACE"; then @@ -2443,6 +2591,7 @@ AC_CONFIG_FILES([ \ Examples/test-suite/uffi/Makefile \ Examples/test-suite/r/Makefile \ Examples/test-suite/go/Makefile \ + Examples/test-suite/javascript/Makefile \ Lib/ocaml/swigp4.ml ]) AC_CONFIG_FILES([preinst-swig], [chmod +x preinst-swig]) From 35e6b73d2acbcc010bd239a83fbf16cecefe7b70 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:57:42 +0000 Subject: [PATCH 0092/1048] Add swig configuration files for v8. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13765 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/jsc/ccomplex.i | 2 +- Lib/javascript/jsc/javascriptfragments.swg | 0 Lib/javascript/jsc/javascripttypemaps.swg | 5 - Lib/javascript/jsc/javascriptvaltypes.swg | 1 - Lib/javascript/v8/ccomplex.i | 26 ++ Lib/javascript/v8/complex.i | 6 + Lib/javascript/{ => v8}/javascript.swg | 8 +- Lib/javascript/v8/javascriptcomplex.swg | 146 +++++++++++ Lib/javascript/v8/javascriptinit.swg | 15 ++ Lib/javascript/{ => v8}/javascriptkw.swg | 0 Lib/javascript/v8/javascriptprimitives.swg | 280 +++++++-------------- Lib/javascript/v8/javascriptruntime.swg | 90 +++++++ Lib/javascript/v8/javascripttypemaps.swg | 16 ++ Lib/javascript/v8/std_common.i | 5 + Lib/javascript/v8/std_complex.i | 19 ++ Lib/javascript/v8/std_except.i | 1 + Lib/javascript/v8/std_map.i | 74 ++++++ Lib/javascript/v8/std_pair.i | 34 +++ Lib/javascript/v8/std_vector.i | 85 +++++++ Lib/javascript/v8/stl.i | 10 + 20 files changed, 630 insertions(+), 193 deletions(-) delete mode 100644 Lib/javascript/jsc/javascriptfragments.swg delete mode 100644 Lib/javascript/jsc/javascriptvaltypes.swg create mode 100644 Lib/javascript/v8/ccomplex.i create mode 100644 Lib/javascript/v8/complex.i rename Lib/javascript/{ => v8}/javascript.swg (76%) create mode 100644 Lib/javascript/v8/javascriptcomplex.swg create mode 100644 Lib/javascript/v8/javascriptinit.swg rename Lib/javascript/{ => v8}/javascriptkw.swg (100%) create mode 100644 Lib/javascript/v8/javascripttypemaps.swg create mode 100755 Lib/javascript/v8/std_common.i create mode 100644 Lib/javascript/v8/std_complex.i create mode 100644 Lib/javascript/v8/std_except.i create mode 100755 Lib/javascript/v8/std_map.i create mode 100755 Lib/javascript/v8/std_pair.i create mode 100755 Lib/javascript/v8/std_vector.i create mode 100755 Lib/javascript/v8/stl.i diff --git a/Lib/javascript/jsc/ccomplex.i b/Lib/javascript/jsc/ccomplex.i index 8eda920bb..50f0f95fe 100644 --- a/Lib/javascript/jsc/ccomplex.i +++ b/Lib/javascript/jsc/ccomplex.i @@ -6,7 +6,7 @@ * ----------------------------------------------------------------------------- */ -%include +%include %{ #include diff --git a/Lib/javascript/jsc/javascriptfragments.swg b/Lib/javascript/jsc/javascriptfragments.swg deleted file mode 100644 index e69de29bb..000000000 diff --git a/Lib/javascript/jsc/javascripttypemaps.swg b/Lib/javascript/jsc/javascripttypemaps.swg index e8711cfc5..9bde8eb2a 100644 --- a/Lib/javascript/jsc/javascripttypemaps.swg +++ b/Lib/javascript/jsc/javascripttypemaps.swg @@ -9,17 +9,12 @@ #define SWIG_SetConstant(name, obj) #define SWIG_Raise(obj, type, desc) SWIG_Javascript_Raise(context, exception, type) -%include - /* Include fundamental fragemt definitions */ %include /* Python fragments for fundamental types */ %include -/* override some of the macros in global valtypes.swg */ -%include - %include /* Include the unified typemap library */ diff --git a/Lib/javascript/jsc/javascriptvaltypes.swg b/Lib/javascript/jsc/javascriptvaltypes.swg deleted file mode 100644 index 8b1378917..000000000 --- a/Lib/javascript/jsc/javascriptvaltypes.swg +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Lib/javascript/v8/ccomplex.i b/Lib/javascript/v8/ccomplex.i new file mode 100644 index 000000000..8eda920bb --- /dev/null +++ b/Lib/javascript/v8/ccomplex.i @@ -0,0 +1,26 @@ +/* ----------------------------------------------------------------------------- + * ccomplex.i + * + * C complex typemaps + * ISO C99: 7.3 Complex arithmetic + * ----------------------------------------------------------------------------- */ + + +%include + +%{ +#include +%} + + +/* C complex constructor */ +#define CCplxConst(r, i) ((r) + I*(i)) + +%swig_cplxflt_convn(float complex, CCplxConst, creal, cimag); +%swig_cplxdbl_convn(double complex, CCplxConst, creal, cimag); +%swig_cplxdbl_convn(complex, CCplxConst, creal, cimag); + +/* declaring the typemaps */ +%typemaps_primitive(SWIG_TYPECHECK_CPLXFLT, float complex); +%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, double complex); +%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, complex); diff --git a/Lib/javascript/v8/complex.i b/Lib/javascript/v8/complex.i new file mode 100644 index 000000000..4c3b3c5e2 --- /dev/null +++ b/Lib/javascript/v8/complex.i @@ -0,0 +1,6 @@ +#ifdef __cplusplus +%include +#else +%include +#endif + diff --git a/Lib/javascript/javascript.swg b/Lib/javascript/v8/javascript.swg similarity index 76% rename from Lib/javascript/javascript.swg rename to Lib/javascript/v8/javascript.swg index fb01a63bb..3a83b6495 100644 --- a/Lib/javascript/javascript.swg +++ b/Lib/javascript/v8/javascript.swg @@ -4,12 +4,16 @@ * Javascript typemaps * ----------------------------------------------------------------------------- */ +%include + +%include + %include %include -%include - %include %include + +%include diff --git a/Lib/javascript/v8/javascriptcomplex.swg b/Lib/javascript/v8/javascriptcomplex.swg new file mode 100644 index 000000000..7d165dce4 --- /dev/null +++ b/Lib/javascript/v8/javascriptcomplex.swg @@ -0,0 +1,146 @@ +/* + Defines the As/From converters for double/float complex, you need to + provide complex Type, the Name you want to use in the converters, + the complex Constructor method, and the Real and Imag complex + accessor methods. + + See the std_complex.i and ccomplex.i for concret examples. +*/ + +/* the common from converter */ +%define %swig_fromcplx_conv(Type, Real, Imag) +%fragment(SWIG_From_frag(Type),"header", + fragment=SWIG_From_frag(double)) +{ +SWIGINTERNINLINE JSObjectRef +SWIG_From_dec(Type)(%ifcplusplus(const Type&, Type) c) +{ + JSValueRef vals[2]; + vals[0] = SWIG_From(double)(Real(c)); + vals[1] = SWIG_From(double)(Imag(c)); + return JSObjectMakeArray(context, 2, vals, NULL); +} +} +%enddef + +/* the double case */ +%define %swig_cplxdbl_conv(Type, Constructor, Real, Imag) +%fragment(SWIG_AsVal_frag(Type),"header", + fragment=SWIG_AsVal_frag(double)) +{ +SWIGINTERN int +SWIG_AsVal_dec(Type) (JSValueRef o, Type* val) +{ + if (JSValueIsObject(context, o)) { + JSObjectRef array; + JSValueRef exception, js_re, js_im; + double re, im; + int res; + + exception = 0; + res = 0; + + array = JSValueToObject(context, o, &exception); + if(exception != 0) + return SWIG_TypeError; + + js_re = JSObjectGetPropertyAtIndex(context, array, 0, &exception); + if(exception != 0) + return SWIG_TypeError; + + js_im = JSObjectGetPropertyAtIndex(context, array, 1, &exception); + if(exception != 0) + return SWIG_TypeError; + + res = SWIG_AsVal(double)(js_re, &re); + if(!SWIG_IsOK(res)) { + return SWIG_TypeError; + } + + res = SWIG_AsVal(double)(js_im, &im); + if(!SWIG_IsOK(res)) { + return SWIG_TypeError; + } + + if (val) *val = Constructor(re, im); + return SWIG_OK; + } else { + double d; + int res = SWIG_AddCast(SWIG_AsVal(double)(o, &d)); + if (SWIG_IsOK(res)) { + if (val) *val = Constructor(d, 0.0); + return res; + } + } + return SWIG_TypeError; +} +} +%swig_fromcplx_conv(Type, Real, Imag); +%enddef + +/* the float case */ +%define %swig_cplxflt_conv(Type, Constructor, Real, Imag) +%fragment(SWIG_AsVal_frag(Type),"header", + fragment=SWIG_AsVal_frag(float)) { +SWIGINTERN int +SWIG_AsVal_dec(Type)(JSValueRef o, Type *val) +{ + if (JSValueIsObject(context, o)) { + JSObjectRef array; + JSValueRef exception, js_re, js_im; + double re, im; + int res; + + exception = 0; + res = 0; + + array = JSValueToObject(context, o, &exception); + if(exception != 0) + return SWIG_TypeError; + + js_re = JSObjectGetPropertyAtIndex(context, array, 0, &exception); + if(exception != 0) + return SWIG_TypeError; + + js_im = JSObjectGetPropertyAtIndex(context, array, 1, &exception); + if(exception != 0) + return SWIG_TypeError; + + res = SWIG_AsVal(double)(js_re, &re); + if(!SWIG_IsOK(res)) { + return SWIG_TypeError; + } + + res = SWIG_AsVal(double)(js_im, &im); + if(!SWIG_IsOK(res)) { + return SWIG_TypeError; + } + + if ((-FLT_MAX <= re && re <= FLT_MAX) && (-FLT_MAX <= im && im <= FLT_MAX)) { + if (val) *val = Constructor(%numeric_cast(re, float), + %numeric_cast(im, float)); + return SWIG_OK; + } else { + return SWIG_OverflowError; + } + } else { + float re; + int res = SWIG_AddCast(SWIG_AsVal(float)(o, &re)); + if (SWIG_IsOK(res)) { + if (val) *val = Constructor(re, 0.0); + return res; + } + } + return SWIG_TypeError; +} +} + +%swig_fromcplx_conv(Type, Real, Imag); +%enddef + +#define %swig_cplxflt_convn(Type, Constructor, Real, Imag) \ +%swig_cplxflt_conv(Type, Constructor, Real, Imag) + + +#define %swig_cplxdbl_convn(Type, Constructor, Real, Imag) \ +%swig_cplxdbl_conv(Type, Constructor, Real, Imag) diff --git a/Lib/javascript/v8/javascriptinit.swg b/Lib/javascript/v8/javascriptinit.swg new file mode 100644 index 000000000..1186b33bc --- /dev/null +++ b/Lib/javascript/v8/javascriptinit.swg @@ -0,0 +1,15 @@ +%insert(init) %{ +SWIGRUNTIME void +SWIG_V8_SetModule(swig_module_info *swig_module) {} + +SWIGRUNTIME swig_module_info * +SWIG_V8_GetModule(void) { + return 0; +} + +#define SWIG_GetModule(clientdata) SWIG_V8_GetModule() +#define SWIG_SetModule(clientdata, pointer) SWIG_V8_SetModule(pointer) + +%} + +%insert(init) "swiginit.swg" diff --git a/Lib/javascript/javascriptkw.swg b/Lib/javascript/v8/javascriptkw.swg similarity index 100% rename from Lib/javascript/javascriptkw.swg rename to Lib/javascript/v8/javascriptkw.swg diff --git a/Lib/javascript/v8/javascriptprimitives.swg b/Lib/javascript/v8/javascriptprimitives.swg index b8eb1e569..09e1ae9f9 100644 --- a/Lib/javascript/v8/javascriptprimitives.swg +++ b/Lib/javascript/v8/javascriptprimitives.swg @@ -1,119 +1,109 @@ -%typemap(in) bool -%{ $1 = ($1_ltype) $input->BooleanValue();%} - -// Primitive types -%typemap(in) char, - signed char, - unsigned char, - short, - unsigned short, - int -%{ $1 = ($1_ltype) $input->Int32Value();%} - -%typemap(in) unsigned int, - long, - unsigned long, - long long, - unsigned long long -%{ $1 = ($1_ltype) $input->UInt32Value();%} - -%typemap(in) float, double -%{ $1 = ($1_ltype) $input->NumberValue();%} - - -%typemap(in) const bool &, bool &, - const char &, char &, - const signed char &, signed char &, - const unsigned char &, unsigned char &, - const short &, short &, - const unsigned short &, unsigned short &, - const int &, int &, - const unsigned int &, unsigned int &, - const long &, long &, - const unsigned long &, unsigned long &, - const long long &, long long &, - const unsigned long long &, unsigned long long &, - const float &, float &, - const double &, double & -%{ - // TODO: typemap(in) const bool& at al +%fragment(SWIG_From_frag(bool),"header") { +SWIGINTERNINLINE +v8::Handle +SWIG_From_dec(bool)(bool value) +{ + return v8::Boolean::New(value); +} } -%typemap(out) bool -%{ $result = v8::Boolean::New($1);%} +%fragment(SWIG_AsVal_frag(bool),"header", + fragment=SWIG_AsVal_frag(long)) { +SWIGINTERN +int SWIG_AsVal_dec(bool)(v8::Handle obj, bool *val) +{ + if(!obj->IsBoolean()) { + return SWIG_ERROR; + } + + if (val) *val = obj->BooleanValue(); + return SWIG_OK; +} +} -%typemap(out) char, - signed char, - unsigned char, - short, - unsigned short, - int -%{ $result = v8::Int32::New($1);%} - -%typemap(out) unsigned int, - long, - unsigned long, - long long, - unsigned long long -%{ $result = v8::UInt32::New($1);%} +%fragment(SWIG_From_frag(int),"header") { +SWIGINTERNINLINE +v8::Handle SWIG_From_dec(int)(int value) +{ + return v8::Int32::New(value); +} +} -%typemap(out) float, double -%{ $result = v8::Number::New($1); %} +%fragment(SWIG_From_frag(long),"header") { +SWIGINTERNINLINE +v8::Handle SWIG_From_dec(long)(long value) +{ + return v8::Integer::New(value); +} +} -%typemap(out) const bool &, bool & -%{ $result = v8::Boolean::New((*$1);%} +%fragment(SWIG_AsVal_frag(long),"header", + fragment="SWIG_CanCastAsInteger") { +SWIGINTERN +int SWIG_AsVal_dec(long)(v8::Handle obj, long* val) +{ + if (!obj->IsInteger()) { + return SWIG_TypeError; + } + if(val) *val = (long) obj->IntegerValue(); + + return SWIG_OK; +} +} -%typemap(out) const char &, char &, - const signed char &, signed char &, - const unsigned char &, unsigned char &, - const short &, short &, - const unsigned short &, unsigned short &, - const int &, int & -%{ $result = v8::Int32::New((*$1);%} - -%typemap(out) const unsigned int &, unsigned int &, - const long &, long &, - const unsigned long &, unsigned long &, - const long long &, long long &, - const unsigned long long &, unsigned long long & -%{ $result = v8::UInt32::New(*$1);%} +/* unsigned long */ -%typemap(out) const float &, float &, - const double &, double & -%{ $result = v8::Number::New(*$1);%} +%fragment(SWIG_From_frag(unsigned long),"header", + fragment=SWIG_From_frag(long)) { +SWIGINTERNINLINE +v8::Handle SWIG_From_dec(unsigned long)(unsigned long value) +{ + return (value > LONG_MAX) ? + v8::Integer::NewFromUnsigned(value) : v8::Integer::New(%numeric_cast(value,long)); +} +} -%typemap(in) short *, - unsigned short *, - int *, - unsigned int *, - long *, - unsigned long *, - long long *, - unsigned long long *, - float *, - double * -%{ - // TODO: typemap(in): short* et al. -%} +%fragment(SWIG_AsVal_frag(unsigned long),"header", + fragment="SWIG_CanCastAsInteger") { +SWIGINTERN +int SWIG_AsVal_dec(unsigned long)(v8::Handle obj, unsigned long *val) +{ + if(!obj->IsNumber()) { + return SWIG_TypeError; + } + + long longVal = (long) obj->NumberValue(); + + if(longVal < 0) { + return SWIG_OverflowError; + } + + if(val) *val = longVal; + + return SWIG_OK; +} +} +%fragment(SWIG_From_frag(double),"header") { +SWIGINTERN +v8::Handle SWIG_From_dec(double) (double val) +{ + return v8::Number::New(val); +} +} -%typemap(out) short *, - unsigned short *, - int *, - unsigned int *, - long *, - unsigned long *, - long long *, - unsigned long long *, - float *, - double * -%{ - // TODO: typemap(out) short* et al. -%} - -%typemap(out) void -%{ $result = v8::Undefined(); %} - +%fragment(SWIG_AsVal_frag(double),"header") { +SWIGINTERN +int SWIG_AsVal_dec(double)(v8::Handle obj, double *val) +{ + if(!obj->IsNumber()) { + return SWIG_TypeError; + } + if(val) *val = obj->NumberValue(); + + return SWIG_OK; +} +} %typemap(in) char * %{ @@ -121,81 +111,3 @@ $1 = *_$1; %} -%typemap(out) char * -%{ - // TODO: output typemap for char* -%} - -%typemap(in) char *& ($*1_ltype temp = 0) %{ - // TODO: input typemap for char*& -%} - -%typemap(out) char *& -%{ - // TODO: output typemap for char*& -%} - -/* char arrays - treat as String */ -%typemap(in) char[ANY], char[] %{ - // TODO: input typemap for char[] -%} - -%typemap(out) char[ANY], char[] -%{ - // TODO: output typemap for char[] -%} - -%typemap(freearg) char *, char *&, char[ANY], char[] //TODO: Not working: A memory leak -%{ - // TODO: freearg char* et al -%} - -/* Typemaps for composite types */ -%typemap(in) SWIGTYPE ($&1_type argp) // Objects passed by value, convert to a pointer -%{ - // TODO: input typemap for composite types -%} - -%typemap(out) SWIGTYPE ($&1_type temp) -%{ - // TODO: output typemap for composite types -%} - -%typemap(in) SWIGTYPE *, SWIGTYPE & -%{ - // TODO: input typemap for ptr types -%} - -%typemap(out) SWIGTYPE *, SWIGTYPE & -%{ - // TODO: output typemap for ptr types -%} - -// TODO: sanity check? -%typemap(arginit) SWIGTYPE * -%{%} - -%typemap(in) SWIGTYPE (CLASS::*) "" - -%typemap(out) SWIGTYPE (CLASS::*) -%{ - // TODO: output typemap for CLASS::* -%} - -// Default array handling -%typemap(in) SWIGTYPE [] %{ - // TODO: typemap for arrays; -%} - -%typemap(out) SWIGTYPE [] %{ $result = $1; %} - -// Some ANSI C typemaps */ -%apply unsigned long { size_t }; - -%apply const unsigned long & { const size_t & }; - -// Array reference typemaps -%apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } - -// const pointers -%apply SWIGTYPE * { SWIGTYPE *const } diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index ad34b6df2..4440fa6d6 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -7,3 +7,93 @@ %insert(runtime) %{ #include %} + +%insert(runtime) "swigrun.swg"; /* SWIG API */ +%insert(runtime) "swigerrors.swg"; /* SWIG errors */ + +%insert(runtime) %{ +#define SWIG_Error(code, msg) SWIG_V8_exception(code, msg) +#define SWIG_exception(code, msg) SWIG_V8_exception(code, msg) +#define SWIG_fail goto fail +%} + +%insert(runtime) %{ +typedef struct { + bool swigCMemOwn; + void *swigCObject; + swig_type_info *info; +}SWIG_PRV_DATA; +%} + +%insert(runtime) %{ + +void SWIG_V8_Raise(const char* type) { + // TODO: throw v8 exception +} + +void SWIG_V8_exception(int code, const char* msg) { + SWIG_V8_Raise(msg); +} + +%} + + +%insert(runtime) %{ +int SWIG_JSC_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_type_info *info, int flags) { + + if(objRef->InternalFieldCount() < 1) { + return SWIG_ERROR; + } + Handle cdataRef = objRef->GetInternalField(0); + + SWIG_PRV_DATA *cdata = (SWIG_PRV_DATA *) v8::External::Unwrap(cdataRef); + if(cdata == NULL) { + return SWIG_ERROR; + } + + if(cdata->info != info) { + bool type_valid = false; + swig_cast_info *t = info->cast; + while(t != NULL) { + if(t->type == cdata->info) { + type_valid = true; + break; + } + t = t->next; + } + if(!type_valid) { + return SWIG_TypeError; + } + } + + *ptr = cdata->swigCObject; + + if(flags & SWIG_POINTER_DISOWN) { + cdata->swigCMemOwn = false; + } + + return SWIG_OK; +} + +int SWIG_V8_ConvertPtr(v8::Handle valRef, void** ptr, swig_type_info *info, int flags) { + if(!valRef->IsObject()) { + return SWIG_TypeError; + } + + v8::Handle objRef = valRef->ToObject(); + + return SWIG_V8_ConvertInstancePtr(context, objRef, ptr, info, flags); +} + +v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, int flags) { + // TODO: wrap ptr into an v8 object + return 0; +} + +#define SWIG_ConvertPtr(obj, ptr, info, flags) SWIG_V8_ConvertPtr(obj, ptr, info, flags) +#define SWIG_NewPointerObj(ptr, info, flags) SWIG_V8_NewPointerObj(ptr, info, flags) + +#define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_V8_ConvertInstancePtr(obj, pptr, type, flags) +#define SWIG_NewInstanceObj(thisvalue, type, flags) SWIG_V8_NewPointerObj(thisvalue, type, flags) + +%} diff --git a/Lib/javascript/v8/javascripttypemaps.swg b/Lib/javascript/v8/javascripttypemaps.swg new file mode 100644 index 000000000..479a1f076 --- /dev/null +++ b/Lib/javascript/v8/javascripttypemaps.swg @@ -0,0 +1,16 @@ +#define SWIG_Object v8::Handle +#define VOID_Object v8::Undefined() +#define SWIG_AppendOutput(result, obj) +#define SWIG_SetConstant(name, obj) +#define SWIG_Raise(obj, type, desc) SWIG_V8_Raise(type) + +/* Include fundamental fragemt definitions */ +%include + +/* Python fragments for fundamental types */ +%include + +%include + +/* Include the unified typemap library */ +%include diff --git a/Lib/javascript/v8/std_common.i b/Lib/javascript/v8/std_common.i new file mode 100755 index 000000000..cee11e8ca --- /dev/null +++ b/Lib/javascript/v8/std_common.i @@ -0,0 +1,5 @@ +%include + +%apply size_t { std::size_t }; +%apply const size_t& { const std::size_t& }; + diff --git a/Lib/javascript/v8/std_complex.i b/Lib/javascript/v8/std_complex.i new file mode 100644 index 000000000..088a4fe7b --- /dev/null +++ b/Lib/javascript/v8/std_complex.i @@ -0,0 +1,19 @@ +/* + * STD C++ complex typemaps + */ + +%include + +%{ +#include +%} + +/* defining the complex as/from converters */ + +%swig_cplxdbl_convn(std::complex, std::complex, std::real, std::imag) +%swig_cplxflt_convn(std::complex, std::complex, std::real, std::imag) + +/* defining the typemaps */ + +%typemaps_primitive(%checkcode(CPLXDBL), std::complex); +%typemaps_primitive(%checkcode(CPLXFLT), std::complex); diff --git a/Lib/javascript/v8/std_except.i b/Lib/javascript/v8/std_except.i new file mode 100644 index 000000000..af98428f6 --- /dev/null +++ b/Lib/javascript/v8/std_except.i @@ -0,0 +1 @@ +%include diff --git a/Lib/javascript/v8/std_map.i b/Lib/javascript/v8/std_map.i new file mode 100755 index 000000000..e7812f38a --- /dev/null +++ b/Lib/javascript/v8/std_map.i @@ -0,0 +1,74 @@ +/* ----------------------------------------------------------------------------- + * std_map.i + * + * SWIG typemaps for std::map + * ----------------------------------------------------------------------------- */ + +%include + +// ------------------------------------------------------------------------ +// std::map +// ------------------------------------------------------------------------ + +%{ +#include +#include +#include +%} + +// exported class + +namespace std { + + template class map { + // add typemaps here + public: + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef K key_type; + typedef T mapped_type; + map(); + map(const map &); + + unsigned int size() const; + bool empty() const; + void clear(); + %extend { + const T& get(const K& key) throw (std::out_of_range) { + std::map::iterator i = self->find(key); + if (i != self->end()) + return i->second; + else + throw std::out_of_range("key not found"); + } + void set(const K& key, const T& x) { + (*self)[key] = x; + } + void del(const K& key) throw (std::out_of_range) { + std::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 K& key) { + std::map::iterator i = self->find(key); + return i != self->end(); + } + } + }; + +// Legacy macros (deprecated) +%define specialize_std_map_on_key(K,CHECK,CONVERT_FROM,CONVERT_TO) +#warning "specialize_std_map_on_key ignored - macro is deprecated and no longer necessary" +%enddef + +%define specialize_std_map_on_value(T,CHECK,CONVERT_FROM,CONVERT_TO) +#warning "specialize_std_map_on_value ignored - macro is deprecated and no longer necessary" +%enddef + +%define specialize_std_map_on_both(K,CHECK_K,CONVERT_K_FROM,CONVERT_K_TO, T,CHECK_T,CONVERT_T_FROM,CONVERT_T_TO) +#warning "specialize_std_map_on_both ignored - macro is deprecated and no longer necessary" +%enddef + +} diff --git a/Lib/javascript/v8/std_pair.i b/Lib/javascript/v8/std_pair.i new file mode 100755 index 000000000..fe45ee676 --- /dev/null +++ b/Lib/javascript/v8/std_pair.i @@ -0,0 +1,34 @@ +/* ----------------------------------------------------------------------------- + * std_pair.i + * + * SWIG typemaps for std::pair + * ----------------------------------------------------------------------------- */ + +%include +%include + +// ------------------------------------------------------------------------ +// std::pair +// ------------------------------------------------------------------------ + +%{ +#include +%} + +namespace std { + + template struct pair { + + pair(); + pair(T first, U second); + pair(const pair& p); + + template pair(const pair &p); + + T first; + U second; + }; + + // add specializations here + +} diff --git a/Lib/javascript/v8/std_vector.i b/Lib/javascript/v8/std_vector.i new file mode 100755 index 000000000..3f29b19c7 --- /dev/null +++ b/Lib/javascript/v8/std_vector.i @@ -0,0 +1,85 @@ +/* ----------------------------------------------------------------------------- + * std_vector.i + * ----------------------------------------------------------------------------- */ + +%include + +%{ +#include +#include +%} + +namespace std { + + template class vector { + public: + typedef size_t size_type; + typedef T value_type; + typedef const value_type& const_reference; + vector(); + vector(size_type n); + size_type size() const; + size_type capacity() const; + void reserve(size_type n); + %rename(isEmpty) empty; + bool empty() const; + void clear(); + %rename(add) push_back; + void push_back(const value_type& x); + %extend { + const_reference get(int i) throw (std::out_of_range) { + int size = int(self->size()); + if (i>=0 && isize()); + if (i>=0 && i class vector { + public: + typedef size_t size_type; + typedef bool value_type; + typedef bool const_reference; + vector(); + vector(size_type n); + size_type size() const; + size_type capacity() const; + void reserve(size_type n); + %rename(isEmpty) empty; + bool empty() const; + void clear(); + %rename(add) push_back; + void push_back(const value_type& x); + %extend { + const_reference get(int i) throw (std::out_of_range) { + int size = int(self->size()); + if (i>=0 && isize()); + if (i>=0 && i +%include +%include +%include +%include + From b39e2bfff0c1082c31149079075faa0999059953 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:57:57 +0000 Subject: [PATCH 0093/1048] Refactor JSC emitter to reduce global state variables. Also meld v8 emitter into javascript.cxx (provisional). git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13766 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/Makefile.am | 1 - Source/Modules/javascript.cxx | 2016 ++++++++++++++++++++---------- Source/Modules/javascript_v8.cxx | 579 --------- 3 files changed, 1372 insertions(+), 1224 deletions(-) delete mode 100644 Source/Modules/javascript_v8.cxx diff --git a/Source/Makefile.am b/Source/Makefile.am index 420fd6d3f..9cd55c7dc 100644 --- a/Source/Makefile.am +++ b/Source/Makefile.am @@ -50,7 +50,6 @@ eswig_SOURCES = CParse/cscanner.c \ Modules/java.cxx \ Modules/lang.cxx \ Modules/javascript.cxx \ - Modules/javascript_v8.cxx \ Modules/lua.cxx \ Modules/main.cxx \ Modules/modula3.cxx \ diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 009bcc400..1fde3cd0c 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -4,28 +4,100 @@ #include #include -/** - * A class that wraps a code snippet used as template for code generation. - */ -class Template { +/********************************************************************** + * JAVASCRIPT: swig module implementation + **********************************************************************/ +/* forward decl: Template is a convenience helper class for dealing with + * code fragments */ +class Template; + +class State { + public: - Template(const String *code); - Template(const String *code, const String *templateName, bool debug = false); + State(): _global(NewHash()) { + // initialize sub-hashes + Setattr(_global, "class", NewHash()); + Setattr(_global, "function", NewHash()); + Setattr(_global, "variable", NewHash()); + } - ~Template(); + ~State() { Delete(_global); } + + DOH *getState(const char* key, bool _new = false) { + if (_new) { + Hash *hash = NewHash(); + Setattr(_global, key, hash); + } + return Getattr(_global, key); + } + + DOH *global() { return _global; } - String *str(); + DOH *global(const char* key, DOH *initial=0) { + if(initial != 0) { + Setattr(_global, key, initial); + } + return Getattr(_global, key); + } - Template & replace(const String *pattern, const String *repl); + DOH *clazz(bool _new = false) { + return getState("class", _new); + } + + DOH *clazz(const char* key, DOH *initial=0) { + DOH *c = clazz(); + if(initial != 0) { + Setattr(c, key, initial); + } + return Getattr(c, key); + } + DOH *function(bool _new = false) { + return getState("function", _new); + } + + DOH *function(const char* key, DOH *initial=0) { + DOH *f = function(); + if(initial != 0) { + Setattr(f, key, initial); + } + return Getattr(f, key); + } + + DOH *variable(bool _new = false) { + return getState("variable", _new); + } + + DOH *variable(const char* key, DOH *initial=0) { + DOH *v = variable(); + if(initial != 0) { + Setattr(v, key, initial); + } + return Getattr(v, key); + } + + static int IsSet(DOH *val) { + if (!val) { + return 0; + } else { + const char *cval = Char(val); + if (!cval) + return 0; + return (strcmp(cval, "0") != 0) ? 1 : 0; + } + } + private: - String *code; - String *templateName; - bool debug; + + Hash *_global; }; +/** + * JSEmitter represents an abstraction of javascript code generators + * for different javascript engines. + **/ class JSEmitter { public: @@ -38,97 +110,91 @@ public: JSEmitter(); - virtual ~ JSEmitter(); + virtual ~JSEmitter(); - /** - * Opens output files and temporary output DOHs. - */ - virtual int initialize(Node *n) = 0; + /** + * Opens output files and temporary output DOHs. + */ + virtual int initialize(Node *n); - /** - * Writes all collected code into the output file(s). - */ + /** + * Writes all collected code into the output file(s). + */ virtual int dump(Node *n) = 0; - /** - * Cleans up all open output DOHs. - */ + /** + * Cleans up all open output DOHs. + */ virtual int close() = 0; - /** - * Switches the context for code generation. - * - * Classes, global variables and global functions may need to - * be registered in certain static tables. - * This method should be used to switch output DOHs correspondingly. - */ + /** + * Switches the context for code generation. + * + * Classes, global variables and global functions may need to + * be registered in certain static tables. + * This method should be used to switch output DOHs correspondingly. + */ virtual int switchNamespace(Node *) { return SWIG_OK; }; - /** - * Invoked at the beginning of the classHandler. - */ - virtual int enterClass(Node *) { - return SWIG_OK; - }; + /** + * Invoked at the beginning of the classHandler. + */ + virtual int enterClass(Node *); - /** - * Invoked at the end of the classHandler. - */ + /** + * Invoked at the end of the classHandler. + */ virtual int exitClass(Node *) { return SWIG_OK; }; - /** - * Invoked at the beginning of the variableHandler. - */ - virtual int enterVariable(Node *) { - return SWIG_OK; - }; + /** + * Invoked at the beginning of the variableHandler. + */ + virtual int enterVariable(Node *); - /** - * Invoked at the end of the variableHandler. - */ + /** + * Invoked at the end of the variableHandler. + */ virtual int exitVariable(Node *) { return SWIG_OK; }; - /** - * Invoked at the beginning of the functionHandler. - */ - virtual int enterFunction(Node *) { - return SWIG_OK; - }; + /** + * Invoked at the beginning of the functionHandler. + */ + virtual int enterFunction(Node *); - /** - * Invoked at the end of the functionHandler. - */ + /** + * Invoked at the end of the functionHandler. + */ virtual int exitFunction(Node *) { return SWIG_OK; }; - /** - * Invoked by functionWrapper callback after call to Language::functionWrapper. - */ + /** + * Invoked by functionWrapper callback after call to Language::functionWrapper. + */ virtual int emitWrapperFunction(Node *n); - /** - * Invoked from constantWrapper after call to Language::constantWrapper. - **/ + /** + * Invoked from constantWrapper after call to Language::constantWrapper. + **/ virtual int emitConstant(Node *n) = 0; - /** - * Registers a given code snippet for a given key name. - * - * This method is called by the fragmentDirective handler - * of the JAVASCRIPT language module. - **/ + /** + * Registers a given code snippet for a given key name. + * + * This method is called by the fragmentDirective handler + * of the JAVASCRIPT language module. + **/ int registerTemplate(const String *name, const String *code); - /** - * Retrieve the code template registered for a given name. - */ + /** + * Retrieve the code template registered for a given name. + */ Template getTemplate(const String *name); void enableDebug(); @@ -137,22 +203,53 @@ public: protected: + /** + * Generates code for a constructor function. + */ virtual int emitCtor(Node *n) = 0; + /** + * Generates code for a destructor function. + */ virtual int emitDtor(Node *n) = 0; + /** + * Generates code for a function. + */ virtual int emitFunction(Node *n, bool is_member) = 0; + /** + * Generates code for a getter function. + */ virtual int emitGetter(Node *n, bool is_member) = 0; + /** + * Generates code for a setter function. + */ virtual int emitSetter(Node *n, bool is_member) = 0; + /** + * Helper function to find out if a function is a setter or not. + * TODO: there should be some kind of support in swig core for that? + */ bool isSetterMethod(Node *n); + /** + * Helper function to retrieve the first parent class node. + */ Node *getBaseClass(Node *n); - + + /** + * Helper function to retrieve a certain typemap. + */ const String *typemapLookup(Node *n, const_String_or_char_ptr tmap_method, SwigType *type, int warning, Node *typemap_attributes = 0); + Parm *skipIgnoredArgs(Parm *p); + + /** + * Enables extra debugging information in typemaps. + * TODO: make this global/static... js_emitter_template_enable_debug + */ void enableDebugTemplates(); protected: @@ -163,132 +260,344 @@ protected: Hash *templates; Wrapper *current_wrapper; + + State state; bool is_static; bool debug; }; -class JSCEmitter:public JSEmitter { +/* factory methods for concrete JSEmitters: */ +JSEmitter *swig_javascript_create_JSCEmitter(); +JSEmitter *swig_javascript_create_V8Emitter(); -private: - - enum MarshallingMode { - Setter, - Getter, - Ctor, - Function - }; +class JAVASCRIPT:public Language { public: - JSCEmitter(); + JAVASCRIPT(): emitter(NULL) {} + + ~JAVASCRIPT() { + delete emitter; + } - virtual ~ JSCEmitter(); - - virtual int initialize(Node *n); - - virtual int dump(Node *n); - - virtual int close(); - - -protected: - - virtual int emitCtor(Node *n); - - virtual int emitDtor(Node *n); - - virtual int enterVariable(Node *n); - - virtual int exitVariable(Node *n); - - virtual int enterFunction(Node *n); - - virtual int exitFunction(Node *n); - - virtual int enterClass(Node *n); - - virtual int exitClass(Node *n); - - virtual int emitFunction(Node *n, bool is_member); - - virtual int emitFunctionDispatcher(Node *n, bool is_member); - - virtual int emitGetter(Node *n, bool is_member); - - virtual int emitSetter(Node *n, bool is_member); - - void marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static = false); - - void marshalOutput(Node *n, String *actioncode, Wrapper *wrapper); - - Parm *skipIgnoredArgs(Parm *p); - - virtual int switchNamespace(Node *n); - - virtual int createNamespace(String *scope); - - virtual Hash *createNamespaceEntry(const char *name, const char *parent); - - virtual int emitNamespaces(); - - virtual int emitConstant(Node *n); + virtual int functionHandler(Node *n); + virtual int globalfunctionHandler(Node *n); + virtual int variableHandler(Node *n); + virtual int globalvariableHandler(Node *n); + virtual int staticmemberfunctionHandler(Node *n); + virtual int classHandler(Node *n); + virtual int functionWrapper(Node *n); + virtual int constantWrapper(Node *n); + + /** + * Registers all %fragments assigned to section "templates". + **/ + virtual int fragmentDirective(Node *n); + virtual void main(int argc, char *argv[]); + virtual int top(Node *n); private: - File *f_wrap_cpp; - File *f_runtime; - File *f_header; - File *f_wrappers; - File *f_init; - - String *NULL_STR; - String *VETO_SET; - const char *GLOBAL_STR; - - // contains context specific structs - // to allow generation different class definition tables - // which are switched on namespace change - Hash *namespaces; - Hash *current_namespace; - - // dynamically filled code parts - - String *create_namespaces_code; - String *register_namespaces_code; - - String *current_class_functions; - String *class_variables_code; - String *class_static_functions_code; - String *class_static_variables_code; - - String *ctor_wrappers; - String *ctor_dispatcher_code; - - String *initializer_code; - String *function_dispatcher_code; - - // state variables - String *current_propertyname; - String *current_getter; - String *current_setter; - bool is_immutable; - - String *current_classname; - String *current_classname_mangled; - String *current_classtype; - String *current_classtype_mangled; - String *current_functionwrapper; - String *current_functionname; + JSEmitter *emitter; }; +/* --------------------------------------------------------------------- + * functionWrapper() + * + * Low level code generator for functions + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::functionWrapper(Node *n) { + + // note: the default implementation only prints a message + // Language::functionWrapper(n); + emitter->emitWrapperFunction(n); + + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * functionHandler() + * + * Function handler for generating wrappers for functions + * --------------------------------------------------------------------- */ +int JAVASCRIPT::functionHandler(Node *n) { + + if (GetFlag(n, "isextension") == 1) { + SetFlag(n, "ismember"); + } + + emitter->enterFunction(n); + Language::functionHandler(n); + emitter->exitFunction(n); + + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * globalfunctionHandler() + * + * Function handler for generating wrappers for functions + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::globalfunctionHandler(Node *n) { + emitter->switchNamespace(n); + Language::globalfunctionHandler(n); + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * staticmemberfunctionHandler() + * + * Function handler for generating wrappers for static member functions + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::staticmemberfunctionHandler(Node *n) { + // workaround: storage=static is not set for static member functions + emitter->setStaticFlag(true); + Language::staticmemberfunctionHandler(n); + emitter->setStaticFlag(false); + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * variableHandler() + * + * Function handler for generating wrappers for variables + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::variableHandler(Node *n) { + + if (!is_assignable(n) + // HACK: don't know why this is assignable? + || Equal(Getattr(n, "type"), "a().char")) { + SetFlag(n, "wrap:immutable"); + } + + emitter->enterVariable(n); + Language::variableHandler(n); + emitter->exitVariable(n); + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * globalvariableHandler() + * + * Function handler for generating wrappers for global variables + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::globalvariableHandler(Node *n) { + + emitter->switchNamespace(n); + Language::globalvariableHandler(n); + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * constantHandler() + * + * Function handler for generating wrappers for constants + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::constantWrapper(Node *n) { + + // Note: callbacks trigger this wrapper handler + // TODO: handle callback declarations + if (Equal(Getattr(n, "kind"), "function")) { + return SWIG_OK; + } + + //Language::constantWrapper(n); + emitter->emitConstant(n); + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * classHandler() + * + * Function handler for generating wrappers for class + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::classHandler(Node *n) { + emitter->switchNamespace(n); + + emitter->enterClass(n); + Language::classHandler(n); + emitter->exitClass(n); + + return SWIG_OK; +} + +int JAVASCRIPT::fragmentDirective(Node *n) { + + // catch all fragment directives that have "templates" as location + // and register them at the emitter. + String *section = Getattr(n, "section"); + + if (Equal(section, "templates")) { + emitter->registerTemplate(Getattr(n, "value"), Getattr(n, "code")); + } else { + Swig_fragment_register(n); + } + + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * top() + * + * Function handler for processing top node of the parse tree + * Wrapper code generation essentially starts from here + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::top(Node *n) { + + emitter->initialize(n); + + Language::top(n); + + emitter->dump(n); + emitter->close(); + + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * main() + * + * Entry point for the JAVASCRIPT module + * --------------------------------------------------------------------- */ + +void JAVASCRIPT::main(int argc, char *argv[]) { + + // Set javascript subdirectory in SWIG library + SWIG_library_directory("javascript"); + + int mode = -1; + + bool debug_templates = false; + for (int i = 1; i < argc; i++) { + if (argv[i]) { + if (strcmp(argv[i], "-v8") == 0) { + Swig_mark_arg(i); + mode = JSEmitter::V8; + SWIG_library_directory("javascript/v8"); + } else if (strcmp(argv[i], "-jsc") == 0) { + Swig_mark_arg(i); + mode = JSEmitter::JavascriptCore; + SWIG_library_directory("javascript/jsc"); + } else if (strcmp(argv[i], "-qt") == 0) { + Swig_mark_arg(i); + mode = JSEmitter::QtScript; + SWIG_library_directory("javascript/qt"); + } else if (strcmp(argv[i], "-debug-templates") == 0) { + Swig_mark_arg(i); + debug_templates = true; + } + } + } + + switch (mode) { + case JSEmitter::V8: + { + emitter = swig_javascript_create_V8Emitter(); + break; + } + case JSEmitter::JavascriptCore: + { + emitter = swig_javascript_create_JSCEmitter(); + break; + } + case JSEmitter::QtScript: + { + Printf(stderr, "QtScript support is not yet implemented."); + SWIG_exit(-1); + break; + } + default: + { + Printf(stderr, "Unknown emitter type."); + SWIG_exit(-1); + break; + } + } + + if (debug_templates) { + emitter->enableDebug(); + } + + // Add a symbol to the parser for conditional compilation + Preprocessor_define("SWIGJAVASCRIPT 1", 0); + + // Add typemap definitions + SWIG_typemap_lang("javascript"); + + // Set configuration file + SWIG_config_file("javascript.swg"); + + allow_overloading(); +} + +/* ----------------------------------------------------------------------------- + * swig_javascript() - Instantiate module + * ----------------------------------------------------------------------------- */ + +static Language *new_swig_javascript() { + return new JAVASCRIPT(); +} + +extern "C" Language *swig_javascript(void) { + return new_swig_javascript(); +} + +/********************************************************************** + * Emitter implementations + **********************************************************************/ + +/** + * A convenience class that wraps a code snippet used as template for code generation. + */ +class Template { + +public: + Template(const String *code); + + Template(const String *code, const String *templateName, bool debug = false); + + ~Template(); + + String *str(); + + Template& replace(const String *pattern, const String *repl); + + Template& pretty_print(DOH *doh); + +private: + String *code; + String *templateName; + bool debug; +}; + +#define __NAME__ "name" +#define NAME_MANGLED "name_mangled" +#define TYPE "type" +#define TYPE_MANGLED "type_mangled" +#define WRAPPER_NAME "wrapper" +#define IS_IMMUTABLE "is_immutable" +#define IS_STATIC "is_static" + /* ----------------------------------------------------------------------------- * JSEmitter() * ----------------------------------------------------------------------------- */ JSEmitter::JSEmitter() -: empty_string(NewString("")), current_wrapper(NULL), is_static(false), debug(false) { +: empty_string(NewString("")), + current_wrapper(NULL), + is_static(false), + debug(false) +{ templates = NewHash(); } @@ -326,6 +635,10 @@ Template JSEmitter::getTemplate(const String *name) { return t; } +int JSEmitter::initialize(Node *) { + return SWIG_OK; +} + void JSEmitter::enableDebug() { debug = true; } @@ -364,6 +677,17 @@ const String *JSEmitter::typemapLookup(Node *n, const_String_or_char_ptr tmap_me return tm; } +/* --------------------------------------------------------------------- + * skipIgnoredArgs() + * --------------------------------------------------------------------- */ + +Parm *JSEmitter::skipIgnoredArgs(Parm *p) { + while (checkAttribute(p, "tmap:in:numinputs", "0")) { + p = Getattr(p, "tmap:in:next"); + } + return p; +} + /* ----------------------------------------------------------------------------- * JSEmitter::getBaseClass() : the node of the base class or NULL * ----------------------------------------------------------------------------- */ @@ -402,10 +726,10 @@ int JSEmitter::emitWrapperFunction(Node *n) { } else if (Cmp(kind, "variable") == 0) { if (isSetterMethod(n)) { - ret = emitSetter(n, is_member); + ret = emitSetter(n, is_member); } else { - ret = emitGetter(n, is_member); + ret = emitGetter(n, is_member); } } else { @@ -436,6 +760,38 @@ int JSEmitter::emitWrapperFunction(Node *n) { return ret; } +int JSEmitter::enterClass(Node *n) { + + state.clazz(true); + state.clazz(__NAME__, Getattr(n, "sym:name")); + state.clazz(NAME_MANGLED, SwigType_manglestr(Getattr(n, "name"))); + state.clazz(TYPE, NewString(Getattr(n, "classtype"))); + + String *type = SwigType_manglestr(Getattr(n, "classtypeobj")); + String *classtype_mangled = NewString(""); + Printf(classtype_mangled, "p%s", type); + Delete(type); + state.clazz(TYPE_MANGLED, classtype_mangled); + + return SWIG_OK; +} + +int JSEmitter::enterFunction(Node *n) { + + state.function(true); + state.function(__NAME__, Getattr(n, "sym:name")); + + return SWIG_OK; +} + +int JSEmitter::enterVariable(Node *n) { + state.variable(true); + state.variable(__NAME__, Swig_scopename_last(Getattr(n, "name"))); + state.variable(IS_IMMUTABLE, Getattr(n, "wrap:immutable")); + return SWIG_OK; +} + + /* ----------------------------------------------------------------------------- * __swigjs_str_ends_with() : c string helper to check suffix match * ----------------------------------------------------------------------------- */ @@ -464,6 +820,7 @@ bool JSEmitter::isSetterMethod(Node *n) { return (__swigjs_str_ends_with((char *) Data(symname), "_set") != 0); } + /* ----------------------------------------------------------------------------- * Template::Template() : creates a Template class for given template code * ----------------------------------------------------------------------------- */ @@ -526,26 +883,143 @@ String *Template::str() { /* ----------------------------------------------------------------------------- * Template& Template::replace(const String* pattern, const String* repl) : * - * replaces all occurances of a given pattern with a given replacement. + * replaces all occurences of a given pattern with a given replacement. * * - pattern: the pattern to be replaced * - repl: the replacement string * - returns a reference to the Template to allow chaining of methods. * ----------------------------------------------------------------------------- */ -Template & Template::replace(const String *pattern, const String *repl) { - ::Replaceall(code, pattern, repl); +Template& Template::replace(const String *pattern, const String *repl) { + Replaceall(code, pattern, repl); return *this; } +Template& Template::pretty_print(DOH *doh) { + Wrapper_pretty_print(str(), doh); + return *this; +} + +/********************************************************************** + * JavascriptCore: JSEmitter implementation for JavascriptCore engine + **********************************************************************/ + +class JSCEmitter:public JSEmitter { + +private: + + enum MarshallingMode { + Setter, + Getter, + Ctor, + Function + }; + +public: + + JSCEmitter(); + + virtual ~ JSCEmitter(); + + virtual int initialize(Node *n); + + virtual int dump(Node *n); + + virtual int close(); + + +protected: + + virtual int emitCtor(Node *n); + + virtual int emitDtor(Node *n); + + virtual int enterVariable(Node *n); + + virtual int exitVariable(Node *n); + + virtual int enterFunction(Node *n); + + virtual int exitFunction(Node *n); + + virtual int enterClass(Node *n); + + virtual int exitClass(Node *n); + + virtual int emitFunction(Node *n, bool is_member); + + virtual int emitFunctionDispatcher(Node *n, bool is_member); + + virtual int emitGetter(Node *n, bool is_member); + + virtual int emitSetter(Node *n, bool is_member); + + virtual int emitConstant(Node *n); + + void marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static = false); + + void marshalOutput(Node *n, String *actioncode, Wrapper *wrapper); + + virtual int switchNamespace(Node *n); + + virtual int createNamespace(String *scope); + + virtual Hash *createNamespaceEntry(const char *name, const char *parent); + + virtual int emitNamespaces(); + +private: + + String *NULL_STR; + String *VETO_SET; + const char *GLOBAL_STR; + + // contains context specific structs + // to allow generation of different class definition tables + // which are switched on namespace change + Hash *namespaces; + Hash *current_namespace; + + // output file and major code parts + File *f_wrap_cpp; + File *f_runtime; + File *f_header; + File *f_wrappers; + File *f_init; + +}; + +// keys for global state variables +#define CREATE_NAMESPACES "create_namespaces" +#define REGISTER_NAMESPACES "register_namespaces" +#define INITIALIZER "initializer" + +// keys for class scoped state variables +#define MEMBER_VARIABLES "member_variables" +#define MEMBER_FUNCTIONS "member_functions" +#define STATIC_FUNCTIONS "static_functions" +#define STATIC_VARIABLES "static_variables" +#define CTORS "ctors" +#define CTOR_DISPATCHERS "ctor_dispatchers" + +// keys for function scoped state variables +#define FUNCTION_DISPATCHERS "function_dispatchers" +#define GETTER "getter" +#define SETTER "setter" + JSCEmitter::JSCEmitter() -: -JSEmitter(), NULL_STR(NewString("NULL")), current_classname(NULL), f_header(NULL), current_classtype(NULL), f_runtime(NULL), current_class_functions(NULL), -f_wrappers(NULL), current_getter(NULL), is_immutable(NULL), create_namespaces_code(NULL), current_classname_mangled(NULL), initializer_code(NULL), -register_namespaces_code(NULL), f_wrap_cpp(NULL), current_setter(NULL), ctor_dispatcher_code(NULL), current_functionwrapper(NULL), -class_static_functions_code(NULL), namespaces(NULL), function_dispatcher_code(NULL), namespaces(NULL), GLOBAL_STR(NULL), current_propertyname(NULL), -current_namespace(NULL), ctor_wrappers(NULL), class_static_variables_code(NULL), class_variables_code(NULL), f_init(NULL), current_functionname(NULL), -current_classtype_mangled(NULL), VETO_SET(NewString("JS_veto_set_variable")) { +: JSEmitter(), + NULL_STR(NewString("NULL")), + VETO_SET(NewString("JS_veto_set_variable")), + GLOBAL_STR(NULL), + namespaces(NULL), + current_namespace(NULL), + f_wrap_cpp(NULL), + f_runtime(NULL), + f_header(NULL), + f_wrappers(NULL), + f_init(NULL) +{ } JSCEmitter::~JSCEmitter() { @@ -553,16 +1027,6 @@ JSCEmitter::~JSCEmitter() { Delete(VETO_SET); } -/* --------------------------------------------------------------------- - * skipIgnoredArgs() - * --------------------------------------------------------------------- */ - -Parm *JSCEmitter::skipIgnoredArgs(Parm *p) { - while (checkAttribute(p, "tmap:in:numinputs", "0")) { - p = Getattr(p, "tmap:in:next"); - } - return p; -} /* --------------------------------------------------------------------- * marshalInputArgs() @@ -577,9 +1041,9 @@ void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Ma Parm *p; int startIdx = 0; - if (is_member && !is_static) + if (is_member && !is_static) { startIdx = 1; - + } int i = 0; for (p = parms; p; p = nextSibling(p), i++) { @@ -590,17 +1054,17 @@ void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Ma case Getter: case Function: if (is_member && !is_static && i == 0) { - Printv(arg, "thisObject", 0); + Printv(arg, "thisObject", 0); } else { - Printf(arg, "argv[%d]", i - startIdx); + Printf(arg, "argv[%d]", i - startIdx); } break; case Setter: if (is_member && !is_static && i == 0) { - Printv(arg, "thisObject", 0); + Printv(arg, "thisObject", 0); } else { - Printv(arg, "value", 0); + Printv(arg, "value", 0); } break; case Ctor: @@ -616,9 +1080,9 @@ void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Ma Setattr(p, "emit:input", arg); if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) { - Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); + Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); } else { - Replaceall(tm, "$disown", "0"); + Replaceall(tm, "$disown", "0"); } Replaceall(tm, "$symname", Getattr(n, "sym:name")); @@ -650,7 +1114,6 @@ void JSCEmitter::marshalOutput(Node *n, String *actioncode, Wrapper *wrapper) { if ((tm = Swig_typemap_lookup_out("out", n, "result", wrapper, actioncode))) { Replaceall(tm, "$result", "jsresult"); - // TODO: May not be the correct way Replaceall(tm, "$objecttype", Swig_scopename_last(SwigType_str(SwigType_strip_qualifiers(type), 0))); if (GetFlag(n, "feature:new")) { @@ -659,9 +1122,12 @@ void JSCEmitter::marshalOutput(Node *n, String *actioncode, Wrapper *wrapper) { Replaceall(tm, "$owner", "0"); } - Printf(wrapper->code, "%s", tm); - if (Len(tm)) + Append(wrapper->code, tm); + + if (Len(tm) > 0) { Printf(wrapper->code, "\n"); + } + } else { Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(type, 0), Getattr(n, "name")); } @@ -669,6 +1135,8 @@ void JSCEmitter::marshalOutput(Node *n, String *actioncode, Wrapper *wrapper) { } int JSCEmitter::initialize(Node *n) { + + JSEmitter::initialize(n); /* Get the output file name */ String *outfile = Getattr(n, "outfile"); @@ -686,9 +1154,9 @@ int JSCEmitter::initialize(Node *n) { f_header = NewString(""); f_wrappers = NewString(""); - create_namespaces_code = NewString(""); - register_namespaces_code = NewString(""); - initializer_code = NewString(""); + state.global(CREATE_NAMESPACES, NewString("")); + state.global(REGISTER_NAMESPACES, NewString("")); + state.global(INITIALIZER, NewString("")); namespaces = NewHash(); Hash *global_namespace = createNamespaceEntry(Char(Getattr(n, "name")), "global"); @@ -718,23 +1186,21 @@ int JSCEmitter::dump(Node *n) { Printv(f_wrap_cpp, f_header, "\n", 0); Printv(f_wrap_cpp, f_wrappers, "\n", 0); - emitNamespaces(); // compose the initializer function using a template Template initializer(getTemplate("JS_initializer")); initializer.replace("${modulename}", module) - .replace("${initializercode}", initializer_code) - .replace("${create_namespaces}", create_namespaces_code) - .replace("${register_namespaces}", register_namespaces_code); - Wrapper_pretty_print(initializer.str(), f_init); + .replace("${initializercode}", state.global(INITIALIZER)) + .replace("${create_namespaces}", state.global(CREATE_NAMESPACES)) + .replace("${register_namespaces}", state.global(REGISTER_NAMESPACES)) + .pretty_print(f_init); - Printv(f_wrap_cpp, f_init, "\n", 0); + Printv(f_wrap_cpp, f_init, 0); return SWIG_OK; } - int JSCEmitter::close() { /* strings */ Delete(f_runtime); @@ -742,14 +1208,10 @@ int JSCEmitter::close() { Delete(f_wrappers); Delete(f_init); - Delete(create_namespaces_code); - Delete(register_namespaces_code); - Delete(initializer_code); - Delete(namespaces); /* files */ - ::Close(f_wrap_cpp); + Close(f_wrap_cpp); Delete(f_wrap_cpp); return SWIG_OK; @@ -757,12 +1219,12 @@ int JSCEmitter::close() { int JSCEmitter::enterFunction(Node *n) { + JSEmitter::enterFunction(n); + + /* Initialize DOH for collecting function dispatchers */ bool is_overloaded = GetFlag(n, "sym:overloaded"); - - current_functionname = Getattr(n, "sym:name"); - - if (is_overloaded && function_dispatcher_code == 0) { - function_dispatcher_code = NewString(""); + if (is_overloaded && state.function(FUNCTION_DISPATCHERS) == 0) { + state.function(FUNCTION_DISPATCHERS, NewString("")); } return SWIG_OK; @@ -771,61 +1233,42 @@ int JSCEmitter::enterFunction(Node *n) { int JSCEmitter::exitFunction(Node *n) { Template t_function = getTemplate("JS_functiondecl"); - String *functionname = current_functionname; - String *functionwrapper = current_functionwrapper; - bool is_member = GetFlag(n, "ismember"); - - // handle overloaded functions - // Note: wrappers for overloaded functions are currently - // not made available (e.g., foo_double, foo_int) - // maybe this could be enabled by an extra feature flag bool is_overloaded = GetFlag(n, "sym:overloaded"); + // handle overloaded functions if (is_overloaded) { if (!Getattr(n, "sym:nextSibling")) { - - functionwrapper = Swig_name_wrapper(Getattr(n, "name")); - // note: set this attribute to transfer ownership - Setattr(n, "wrap:dispatcher", functionwrapper); - + state.function(WRAPPER_NAME, Swig_name_wrapper(Getattr(n, "name"))); // create dispatcher emitFunctionDispatcher(n, is_member); - - Delete(function_dispatcher_code); - function_dispatcher_code = 0; - } else { - //don't register wrappers of overloaded functions in function tables return SWIG_OK; } } - t_function.replace("${functionname}", functionname) - .replace("${functionwrapper}", functionwrapper); + t_function.replace("${functionname}", state.function(__NAME__)) + .replace("${functionwrapper}", state.function(WRAPPER_NAME)); if (is_member) { - if (Equal(Getattr(n, "storage"), "static")) { - Printv(class_static_functions_code, t_function.str(), 0); - + Append(state.clazz(STATIC_FUNCTIONS), t_function.str()); } else { - Printv(current_class_functions, t_function.str(), 0); + Append(state.clazz(MEMBER_FUNCTIONS), t_function.str()); } - } else { - Printv(Getattr(current_namespace, "functions"), t_function.str(), 0); + Append(Getattr(current_namespace, "functions"), t_function.str()); } return SWIG_OK; } int JSCEmitter::enterVariable(Node *n) { - current_getter = NULL_STR; - current_setter = VETO_SET; - current_propertyname = Swig_scopename_last(Getattr(n, "name")); - is_immutable = GetFlag(n, "wrap:immutable"); + JSEmitter::enterVariable(n); + + state.variable(GETTER, NULL_STR); + state.variable(SETTER, VETO_SET); return SWIG_OK; } @@ -833,71 +1276,59 @@ int JSCEmitter::enterVariable(Node *n) { int JSCEmitter::exitVariable(Node *n) { Template t_variable(getTemplate("JS_variabledecl")); - t_variable.replace("${setname}", current_setter) - .replace("${getname}", current_getter) - .replace("${propertyname}", current_propertyname); + t_variable.replace("${setname}", state.variable(SETTER)) + .replace("${getname}", state.variable(GETTER)) + .replace("${propertyname}", state.variable(__NAME__)); if (GetFlag(n, "ismember")) { if (Equal(Getattr(n, "storage"), "static") || (Equal(Getattr(n, "nodeType"), "enumitem"))) { - - Printv(class_static_variables_code, t_variable.str(), 0); - + Append(state.clazz(STATIC_VARIABLES), t_variable.str()); } else { - Printv(class_variables_code, t_variable.str(), 0); + Append(state.clazz(MEMBER_VARIABLES), t_variable.str()); } } else { - Printv(Getattr(current_namespace, "values"), t_variable.str(), 0); + Append(Getattr(current_namespace, "values"), t_variable.str()); } return SWIG_OK; } int JSCEmitter::enterClass(Node *n) { + JSEmitter::enterClass(n); - current_classname = Getattr(n, "sym:name"); - current_classname_mangled = SwigType_manglestr(Getattr(n, "name")); - current_classtype = NewString(Getattr(n, "classtype")); - - String *type = SwigType_manglestr(Getattr(n, "classtypeobj")); - current_classtype_mangled = NewString(""); - Printf(current_classtype_mangled, "p%s", type); - Delete(type); + state.clazz(MEMBER_VARIABLES, NewString("")); + state.clazz(MEMBER_FUNCTIONS, NewString("")); + state.clazz(STATIC_VARIABLES, NewString("")); + state.clazz(STATIC_FUNCTIONS, NewString("")); + state.clazz(CTORS, NewString("")); + state.clazz(CTOR_DISPATCHERS, NewString("")); Template t_class_defn = getTemplate("JS_class_definition"); - t_class_defn.replace("${classname_mangled}", current_classname_mangled); - Wrapper_pretty_print(t_class_defn.str(), f_wrappers); - - class_variables_code = NewString(""); - current_class_functions = NewString(""); - class_static_variables_code = NewString(""); - class_static_functions_code = NewString(""); - ctor_wrappers = NewString(""); - ctor_dispatcher_code = NewString(""); + t_class_defn.replace("${classname_mangled}", state.clazz(NAME_MANGLED)) + .pretty_print(f_wrappers); return SWIG_OK; } int JSCEmitter::exitClass(Node *n) { - String *mangled_name = SwigType_manglestr(Getattr(n, "name")); - Template t_class_tables(getTemplate("JS_class_tables")); - t_class_tables.replace("${classname_mangled}", mangled_name) - .replace("${jsclassvariables}", class_variables_code) - .replace("${jsclassfunctions}", current_class_functions) - .replace("${jsstaticclassfunctions}", class_static_functions_code) - .replace("${jsstaticclassvariables}", class_static_variables_code); - Wrapper_pretty_print(t_class_tables.str(), f_wrappers); + t_class_tables.replace("${classname_mangled}", state.clazz(NAME_MANGLED)) + .replace("${jsclassvariables}", state.clazz(MEMBER_VARIABLES)) + .replace("${jsclassfunctions}", state.clazz(MEMBER_FUNCTIONS)) + .replace("${jsstaticclassfunctions}", state.clazz(STATIC_FUNCTIONS)) + .replace("${jsstaticclassvariables}", state.clazz(STATIC_VARIABLES)) + .pretty_print(f_wrappers); /* adds the ctor wrappers at this position */ // Note: this is necessary to avoid extra forward declarations. - Printv(f_wrappers, ctor_wrappers, 0); + Append(f_wrappers, state.clazz(CTORS)); /* adds the main constructor wrapper function */ Template t_mainctor(getTemplate("JS_mainctordefn")); - t_mainctor.replace("${classname_mangled}", mangled_name) - .replace("${DISPATCH_CASES}", ctor_dispatcher_code); - Wrapper_pretty_print(t_mainctor.str(), f_wrappers); + t_mainctor.replace("${classname_mangled}", state.clazz(NAME_MANGLED)) + .replace("${DISPATCH_CASES}", state.clazz(CTOR_DISPATCHERS)) + .pretty_print(f_wrappers); /* adds a class template statement to initializer function */ Template t_classtemplate(getTemplate("JS_create_class_template")); @@ -909,47 +1340,21 @@ int JSCEmitter::exitClass(Node *n) { Delete(base_name_mangled); base_name_mangled = SwigType_manglestr(Getattr(base_class, "name")); } + t_classtemplate.replace("${classname_mangled}", state.clazz(NAME_MANGLED)) + .replace("${classtype_mangled}", state.clazz(TYPE_MANGLED)) + .replace("${base_classname}", base_name_mangled) + .pretty_print(state.global(INITIALIZER)); + Delete(base_name_mangled); - t_classtemplate.replace("${classname_mangled}", mangled_name) - .replace("${classtype_mangled}", current_classtype_mangled) - .replace("${base_classname}", base_name_mangled); - Wrapper_pretty_print(t_classtemplate.str(), initializer_code); - -/* - String *clientdata = NewString(""); - Printv(clientdata, mangled_name, "_classRef", 0); - SwigType_remember_clientdata(current_classtype_mangled, clientdata); -*/ - - SwigType_remember_clientdata(current_classtype_mangled, NewString("0")); + /* Note: this makes sure that there is a swig_type added for this class */ + SwigType_remember_clientdata(state.clazz(TYPE_MANGLED), NewString("0")); /* adds a class registration statement to initializer function */ Template t_registerclass(getTemplate("JS_register_class")); - t_registerclass.replace("${classname}", current_classname) - .replace("${classname_mangled}", current_classname_mangled) - .replace("${namespace_mangled}", Getattr(current_namespace, "name_mangled")); - - Wrapper_pretty_print(t_registerclass.str(), initializer_code); - - /* clean up all DOHs */ - Delete(class_variables_code); - Delete(current_class_functions); - Delete(class_static_variables_code); - Delete(class_static_functions_code); - Delete(ctor_wrappers); - Delete(mangled_name); - Delete(ctor_dispatcher_code); - class_variables_code = 0; - current_class_functions = 0; - class_static_variables_code = 0; - class_static_functions_code = 0; - ctor_wrappers = 0; - ctor_dispatcher_code = 0; - - Delete(current_classname); - Delete(current_classname_mangled); - Delete(current_classtype); - Delete(current_classtype_mangled); + t_registerclass.replace("${classname}", state.clazz(__NAME__)) + .replace("${classname_mangled}", state.clazz(NAME_MANGLED)) + .replace("${namespace_mangled}", Getattr(current_namespace, "name_mangled")) + .pretty_print(state.global(INITIALIZER)); return SWIG_OK; } @@ -959,9 +1364,8 @@ int JSCEmitter::emitCtor(Node *n) { Template t_ctor(getTemplate("JS_ctordefn")); String *mangled_name = SwigType_manglestr(Getattr(n, "name")); - String *name = (Getattr(n, "wrap:name")); String *overname = Getattr(n, "sym:overname"); - String *wrap_name = Swig_name_wrapper(name); + String *wrap_name = Swig_name_wrapper(Getattr(n, "wrap:name")); Setattr(n, "wrap:name", wrap_name); ParmList *params = Getattr(n, "parms"); @@ -979,30 +1383,27 @@ int JSCEmitter::emitCtor(Node *n) { .replace("${overloadext}", overname) .replace("${LOCALS}", current_wrapper->locals) .replace("${CODE}", current_wrapper->code) - .replace("${type_mangled}", current_classtype_mangled); - - Wrapper_pretty_print(t_ctor.str(), ctor_wrappers); + .replace("${type_mangled}", state.clazz(TYPE_MANGLED)) + .pretty_print(state.clazz(CTORS)); String *argcount = NewString(""); Printf(argcount, "%d", num_args); - Template t_ctor_case(getTemplate("JS_ctor_dispatch_case")); t_ctor_case.replace("${classname_mangled}", mangled_name) .replace("${overloadext}", overname) .replace("${argcount}", argcount); - Printv(ctor_dispatcher_code, t_ctor_case.str(), 0); + Append(state.clazz(CTOR_DISPATCHERS), t_ctor_case.str()); Delete(argcount); return SWIG_OK; - } int JSCEmitter::emitDtor(Node *) { Template t_dtor = getTemplate("JS_destructordefn"); - t_dtor.replace("${classname_mangled}", current_classname_mangled) - .replace("${type}", current_classtype); - Wrapper_pretty_print(t_dtor.str(), f_wrappers); + t_dtor.replace("${classname_mangled}", state.clazz(NAME_MANGLED)) + .replace("${type}", state.clazz(TYPE)) + .pretty_print(f_wrappers); return SWIG_OK; } @@ -1011,10 +1412,9 @@ int JSCEmitter::emitGetter(Node *n, bool is_member) { Template t_getter(getTemplate("JS_getproperty")); bool is_static = Equal(Getattr(n, "storage"), "static"); - String *name = Getattr(n, "wrap:name"); - String *wrap_name = Swig_name_wrapper(name); - current_getter = wrap_name; + String *wrap_name = Swig_name_wrapper(Getattr(n, "wrap:name")); Setattr(n, "wrap:name", wrap_name); + state.variable(GETTER, wrap_name); ParmList *params = Getattr(n, "parms"); emit_parameter_variables(params, current_wrapper); @@ -1027,26 +1427,25 @@ int JSCEmitter::emitGetter(Node *n, bool is_member) { t_getter.replace("${getname}", wrap_name) .replace("${LOCALS}", current_wrapper->locals) - .replace("${CODE}", current_wrapper->code); - - Wrapper_pretty_print(t_getter.str(), f_wrappers); + .replace("${CODE}", current_wrapper->code) + .pretty_print(f_wrappers); return SWIG_OK; } int JSCEmitter::emitSetter(Node *n, bool is_member) { - // skip variable that are immutable - if (is_immutable) + // skip variables that are immutable + if (State::IsSet(state.variable(IS_IMMUTABLE))) { return SWIG_OK; + } Template t_setter(getTemplate("JS_setproperty")); bool is_static = Equal(Getattr(n, "storage"), "static"); - String *name = Getattr(n, "wrap:name"); - String *wrap_name = Swig_name_wrapper(name); - current_setter = wrap_name; + String *wrap_name = Swig_name_wrapper(Getattr(n, "wrap:name")); Setattr(n, "wrap:name", wrap_name); + state.variable(SETTER, wrap_name); ParmList *params = Getattr(n, "parms"); emit_parameter_variables(params, current_wrapper); @@ -1058,15 +1457,14 @@ int JSCEmitter::emitSetter(Node *n, bool is_member) { t_setter.replace("${setname}", wrap_name) .replace("${LOCALS}", current_wrapper->locals) - .replace("${CODE}", current_wrapper->code); - - Wrapper_pretty_print(t_setter.str(), f_wrappers); + .replace("${CODE}", current_wrapper->code) + .pretty_print(f_wrappers); return SWIG_OK; } /* ----------------------------------------------------------------------------- - * swig::JSEmitter::emitConstant() : triggers code generation for constants + * JSCEmitter::emitConstant() : triggers code generation for constants * ----------------------------------------------------------------------------- */ int JSCEmitter::emitConstant(Node *n) { @@ -1091,7 +1489,7 @@ int JSCEmitter::emitConstant(Node *n) { Template t_getter(getTemplate("JS_getproperty")); - current_getter = wrap_name; + state.variable(GETTER, wrap_name); Setattr(n, "wrap:name", wrap_name); Printf(action, "result = %s;\n", value); @@ -1102,9 +1500,8 @@ int JSCEmitter::emitConstant(Node *n) { t_getter.replace("${getname}", wrap_name) .replace("${LOCALS}", current_wrapper->locals) - .replace("${CODE}", current_wrapper->code); - - Wrapper_pretty_print(t_getter.str(), f_wrappers); + .replace("${CODE}", current_wrapper->code) + .pretty_print(f_wrappers); DelWrapper(current_wrapper); current_wrapper = 0; @@ -1125,15 +1522,14 @@ int JSCEmitter::emitFunction(Node *n, bool is_member) { bool is_static = JSEmitter::is_static || Equal(Getattr(n, "storage"), "static"); bool is_overloaded = GetFlag(n, "sym:overloaded"); - String *name = Getattr(n, "sym:name"); - String *wrap_name = Swig_name_wrapper(name); + String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); if (is_overloaded) { Append(wrap_name, Getattr(n, "sym:overname")); } - current_functionwrapper = wrap_name; Setattr(n, "wrap:name", wrap_name); + state.function(WRAPPER_NAME, wrap_name); ParmList *params = Getattr(n, "parms"); emit_parameter_variables(params, current_wrapper); @@ -1146,8 +1542,8 @@ int JSCEmitter::emitFunction(Node *n, bool is_member) { t_function.replace("${functionname}", wrap_name) .replace("${LOCALS}", current_wrapper->locals) - .replace("${CODE}", current_wrapper->code); - Wrapper_pretty_print(t_function.str(), f_wrappers); + .replace("${CODE}", current_wrapper->code) + .pretty_print(f_wrappers); if (is_overloaded) { Template t_dispatch_case = getTemplate("JS_function_dispatch_case"); @@ -1157,9 +1553,9 @@ int JSCEmitter::emitFunction(Node *n, bool is_member) { Printf(argcount, "%d", argc); t_dispatch_case.replace("${functionwrapper}", wrap_name) - .replace("${argcount}", argcount); + .replace("${argcount}", argcount); - Printv(function_dispatcher_code, t_dispatch_case.str(), 0); + Append(state.function(FUNCTION_DISPATCHERS), t_dispatch_case.str()); Delete(argcount); } @@ -1177,14 +1573,13 @@ int JSCEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { Wrapper_add_local(wrapper, "jsresult", "JSValueRef jsresult"); - Append(wrapper->code, function_dispatcher_code); + Append(wrapper->code, state.function(FUNCTION_DISPATCHERS)); Append(wrapper->code, getTemplate("JS_function_dispatch_case_default").str()); t_function.replace("${functionname}", wrap_name) .replace("${LOCALS}", wrapper->locals) - .replace("${CODE}", wrapper->code); - - Wrapper_pretty_print(t_function.str(), f_wrappers); + .replace("${CODE}", wrapper->code) + .pretty_print(f_wrappers); DelWrapper(wrapper); @@ -1192,22 +1587,18 @@ int JSCEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { } int JSCEmitter::switchNamespace(Node *n) { + if (!GetFlag(n, "feature:nspace")) { current_namespace = Getattr(namespaces, "::"); - } else { - String *scope = Swig_scopename_prefix(Getattr(n, "name")); - if (scope) { // if the scope is not yet registered // create all scopes/namespaces recursively if (!Getattr(namespaces, scope)) { - createNamespace(scope); + createNamespace(scope); } - current_namespace = Getattr(namespaces, scope); - } else { current_namespace = Getattr(namespaces, "::"); } @@ -1219,9 +1610,7 @@ int JSCEmitter::switchNamespace(Node *n) { int JSCEmitter::createNamespace(String *scope) { String *parent_scope = Swig_scopename_prefix(scope); - Hash *parent_namespace; - if (parent_scope == 0) { parent_namespace = Getattr(namespaces, "::"); } else if (!Getattr(namespaces, parent_scope)) { @@ -1230,14 +1619,12 @@ int JSCEmitter::createNamespace(String *scope) { } else { parent_namespace = Getattr(namespaces, parent_scope); } - assert(parent_namespace != 0); Hash *new_namespace = createNamespaceEntry(Char(scope), Char(Getattr(parent_namespace, "name"))); Setattr(namespaces, scope, new_namespace); Delete(parent_scope); - return SWIG_OK; } @@ -1249,9 +1636,8 @@ Hash *JSCEmitter::createNamespaceEntry(const char *name, const char *parent) { Setattr(entry, "parent", NewString(parent)); Setattr(entry, "functions", NewString("")); Setattr(entry, "values", NewString("")); - + Delete(_name); - return entry; } @@ -1259,7 +1645,6 @@ int JSCEmitter::emitNamespaces() { Iterator it; for (it = First(namespaces); it.item; it = Next(it)) { Hash *entry = it.item; - String *name = Getattr(entry, "name"); String *parent = Getattr(entry, "parent"); String *functions = Getattr(entry, "functions"); @@ -1269,319 +1654,662 @@ int JSCEmitter::emitNamespaces() { Template namespace_definition(getTemplate("JS_globaldefn")); namespace_definition.replace("${jsglobalvariables}", variables) - .replace("${jsglobalfunctions}", functions) - .replace("${namespace}", name_mangled); - Wrapper_pretty_print(namespace_definition.str(), f_wrap_cpp); + .replace("${jsglobalfunctions}", functions) + .replace("${namespace}", name_mangled) + .pretty_print(f_wrap_cpp); Template t_createNamespace(getTemplate("JS_create_namespace")); t_createNamespace.replace("${namespace}", name_mangled); - Printv(create_namespaces_code, t_createNamespace.str(), 0); + Append(state.global(CREATE_NAMESPACES), t_createNamespace.str()); Template t_registerNamespace(getTemplate("JS_register_namespace")); t_registerNamespace.replace("${namespace_mangled}", name_mangled) - .replace("${namespace}", name) - .replace("${parent_namespace}", parent_mangled); - Printv(register_namespaces_code, t_registerNamespace.str(), 0); + .replace("${namespace}", name) + .replace("${parent_namespace}", parent_mangled); + Append(state.global(REGISTER_NAMESPACES), t_registerNamespace.str()); } return SWIG_OK; } -JSEmitter *swig_javascript_create_JSC_emitter() { +JSEmitter *swig_javascript_create_JSCEmitter() { return new JSCEmitter(); } -extern JSEmitter *swig_javascript_create_JSC_emitter(); - -/* ******************************************************************** - * JAVASCRIPT - * ********************************************************************/ - -class JAVASCRIPT:public Language { - +/* +class V8Emitter: public JSEmitter { + public: - JAVASCRIPT() { - emitter = NULL; - } ~JAVASCRIPT() { - } - virtual int functionHandler(Node *n); - virtual int globalfunctionHandler(Node *n); - virtual int variableHandler(Node *n); - virtual int globalvariableHandler(Node *n); - virtual int staticmemberfunctionHandler(Node *n); - virtual int classHandler(Node *n); - virtual int functionWrapper(Node *n); - virtual int constantWrapper(Node *n); - /** - * Registers all %fragments assigned to section "templates" with the Emitter. - **/ - virtual int fragmentDirective(Node *n); + V8Emitter(); - virtual int constantDirective(Node *n); + virtual ~V8Emitter(); + + virtual int Initialize(Node *n); - virtual void main(int argc, char *argv[]); - virtual int top(Node *n); + virtual int Dump(Node *n); + + virtual int Close(); + + virtual int SwitchContext(Node *n); + + virtual int EnterClass(Node *n); + + virtual int ExitClass(Node *n); + + virtual int EnterVariable(Node *n); + + virtual int ExitVariable(Node *n); + + virtual int EnterFunction(Node *n); + + virtual int ExitFunction(Node *n); + +protected: + + int CreateNamespace(String* scope); + + virtual int EmitCtor(Node *n); + + virtual int EmitDtor(Node *n); + + virtual int EmitFunction(Node *n, bool is_member); + + virtual int EmitGetter(Node *n, bool is_member); + + virtual int EmitSetter(Node *n, bool is_member); + + void marshalInputArgs(Node *n, ParmList *parms, int numarg, Wrapper *wrapper); + + void marshalOutput(Node *n, String *actioncode, Wrapper *wrapper); + + Parm *skipIgnoredArgs(Parm *p); private: - JSEmitter * emitter; + File *f_runtime; + File *f_header; + File *f_class_templates; + File *f_wrapper; + + File *f_init_namespaces; + File *f_init_class_templates; + File *f_init_wrappers; + File *f_init_inheritance; + File *f_init_class_instances; + File *f_init_static_wrappers; + File *f_init_register_classes; + File *f_init_register_namespaces; + + // the output cpp file + File *f_wrap_cpp; + + // state variables + String* current_context; + String* current_class_type; + String* current_classname_mangled; + String* current_classname_unqualified; + String* current_variable_mangled; + String* current_variable_unqualified; + String* current_getter; + String* current_setter; + String* current_function_mangled; + String* current_function_unqualified; + + String* GLOBAL; + String* NULL_STR; + Hash* namespaces; }; +*/ -/* --------------------------------------------------------------------- - * functionWrapper() - * - * Low level code generator for functions - * --------------------------------------------------------------------- */ +/* +// name of templates +#define V8_INITIALIZER "v8_initializer" +#define V8_DECL_CLASSTEMPLATE "v8_declare_class_template" +#define V8_DEFINE_CLASSTEMPLATE "v8_define_class_template" +#define V8_CREATE_CLASS_INSTANCE "v8_create_class_instance" +#define V8_INHERIT "v8_inherit" +#define V8_REGISTER_CLASS "v8_register_class" +#define V8_CTOR_WRAPPER "v8_ctor_wrapper" +#define V8_GETTER "v8_getter" +#define V8_SETTER "v8_setter" +#define V8_FUNCTION "v8_function" +#define V8_RETRIEVE_THIS "v8_retrieve_this" +#define V8_REGISTER_MEMBER_FUNCTION "v8_register_member_function" +#define V8_REGISTER_GLOBAL_FUNCTION "v8_register_global_function" +#define V8_REGISTER_MEMBER_VARIABLE "v8_register_member_variable" +#define V8_REGISTER_GLOBAL_VARIABLE "v8_register_global_variable" +#define V8_CREATE_NAMESPACE "v8_create_namespace" +#define V8_REGISTER_NAMESPACE "v8_register_namespace" +#define V8_THIS_PTR "v8_this_ptr" -int JAVASCRIPT::functionWrapper(Node *n) { +// keywords used in templates +#define KW_MODULE_NAME "${MODULE}" +#define KW_MANGLED_NAME "${NAME_MANGLED}" +#define KW_UNQUALIFIED_NAME "${NAME_UNQUALIFIED}" +#define KW_CLASSNAME_MANGLED "${CLASSNAME_MANGLED}" +#define KW_BASE_CLASS "${BASE_CLASS}" +#define KW_CONTEXT "${CONTEXT}" +#define KW_TYPE "${TYPE}" +#define KW_ARG "${ARG}" +#define KW_WRAPPER "${WRAPPER}" +#define KW_GETTER "${GETTER}" +#define KW_SETTER "${SETTER}" - // note: the default implementation only prints a message - // Language::functionWrapper(n); +#define KW_NAME_SPACES "${PART_NAMESPACES}" +#define KW_CLASS_TEMPLATES "${PART_CLASS_TEMPLATES}" +#define KW_WRAPPERS "${PART_WRAPPERS}" +#define KW_INHERITANCE "${PART_INHERITANCE}" +#define KW_CLASS_INSTANCES "${PART_CLASS_INSTANCES}" +#define KW_STATIC_WRAPPERS "${PART_STATIC_WRAPPERS}" +#define KW_REGISTER_CLASSES "${PART_REGISTER_CLASSES}" +#define KW_REGISTER_NS "${PART_REGISTER_NS}" - emitter->emitWrapperFunction(n); +#define KW_LOCALS "${LOCALS}" +#define KW_CODE "${CODE}" +#define KW_MARSHAL_INPUT "${MARSHAL_INPUT}" +#define KW_ACTION "${ACTION}" +#define KW_MARSHAL_OUTPUT "${MARSHAL_OUTPUT}" - return SWIG_OK; +V8Emitter::V8Emitter() + : JSEmitter(), + GLOBAL(NewString("global")), + NULL_STR(NewString("0")), + namespaces(NewHash()) +{ } -/* --------------------------------------------------------------------- - * functionHandler() - * - * Function handler for generating wrappers for functions - * --------------------------------------------------------------------- */ -int JAVASCRIPT::functionHandler(Node *n) { - - if (GetFlag(n, "isextension") == 1) - SetFlag(n, "ismember"); - - emitter->enterFunction(n); - - Language::functionHandler(n); - - emitter->exitFunction(n); - - return SWIG_OK; +V8Emitter::~V8Emitter() +{ + Delete(GLOBAL); + Delete(NULL_STR); + Delete(namespaces); } -/* --------------------------------------------------------------------- - * globalfunctionHandler() - * - * Function handler for generating wrappers for functions - * --------------------------------------------------------------------- */ +int V8Emitter::initialize(Node *n) +{ + + // Get the output file name + String *outfile = Getattr(n,"outfile"); + f_wrap_cpp = NewFile(outfile, "w", SWIG_output_files()); + if (!f_wrap_cpp) { + FileErrorDisplay(outfile); + SWIG_exit(EXIT_FAILURE); + } -int JAVASCRIPT::globalfunctionHandler(Node *n) { - emitter->switchNamespace(n); + f_runtime = NewString(""); + f_header = NewString(""); + f_class_templates = NewString(""); + f_wrapper = NewString(""); + + f_init_namespaces = NewString(""); + f_init_class_templates = NewString(""); + f_init_wrappers = NewString(""); + f_init_inheritance = NewString(""); + f_init_class_instances = NewString(""); + f_init_static_wrappers = NewString(""); + f_init_register_classes = NewString(""); + f_init_register_namespaces = NewString(""); - Language::globalfunctionHandler(n); - return SWIG_OK; -} + // note: this is necessary for built-in generation of swig runtime code + Swig_register_filebyname("runtime", f_runtime); -int JAVASCRIPT::staticmemberfunctionHandler(Node *n) { - // workaround: storage=static is not set for static member functions - emitter->setStaticFlag(true); - Language::staticmemberfunctionHandler(n); - emitter->setStaticFlag(false); - return SWIG_OK; -} - - -/* --------------------------------------------------------------------- - * variableHandler() - * - * Function handler for generating wrappers for variables - * --------------------------------------------------------------------- */ - -int JAVASCRIPT::variableHandler(Node *n) { - - if (!is_assignable(n) - // HACK: don't know why this is assignable? But does not compile - || Equal(Getattr(n, "type"), "a().char")) { - SetFlag(n, "wrap:immutable"); - } - emitter->enterVariable(n); - - Language::variableHandler(n); - - emitter->exitVariable(n); - - return SWIG_OK; -} - -/* --------------------------------------------------------------------- - * globalvariableHandler() - * - * Function handler for generating wrappers for global variables - * --------------------------------------------------------------------- */ - -int JAVASCRIPT::globalvariableHandler(Node *n) { - - emitter->switchNamespace(n); - - Language::globalvariableHandler(n); - return SWIG_OK; -} - -/* --------------------------------------------------------------------- - * constantHandler() - * - * Function handler for generating wrappers for constants - * --------------------------------------------------------------------- */ - - -int JAVASCRIPT::constantWrapper(Node *n) { - - // TODO: handle callback declarations - //Note: callbacks trigger this wrapper handler - if (Equal(Getattr(n, "kind"), "function")) { return SWIG_OK; - } - //Language::constantWrapper(n); - emitter->emitConstant(n); - - return SWIG_OK; } -/* --------------------------------------------------------------------- - * classHandler() - * - * Function handler for generating wrappers for class - * --------------------------------------------------------------------- */ +int V8Emitter::dump(Node *n) +{ + // Get the module name + String* module = Getattr(n,"name"); -int JAVASCRIPT::classHandler(Node *n) { - emitter->switchNamespace(n); + // write the swig banner + Swig_banner(f_wrap_cpp); - emitter->enterClass(n); - Language::classHandler(n); - emitter->exitClass(n); + Printv(f_wrap_cpp, f_runtime, "\n", 0); + Printv(f_wrap_cpp, f_header, "\n", 0); + Printv(f_wrap_cpp, f_class_templates, "\n", 0); + Printv(f_wrap_cpp, f_wrapper, "\n", 0); - return SWIG_OK; + // compose the initializer function using a template + // filled with sub-parts + Template initializer(GetTemplate(V8_INITIALIZER)); + initializer.Replace(KW_MODULE_NAME, module) + .Replace(KW_NAME_SPACES, f_init_namespaces) + .Replace(KW_CLASS_TEMPLATES, f_init_class_templates) + .Replace(KW_WRAPPERS, f_init_wrappers) + .Replace(KW_INHERITANCE, f_init_inheritance) + .Replace(KW_CLASS_INSTANCES, f_init_class_instances) + .Replace(KW_STATIC_WRAPPERS, f_init_static_wrappers) + .Replace(KW_REGISTER_CLASSES, f_init_register_classes) + .Replace(KW_REGISTER_NS, f_init_register_namespaces); + Wrapper_pretty_print(initializer.str(), f_wrap_cpp); + + return SWIG_OK; } -int JAVASCRIPT::fragmentDirective(Node *n) { - - // catch all fragment directives that have "templates" as location - // and register them at the emitter. - String *section = Getattr(n, "section"); - - if (Cmp(section, "templates") == 0) { - emitter->registerTemplate(Getattr(n, "value"), Getattr(n, "code")); - } else { - Swig_fragment_register(n); - } - - return SWIG_OK; +int V8Emitter::close() +{ + // strings + Delete(f_runtime); + Delete(f_header); + Delete(f_class_templates); + Delete(f_wrapper); + Delete(f_init_namespaces); + Delete(f_init_class_templates); + Delete(f_init_wrappers); + Delete(f_init_inheritance); + Delete(f_init_class_instances); + Delete(f_init_static_wrappers); + Delete(f_init_register_classes); + Delete(f_init_register_namespaces); + + // files + Close(f_wrap_cpp); + Delete(f_wrap_cpp); + + return SWIG_OK; } -int JAVASCRIPT::constantDirective(Node *n) { - - Language::constantDirective(n); - - return SWIG_OK; +int V8Emitter::SwitchContext(Node *n) +{ + String* scope = Swig_scopename_prefix(Getattr(n, "name")); + + if (scope) { + // if the scope is not yet registered + // create all scopes/namespaces recursively + if(!Getattr(namespaces, scope)) { + CreateNamespace(scope); + } + current_context = Getattr(namespaces, scope); + } else { + current_context = GLOBAL; + } + + return SWIG_OK; } -/* --------------------------------------------------------------------- - * top() - * - * Function handler for processing top node of the parse tree - * Wrapper code generation essentially starts from here - * --------------------------------------------------------------------- */ +int V8Emitter::CreateNamespace(String* scope) { + String* parent_scope = Swig_scopename_prefix(scope); + String* parent_scope_mangled = 0; -int JAVASCRIPT::top(Node *n) { + if(!parent_scope) { + parent_scope_mangled = NewString("global"); + } else { + parent_scope_mangled = Swig_name_mangle(parent_scope); - emitter->initialize(n); + } + + if (parent_scope && !Getattr(namespaces, parent_scope)) { + CreateNamespace(parent_scope); + } + + String* scope_mangled = Swig_string_mangle(scope); + String* scope_unqualified = Swig_scopename_last(scope); + Setattr(namespaces, scope, scope_mangled); + + // create namespace object and register it to the parent scope + Template t_create_ns(GetTemplate(V8_CREATE_NAMESPACE)); + t_create_ns.Replace(KW_MANGLED_NAME, scope_mangled); + + Template t_register_ns(GetTemplate(V8_REGISTER_NAMESPACE)); + t_register_ns.Replace(KW_MANGLED_NAME, scope_mangled) + .Replace(KW_CONTEXT, parent_scope_mangled) + .Replace(KW_UNQUALIFIED_NAME, scope_unqualified); - Language::top(n); + Printv(f_init_namespaces, t_create_ns.str(), 0); + // prepend in order to achieve reversed order of registration statements + Insert(f_init_register_namespaces, 0, t_register_ns.str()); - emitter->dump(n); - emitter->close(); - - delete emitter; - - return SWIG_OK; + Delete(parent_scope); + Delete(parent_scope_mangled); + Delete(scope_unqualified); + return SWIG_OK; } -/* --------------------------------------------------------------------- - * main() - * - * Entry point for the JAVASCRIPT module - * --------------------------------------------------------------------- */ +int V8Emitter::EnterClass(Node *n) +{ + current_classname_mangled = Swig_string_mangle(Getattr(n, "name")); + current_classname_unqualified = Swig_scopename_last(Getattr(n, "name")); + current_class_type = Getattr(n, "classtype"); + + // emit declaration of a v8 class template + Template t_decl_class(GetTemplate(V8_DECL_CLASSTEMPLATE)); + t_decl_class.Replace(KW_MANGLED_NAME, current_classname_mangled); + Printv(f_class_templates, t_decl_class.str(), 0); -void JAVASCRIPT::main(int argc, char *argv[]) { + // emit definition of v8 class template + Template t_def_class(GetTemplate(V8_DEFINE_CLASSTEMPLATE)); + t_def_class.Replace(KW_MANGLED_NAME, current_classname_mangled) + .Replace(KW_UNQUALIFIED_NAME, current_classname_unqualified); + Printv(f_init_class_templates, t_def_class.str(), 0); + + Template t_class_instance(GetTemplate(V8_CREATE_CLASS_INSTANCE)); + t_class_instance.Replace(KW_MANGLED_NAME, current_classname_mangled); + Printv(f_init_class_instances, t_class_instance.str(), 0); - // Set javascript subdirectory in SWIG library - SWIG_library_directory("javascript"); + return SWIG_OK; +} - int mode = -1; +int V8Emitter::ExitClass(Node *n) +{ + // emit inheritance setup + Node* baseClass = GetBaseClass(n); + if(baseClass) { + Template t_inherit(GetTemplate(V8_INHERIT)); + t_inherit.Replace(KW_MANGLED_NAME, current_classname_mangled) + .Replace(KW_BASE_CLASS, Swig_string_mangle(Getattr(baseClass, "name"))); + Printv(f_init_inheritance, t_inherit.str(), 0); + } + + // emit registeration of class template + Template t_register(GetTemplate(V8_REGISTER_CLASS)); + t_register.Replace(KW_MANGLED_NAME, current_classname_mangled) + .Replace(KW_UNQUALIFIED_NAME, current_classname_unqualified) + .Replace(KW_CONTEXT, Swig_string_mangle(current_context)); + Printv(f_init_register_classes, t_register.str(), 0); - bool debug_templates = false; - for (int i = 1; i < argc; i++) { - if (argv[i]) { - if (strcmp(argv[i], "-v8") == 0) { - Swig_mark_arg(i); - mode = JSEmitter::V8; - SWIG_library_directory("javascript/v8"); - } else if (strcmp(argv[i], "-jsc") == 0) { - Swig_mark_arg(i); - mode = JSEmitter::JavascriptCore; - SWIG_library_directory("javascript/jsc"); - } else if (strcmp(argv[i], "-qt") == 0) { - Swig_mark_arg(i); - mode = JSEmitter::QtScript; - SWIG_library_directory("javascript/qt"); - } else if (strcmp(argv[i], "-debug-templates") == 0) { - Swig_mark_arg(i); - debug_templates = true; + Delete(current_classname_mangled); + Delete(current_classname_unqualified); + current_classname_mangled = 0; + current_classname_unqualified = 0; + current_class_type = 0; + + return SWIG_OK; +} + +int V8Emitter::EnterVariable(Node* n) +{ + current_variable_unqualified = Swig_scopename_last(Getattr(n, "name")); + if(GetFlag(n, "ismember")) { + current_variable_mangled = NewString(""); + Printf(current_variable_mangled, "%s_%s", current_classname_mangled, current_variable_unqualified); + } else { + current_variable_mangled = Swig_string_mangle(Getattr(n, "name")); + } + + current_getter = NULL_STR; + current_setter = NULL_STR; + + return SWIG_OK; +} + +int V8Emitter::ExitVariable(Node* n) +{ + if(GetFlag(n, "ismember")) { + if(Equal(Getattr(n, "storage"), "static")) { + Template t_register(GetTemplate(V8_REGISTER_GLOBAL_VARIABLE)); + String *class_instance = NewString(""); + Printf(class_instance, "class_%s", current_classname_mangled); + t_register.Replace(KW_CONTEXT, class_instance) + .Replace(KW_UNQUALIFIED_NAME, current_variable_unqualified) + .Replace(KW_GETTER, current_getter) + .Replace(KW_SETTER, current_setter); + Printv(f_init_static_wrappers, t_register.str(), 0); + Delete(class_instance); + } else { + Template t_register(GetTemplate(V8_REGISTER_MEMBER_VARIABLE)); + t_register.Replace(KW_CLASSNAME_MANGLED, current_classname_mangled) + .Replace(KW_UNQUALIFIED_NAME, current_variable_unqualified) + .Replace(KW_GETTER, current_getter) + .Replace(KW_SETTER, current_setter); + Printv(f_init_wrappers, t_register.str(), 0); + } + } else { + Template t_register(GetTemplate(V8_REGISTER_GLOBAL_VARIABLE)); + t_register.Replace(KW_CONTEXT, current_context) + .Replace(KW_UNQUALIFIED_NAME, current_variable_unqualified) + .Replace(KW_GETTER, current_getter) + .Replace(KW_SETTER, current_setter); + Printv(f_init_wrappers, t_register.str(), 0); + } + + Delete(current_variable_mangled); + Delete(current_variable_unqualified); + current_variable_mangled = 0; + current_variable_unqualified = 0; + + return SWIG_OK; +} + +int V8Emitter::EnterFunction(Node* n) +{ + current_function_unqualified = Swig_scopename_last(Getattr(n, "name")); + if(GetFlag(n, "ismember")) { + current_function_mangled = NewString(""); + Printf(current_function_mangled, "%s_%s", current_classname_mangled, current_function_unqualified); + } else { + current_function_mangled = Swig_string_mangle(Getattr(n, "name")); + } + + return SWIG_OK; +} + +int V8Emitter::ExitFunction(Node* n) +{ + // register the function at the specific context + if(GetFlag(n, "ismember")) { + if(Equal(Getattr(n, "storage"), "static")) { + Template t_register(GetTemplate(V8_REGISTER_GLOBAL_FUNCTION)); + String *class_instance = NewString(""); + Printf(class_instance, "class_%s", current_classname_mangled); + t_register.Replace(KW_CONTEXT, class_instance) + .Replace(KW_UNQUALIFIED_NAME, current_function_unqualified) + .Replace(KW_MANGLED_NAME, Getattr(n, "wrap:name")); + Printv(f_init_static_wrappers, t_register.str(), 0); + Delete(class_instance); + } else { + Template t_register(GetTemplate(V8_REGISTER_MEMBER_FUNCTION)); + t_register.Replace(KW_CLASSNAME_MANGLED, current_classname_mangled) + .Replace(KW_UNQUALIFIED_NAME, current_function_unqualified) + .Replace(KW_MANGLED_NAME, Getattr(n, "wrap:name")); + Printv(f_init_wrappers, t_register.str(), "\n", 0); + } + } else { + Template t_register(GetTemplate(V8_REGISTER_GLOBAL_FUNCTION)); + t_register.Replace(KW_CONTEXT, current_context) + .Replace(KW_UNQUALIFIED_NAME, current_function_unqualified) + .Replace(KW_MANGLED_NAME, Getattr(n, "wrap:name")); + Printv(f_init_wrappers, t_register.str(), 0); + } + + + Delete(current_function_mangled); + Delete(current_function_unqualified); + current_function_mangled = 0; + current_function_unqualified = 0; + + return SWIG_OK; +} + +int V8Emitter::EmitCtor(Node* n) +{ + // TODO: handle overloaded ctors using a dispatcher + Template t(GetTemplate(V8_CTOR_WRAPPER)); + + //HACK: manually add declaration of instance pointer + Printf(current_wrapper->locals, "%sresult;", SwigType_str(Getattr(n, "type"),0)); + + String* action = emit_action(n); + Printv(current_wrapper->code, action, 0); + + t.Replace(KW_MANGLED_NAME, current_classname_mangled) + .Replace(KW_UNQUALIFIED_NAME, current_classname_unqualified) + .Replace(KW_LOCALS, current_wrapper->locals) + .Replace(KW_CODE, current_wrapper->code); + + Wrapper_pretty_print(t.str(), f_wrapper); + + return SWIG_OK; +} + +int V8Emitter::EmitDtor(Node* n) +{ + // TODO: + // find out how to register a dtor in v8 + return SWIG_OK; +} + +int V8Emitter::EmitGetter(Node *n, bool is_member) { + Template t_getter(GetTemplate(V8_GETTER)); + + current_getter = Getattr(n,"wrap:name"); + + ParmList *params = Getattr(n,"parms"); + emit_parameter_variables(params, current_wrapper); + emit_attach_parmmaps(params, current_wrapper); + + int num_args = emit_num_arguments(params); + String* action = emit_action(n); + marshalInputArgs(n, params, num_args, current_wrapper); + marshalOutput(n, action, current_wrapper); + + t_getter.Replace(KW_MANGLED_NAME, current_variable_mangled) + .Replace(KW_LOCALS, current_wrapper->locals) + .Replace(KW_CODE, current_wrapper->code); + + Wrapper_pretty_print(t_getter.str(), f_wrapper); + + return SWIG_OK; +} + +int V8Emitter::EmitSetter(Node* n, bool is_member) +{ + Template t_setter(GetTemplate(V8_SETTER)); + + current_setter = Getattr(n,"wrap:name"); + + ParmList *params = Getattr(n,"parms"); + emit_parameter_variables(params, current_wrapper); + emit_attach_parmmaps(params, current_wrapper); + + int num_args = emit_num_arguments(params); + String* action = emit_action(n); + marshalInputArgs(n, params, num_args, current_wrapper); + Printv(current_wrapper->code, action, 0); + + t_setter.Replace(KW_MANGLED_NAME, current_variable_mangled) + .Replace(KW_LOCALS, current_wrapper->locals) + .Replace(KW_CODE, current_wrapper->code); + + Wrapper_pretty_print(t_setter.str(), f_wrapper); + + return SWIG_OK; +} + + +int V8Emitter::EmitFunction(Node* n, bool is_member) +{ + Template t_function(GetTemplate(V8_FUNCTION)); + + String* wrap_name = NewString(""); + Printv(wrap_name, current_function_mangled, 0); + Setattr(n, "wrap:name", wrap_name); + + ParmList *params = Getattr(n,"parms"); + emit_parameter_variables(params, current_wrapper); + emit_attach_parmmaps(params, current_wrapper); + + int num_args = emit_num_arguments(params); + String* action = emit_action(n); + marshalInputArgs(n, params, num_args, current_wrapper); + marshalOutput(n, action, current_wrapper); + + t_function.Replace(KW_MANGLED_NAME, current_function_mangled) + .Replace(KW_LOCALS, current_wrapper->locals) + .Replace(KW_CODE, current_wrapper->code); + Wrapper_pretty_print(t_function.str(), f_wrapper); + + return SWIG_OK; +} + +void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, int numarg, Wrapper *wrapper) { + String *tm; + Parm *p; + + bool is_member = (current_class_type != 0); + bool is_setter = IsSetterMethod(n); + bool is_function = (current_function_mangled != 0); + + int start_idx; + if(is_member) { + start_idx = 1; + } else { + start_idx = 0; + } + + // retrieve this pointer for member functions + if(is_member) { + + Template t_selfptr(GetTemplate(V8_THIS_PTR)); + String *type_str = SwigType_strip_qualifiers(SwigType_str(current_class_type,0)); + String *arg_str; + if(is_function) { + arg_str = NewString("args"); + } else { + arg_str = NewString("info"); + } + + t_selfptr.Replace(KW_TYPE, type_str) + .Replace(KW_ARG, arg_str); + Printv(wrapper->code, t_selfptr.str(), 0); + + Delete(type_str); + Delete(arg_str); + } + + int i = 0; + for (i = 0, p = parms; i < numarg; i++) + { + p = skipIgnoredArgs(p); + SwigType *pt = Getattr(p, "type"); + + String *arg = NewString(""); + if (i == 0) { + if(start_idx == 0) { + Printv(arg, is_setter?"value":"args[0]", 0); + } else { + p = Getattr(p, "tmap:in:next"); + Delete(arg); + continue; // special case: skip the typemaps for the first argument + } + } else { + Printf(arg, is_setter?"value":"args[%d]", i - start_idx); + } + + if ((tm = Getattr(p, "tmap:in"))) // Get typemap for this argument + { + Replaceall(tm, "$input", arg); + Setattr(p, "emit:input", arg); + Printf(wrapper->code, "%s\n", tm); + p = Getattr(p, "tmap:in:next"); + } else { + Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0)); + p = nextSibling(p); + } + Delete(arg); + } +} + +void V8Emitter::marshalOutput(Node *n, String *actioncode, Wrapper *wrapper) { + SwigType *type = Getattr(n, "type"); + Setattr(n, "type", type); + String *tm; + if ((tm = Swig_typemap_lookup_out("out", n, "result", wrapper, actioncode))) + { + Replaceall(tm, "$result", "jsresult"); + // TODO: May not be the correct way + Replaceall(tm, "$objecttype", Swig_scopename_last(SwigType_str(SwigType_strip_qualifiers(type), 0))); + Printf(wrapper->code, "%s", tm); + if (Len(tm)) + Printf(wrapper->code, "\n"); + } else { + Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(type, 0), Getattr(n, "name")); } - } - } - - switch (mode) { - case JSEmitter::V8: - { - // TODO: emitter = create_v8_emitter(); - break; - } - case JSEmitter::JavascriptCore: - { - emitter = swig_javascript_create_JSC_emitter(); - break; - } - case JSEmitter::QtScript: - { - // TODO: emitter = create_qtscript_emitter(); - break; - } - default: - { - Printf(stderr, "Unknown emitter type."); - SWIG_exit(-1); - break; - } - } - - if (debug_templates) { - emitter->enableDebug(); - } - // Add a symbol to the parser for conditional compilation - Preprocessor_define("SWIGJAVASCRIPT 1", 0); - - // Add typemap definitions - SWIG_typemap_lang("javascript"); - - // Set configuration file - SWIG_config_file("javascript.swg"); - - allow_overloading(); + emit_return_variable(n, type, wrapper); } -/* ----------------------------------------------------------------------------- - * swig_JAVASCRIPT() - Instantiate module - * ----------------------------------------------------------------------------- */ - -static Language *new_swig_javascript() { - return new JAVASCRIPT(); +*/ +JSEmitter *swig_javascript_create_V8Emitter() { + return 0; } -extern "C" Language *swig_javascript(void) { - return new_swig_javascript(); -} diff --git a/Source/Modules/javascript_v8.cxx b/Source/Modules/javascript_v8.cxx deleted file mode 100644 index cacceb214..000000000 --- a/Source/Modules/javascript_v8.cxx +++ /dev/null @@ -1,579 +0,0 @@ -#include "javascript_v8.h" -#include "swigmod.h" - -/* ----------------------------------------------------------------------- - * String constants that are used in Lib/javascript/v8/javascriptcode.swg - *------------------------------------------------------------------------ */ - -// name of templates -#define V8_INITIALIZER "v8_initializer" -#define V8_DECL_CLASSTEMPLATE "v8_declare_class_template" -#define V8_DEFINE_CLASSTEMPLATE "v8_define_class_template" -#define V8_CREATE_CLASS_INSTANCE "v8_create_class_instance" -#define V8_INHERIT "v8_inherit" -#define V8_REGISTER_CLASS "v8_register_class" -#define V8_CTOR_WRAPPER "v8_ctor_wrapper" -#define V8_GETTER "v8_getter" -#define V8_SETTER "v8_setter" -#define V8_FUNCTION "v8_function" -#define V8_RETRIEVE_THIS "v8_retrieve_this" -#define V8_REGISTER_MEMBER_FUNCTION "v8_register_member_function" -#define V8_REGISTER_GLOBAL_FUNCTION "v8_register_global_function" -#define V8_REGISTER_MEMBER_VARIABLE "v8_register_member_variable" -#define V8_REGISTER_GLOBAL_VARIABLE "v8_register_global_variable" -#define V8_CREATE_NAMESPACE "v8_create_namespace" -#define V8_REGISTER_NAMESPACE "v8_register_namespace" -#define V8_THIS_PTR "v8_this_ptr" - - -// keywords used in templates -#define KW_MODULE_NAME "${MODULE}" -#define KW_MANGLED_NAME "${NAME_MANGLED}" -#define KW_UNQUALIFIED_NAME "${NAME_UNQUALIFIED}" -#define KW_CLASSNAME_MANGLED "${CLASSNAME_MANGLED}" -#define KW_BASE_CLASS "${BASE_CLASS}" -#define KW_CONTEXT "${CONTEXT}" -#define KW_TYPE "${TYPE}" -#define KW_ARG "${ARG}" -#define KW_WRAPPER "${WRAPPER}" -#define KW_GETTER "${GETTER}" -#define KW_SETTER "${SETTER}" - -#define KW_NAME_SPACES "${PART_NAMESPACES}" -#define KW_CLASS_TEMPLATES "${PART_CLASS_TEMPLATES}" -#define KW_WRAPPERS "${PART_WRAPPERS}" -#define KW_INHERITANCE "${PART_INHERITANCE}" -#define KW_CLASS_INSTANCES "${PART_CLASS_INSTANCES}" -#define KW_STATIC_WRAPPERS "${PART_STATIC_WRAPPERS}" -#define KW_REGISTER_CLASSES "${PART_REGISTER_CLASSES}" -#define KW_REGISTER_NS "${PART_REGISTER_NS}" - -#define KW_LOCALS "${LOCALS}" -#define KW_CODE "${CODE}" -#define KW_MARSHAL_INPUT "${MARSHAL_INPUT}" -#define KW_ACTION "${ACTION}" -#define KW_MARSHAL_OUTPUT "${MARSHAL_OUTPUT}" - -V8Emitter::V8Emitter() - : JSEmitter(), - GLOBAL(NewString("global")), - NULL_STR(NewString("0")), - namespaces(NewHash()) -{ -} - -V8Emitter::~V8Emitter() -{ - Delete(GLOBAL); - Delete(NULL_STR); - Delete(namespaces); -} - -int V8Emitter::Initialize(Node *n) -{ - - /* Get the output file name */ - String *outfile = Getattr(n,"outfile"); - f_wrap_cpp = NewFile(outfile, "w", SWIG_output_files()); - if (!f_wrap_cpp) { - FileErrorDisplay(outfile); - SWIG_exit(EXIT_FAILURE); - } - - f_runtime = NewString(""); - f_header = NewString(""); - f_class_templates = NewString(""); - f_wrapper = NewString(""); - - f_init_namespaces = NewString(""); - f_init_class_templates = NewString(""); - f_init_wrappers = NewString(""); - f_init_inheritance = NewString(""); - f_init_class_instances = NewString(""); - f_init_static_wrappers = NewString(""); - f_init_register_classes = NewString(""); - f_init_register_namespaces = NewString(""); - - // note: this is necessary for built-in generation of swig runtime code - Swig_register_filebyname("runtime", f_runtime); - - return SWIG_OK; -} - -int V8Emitter::Dump(Node *n) -{ - /* Get the module name */ - String* module = Getattr(n,"name"); - - // write the swig banner - Swig_banner(f_wrap_cpp); - - Printv(f_wrap_cpp, f_runtime, "\n", 0); - Printv(f_wrap_cpp, f_header, "\n", 0); - Printv(f_wrap_cpp, f_class_templates, "\n", 0); - Printv(f_wrap_cpp, f_wrapper, "\n", 0); - - // compose the initializer function using a template - // filled with sub-parts - Template initializer(GetTemplate(V8_INITIALIZER)); - initializer.Replace(KW_MODULE_NAME, module) - .Replace(KW_NAME_SPACES, f_init_namespaces) - .Replace(KW_CLASS_TEMPLATES, f_init_class_templates) - .Replace(KW_WRAPPERS, f_init_wrappers) - .Replace(KW_INHERITANCE, f_init_inheritance) - .Replace(KW_CLASS_INSTANCES, f_init_class_instances) - .Replace(KW_STATIC_WRAPPERS, f_init_static_wrappers) - .Replace(KW_REGISTER_CLASSES, f_init_register_classes) - .Replace(KW_REGISTER_NS, f_init_register_namespaces); - Wrapper_pretty_print(initializer.str(), f_wrap_cpp); - - return SWIG_OK; -} - -int V8Emitter::Close() -{ - /* strings */ - Delete(f_runtime); - Delete(f_header); - Delete(f_class_templates); - Delete(f_wrapper); - Delete(f_init_namespaces); - Delete(f_init_class_templates); - Delete(f_init_wrappers); - Delete(f_init_inheritance); - Delete(f_init_class_instances); - Delete(f_init_static_wrappers); - Delete(f_init_register_classes); - Delete(f_init_register_namespaces); - - /* files */ - ::Close(f_wrap_cpp); - Delete(f_wrap_cpp); - - return SWIG_OK; -} - -int V8Emitter::SwitchContext(Node *n) -{ - String* scope = Swig_scopename_prefix(Getattr(n, "name")); - - if (scope) { - // if the scope is not yet registered - // create all scopes/namespaces recursively - if(!Getattr(namespaces, scope)) { - CreateNamespace(scope); - } - current_context = Getattr(namespaces, scope); - } else { - current_context = GLOBAL; - } - - return SWIG_OK; -} - -int V8Emitter::CreateNamespace(String* scope) { - String* parent_scope = Swig_scopename_prefix(scope); - String* parent_scope_mangled = 0; - - if(!parent_scope) { - parent_scope_mangled = NewString("global"); - } else { - parent_scope_mangled = Swig_name_mangle(parent_scope); - - } - - if (parent_scope && !Getattr(namespaces, parent_scope)) { - CreateNamespace(parent_scope); - } - - String* scope_mangled = Swig_string_mangle(scope); - String* scope_unqualified = Swig_scopename_last(scope); - Setattr(namespaces, scope, scope_mangled); - - // create namespace object and register it to the parent scope - Template t_create_ns(GetTemplate(V8_CREATE_NAMESPACE)); - t_create_ns.Replace(KW_MANGLED_NAME, scope_mangled); - - Template t_register_ns(GetTemplate(V8_REGISTER_NAMESPACE)); - t_register_ns.Replace(KW_MANGLED_NAME, scope_mangled) - .Replace(KW_CONTEXT, parent_scope_mangled) - .Replace(KW_UNQUALIFIED_NAME, scope_unqualified); - - Printv(f_init_namespaces, t_create_ns.str(), 0); - // prepend in order to achieve reversed order of registration statements - Insert(f_init_register_namespaces, 0, t_register_ns.str()); - - Delete(parent_scope); - Delete(parent_scope_mangled); - Delete(scope_unqualified); - return SWIG_OK; -} - -int V8Emitter::EnterClass(Node *n) -{ - current_classname_mangled = Swig_string_mangle(Getattr(n, "name")); - current_classname_unqualified = Swig_scopename_last(Getattr(n, "name")); - current_class_type = Getattr(n, "classtype"); - - // emit declaration of a v8 class template - Template t_decl_class(GetTemplate(V8_DECL_CLASSTEMPLATE)); - t_decl_class.Replace(KW_MANGLED_NAME, current_classname_mangled); - Printv(f_class_templates, t_decl_class.str(), 0); - - // emit definition of v8 class template - Template t_def_class(GetTemplate(V8_DEFINE_CLASSTEMPLATE)); - t_def_class.Replace(KW_MANGLED_NAME, current_classname_mangled) - .Replace(KW_UNQUALIFIED_NAME, current_classname_unqualified); - Printv(f_init_class_templates, t_def_class.str(), 0); - - Template t_class_instance(GetTemplate(V8_CREATE_CLASS_INSTANCE)); - t_class_instance.Replace(KW_MANGLED_NAME, current_classname_mangled); - Printv(f_init_class_instances, t_class_instance.str(), 0); - - return SWIG_OK; -} - -int V8Emitter::ExitClass(Node *n) -{ - // emit inheritance setup - Node* baseClass = GetBaseClass(n); - if(baseClass) { - Template t_inherit(GetTemplate(V8_INHERIT)); - t_inherit.Replace(KW_MANGLED_NAME, current_classname_mangled) - .Replace(KW_BASE_CLASS, Swig_string_mangle(Getattr(baseClass, "name"))); - Printv(f_init_inheritance, t_inherit.str(), 0); - } - - // emit registeration of class template - Template t_register(GetTemplate(V8_REGISTER_CLASS)); - t_register.Replace(KW_MANGLED_NAME, current_classname_mangled) - .Replace(KW_UNQUALIFIED_NAME, current_classname_unqualified) - .Replace(KW_CONTEXT, Swig_string_mangle(current_context)); - Printv(f_init_register_classes, t_register.str(), 0); - - Delete(current_classname_mangled); - Delete(current_classname_unqualified); - current_classname_mangled = 0; - current_classname_unqualified = 0; - current_class_type = 0; - - return SWIG_OK; -} - -int V8Emitter::EnterVariable(Node* n) -{ - current_variable_unqualified = Swig_scopename_last(Getattr(n, "name")); - if(GetFlag(n, "ismember")) { - current_variable_mangled = NewString(""); - Printf(current_variable_mangled, "%s_%s", current_classname_mangled, current_variable_unqualified); - } else { - current_variable_mangled = Swig_string_mangle(Getattr(n, "name")); - } - - current_getter = NULL_STR; - current_setter = NULL_STR; - - return SWIG_OK; -} - -int V8Emitter::ExitVariable(Node* n) -{ - if(GetFlag(n, "ismember")) { - if(Equal(Getattr(n, "storage"), "static")) { - Template t_register(GetTemplate(V8_REGISTER_GLOBAL_VARIABLE)); - String *class_instance = NewString(""); - Printf(class_instance, "class_%s", current_classname_mangled); - t_register.Replace(KW_CONTEXT, class_instance) - .Replace(KW_UNQUALIFIED_NAME, current_variable_unqualified) - .Replace(KW_GETTER, current_getter) - .Replace(KW_SETTER, current_setter); - Printv(f_init_static_wrappers, t_register.str(), 0); - Delete(class_instance); - } else { - Template t_register(GetTemplate(V8_REGISTER_MEMBER_VARIABLE)); - t_register.Replace(KW_CLASSNAME_MANGLED, current_classname_mangled) - .Replace(KW_UNQUALIFIED_NAME, current_variable_unqualified) - .Replace(KW_GETTER, current_getter) - .Replace(KW_SETTER, current_setter); - Printv(f_init_wrappers, t_register.str(), 0); - } - } else { - Template t_register(GetTemplate(V8_REGISTER_GLOBAL_VARIABLE)); - t_register.Replace(KW_CONTEXT, current_context) - .Replace(KW_UNQUALIFIED_NAME, current_variable_unqualified) - .Replace(KW_GETTER, current_getter) - .Replace(KW_SETTER, current_setter); - Printv(f_init_wrappers, t_register.str(), 0); - } - - Delete(current_variable_mangled); - Delete(current_variable_unqualified); - current_variable_mangled = 0; - current_variable_unqualified = 0; - - return SWIG_OK; -} - -int V8Emitter::EnterFunction(Node* n) -{ - current_function_unqualified = Swig_scopename_last(Getattr(n, "name")); - - if(GetFlag(n, "ismember")) { - current_function_mangled = NewString(""); - Printf(current_function_mangled, "%s_%s", current_classname_mangled, current_function_unqualified); - } else { - current_function_mangled = Swig_string_mangle(Getattr(n, "name")); - } - - return SWIG_OK; -} - -int V8Emitter::ExitFunction(Node* n) -{ - // register the function at the specific context - if(GetFlag(n, "ismember")) { - if(Equal(Getattr(n, "storage"), "static")) { - Template t_register(GetTemplate(V8_REGISTER_GLOBAL_FUNCTION)); - String *class_instance = NewString(""); - Printf(class_instance, "class_%s", current_classname_mangled); - t_register.Replace(KW_CONTEXT, class_instance) - .Replace(KW_UNQUALIFIED_NAME, current_function_unqualified) - .Replace(KW_MANGLED_NAME, Getattr(n, "wrap:name")); - Printv(f_init_static_wrappers, t_register.str(), 0); - Delete(class_instance); - } else { - Template t_register(GetTemplate(V8_REGISTER_MEMBER_FUNCTION)); - t_register.Replace(KW_CLASSNAME_MANGLED, current_classname_mangled) - .Replace(KW_UNQUALIFIED_NAME, current_function_unqualified) - .Replace(KW_MANGLED_NAME, Getattr(n, "wrap:name")); - Printv(f_init_wrappers, t_register.str(), "\n", 0); - } - } else { - Template t_register(GetTemplate(V8_REGISTER_GLOBAL_FUNCTION)); - t_register.Replace(KW_CONTEXT, current_context) - .Replace(KW_UNQUALIFIED_NAME, current_function_unqualified) - .Replace(KW_MANGLED_NAME, Getattr(n, "wrap:name")); - Printv(f_init_wrappers, t_register.str(), 0); - } - - - Delete(current_function_mangled); - Delete(current_function_unqualified); - current_function_mangled = 0; - current_function_unqualified = 0; - - return SWIG_OK; -} - -int V8Emitter::EmitCtor(Node* n) -{ - // TODO: handle overloaded ctors using a dispatcher - Template t(GetTemplate(V8_CTOR_WRAPPER)); - - //HACK: manually add declaration of instance pointer - Printf(current_wrapper->locals, "%sresult;", SwigType_str(Getattr(n, "type"),0)); - - String* action = emit_action(n); - Printv(current_wrapper->code, action, 0); - - t.Replace(KW_MANGLED_NAME, current_classname_mangled) - .Replace(KW_UNQUALIFIED_NAME, current_classname_unqualified) - .Replace(KW_LOCALS, current_wrapper->locals) - .Replace(KW_CODE, current_wrapper->code); - - Wrapper_pretty_print(t.str(), f_wrapper); - - return SWIG_OK; -} - -int V8Emitter::EmitDtor(Node* n) -{ - // TODO: - // find out how to register a dtor in v8 - - Printv(f_wrapper, "/* TODO: Wrap dtor */\n", 0); - - return SWIG_OK; -} - -int V8Emitter::EmitGetter(Node *n, bool is_member) { - Template t_getter(GetTemplate(V8_GETTER)); - - current_getter = Getattr(n,"wrap:name"); - - ParmList *params = Getattr(n,"parms"); - emit_parameter_variables(params, current_wrapper); - emit_attach_parmmaps(params, current_wrapper); - - int num_args = emit_num_arguments(params); - String* action = emit_action(n); - marshalInputArgs(n, params, num_args, current_wrapper); - marshalOutput(n, action, current_wrapper); - - t_getter.Replace(KW_MANGLED_NAME, current_variable_mangled) - .Replace(KW_LOCALS, current_wrapper->locals) - .Replace(KW_CODE, current_wrapper->code); - - Wrapper_pretty_print(t_getter.str(), f_wrapper); - - return SWIG_OK; -} - -int V8Emitter::EmitSetter(Node* n, bool is_member) -{ - Template t_setter(GetTemplate(V8_SETTER)); - - current_setter = Getattr(n,"wrap:name"); - - ParmList *params = Getattr(n,"parms"); - emit_parameter_variables(params, current_wrapper); - emit_attach_parmmaps(params, current_wrapper); - - int num_args = emit_num_arguments(params); - String* action = emit_action(n); - marshalInputArgs(n, params, num_args, current_wrapper); - Printv(current_wrapper->code, action, 0); - - t_setter.Replace(KW_MANGLED_NAME, current_variable_mangled) - .Replace(KW_LOCALS, current_wrapper->locals) - .Replace(KW_CODE, current_wrapper->code); - - Wrapper_pretty_print(t_setter.str(), f_wrapper); - - return SWIG_OK; -} - - -int V8Emitter::EmitFunction(Node* n, bool is_member) -{ - Template t_function(GetTemplate(V8_FUNCTION)); - - String* wrap_name = NewString(""); - Printv(wrap_name, current_function_mangled, 0); - Setattr(n, "wrap:name", wrap_name); - - ParmList *params = Getattr(n,"parms"); - emit_parameter_variables(params, current_wrapper); - emit_attach_parmmaps(params, current_wrapper); - - int num_args = emit_num_arguments(params); - String* action = emit_action(n); - marshalInputArgs(n, params, num_args, current_wrapper); - marshalOutput(n, action, current_wrapper); - - t_function.Replace(KW_MANGLED_NAME, current_function_mangled) - .Replace(KW_LOCALS, current_wrapper->locals) - .Replace(KW_CODE, current_wrapper->code); - Wrapper_pretty_print(t_function.str(), f_wrapper); - - return SWIG_OK; -} - - - -void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, int numarg, Wrapper *wrapper) { - String *tm; - Parm *p; - - bool is_member = (current_class_type != 0); - bool is_setter = IsSetterMethod(n); - bool is_function = (current_function_mangled != 0); - - int start_idx; - if(is_member) { - start_idx = 1; - } else { - start_idx = 0; - } - - // retrieve this pointer for member functions - if(is_member) { - - Template t_selfptr(GetTemplate(V8_THIS_PTR)); - String *type_str = SwigType_strip_qualifiers(SwigType_str(current_class_type,0)); - String *arg_str; - if(is_function) { - arg_str = NewString("args"); - } else { - arg_str = NewString("info"); - } - - t_selfptr.Replace(KW_TYPE, type_str) - .Replace(KW_ARG, arg_str); - Printv(wrapper->code, t_selfptr.str(), 0); - - Delete(type_str); - Delete(arg_str); - } - - int i = 0; - for (i = 0, p = parms; i < numarg; i++) - { - p = skipIgnoredArgs(p); - SwigType *pt = Getattr(p, "type"); - - String *arg = NewString(""); - if (i == 0) { - if(start_idx == 0) { - Printv(arg, is_setter?"value":"args[0]", 0); - } else { - p = Getattr(p, "tmap:in:next"); - Delete(arg); - continue; // special case: skip the typemaps for the first argument - } - } else { - Printf(arg, is_setter?"value":"args[%d]", i - start_idx); - } - - if ((tm = Getattr(p, "tmap:in"))) // Get typemap for this argument - { - Replaceall(tm, "$input", arg); - Setattr(p, "emit:input", arg); - Printf(wrapper->code, "%s\n", tm); - p = Getattr(p, "tmap:in:next"); - } else { - Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0)); - p = nextSibling(p); - } - Delete(arg); - } -} - -/* --------------------------------------------------------------------- - * marshalOutput() - * - * Process the return value of the C/C++ function call - * and convert them into the Javascript types using the - * supplied typemaps. - * --------------------------------------------------------------------- */ - -void V8Emitter::marshalOutput(Node *n, String *actioncode, Wrapper *wrapper) { - SwigType *type = Getattr(n, "type"); - Setattr(n, "type", type); - String *tm; - if ((tm = Swig_typemap_lookup_out("out", n, "result", wrapper, actioncode))) - { - Replaceall(tm, "$result", "jsresult"); - // TODO: May not be the correct way - Replaceall(tm, "$objecttype", Swig_scopename_last(SwigType_str(SwigType_strip_qualifiers(type), 0))); - Printf(wrapper->code, "%s", tm); - if (Len(tm)) - Printf(wrapper->code, "\n"); - } else { - Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(type, 0), Getattr(n, "name")); - } - emit_return_variable(n, type, wrapper); -} - -Parm* V8Emitter::skipIgnoredArgs(Parm *p) { - while (checkAttribute(p, "tmap:in:numinputs", "0")) { - p = Getattr(p, "tmap:in:next"); - } - return p; -} - - -JSEmitter* create_v8_emitter() -{ - return new V8Emitter(); -} From 9af3c4879bbd2103548afbfbff200eff6a78418a Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:58:11 +0000 Subject: [PATCH 0094/1048] Switch to global variable for enabling code template debug information. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13767 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/Modules/javascript.cxx | 26 ++++++++------------------ 1 file changed, 8 insertions(+), 18 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 1fde3cd0c..4ba83f8f2 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -12,6 +12,11 @@ * code fragments */ class Template; +/** + * Enables extra debugging information in typemaps. + */ +bool js_template_enable_debug = false; + class State { public: @@ -197,8 +202,6 @@ public: */ Template getTemplate(const String *name); - void enableDebug(); - void setStaticFlag(bool is_static = false); protected: @@ -246,12 +249,6 @@ protected: Parm *skipIgnoredArgs(Parm *p); - /** - * Enables extra debugging information in typemaps. - * TODO: make this global/static... js_emitter_template_enable_debug - */ - void enableDebugTemplates(); - protected: // empty string used at different places in the code @@ -264,8 +261,6 @@ protected: State state; bool is_static; - - bool debug; }; /* factory methods for concrete JSEmitters: */ @@ -525,7 +520,7 @@ void JAVASCRIPT::main(int argc, char *argv[]) { } if (debug_templates) { - emitter->enableDebug(); + js_template_enable_debug = true; } // Add a symbol to the parser for conditional compilation @@ -595,8 +590,7 @@ private: JSEmitter::JSEmitter() : empty_string(NewString("")), current_wrapper(NULL), - is_static(false), - debug(false) + is_static(false) { templates = NewHash(); } @@ -630,7 +624,7 @@ Template JSEmitter::getTemplate(const String *name) { SWIG_exit(EXIT_FAILURE); } - Template t(templ, name, debug); + Template t(templ, name, js_template_enable_debug); return t; } @@ -639,10 +633,6 @@ int JSEmitter::initialize(Node *) { return SWIG_OK; } -void JSEmitter::enableDebug() { - debug = true; -} - void JSEmitter::setStaticFlag(bool _is_static) { is_static = _is_static; } From b778c4816b63e12e72cb3c2a97e904411465329a Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:58:23 +0000 Subject: [PATCH 0095/1048] Remove a global variable from JSEmitter by making use of JSEmitterState. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13768 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/Modules/javascript.cxx | 84 ++++++++++++++++++++--------------- 1 file changed, 48 insertions(+), 36 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 4ba83f8f2..d8ab2c33c 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -8,27 +8,40 @@ * JAVASCRIPT: swig module implementation **********************************************************************/ -/* forward decl: Template is a convenience helper class for dealing with - * code fragments */ -class Template; - /** * Enables extra debugging information in typemaps. */ bool js_template_enable_debug = false; -class State { +// keywords used for state variables + +#undef NAME +#define NAME "name" +#define NAME_MANGLED "name_mangled" +#define TYPE "type" +#define TYPE_MANGLED "type_mangled" +#define WRAPPER_NAME "wrapper" +#define IS_IMMUTABLE "is_immutable" +#define IS_STATIC "is_static" + +/** + * A convenience class to manage state variables for emitters. + * The implementation delegates to swig Hash DOHs and provides + * named sub-hashes for class, variable, and function states. + */ +class JSEmitterState { public: - State(): _global(NewHash()) { + JSEmitterState(): + _global(NewHash()) { // initialize sub-hashes Setattr(_global, "class", NewHash()); Setattr(_global, "function", NewHash()); Setattr(_global, "variable", NewHash()); } - ~State() { Delete(_global); } + ~JSEmitterState() { Delete(_global); } DOH *getState(const char* key, bool _new = false) { if (_new) { @@ -99,12 +112,20 @@ private: Hash *_global; }; +/* forward decl: Template is a convenience helper class for dealing with + * code fragments */ +class Template; + /** * JSEmitter represents an abstraction of javascript code generators * for different javascript engines. **/ class JSEmitter { +protected: + + typedef JSEmitterState State; + public: enum JSEmitterType { @@ -202,7 +223,7 @@ public: */ Template getTemplate(const String *name); - void setStaticFlag(bool is_static = false); + State &getState(); protected: @@ -259,8 +280,6 @@ protected: Wrapper *current_wrapper; State state; - - bool is_static; }; /* factory methods for concrete JSEmitters: */ @@ -351,9 +370,9 @@ int JAVASCRIPT::globalfunctionHandler(Node *n) { int JAVASCRIPT::staticmemberfunctionHandler(Node *n) { // workaround: storage=static is not set for static member functions - emitter->setStaticFlag(true); + emitter->getState().function(IS_STATIC, NewString("1")); Language::staticmemberfunctionHandler(n); - emitter->setStaticFlag(false); + emitter->getState().function(IS_STATIC, NULL); return SWIG_OK; } @@ -575,22 +594,13 @@ private: bool debug; }; -#define __NAME__ "name" -#define NAME_MANGLED "name_mangled" -#define TYPE "type" -#define TYPE_MANGLED "type_mangled" -#define WRAPPER_NAME "wrapper" -#define IS_IMMUTABLE "is_immutable" -#define IS_STATIC "is_static" - /* ----------------------------------------------------------------------------- * JSEmitter() * ----------------------------------------------------------------------------- */ JSEmitter::JSEmitter() : empty_string(NewString("")), - current_wrapper(NULL), - is_static(false) + current_wrapper(NULL) { templates = NewHash(); } @@ -629,12 +639,12 @@ Template JSEmitter::getTemplate(const String *name) { return t; } -int JSEmitter::initialize(Node *) { - return SWIG_OK; +JSEmitterState &JSEmitter::getState() { + return state; } -void JSEmitter::setStaticFlag(bool _is_static) { - is_static = _is_static; +int JSEmitter::initialize(Node *) { + return SWIG_OK; } /* ----------------------------------------------------------------------------- @@ -753,7 +763,7 @@ int JSEmitter::emitWrapperFunction(Node *n) { int JSEmitter::enterClass(Node *n) { state.clazz(true); - state.clazz(__NAME__, Getattr(n, "sym:name")); + state.clazz(NAME, Getattr(n, "sym:name")); state.clazz(NAME_MANGLED, SwigType_manglestr(Getattr(n, "name"))); state.clazz(TYPE, NewString(Getattr(n, "classtype"))); @@ -769,14 +779,14 @@ int JSEmitter::enterClass(Node *n) { int JSEmitter::enterFunction(Node *n) { state.function(true); - state.function(__NAME__, Getattr(n, "sym:name")); + state.function(NAME, Getattr(n, "sym:name")); return SWIG_OK; } int JSEmitter::enterVariable(Node *n) { state.variable(true); - state.variable(__NAME__, Swig_scopename_last(Getattr(n, "name"))); + state.variable(NAME, Swig_scopename_last(Getattr(n, "name"))); state.variable(IS_IMMUTABLE, Getattr(n, "wrap:immutable")); return SWIG_OK; } @@ -1238,7 +1248,7 @@ int JSCEmitter::exitFunction(Node *n) { } } - t_function.replace("${functionname}", state.function(__NAME__)) + t_function.replace("${functionname}", state.function(NAME)) .replace("${functionwrapper}", state.function(WRAPPER_NAME)); if (is_member) { @@ -1268,7 +1278,7 @@ int JSCEmitter::exitVariable(Node *n) { Template t_variable(getTemplate("JS_variabledecl")); t_variable.replace("${setname}", state.variable(SETTER)) .replace("${getname}", state.variable(GETTER)) - .replace("${propertyname}", state.variable(__NAME__)); + .replace("${propertyname}", state.variable(NAME)); if (GetFlag(n, "ismember")) { if (Equal(Getattr(n, "storage"), "static") || (Equal(Getattr(n, "nodeType"), "enumitem"))) { @@ -1341,7 +1351,7 @@ int JSCEmitter::exitClass(Node *n) { /* adds a class registration statement to initializer function */ Template t_registerclass(getTemplate("JS_register_class")); - t_registerclass.replace("${classname}", state.clazz(__NAME__)) + t_registerclass.replace("${classname}", state.clazz(NAME)) .replace("${classname_mangled}", state.clazz(NAME_MANGLED)) .replace("${namespace_mangled}", Getattr(current_namespace, "name_mangled")) .pretty_print(state.global(INITIALIZER)); @@ -1509,23 +1519,24 @@ int JSCEmitter::emitFunction(Node *n, bool is_member) { // in these cases the context (staticmemberfunctionHandler) is // exploited and a flag is set temporarily // TODO: this could be done in general with is_member and is_static - bool is_static = JSEmitter::is_static || Equal(Getattr(n, "storage"), "static"); - + bool is_static = State::IsSet(state.function(IS_STATIC)) || Equal(Getattr(n, "storage"), "static"); bool is_overloaded = GetFlag(n, "sym:overloaded"); - String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); + // prepare the function wrapper name + String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); if (is_overloaded) { Append(wrap_name, Getattr(n, "sym:overname")); } - Setattr(n, "wrap:name", wrap_name); state.function(WRAPPER_NAME, wrap_name); + // prepare local variables ParmList *params = Getattr(n, "parms"); emit_parameter_variables(params, current_wrapper); emit_attach_parmmaps(params, current_wrapper); Wrapper_add_local(current_wrapper, "jsresult", "JSValueRef jsresult"); + // prepare code part String *action = emit_action(n); marshalInputArgs(n, params, current_wrapper, Function, is_member, is_static); marshalOutput(n, action, current_wrapper); @@ -1535,6 +1546,7 @@ int JSCEmitter::emitFunction(Node *n, bool is_member) { .replace("${CODE}", current_wrapper->code) .pretty_print(f_wrappers); + // handle function overloading if (is_overloaded) { Template t_dispatch_case = getTemplate("JS_function_dispatch_case"); From 8577ae41791303471a80fde1384f319ef5ababb9 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:58:37 +0000 Subject: [PATCH 0096/1048] Minor clean up. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13769 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/Makefile.in | 4 +- Source/Modules/javascript.cxx | 410 ++++++++++++++++++---------------- 2 files changed, 225 insertions(+), 189 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 80f807631..afe135964 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -535,7 +535,7 @@ JSCXXFLAGS = @JSCXXFLAGS@ # ---------------------------------------------------------------- javascript: $(SRCS) - $(SWIG) -javascript -jsc -debug-templates $(SWIGOPT) $(INTERFACEPATH) + $(SWIG) -javascript -jsc $(SWIGOPT) $(INTERFACEPATH) $(CC) -c $(CCSHARED) $(JSCFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(JS_INCLUDE) $(JSLDSHARED) $(CCSHARED) $(JSCFLAGS) $(OBJS) $(IOBJS) $(JS_DLNK) $(LIBS) -o $(JS_LIBPREFIX)$(TARGET)$(JSSO) @@ -544,7 +544,7 @@ javascript: $(SRCS) # ---------------------------------------------------------------- javascript_cpp: $(SRCS) - $(SWIG) -javascript -jsc -c++ -debug-templates $(SWIGOPT) $(INTERFACEPATH) + $(SWIG) -javascript -jsc -c++ $(SWIGOPT) $(INTERFACEPATH) $(CXX) -c $(CCSHARED) $(JSCXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(JS_INCLUDE) $(JSCXXSHARED) $(CCSHARED) $(OBJS) $(IOBJS) $(JS_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(JS_LIBPREFIX)$(TARGET)$(JSSO) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index d8ab2c33c..fd41f90e1 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1,13 +1,5 @@ #include "swigmod.h" -#include -#include -#include - -/********************************************************************** - * JAVASCRIPT: swig module implementation - **********************************************************************/ - /** * Enables extra debugging information in typemaps. */ @@ -15,7 +7,6 @@ bool js_template_enable_debug = false; // keywords used for state variables -#undef NAME #define NAME "name" #define NAME_MANGLED "name_mangled" #define TYPE "type" @@ -33,88 +24,60 @@ class JSEmitterState { public: - JSEmitterState(): - _global(NewHash()) { - // initialize sub-hashes - Setattr(_global, "class", NewHash()); - Setattr(_global, "function", NewHash()); - Setattr(_global, "variable", NewHash()); - } + JSEmitterState(); - ~JSEmitterState() { Delete(_global); } + ~JSEmitterState(); + + DOH *global(); - DOH *getState(const char* key, bool _new = false) { - if (_new) { - Hash *hash = NewHash(); - Setattr(_global, key, hash); - } - return Getattr(_global, key); - } + DOH *global(const char* key, DOH *initial = 0); - DOH *global() { return _global; } - - DOH *global(const char* key, DOH *initial=0) { - if(initial != 0) { - Setattr(_global, key, initial); - } - return Getattr(_global, key); - } - - DOH *clazz(bool _new = false) { - return getState("class", _new); - } + DOH *clazz(bool reset = false); - DOH *clazz(const char* key, DOH *initial=0) { - DOH *c = clazz(); - if(initial != 0) { - Setattr(c, key, initial); - } - return Getattr(c, key); - } + DOH *clazz(const char* key, DOH *initial = 0); - DOH *function(bool _new = false) { - return getState("function", _new); - } + DOH *function(bool reset = false); - DOH *function(const char* key, DOH *initial=0) { - DOH *f = function(); - if(initial != 0) { - Setattr(f, key, initial); - } - return Getattr(f, key); - } + DOH *function(const char* key, DOH *initial = 0); - DOH *variable(bool _new = false) { - return getState("variable", _new); - } + DOH *variable(bool reset = false); - DOH *variable(const char* key, DOH *initial=0) { - DOH *v = variable(); - if(initial != 0) { - Setattr(v, key, initial); - } - return Getattr(v, key); - } + DOH *variable(const char* key, DOH *initial = 0); - static int IsSet(DOH *val) { - if (!val) { - return 0; - } else { - const char *cval = Char(val); - if (!cval) - return 0; - return (strcmp(cval, "0") != 0) ? 1 : 0; - } - } + static int IsSet(DOH *val); private: + DOH *getState(const char* key, bool reset = false); + Hash *_global; }; -/* forward decl: Template is a convenience helper class for dealing with - * code fragments */ -class Template; +/** + * A convenience class that wraps a code snippet used as template + * for code generation. + */ +class Template { + +public: + Template(const String *code); + + Template(const String *code, const String *templateName); + + ~Template(); + + String *str(); + + Template& replace(const String *pattern, const String *repl); + + Template& pretty_print(DOH *doh); + +private: + + String *code; + String *templateName; + +}; /** * JSEmitter represents an abstraction of javascript code generators @@ -134,9 +97,9 @@ public: QtScript }; - JSEmitter(); + JSEmitter(); - virtual ~JSEmitter(); + virtual ~JSEmitter(); /** * Opens output files and temporary output DOHs. @@ -282,6 +245,10 @@ protected: State state; }; +/********************************************************************** + * JAVASCRIPT: swig module implementation + **********************************************************************/ + /* factory methods for concrete JSEmitters: */ JSEmitter *swig_javascript_create_JSCEmitter(); JSEmitter *swig_javascript_create_V8Emitter(); @@ -385,7 +352,8 @@ int JAVASCRIPT::staticmemberfunctionHandler(Node *n) { int JAVASCRIPT::variableHandler(Node *n) { if (!is_assignable(n) - // HACK: don't know why this is assignable? + // FIXME: test "arrays_global" does not compile with that as it is not allowed to assign to char[] + // probably some error in char[] typemap || Equal(Getattr(n, "type"), "a().char")) { SetFlag(n, "wrap:immutable"); } @@ -393,6 +361,7 @@ int JAVASCRIPT::variableHandler(Node *n) { emitter->enterVariable(n); Language::variableHandler(n); emitter->exitVariable(n); + return SWIG_OK; } @@ -406,6 +375,7 @@ int JAVASCRIPT::globalvariableHandler(Node *n) { emitter->switchNamespace(n); Language::globalvariableHandler(n); + return SWIG_OK; } @@ -422,9 +392,8 @@ int JAVASCRIPT::constantWrapper(Node *n) { if (Equal(Getattr(n, "kind"), "function")) { return SWIG_OK; } - - //Language::constantWrapper(n); emitter->emitConstant(n); + return SWIG_OK; } @@ -506,7 +475,7 @@ void JAVASCRIPT::main(int argc, char *argv[]) { Swig_mark_arg(i); mode = JSEmitter::QtScript; SWIG_library_directory("javascript/qt"); - } else if (strcmp(argv[i], "-debug-templates") == 0) { + } else if (strcmp(argv[i], "-debug-codetemplates") == 0) { Swig_mark_arg(i); debug_templates = true; } @@ -570,30 +539,6 @@ extern "C" Language *swig_javascript(void) { * Emitter implementations **********************************************************************/ -/** - * A convenience class that wraps a code snippet used as template for code generation. - */ -class Template { - -public: - Template(const String *code); - - Template(const String *code, const String *templateName, bool debug = false); - - ~Template(); - - String *str(); - - Template& replace(const String *pattern, const String *repl); - - Template& pretty_print(DOH *doh); - -private: - String *code; - String *templateName; - bool debug; -}; - /* ----------------------------------------------------------------------------- * JSEmitter() * ----------------------------------------------------------------------------- */ @@ -634,7 +579,7 @@ Template JSEmitter::getTemplate(const String *name) { SWIG_exit(EXIT_FAILURE); } - Template t(templ, name, js_template_enable_debug); + Template t(templ, name); return t; } @@ -820,86 +765,6 @@ bool JSEmitter::isSetterMethod(Node *n) { return (__swigjs_str_ends_with((char *) Data(symname), "_set") != 0); } - -/* ----------------------------------------------------------------------------- - * Template::Template() : creates a Template class for given template code - * ----------------------------------------------------------------------------- */ - -Template::Template(const String *code_) { - - if (!code_) { - Printf(stdout, "Template code was null. Illegal input for template."); - SWIG_exit(EXIT_FAILURE); - } - debug = false; - code = NewString(code_); - templateName = NewString(""); -} - -Template::Template(const String *code_, const String *templateName_, bool debug_) { - - if (!code_) { - Printf(stdout, "Template code was null. Illegal input for template."); - SWIG_exit(EXIT_FAILURE); - } - - code = NewString(code_); - templateName = NewString(templateName_); - debug = debug_; -} - - -/* ----------------------------------------------------------------------------- - * Template::~Template() : cleans up of Template. - * ----------------------------------------------------------------------------- */ - -Template::~Template() { - Delete(code); - Delete(templateName); -} - -/* ----------------------------------------------------------------------------- - * String* Template::str() : retrieves the current content of the template. - * ----------------------------------------------------------------------------- */ - -String *Template::str() { - if (debug) { - String *pre_code = NewString(""); - String *post_code = NewString(""); - String *debug_code = NewString(""); - Printf(pre_code, "//begin fragment(\"%s\")\n", templateName); - Printf(post_code, "//end fragment(\"%s\")\n", templateName); - Printf(debug_code, "%s\n%s\n%s", pre_code, code, post_code); - - Delete(code); - Delete(pre_code); - Delete(post_code); - - code = debug_code; - } - return code; -} - -/* ----------------------------------------------------------------------------- - * Template& Template::replace(const String* pattern, const String* repl) : - * - * replaces all occurences of a given pattern with a given replacement. - * - * - pattern: the pattern to be replaced - * - repl: the replacement string - * - returns a reference to the Template to allow chaining of methods. - * ----------------------------------------------------------------------------- */ - -Template& Template::replace(const String *pattern, const String *repl) { - Replaceall(code, pattern, repl); - return *this; -} - -Template& Template::pretty_print(DOH *doh) { - Wrapper_pretty_print(str(), doh); - return *this; -} - /********************************************************************** * JavascriptCore: JSEmitter implementation for JavascriptCore engine **********************************************************************/ @@ -2315,3 +2180,174 @@ JSEmitter *swig_javascript_create_V8Emitter() { return 0; } + +/********************************************************************** + * Helper implementations + **********************************************************************/ + +JSEmitterState::JSEmitterState() + : _global(NewHash()) +{ + // initialize sub-hashes + Setattr(_global, "class", NewHash()); + Setattr(_global, "function", NewHash()); + Setattr(_global, "variable", NewHash()); +} + +JSEmitterState::~JSEmitterState() +{ + Delete(_global); +} + +DOH *JSEmitterState::getState(const char* key, bool _new) +{ + if (_new) { + Hash *hash = NewHash(); + Setattr(_global, key, hash); + } + return Getattr(_global, key); +} + +DOH *JSEmitterState::global() { + return _global; +} + +DOH *JSEmitterState::global(const char* key, DOH *initial) +{ + if(initial != 0) { + Setattr(_global, key, initial); + } + return Getattr(_global, key); +} + +DOH *JSEmitterState::clazz(bool _new) +{ + return getState("class", _new); +} + +DOH *JSEmitterState::clazz(const char* key, DOH *initial) +{ + DOH *c = clazz(); + if(initial != 0) { + Setattr(c, key, initial); + } + return Getattr(c, key); +} + +DOH *JSEmitterState::function(bool _new) +{ + return getState("function", _new); +} + +DOH *JSEmitterState::function(const char* key, DOH *initial) +{ + DOH *f = function(); + if(initial != 0) { + Setattr(f, key, initial); + } + return Getattr(f, key); +} + +DOH *JSEmitterState::variable(bool _new) +{ + return getState("variable", _new); +} + +DOH *JSEmitterState::variable(const char* key, DOH *initial) +{ + DOH *v = variable(); + if(initial != 0) { + Setattr(v, key, initial); + } + return Getattr(v, key); +} + +/*static*/ +int JSEmitterState::IsSet(DOH *val) +{ + if (!val) { + return 0; + } else { + const char *cval = Char(val); + if (!cval) + return 0; + return (strcmp(cval, "0") != 0) ? 1 : 0; + } +} + +/* ----------------------------------------------------------------------------- + * Template::Template() : creates a Template class for given template code + * ----------------------------------------------------------------------------- */ + +Template::Template(const String *code_) { + + if (!code_) { + Printf(stdout, "Template code was null. Illegal input for template."); + SWIG_exit(EXIT_FAILURE); + } + code = NewString(code_); + templateName = NewString(""); +} + +Template::Template(const String *code_, const String *templateName_) { + + if (!code_) { + Printf(stdout, "Template code was null. Illegal input for template."); + SWIG_exit(EXIT_FAILURE); + } + + code = NewString(code_); + templateName = NewString(templateName_); +} + + +/* ----------------------------------------------------------------------------- + * Template::~Template() : cleans up of Template. + * ----------------------------------------------------------------------------- */ + +Template::~Template() { + Delete(code); + Delete(templateName); +} + +/* ----------------------------------------------------------------------------- + * String* Template::str() : retrieves the current content of the template. + * ----------------------------------------------------------------------------- */ + +String *Template::str() { + if (js_template_enable_debug) { + String *pre_code = NewString(""); + String *post_code = NewString(""); + String *debug_code = NewString(""); + Printf(pre_code, "//begin fragment(\"%s\")\n", templateName); + Printf(post_code, "//end fragment(\"%s\")\n", templateName); + Printf(debug_code, "%s\n%s\n%s", pre_code, code, post_code); + + Delete(code); + Delete(pre_code); + Delete(post_code); + + code = debug_code; + } + return code; +} + +/* ----------------------------------------------------------------------------- + * Template& Template::replace(const String* pattern, const String* repl) : + * + * replaces all occurences of a given pattern with a given replacement. + * + * - pattern: the pattern to be replaced + * - repl: the replacement string + * - returns a reference to the Template to allow chaining of methods. + * ----------------------------------------------------------------------------- */ + +Template& Template::replace(const String *pattern, const String *repl) { + Replaceall(code, pattern, repl); + return *this; +} + +Template& Template::pretty_print(DOH *doh) { + Wrapper_pretty_print(str(), doh); + return *this; +} From 46624e24e5b6204ce7fd03be433ec1883fd98f96 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:58:49 +0000 Subject: [PATCH 0097/1048] Remove member variable current_wrapper from JSEmitter. Instead each emitting function creates local wrapper instance. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13770 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/Modules/javascript.cxx | 162 ++++++++++++++++++---------------- 1 file changed, 84 insertions(+), 78 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index fd41f90e1..f4c1e6cff 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -239,8 +239,6 @@ protected: String *empty_string; Hash *templates; - - Wrapper *current_wrapper; State state; }; @@ -544,8 +542,7 @@ extern "C" Language *swig_javascript(void) { * ----------------------------------------------------------------------------- */ JSEmitter::JSEmitter() -: empty_string(NewString("")), - current_wrapper(NULL) +: empty_string(NewString("")) { templates = NewHash(); } @@ -645,10 +642,8 @@ Node *JSEmitter::getBaseClass(Node *n) { while (base.item && GetFlag(base.item, "feature:ignore")) { base = Next(base); } - return base.item; } - return NULL; } @@ -659,9 +654,6 @@ Node *JSEmitter::getBaseClass(Node *n) { int JSEmitter::emitWrapperFunction(Node *n) { int ret = SWIG_OK; - current_wrapper = NewWrapper(); - Setattr(n, "wrap:name", Getattr(n, "sym:name")); - String *kind = Getattr(n, "kind"); if (kind) { @@ -699,9 +691,6 @@ int JSEmitter::emitWrapperFunction(Node *n) { } } - DelWrapper(current_wrapper); - current_wrapper = 0; - return ret; } @@ -1225,6 +1214,8 @@ int JSCEmitter::exitClass(Node *n) { } int JSCEmitter::emitCtor(Node *n) { + + Wrapper *wrapper = NewWrapper(); Template t_ctor(getTemplate("JS_ctordefn")); String *mangled_name = SwigType_manglestr(Getattr(n, "name")); @@ -1234,20 +1225,20 @@ int JSCEmitter::emitCtor(Node *n) { Setattr(n, "wrap:name", wrap_name); ParmList *params = Getattr(n, "parms"); - emit_parameter_variables(params, current_wrapper); - emit_attach_parmmaps(params, current_wrapper); + emit_parameter_variables(params, wrapper); + emit_attach_parmmaps(params, wrapper); - Printf(current_wrapper->locals, "%sresult;", SwigType_str(Getattr(n, "type"), 0)); + Printf(wrapper->locals, "%sresult;", SwigType_str(Getattr(n, "type"), 0)); int num_args = emit_num_arguments(params); String *action = emit_action(n); - marshalInputArgs(n, params, current_wrapper, Ctor, true); + marshalInputArgs(n, params, wrapper, Ctor, true); - Printv(current_wrapper->code, action, "\n", 0); + Printv(wrapper->code, action, "\n", 0); t_ctor.replace("${classname_mangled}", mangled_name) .replace("${overloadext}", overname) - .replace("${LOCALS}", current_wrapper->locals) - .replace("${CODE}", current_wrapper->code) + .replace("${LOCALS}", wrapper->locals) + .replace("${CODE}", wrapper->code) .replace("${type_mangled}", state.clazz(TYPE_MANGLED)) .pretty_print(state.clazz(CTORS)); @@ -1259,6 +1250,8 @@ int JSCEmitter::emitCtor(Node *n) { .replace("${argcount}", argcount); Append(state.clazz(CTOR_DISPATCHERS), t_ctor_case.str()); Delete(argcount); + + DelWrapper(wrapper); return SWIG_OK; } @@ -1274,6 +1267,8 @@ int JSCEmitter::emitDtor(Node *) { } int JSCEmitter::emitGetter(Node *n, bool is_member) { + Wrapper *wrapper = NewWrapper(); + Template t_getter(getTemplate("JS_getproperty")); bool is_static = Equal(Getattr(n, "storage"), "static"); @@ -1282,19 +1277,21 @@ int JSCEmitter::emitGetter(Node *n, bool is_member) { state.variable(GETTER, wrap_name); ParmList *params = Getattr(n, "parms"); - emit_parameter_variables(params, current_wrapper); - emit_attach_parmmaps(params, current_wrapper); - Wrapper_add_local(current_wrapper, "jsresult", "JSValueRef jsresult"); + emit_parameter_variables(params, wrapper); + emit_attach_parmmaps(params, wrapper); + Wrapper_add_local(wrapper, "jsresult", "JSValueRef jsresult"); String *action = emit_action(n); - marshalInputArgs(n, params, current_wrapper, Getter, is_member, is_static); - marshalOutput(n, action, current_wrapper); + marshalInputArgs(n, params, wrapper, Getter, is_member, is_static); + marshalOutput(n, action, wrapper); t_getter.replace("${getname}", wrap_name) - .replace("${LOCALS}", current_wrapper->locals) - .replace("${CODE}", current_wrapper->code) + .replace("${LOCALS}", wrapper->locals) + .replace("${CODE}", wrapper->code) .pretty_print(f_wrappers); + DelWrapper(wrapper); + return SWIG_OK; } @@ -1304,6 +1301,8 @@ int JSCEmitter::emitSetter(Node *n, bool is_member) { if (State::IsSet(state.variable(IS_IMMUTABLE))) { return SWIG_OK; } + + Wrapper *wrapper = NewWrapper(); Template t_setter(getTemplate("JS_setproperty")); bool is_static = Equal(Getattr(n, "storage"), "static"); @@ -1313,18 +1312,20 @@ int JSCEmitter::emitSetter(Node *n, bool is_member) { state.variable(SETTER, wrap_name); ParmList *params = Getattr(n, "parms"); - emit_parameter_variables(params, current_wrapper); - emit_attach_parmmaps(params, current_wrapper); + emit_parameter_variables(params, wrapper); + emit_attach_parmmaps(params, wrapper); String *action = emit_action(n); - marshalInputArgs(n, params, current_wrapper, Setter, is_member, is_static); - Append(current_wrapper->code, action); + marshalInputArgs(n, params, wrapper, Setter, is_member, is_static); + Append(wrapper->code, action); t_setter.replace("${setname}", wrap_name) - .replace("${LOCALS}", current_wrapper->locals) - .replace("${CODE}", current_wrapper->code) + .replace("${LOCALS}", wrapper->locals) + .replace("${CODE}", wrapper->code) .pretty_print(f_wrappers); + DelWrapper(wrapper); + return SWIG_OK; } @@ -1334,16 +1335,24 @@ int JSCEmitter::emitSetter(Node *n, bool is_member) { int JSCEmitter::emitConstant(Node *n) { + Wrapper *wrapper = NewWrapper(); + + Template t_getter(getTemplate("JS_getproperty")); + // call the variable methods as a constants are // registred in same way enterVariable(n); - current_wrapper = NewWrapper(); + // prepare function wrapper name + String *wrap_name = Swig_name_wrapper(Getattr(n, "name")); + state.variable(GETTER, wrap_name); + Setattr(n, "wrap:name", wrap_name); + // prepare local variables + Wrapper_add_local(wrapper, "jsresult", "JSValueRef jsresult"); + + // prepare action String *action = NewString(""); - - String *name = Getattr(n, "name"); - String *wrap_name = Swig_name_wrapper(name); String *value = Getattr(n, "rawval"); if (value == NULL) { value = Getattr(n, "rawvalue"); @@ -1351,32 +1360,27 @@ int JSCEmitter::emitConstant(Node *n) { if (value == NULL) { value = Getattr(n, "value"); } - - Template t_getter(getTemplate("JS_getproperty")); - - state.variable(GETTER, wrap_name); - Setattr(n, "wrap:name", wrap_name); - Printf(action, "result = %s;\n", value); Setattr(n, "wrap:action", action); - Wrapper_add_local(current_wrapper, "jsresult", "JSValueRef jsresult"); - marshalOutput(n, action, current_wrapper); + marshalOutput(n, action, wrapper); t_getter.replace("${getname}", wrap_name) - .replace("${LOCALS}", current_wrapper->locals) - .replace("${CODE}", current_wrapper->code) + .replace("${LOCALS}", wrapper->locals) + .replace("${CODE}", wrapper->code) .pretty_print(f_wrappers); - DelWrapper(current_wrapper); - current_wrapper = 0; - exitVariable(n); + DelWrapper(wrapper); + return SWIG_OK; } int JSCEmitter::emitFunction(Node *n, bool is_member) { + + Wrapper *wrapper = NewWrapper(); + Template t_function(getTemplate("JS_functionwrapper")); // Note: there is an inconsistency in SWIG with static member functions @@ -1397,18 +1401,18 @@ int JSCEmitter::emitFunction(Node *n, bool is_member) { // prepare local variables ParmList *params = Getattr(n, "parms"); - emit_parameter_variables(params, current_wrapper); - emit_attach_parmmaps(params, current_wrapper); - Wrapper_add_local(current_wrapper, "jsresult", "JSValueRef jsresult"); + emit_parameter_variables(params, wrapper); + emit_attach_parmmaps(params, wrapper); + Wrapper_add_local(wrapper, "jsresult", "JSValueRef jsresult"); // prepare code part String *action = emit_action(n); - marshalInputArgs(n, params, current_wrapper, Function, is_member, is_static); - marshalOutput(n, action, current_wrapper); + marshalInputArgs(n, params, wrapper, Function, is_member, is_static); + marshalOutput(n, action, wrapper); t_function.replace("${functionname}", wrap_name) - .replace("${LOCALS}", current_wrapper->locals) - .replace("${CODE}", current_wrapper->code) + .replace("${LOCALS}", wrapper->locals) + .replace("${CODE}", wrapper->code) .pretty_print(f_wrappers); // handle function overloading @@ -1426,6 +1430,8 @@ int JSCEmitter::emitFunction(Node *n, bool is_member) { Delete(argcount); } + + DelWrapper(wrapper); return SWIG_OK; } @@ -1994,15 +2000,15 @@ int V8Emitter::EmitCtor(Node* n) Template t(GetTemplate(V8_CTOR_WRAPPER)); //HACK: manually add declaration of instance pointer - Printf(current_wrapper->locals, "%sresult;", SwigType_str(Getattr(n, "type"),0)); + Printf(wrapper->locals, "%sresult;", SwigType_str(Getattr(n, "type"),0)); String* action = emit_action(n); - Printv(current_wrapper->code, action, 0); + Printv(wrapper->code, action, 0); t.Replace(KW_MANGLED_NAME, current_classname_mangled) .Replace(KW_UNQUALIFIED_NAME, current_classname_unqualified) - .Replace(KW_LOCALS, current_wrapper->locals) - .Replace(KW_CODE, current_wrapper->code); + .Replace(KW_LOCALS, wrapper->locals) + .Replace(KW_CODE, wrapper->code); Wrapper_pretty_print(t.str(), f_wrapper); @@ -2022,17 +2028,17 @@ int V8Emitter::EmitGetter(Node *n, bool is_member) { current_getter = Getattr(n,"wrap:name"); ParmList *params = Getattr(n,"parms"); - emit_parameter_variables(params, current_wrapper); - emit_attach_parmmaps(params, current_wrapper); + emit_parameter_variables(params, wrapper); + emit_attach_parmmaps(params, wrapper); int num_args = emit_num_arguments(params); String* action = emit_action(n); - marshalInputArgs(n, params, num_args, current_wrapper); - marshalOutput(n, action, current_wrapper); + marshalInputArgs(n, params, num_args, wrapper); + marshalOutput(n, action, wrapper); t_getter.Replace(KW_MANGLED_NAME, current_variable_mangled) - .Replace(KW_LOCALS, current_wrapper->locals) - .Replace(KW_CODE, current_wrapper->code); + .Replace(KW_LOCALS, wrapper->locals) + .Replace(KW_CODE, wrapper->code); Wrapper_pretty_print(t_getter.str(), f_wrapper); @@ -2046,17 +2052,17 @@ int V8Emitter::EmitSetter(Node* n, bool is_member) current_setter = Getattr(n,"wrap:name"); ParmList *params = Getattr(n,"parms"); - emit_parameter_variables(params, current_wrapper); - emit_attach_parmmaps(params, current_wrapper); + emit_parameter_variables(params, wrapper); + emit_attach_parmmaps(params, wrapper); int num_args = emit_num_arguments(params); String* action = emit_action(n); - marshalInputArgs(n, params, num_args, current_wrapper); - Printv(current_wrapper->code, action, 0); + marshalInputArgs(n, params, num_args, wrapper); + Printv(wrapper->code, action, 0); t_setter.Replace(KW_MANGLED_NAME, current_variable_mangled) - .Replace(KW_LOCALS, current_wrapper->locals) - .Replace(KW_CODE, current_wrapper->code); + .Replace(KW_LOCALS, wrapper->locals) + .Replace(KW_CODE, wrapper->code); Wrapper_pretty_print(t_setter.str(), f_wrapper); @@ -2073,17 +2079,17 @@ int V8Emitter::EmitFunction(Node* n, bool is_member) Setattr(n, "wrap:name", wrap_name); ParmList *params = Getattr(n,"parms"); - emit_parameter_variables(params, current_wrapper); - emit_attach_parmmaps(params, current_wrapper); + emit_parameter_variables(params, wrapper); + emit_attach_parmmaps(params, wrapper); int num_args = emit_num_arguments(params); String* action = emit_action(n); - marshalInputArgs(n, params, num_args, current_wrapper); - marshalOutput(n, action, current_wrapper); + marshalInputArgs(n, params, num_args, wrapper); + marshalOutput(n, action, wrapper); t_function.Replace(KW_MANGLED_NAME, current_function_mangled) - .Replace(KW_LOCALS, current_wrapper->locals) - .Replace(KW_CODE, current_wrapper->code); + .Replace(KW_LOCALS, wrapper->locals) + .Replace(KW_CODE, wrapper->code); Wrapper_pretty_print(t_function.str(), f_wrapper); return SWIG_OK; From c470864d127561d55d36e115ffffffc33cf2ff96 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:59:03 +0000 Subject: [PATCH 0098/1048] Remove some dead code and an obsolete member variable from JSEmitter. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13771 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/Makefile.in | 4 +-- Source/Modules/javascript.cxx | 68 ++++++++++------------------------- 2 files changed, 20 insertions(+), 52 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index afe135964..250ce4e0e 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -535,7 +535,7 @@ JSCXXFLAGS = @JSCXXFLAGS@ # ---------------------------------------------------------------- javascript: $(SRCS) - $(SWIG) -javascript -jsc $(SWIGOPT) $(INTERFACEPATH) + $(SWIG) -javascript -jsc -debug-codetemplates $(SWIGOPT) $(INTERFACEPATH) $(CC) -c $(CCSHARED) $(JSCFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(JS_INCLUDE) $(JSLDSHARED) $(CCSHARED) $(JSCFLAGS) $(OBJS) $(IOBJS) $(JS_DLNK) $(LIBS) -o $(JS_LIBPREFIX)$(TARGET)$(JSSO) @@ -544,7 +544,7 @@ javascript: $(SRCS) # ---------------------------------------------------------------- javascript_cpp: $(SRCS) - $(SWIG) -javascript -jsc -c++ $(SWIGOPT) $(INTERFACEPATH) + $(SWIG) -c++ -javascript -jsc -debug-codetemplates $(SWIGOPT) $(INTERFACEPATH) $(CXX) -c $(CCSHARED) $(JSCXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(JS_INCLUDE) $(JSCXXSHARED) $(CCSHARED) $(OBJS) $(IOBJS) $(JS_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(JS_LIBPREFIX)$(TARGET)$(JSSO) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index f4c1e6cff..67c145dc7 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -6,7 +6,6 @@ bool js_template_enable_debug = false; // keywords used for state variables - #define NAME "name" #define NAME_MANGLED "name_mangled" #define TYPE "type" @@ -226,18 +225,10 @@ protected: */ Node *getBaseClass(Node *n); - /** - * Helper function to retrieve a certain typemap. - */ - const String *typemapLookup(Node *n, const_String_or_char_ptr tmap_method, SwigType *type, int warning, Node *typemap_attributes = 0); - Parm *skipIgnoredArgs(Parm *p); protected: - // empty string used at different places in the code - String *empty_string; - Hash *templates; State state; @@ -334,10 +325,14 @@ int JAVASCRIPT::globalfunctionHandler(Node *n) { * --------------------------------------------------------------------- */ int JAVASCRIPT::staticmemberfunctionHandler(Node *n) { - // workaround: storage=static is not set for static member functions - emitter->getState().function(IS_STATIC, NewString("1")); + /* + * Note: storage=static is not set for static member functions. + * It also is not working to set that attribute here. + * Instead the according state variable is set directly. + */ + SetFlag(emitter->getState().function(), IS_STATIC); Language::staticmemberfunctionHandler(n); - emitter->getState().function(IS_STATIC, NULL); + Setattr(emitter->getState().function(), IS_STATIC, 0); return SWIG_OK; } @@ -542,9 +537,8 @@ extern "C" Language *swig_javascript(void) { * ----------------------------------------------------------------------------- */ JSEmitter::JSEmitter() -: empty_string(NewString("")) +: templates(NewHash()) { - templates = NewHash(); } /* ----------------------------------------------------------------------------- @@ -552,7 +546,6 @@ JSEmitter::JSEmitter() * ----------------------------------------------------------------------------- */ JSEmitter::~JSEmitter() { - Delete(empty_string); Delete(templates); } @@ -589,36 +582,6 @@ int JSEmitter::initialize(Node *) { return SWIG_OK; } -/* ----------------------------------------------------------------------------- - * JSEmitter::typemapLookup() - * - * n - for input only and must contain info for Getfile(n) and Getline(n) to work - * tmap_method - typemap method name - * type - typemap type to lookup - * warning - warning number to issue if no typemaps found - * typemap_attributes - the typemap attributes are attached to this node and will - * also be used for temporary storage if non null - * return is never NULL, unlike Swig_typemap_lookup() - * ----------------------------------------------------------------------------- */ - -const String *JSEmitter::typemapLookup(Node *n, const_String_or_char_ptr tmap_method, SwigType *type, int warning, Node *typemap_attributes) { - Node *node = !typemap_attributes ? NewHash() : typemap_attributes; - Setattr(node, "type", type); - Setfile(node, Getfile(n)); - Setline(node, Getline(n)); - const String *tm = Swig_typemap_lookup(tmap_method, node, "", 0); - if (!tm) { - tm = empty_string; - if (warning != WARN_NONE) { - Swig_warning(warning, Getfile(n), Getline(n), "No %s typemap defined for %s\n", tmap_method, SwigType_str(type, 0)); - } - } - if (!typemap_attributes) { - Delete(node); - } - return tm; -} - /* --------------------------------------------------------------------- * skipIgnoredArgs() * --------------------------------------------------------------------- */ @@ -1221,7 +1184,7 @@ int JSCEmitter::emitCtor(Node *n) { String *mangled_name = SwigType_manglestr(Getattr(n, "name")); String *overname = Getattr(n, "sym:overname"); - String *wrap_name = Swig_name_wrapper(Getattr(n, "wrap:name")); + String *wrap_name = Swig_name_wrapper(Getattr(n, "name")); Setattr(n, "wrap:name", wrap_name); ParmList *params = Getattr(n, "parms"); @@ -1272,15 +1235,18 @@ int JSCEmitter::emitGetter(Node *n, bool is_member) { Template t_getter(getTemplate("JS_getproperty")); bool is_static = Equal(Getattr(n, "storage"), "static"); - String *wrap_name = Swig_name_wrapper(Getattr(n, "wrap:name")); + // prepare wrapper name + String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); Setattr(n, "wrap:name", wrap_name); state.variable(GETTER, wrap_name); + // prepare local variables ParmList *params = Getattr(n, "parms"); emit_parameter_variables(params, wrapper); emit_attach_parmmaps(params, wrapper); Wrapper_add_local(wrapper, "jsresult", "JSValueRef jsresult"); + // prepare code part String *action = emit_action(n); marshalInputArgs(n, params, wrapper, Getter, is_member, is_static); marshalOutput(n, action, wrapper); @@ -1307,14 +1273,17 @@ int JSCEmitter::emitSetter(Node *n, bool is_member) { Template t_setter(getTemplate("JS_setproperty")); bool is_static = Equal(Getattr(n, "storage"), "static"); - String *wrap_name = Swig_name_wrapper(Getattr(n, "wrap:name")); + // prepare wrapper name + String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); Setattr(n, "wrap:name", wrap_name); state.variable(SETTER, wrap_name); + // prepare local variables ParmList *params = Getattr(n, "parms"); emit_parameter_variables(params, wrapper); emit_attach_parmmaps(params, wrapper); + // prepare code part String *action = emit_action(n); marshalInputArgs(n, params, wrapper, Setter, is_member, is_static); Append(wrapper->code, action); @@ -1351,7 +1320,7 @@ int JSCEmitter::emitConstant(Node *n) { // prepare local variables Wrapper_add_local(wrapper, "jsresult", "JSValueRef jsresult"); - // prepare action + // prepare code part String *action = NewString(""); String *value = Getattr(n, "rawval"); if (value == NULL) { @@ -1362,7 +1331,6 @@ int JSCEmitter::emitConstant(Node *n) { } Printf(action, "result = %s;\n", value); Setattr(n, "wrap:action", action); - marshalOutput(n, action, wrapper); t_getter.replace("${getname}", wrap_name) From 16077503c86919dbedd3d76318a23323404f4f58 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:59:18 +0000 Subject: [PATCH 0099/1048] Fix former workaround by concerning static member functions. "storage" attribute is removed by Language::staticmemberfunctionHandler which was resolved by a workaround before. Now, the implementation relies completely on state flags retrieved at a proper point. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13772 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/Modules/javascript.cxx | 85 ++++++++--------- Source/Modules/javascript_emitter.h | 139 ---------------------------- Source/Modules/javascript_v8.h | 90 ------------------ 3 files changed, 40 insertions(+), 274 deletions(-) delete mode 100644 Source/Modules/javascript_emitter.h delete mode 100644 Source/Modules/javascript_v8.h diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 67c145dc7..1c6ab7e78 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -202,17 +202,17 @@ protected: /** * Generates code for a function. */ - virtual int emitFunction(Node *n, bool is_member) = 0; + virtual int emitFunction(Node *n, bool is_member, bool is_static) = 0; /** * Generates code for a getter function. */ - virtual int emitGetter(Node *n, bool is_member) = 0; + virtual int emitGetter(Node *n, bool is_member, bool is_static) = 0; /** * Generates code for a setter function. */ - virtual int emitSetter(Node *n, bool is_member) = 0; + virtual int emitSetter(Node *n, bool is_member, bool is_static) = 0; /** * Helper function to find out if a function is a setter or not. @@ -315,6 +315,7 @@ int JAVASCRIPT::functionHandler(Node *n) { int JAVASCRIPT::globalfunctionHandler(Node *n) { emitter->switchNamespace(n); Language::globalfunctionHandler(n); + return SWIG_OK; } @@ -326,13 +327,11 @@ int JAVASCRIPT::globalfunctionHandler(Node *n) { int JAVASCRIPT::staticmemberfunctionHandler(Node *n) { /* - * Note: storage=static is not set for static member functions. - * It also is not working to set that attribute here. - * Instead the according state variable is set directly. + * Note: storage=static is removed by Language::staticmemberfunctionHandler. + * So, don't rely on that after here. Instead use the state variable which is + * set by JSEmitter::enterFunction(). */ - SetFlag(emitter->getState().function(), IS_STATIC); - Language::staticmemberfunctionHandler(n); - Setattr(emitter->getState().function(), IS_STATIC, 0); + Language::staticmemberfunctionHandler(n); return SWIG_OK; } @@ -344,14 +343,7 @@ int JAVASCRIPT::staticmemberfunctionHandler(Node *n) { int JAVASCRIPT::variableHandler(Node *n) { - if (!is_assignable(n) - // FIXME: test "arrays_global" does not compile with that as it is not allowed to assign to char[] - // probably some error in char[] typemap - || Equal(Getattr(n, "type"), "a().char")) { - SetFlag(n, "wrap:immutable"); - } - - emitter->enterVariable(n); + emitter->enterVariable(n); Language::variableHandler(n); emitter->exitVariable(n); @@ -622,20 +614,18 @@ int JSEmitter::emitWrapperFunction(Node *n) { if (kind) { bool is_member = GetFlag(n, "ismember"); if (Cmp(kind, "function") == 0) { - ret = emitFunction(n, is_member); - + bool is_static = GetFlag(state.function(), IS_STATIC); + ret = emitFunction(n, is_member, is_static); } else if (Cmp(kind, "variable") == 0) { + bool is_static = GetFlag(state.variable(), IS_STATIC); if (isSetterMethod(n)) { - ret = emitSetter(n, is_member); - + ret = emitSetter(n, is_member, is_static); } else { - ret = emitGetter(n, is_member); - + ret = emitGetter(n, is_member, is_static); } } else { Printf(stderr, "Warning: unsupported wrapper function type\n"); Swig_print_node(n); - ret = SWIG_ERROR; } } else { @@ -643,10 +633,8 @@ int JSEmitter::emitWrapperFunction(Node *n) { if (Cmp(view, "constructorHandler") == 0) { ret = emitCtor(n); - } else if (Cmp(view, "destructorHandler") == 0) { ret = emitDtor(n); - } else { Printf(stderr, "Warning: unsupported wrapper function type"); Swig_print_node(n); @@ -677,14 +665,29 @@ int JSEmitter::enterFunction(Node *n) { state.function(true); state.function(NAME, Getattr(n, "sym:name")); + if(Equal(Getattr(n, "storage"), "static")) { + SetFlag(state.function(), IS_STATIC); + } return SWIG_OK; } int JSEmitter::enterVariable(Node *n) { + state.variable(true); state.variable(NAME, Swig_scopename_last(Getattr(n, "name"))); - state.variable(IS_IMMUTABLE, Getattr(n, "wrap:immutable")); + + if(Equal(Getattr(n, "storage"), "static")) { + SetFlag(state.variable(), IS_STATIC); + } + + if (!Language::instance()->is_assignable(n) + // FIXME: test "arrays_global" does not compile with that as it is not allowed to assign to char[] + // probably some error in char[] typemap + || Equal(Getattr(n, "type"), "a().char")) { + SetFlag(state.variable(), IS_IMMUTABLE); + } + return SWIG_OK; } @@ -763,13 +766,13 @@ protected: virtual int exitClass(Node *n); - virtual int emitFunction(Node *n, bool is_member); + virtual int emitFunction(Node *n, bool is_member, bool is_static); virtual int emitFunctionDispatcher(Node *n, bool is_member); - virtual int emitGetter(Node *n, bool is_member); + virtual int emitGetter(Node *n, bool is_member, bool is_static); - virtual int emitSetter(Node *n, bool is_member); + virtual int emitSetter(Node *n, bool is_member, bool is_static); virtual int emitConstant(Node *n); @@ -1069,7 +1072,7 @@ int JSCEmitter::exitFunction(Node *n) { .replace("${functionwrapper}", state.function(WRAPPER_NAME)); if (is_member) { - if (Equal(Getattr(n, "storage"), "static")) { + if (GetFlag(state.function(), IS_STATIC)) { Append(state.clazz(STATIC_FUNCTIONS), t_function.str()); } else { Append(state.clazz(MEMBER_FUNCTIONS), t_function.str()); @@ -1098,7 +1101,8 @@ int JSCEmitter::exitVariable(Node *n) { .replace("${propertyname}", state.variable(NAME)); if (GetFlag(n, "ismember")) { - if (Equal(Getattr(n, "storage"), "static") || (Equal(Getattr(n, "nodeType"), "enumitem"))) { + if (GetFlag(state.function(), IS_STATIC) + || Equal(Getattr(n, "nodeType"), "enumitem")) { Append(state.clazz(STATIC_VARIABLES), t_variable.str()); } else { Append(state.clazz(MEMBER_VARIABLES), t_variable.str()); @@ -1229,12 +1233,10 @@ int JSCEmitter::emitDtor(Node *) { return SWIG_OK; } -int JSCEmitter::emitGetter(Node *n, bool is_member) { +int JSCEmitter::emitGetter(Node *n, bool is_member, bool is_static) { Wrapper *wrapper = NewWrapper(); - Template t_getter(getTemplate("JS_getproperty")); - bool is_static = Equal(Getattr(n, "storage"), "static"); - + // prepare wrapper name String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); Setattr(n, "wrap:name", wrap_name); @@ -1261,7 +1263,7 @@ int JSCEmitter::emitGetter(Node *n, bool is_member) { return SWIG_OK; } -int JSCEmitter::emitSetter(Node *n, bool is_member) { +int JSCEmitter::emitSetter(Node *n, bool is_member, bool is_static) { // skip variables that are immutable if (State::IsSet(state.variable(IS_IMMUTABLE))) { @@ -1271,7 +1273,6 @@ int JSCEmitter::emitSetter(Node *n, bool is_member) { Wrapper *wrapper = NewWrapper(); Template t_setter(getTemplate("JS_setproperty")); - bool is_static = Equal(Getattr(n, "storage"), "static"); // prepare wrapper name String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); @@ -1345,18 +1346,12 @@ int JSCEmitter::emitConstant(Node *n) { return SWIG_OK; } -int JSCEmitter::emitFunction(Node *n, bool is_member) { +int JSCEmitter::emitFunction(Node *n, bool is_member, bool is_static) { Wrapper *wrapper = NewWrapper(); Template t_function(getTemplate("JS_functionwrapper")); - // Note: there is an inconsistency in SWIG with static member functions - // that do not have storage:static - // in these cases the context (staticmemberfunctionHandler) is - // exploited and a flag is set temporarily - // TODO: this could be done in general with is_member and is_static - bool is_static = State::IsSet(state.function(IS_STATIC)) || Equal(Getattr(n, "storage"), "static"); bool is_overloaded = GetFlag(n, "sym:overloaded"); // prepare the function wrapper name diff --git a/Source/Modules/javascript_emitter.h b/Source/Modules/javascript_emitter.h deleted file mode 100644 index b73bb55b4..000000000 --- a/Source/Modules/javascript_emitter.h +++ /dev/null @@ -1,139 +0,0 @@ -#ifndef JAVASCRIPT_EMITTER_H -#define JAVASCRIPT_EMITTER_H - -#include "swigmod.h" - -/** - * A class that wraps a code snippet used as template for code generation. - */ -class Template { - -public: - Template(const String* code); - - ~Template(); - - String* str(); - - Template& Replace(const String* pattern, const String* repl); - -private: - String* m_code; -}; - -class JSEmitter { - -public: - - enum JSEmitterType { - JavascriptCore, - V8, - QtScript - }; - - JSEmitter(); - - virtual ~JSEmitter(); - - /** - * Opens output files and temporary output DOHs. - */ - virtual int Initialize(Node *n) = 0; - - /** - * Writes all collected code into the output file(s). - */ - virtual int Dump(Node *n) = 0; - - /** - * Cleans up all open output DOHs. - */ - virtual int Close() = 0; - - /** - * Switches the context for code generation. - * - * Classes, global variables and global functions may need to - * be registered in certain static tables. - * This method should be used to switch output DOHs correspondingly. - */ - virtual int SwitchContext(Node *n) { return SWIG_OK; }; - - /** - * Invoked at the beginning of the classHandler. - */ - virtual int EnterClass(Node *n) { return SWIG_OK; }; - - /** - * Invoked at the end of the classHandler. - */ - virtual int ExitClass(Node *n) { return SWIG_OK; }; - - /** - * Invoked at the beginning of the variableHandler. - */ - virtual int EnterVariable(Node *n) { return SWIG_OK; }; - - /** - * Invoked at the end of the variableHandler. - */ - virtual int ExitVariable(Node *n) { return SWIG_OK; }; - - /** - * Invoked at the beginning of the functionHandler. - */ - virtual int EnterFunction(Node *n) { return SWIG_OK; }; - - /** - * Invoked at the end of the functionHandler. - */ - virtual int ExitFunction(Node *n) { return SWIG_OK; }; - - /** - * Invoked by functionWrapper callback after call to Language::functionWrapper. - */ - virtual int EmitWrapperFunction(Node *n); - - /** - * Registers a given code snippet for a given key name. - * - * This method is called by the fragmentDirective handler - * of the JAVASCRIPT language module. - */ - int RegisterTemplate(const String *name, const String *code); - - /** - * Retrieve the code template registered for a given name. - */ - const String* GetTemplate(const String *name); - -protected: - - virtual int EmitCtor(Node *n) = 0; - - virtual int EmitDtor(Node *n) = 0; - - virtual int EmitFunction(Node *n, bool is_member) = 0; - - virtual int EmitGetter(Node *n, bool is_member) = 0; - - virtual int EmitSetter(Node *n, bool is_member) = 0; - - bool IsSetterMethod(Node *n); - - Node* GetBaseClass(Node *n); - - const String* typemapLookup(Node *n, const_String_or_char_ptr tmap_method, - SwigType *type, int warning, Node *typemap_attributes = 0); - -protected: - - // empty string used at different places in the code - String *empty_string; - - Hash *templates; - - Wrapper* current_wrapper; -}; - -#endif // JAVASCRIPT_EMITTER_H diff --git a/Source/Modules/javascript_v8.h b/Source/Modules/javascript_v8.h deleted file mode 100644 index 8d9e6d0b0..000000000 --- a/Source/Modules/javascript_v8.h +++ /dev/null @@ -1,90 +0,0 @@ -#ifndef JAVASCRIPT_V8_H -#define JAVASCRIPT_V8_H - -#include "javascript_emitter.h" - -class V8Emitter: public JSEmitter { - -public: - - V8Emitter(); - - virtual ~V8Emitter(); - - virtual int Initialize(Node *n); - - virtual int Dump(Node *n); - - virtual int Close(); - - virtual int SwitchContext(Node *n); - - virtual int EnterClass(Node *n); - - virtual int ExitClass(Node *n); - - virtual int EnterVariable(Node *n); - - virtual int ExitVariable(Node *n); - - virtual int EnterFunction(Node *n); - - virtual int ExitFunction(Node *n); - -protected: - - int CreateNamespace(String* scope); - - virtual int EmitCtor(Node *n); - - virtual int EmitDtor(Node *n); - - virtual int EmitFunction(Node *n, bool is_member); - - virtual int EmitGetter(Node *n, bool is_member); - - virtual int EmitSetter(Node *n, bool is_member); - - void marshalInputArgs(Node *n, ParmList *parms, int numarg, Wrapper *wrapper); - - void marshalOutput(Node *n, String *actioncode, Wrapper *wrapper); - - Parm *skipIgnoredArgs(Parm *p); - -private: - - File *f_runtime; - File *f_header; - File *f_class_templates; - File *f_wrapper; - - File *f_init_namespaces; - File *f_init_class_templates; - File *f_init_wrappers; - File *f_init_inheritance; - File *f_init_class_instances; - File *f_init_static_wrappers; - File *f_init_register_classes; - File *f_init_register_namespaces; - - // the output cpp file - File *f_wrap_cpp; - - // state variables - String* current_context; - String* current_class_type; - String* current_classname_mangled; - String* current_classname_unqualified; - String* current_variable_mangled; - String* current_variable_unqualified; - String* current_getter; - String* current_setter; - String* current_function_mangled; - String* current_function_unqualified; - - String* GLOBAL; - String* NULL_STR; - Hash* namespaces; -}; - -#endif // JAVASCRIPT_V8_H From d2debe32703c0d1f6b4ca22623b2d13e206be64b Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:59:31 +0000 Subject: [PATCH 0100/1048] Add more verbose temporary flags for setters in variable wrappers. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13773 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/Modules/lang.cxx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index c797a101e..afa640e56 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -1451,7 +1451,9 @@ int Language::membervariableHandler(Node *n) { } if (make_set_wrapper) { Setattr(n, "sym:name", mrename_set); + SetFlag(n, "wrap:issetter"); functionWrapper(n); + Delattr(n, "wrap:issetter"); } else { SetFlag(n, "feature:immutable"); } @@ -2910,7 +2912,9 @@ int Language::variableWrapper(Node *n) { Delete(pname0); } if (make_set_wrapper) { + SetFlag(n, "wrap:issetter"); functionWrapper(n); + Delattr(n, "wrap:issetter"); } /* Restore parameters */ Setattr(n, "sym:name", symname); From 66ead9afb2501d02c9ded79309e64a5bc953da5a Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:59:43 +0000 Subject: [PATCH 0101/1048] Simplify implementation using new issetter flag. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13774 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/Modules/javascript.cxx | 38 ++--------------------------------- 1 file changed, 2 insertions(+), 36 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 1c6ab7e78..667462091 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -214,12 +214,6 @@ protected: */ virtual int emitSetter(Node *n, bool is_member, bool is_static) = 0; - /** - * Helper function to find out if a function is a setter or not. - * TODO: there should be some kind of support in swig core for that? - */ - bool isSetterMethod(Node *n); - /** * Helper function to retrieve the first parent class node. */ @@ -618,7 +612,8 @@ int JSEmitter::emitWrapperFunction(Node *n) { ret = emitFunction(n, is_member, is_static); } else if (Cmp(kind, "variable") == 0) { bool is_static = GetFlag(state.variable(), IS_STATIC); - if (isSetterMethod(n)) { + bool is_setter = GetFlag(n, "wrap:issetter"); + if (is_setter) { ret = emitSetter(n, is_member, is_static); } else { ret = emitGetter(n, is_member, is_static); @@ -691,35 +686,6 @@ int JSEmitter::enterVariable(Node *n) { return SWIG_OK; } - -/* ----------------------------------------------------------------------------- - * __swigjs_str_ends_with() : c string helper to check suffix match - * ----------------------------------------------------------------------------- */ - -int __swigjs_str_ends_with(const char *str, const char *suffix) { - - if (str == NULL || suffix == NULL) - return 0; - - size_t str_len = strlen(str); - size_t suffix_len = strlen(suffix); - - if (suffix_len > str_len) - return 0; - - return 0 == strncmp(str + str_len - suffix_len, suffix, suffix_len); -} - - -/* ----------------------------------------------------------------------------- - * JSEmitter::isSetterMethod() : helper to check if a method is a setter function - * ----------------------------------------------------------------------------- */ - -bool JSEmitter::isSetterMethod(Node *n) { - String *symname = Getattr(n, "sym:name"); - return (__swigjs_str_ends_with((char *) Data(symname), "_set") != 0); -} - /********************************************************************** * JavascriptCore: JSEmitter implementation for JavascriptCore engine **********************************************************************/ From 387da69e843e7359ba1fb70f0eadbd077e8cf461 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 00:59:55 +0000 Subject: [PATCH 0102/1048] Pull namespace implementation up to be shared between js emitters. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13775 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/Modules/javascript.cxx | 135 ++++++++++++++++++---------------- 1 file changed, 70 insertions(+), 65 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 667462091..ef878dd9c 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -122,9 +122,7 @@ public: * be registered in certain static tables. * This method should be used to switch output DOHs correspondingly. */ - virtual int switchNamespace(Node *) { - return SWIG_OK; - }; + virtual int switchNamespace(Node *); /** * Invoked at the beginning of the classHandler. @@ -221,11 +219,24 @@ protected: Parm *skipIgnoredArgs(Parm *p); + virtual int createNamespace(String *scope); + + virtual Hash *createNamespaceEntry(const char *name, const char *parent) = 0; + + virtual int emitNamespaces() = 0; + protected: Hash *templates; State state; + + // contains context specific structs + // to allow generation of different class definition tables + // which are switched on namespace change + Hash *namespaces; + Hash *current_namespace; + }; /********************************************************************** @@ -523,7 +534,9 @@ extern "C" Language *swig_javascript(void) { * ----------------------------------------------------------------------------- */ JSEmitter::JSEmitter() -: templates(NewHash()) +: templates(NewHash()), + namespaces(NULL), + current_namespace(NULL) { } @@ -564,7 +577,16 @@ JSEmitterState &JSEmitter::getState() { return state; } -int JSEmitter::initialize(Node *) { +int JSEmitter::initialize(Node * n) { + + if(namespaces != NULL) { + Delete(namespaces); + } + namespaces = NewHash(); + Hash *global_namespace = createNamespaceEntry(Char(Getattr(n, "name")), "global"); + Setattr(namespaces, "::", global_namespace); + current_namespace = global_namespace; + return SWIG_OK; } @@ -686,6 +708,49 @@ int JSEmitter::enterVariable(Node *n) { return SWIG_OK; } +int JSEmitter::switchNamespace(Node *n) { + + if (!GetFlag(n, "feature:nspace")) { + current_namespace = Getattr(namespaces, "::"); + } else { + String *scope = Swig_scopename_prefix(Getattr(n, "name")); + if (scope) { + // if the scope is not yet registered + // create all scopes/namespaces recursively + if (!Getattr(namespaces, scope)) { + createNamespace(scope); + } + current_namespace = Getattr(namespaces, scope); + } else { + current_namespace = Getattr(namespaces, "::"); + } + } + + return SWIG_OK; +} + +int JSEmitter::createNamespace(String *scope) { + + String *parent_scope = Swig_scopename_prefix(scope); + Hash *parent_namespace; + if (parent_scope == 0) { + parent_namespace = Getattr(namespaces, "::"); + } else if (!Getattr(namespaces, parent_scope)) { + createNamespace(parent_scope); + parent_namespace = Getattr(namespaces, parent_scope); + } else { + parent_namespace = Getattr(namespaces, parent_scope); + } + assert(parent_namespace != 0); + + Hash *new_namespace = createNamespaceEntry(Char(scope), Char(Getattr(parent_namespace, "name"))); + Setattr(namespaces, scope, new_namespace); + + Delete(parent_scope); + return SWIG_OK; +} + + /********************************************************************** * JavascriptCore: JSEmitter implementation for JavascriptCore engine **********************************************************************/ @@ -746,10 +811,6 @@ protected: void marshalOutput(Node *n, String *actioncode, Wrapper *wrapper); - virtual int switchNamespace(Node *n); - - virtual int createNamespace(String *scope); - virtual Hash *createNamespaceEntry(const char *name, const char *parent); virtual int emitNamespaces(); @@ -760,11 +821,6 @@ private: String *VETO_SET; const char *GLOBAL_STR; - // contains context specific structs - // to allow generation of different class definition tables - // which are switched on namespace change - Hash *namespaces; - Hash *current_namespace; // output file and major code parts File *f_wrap_cpp; @@ -798,8 +854,6 @@ JSCEmitter::JSCEmitter() NULL_STR(NewString("NULL")), VETO_SET(NewString("JS_veto_set_variable")), GLOBAL_STR(NULL), - namespaces(NULL), - current_namespace(NULL), f_wrap_cpp(NULL), f_runtime(NULL), f_header(NULL), @@ -907,13 +961,11 @@ void JSCEmitter::marshalOutput(Node *n, String *actioncode, Wrapper *wrapper) { } else { Replaceall(tm, "$owner", "0"); } - Append(wrapper->code, tm); if (Len(tm) > 0) { Printf(wrapper->code, "\n"); } - } else { Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(type, 0), Getattr(n, "name")); } @@ -944,11 +996,6 @@ int JSCEmitter::initialize(Node *n) { state.global(REGISTER_NAMESPACES, NewString("")); state.global(INITIALIZER, NewString("")); - namespaces = NewHash(); - Hash *global_namespace = createNamespaceEntry(Char(Getattr(n, "name")), "global"); - Setattr(namespaces, "::", global_namespace); - current_namespace = global_namespace; - /* Register file targets with the SWIG file handler */ Swig_register_filebyname("begin", f_wrap_cpp); Swig_register_filebyname("header", f_header); @@ -1388,48 +1435,6 @@ int JSCEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { return SWIG_OK; } -int JSCEmitter::switchNamespace(Node *n) { - - if (!GetFlag(n, "feature:nspace")) { - current_namespace = Getattr(namespaces, "::"); - } else { - String *scope = Swig_scopename_prefix(Getattr(n, "name")); - if (scope) { - // if the scope is not yet registered - // create all scopes/namespaces recursively - if (!Getattr(namespaces, scope)) { - createNamespace(scope); - } - current_namespace = Getattr(namespaces, scope); - } else { - current_namespace = Getattr(namespaces, "::"); - } - } - - return SWIG_OK; -} - -int JSCEmitter::createNamespace(String *scope) { - - String *parent_scope = Swig_scopename_prefix(scope); - Hash *parent_namespace; - if (parent_scope == 0) { - parent_namespace = Getattr(namespaces, "::"); - } else if (!Getattr(namespaces, parent_scope)) { - createNamespace(parent_scope); - parent_namespace = Getattr(namespaces, parent_scope); - } else { - parent_namespace = Getattr(namespaces, parent_scope); - } - assert(parent_namespace != 0); - - Hash *new_namespace = createNamespaceEntry(Char(scope), Char(Getattr(parent_namespace, "name"))); - Setattr(namespaces, scope, new_namespace); - - Delete(parent_scope); - return SWIG_OK; -} - Hash *JSCEmitter::createNamespaceEntry(const char *name, const char *parent) { Hash *entry = NewHash(); String *_name = NewString(name); From 4d9ca620abcfed848785ca4825f6a61648387829 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:00:15 +0000 Subject: [PATCH 0103/1048] Refactored JSEmitters to share unified code. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13776 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/Modules/javascript.cxx | 1001 +++++++++++++-------------------- 1 file changed, 381 insertions(+), 620 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index ef878dd9c..69c5e4adf 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -88,6 +88,13 @@ protected: typedef JSEmitterState State; + enum MarshallingMode { + Setter, + Getter, + Ctor, + Function + }; + public: enum JSEmitterType { @@ -168,7 +175,7 @@ public: /** * Invoked from constantWrapper after call to Language::constantWrapper. **/ - virtual int emitConstant(Node *n) = 0; + virtual int emitConstant(Node *n); /** * Registers a given code snippet for a given key name. @@ -190,27 +197,33 @@ protected: /** * Generates code for a constructor function. */ - virtual int emitCtor(Node *n) = 0; + virtual int emitCtor(Node *n); /** * Generates code for a destructor function. */ - virtual int emitDtor(Node *n) = 0; + virtual int emitDtor(Node *n); /** * Generates code for a function. */ - virtual int emitFunction(Node *n, bool is_member, bool is_static) = 0; + virtual int emitFunction(Node *n, bool is_member, bool is_static); + + virtual int emitFunctionDispatcher(Node *n, bool /*is_member */ ); /** * Generates code for a getter function. */ - virtual int emitGetter(Node *n, bool is_member, bool is_static) = 0; + virtual int emitGetter(Node *n, bool is_member, bool is_static); /** * Generates code for a setter function. */ - virtual int emitSetter(Node *n, bool is_member, bool is_static) = 0; + virtual int emitSetter(Node *n, bool is_member, bool is_static); + + virtual void marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) = 0; + + virtual void marshalOutput(Node *n, String *actioncode, Wrapper *wrapper); /** * Helper function to retrieve the first parent class node. @@ -221,7 +234,7 @@ protected: virtual int createNamespace(String *scope); - virtual Hash *createNamespaceEntry(const char *name, const char *parent) = 0; + virtual Hash *createNamespaceEntry(const char *name, const char *parent); virtual int emitNamespaces() = 0; @@ -231,12 +244,14 @@ protected: State state; - // contains context specific structs - // to allow generation of different class definition tables + // contains context specific data (DOHs) + // to allow generation of namespace related code // which are switched on namespace change Hash *namespaces; Hash *current_namespace; + File *f_wrappers; + }; /********************************************************************** @@ -244,6 +259,7 @@ protected: **********************************************************************/ /* factory methods for concrete JSEmitters: */ + JSEmitter *swig_javascript_create_JSCEmitter(); JSEmitter *swig_javascript_create_V8Emitter(); @@ -265,13 +281,13 @@ public: virtual int classHandler(Node *n); virtual int functionWrapper(Node *n); virtual int constantWrapper(Node *n); + virtual void main(int argc, char *argv[]); + virtual int top(Node *n); /** * Registers all %fragments assigned to section "templates". **/ virtual int fragmentDirective(Node *n); - virtual void main(int argc, char *argv[]); - virtual int top(Node *n); private: @@ -536,7 +552,8 @@ extern "C" Language *swig_javascript(void) { JSEmitter::JSEmitter() : templates(NewHash()), namespaces(NULL), - current_namespace(NULL) + current_namespace(NULL), + f_wrappers(NULL) { } @@ -557,7 +574,7 @@ int JSEmitter::registerTemplate(const String *name, const String *code) { } /* ----------------------------------------------------------------------------- - * JSEmitter::GetTemplate() : Retrieves a registered a code template + * JSEmitter::getTemplate() : Retrieves a registered a code template * ----------------------------------------------------------------------------- */ Template JSEmitter::getTemplate(const String *name) { @@ -587,6 +604,8 @@ int JSEmitter::initialize(Node * n) { Setattr(namespaces, "::", global_namespace); current_namespace = global_namespace; + f_wrappers = NewString(""); + return SWIG_OK; } @@ -750,6 +769,16 @@ int JSEmitter::createNamespace(String *scope) { return SWIG_OK; } +Hash *JSEmitter::createNamespaceEntry(const char *_name, const char *parent) { + Hash *entry = NewHash(); + String *name = NewString(_name); + Setattr(entry, "name", Swig_scopename_last(name)); + Setattr(entry, "name_mangled", Swig_name_mangle(name)); + Setattr(entry, "parent", NewString(parent)); + + Delete(name); + return entry; +} /********************************************************************** * JavascriptCore: JSEmitter implementation for JavascriptCore engine @@ -757,15 +786,6 @@ int JSEmitter::createNamespace(String *scope) { class JSCEmitter:public JSEmitter { -private: - - enum MarshallingMode { - Setter, - Getter, - Ctor, - Function - }; - public: JSCEmitter(); @@ -781,10 +801,6 @@ public: protected: - virtual int emitCtor(Node *n); - - virtual int emitDtor(Node *n); - virtual int enterVariable(Node *n); virtual int exitVariable(Node *n); @@ -797,19 +813,7 @@ protected: virtual int exitClass(Node *n); - virtual int emitFunction(Node *n, bool is_member, bool is_static); - - virtual int emitFunctionDispatcher(Node *n, bool is_member); - - virtual int emitGetter(Node *n, bool is_member, bool is_static); - - virtual int emitSetter(Node *n, bool is_member, bool is_static); - - virtual int emitConstant(Node *n); - - void marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static = false); - - void marshalOutput(Node *n, String *actioncode, Wrapper *wrapper); + virtual void marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static); virtual Hash *createNamespaceEntry(const char *name, const char *parent); @@ -826,7 +830,6 @@ private: File *f_wrap_cpp; File *f_runtime; File *f_header; - File *f_wrappers; File *f_init; }; @@ -857,7 +860,6 @@ JSCEmitter::JSCEmitter() f_wrap_cpp(NULL), f_runtime(NULL), f_header(NULL), - f_wrappers(NULL), f_init(NULL) { } @@ -934,44 +936,6 @@ void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Ma } } -/* --------------------------------------------------------------------- -* marshalOutput() -* -* Process the return value of the C/C++ function call -* and convert them into the Javascript types using the -* supplied typemaps. -* --------------------------------------------------------------------- */ - -void JSCEmitter::marshalOutput(Node *n, String *actioncode, Wrapper *wrapper) { - SwigType *type = Getattr(n, "type"); - Setattr(n, "type", type); - String *tm; - - // HACK: output types are not registered as swig_types automatically - if (SwigType_ispointer(type)) { - SwigType_remember_clientdata(type, NewString("0")); - } - - if ((tm = Swig_typemap_lookup_out("out", n, "result", wrapper, actioncode))) { - Replaceall(tm, "$result", "jsresult"); - Replaceall(tm, "$objecttype", Swig_scopename_last(SwigType_str(SwigType_strip_qualifiers(type), 0))); - - if (GetFlag(n, "feature:new")) { - Replaceall(tm, "$owner", "SWIG_POINTER_OWN"); - } else { - Replaceall(tm, "$owner", "0"); - } - Append(wrapper->code, tm); - - if (Len(tm) > 0) { - Printf(wrapper->code, "\n"); - } - } else { - Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(type, 0), Getattr(n, "name")); - } - emit_return_variable(n, type, wrapper); -} - int JSCEmitter::initialize(Node *n) { JSEmitter::initialize(n); @@ -990,7 +954,6 @@ int JSCEmitter::initialize(Node *n) { f_runtime = NewString(""); f_init = NewString(""); f_header = NewString(""); - f_wrappers = NewString(""); state.global(CREATE_NAMESPACES, NewString("")); state.global(REGISTER_NAMESPACES, NewString("")); @@ -1193,7 +1156,7 @@ int JSCEmitter::exitClass(Node *n) { return SWIG_OK; } -int JSCEmitter::emitCtor(Node *n) { +int JSEmitter::emitCtor(Node *n) { Wrapper *wrapper = NewWrapper(); @@ -1212,7 +1175,7 @@ int JSCEmitter::emitCtor(Node *n) { int num_args = emit_num_arguments(params); String *action = emit_action(n); - marshalInputArgs(n, params, wrapper, Ctor, true); + marshalInputArgs(n, params, wrapper, Ctor, true, false); Printv(wrapper->code, action, "\n", 0); t_ctor.replace("${classname_mangled}", mangled_name) @@ -1236,7 +1199,7 @@ int JSCEmitter::emitCtor(Node *n) { return SWIG_OK; } -int JSCEmitter::emitDtor(Node *) { +int JSEmitter::emitDtor(Node *) { Template t_dtor = getTemplate("JS_destructordefn"); t_dtor.replace("${classname_mangled}", state.clazz(NAME_MANGLED)) @@ -1246,7 +1209,7 @@ int JSCEmitter::emitDtor(Node *) { return SWIG_OK; } -int JSCEmitter::emitGetter(Node *n, bool is_member, bool is_static) { +int JSEmitter::emitGetter(Node *n, bool is_member, bool is_static) { Wrapper *wrapper = NewWrapper(); Template t_getter(getTemplate("JS_getproperty")); @@ -1276,7 +1239,7 @@ int JSCEmitter::emitGetter(Node *n, bool is_member, bool is_static) { return SWIG_OK; } -int JSCEmitter::emitSetter(Node *n, bool is_member, bool is_static) { +int JSEmitter::emitSetter(Node *n, bool is_member, bool is_static) { // skip variables that are immutable if (State::IsSet(state.variable(IS_IMMUTABLE))) { @@ -1316,7 +1279,7 @@ int JSCEmitter::emitSetter(Node *n, bool is_member, bool is_static) { * JSCEmitter::emitConstant() : triggers code generation for constants * ----------------------------------------------------------------------------- */ -int JSCEmitter::emitConstant(Node *n) { +int JSEmitter::emitConstant(Node *n) { Wrapper *wrapper = NewWrapper(); @@ -1359,10 +1322,9 @@ int JSCEmitter::emitConstant(Node *n) { return SWIG_OK; } -int JSCEmitter::emitFunction(Node *n, bool is_member, bool is_static) { - - Wrapper *wrapper = NewWrapper(); +int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { + Wrapper *wrapper = NewWrapper(); Template t_function(getTemplate("JS_functionwrapper")); bool is_overloaded = GetFlag(n, "sym:overloaded"); @@ -1412,7 +1374,7 @@ int JSCEmitter::emitFunction(Node *n, bool is_member, bool is_static) { return SWIG_OK; } -int JSCEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { +int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { Template t_function(getTemplate("JS_functionwrapper")); @@ -1435,16 +1397,40 @@ int JSCEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { return SWIG_OK; } +void JSEmitter::marshalOutput(Node *n, String *actioncode, Wrapper *wrapper) { + SwigType *type = Getattr(n, "type"); + Setattr(n, "type", type); + String *tm; + + // HACK: output types are not registered as swig_types automatically + if (SwigType_ispointer(type)) { + SwigType_remember_clientdata(type, NewString("0")); + } + + if ((tm = Swig_typemap_lookup_out("out", n, "result", wrapper, actioncode))) { + Replaceall(tm, "$result", "jsresult"); + Replaceall(tm, "$objecttype", Swig_scopename_last(SwigType_str(SwigType_strip_qualifiers(type), 0))); + + if (GetFlag(n, "feature:new")) { + Replaceall(tm, "$owner", "SWIG_POINTER_OWN"); + } else { + Replaceall(tm, "$owner", "0"); + } + Append(wrapper->code, tm); + + if (Len(tm) > 0) { + Printf(wrapper->code, "\n"); + } + } else { + Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(type, 0), Getattr(n, "name")); + } + emit_return_variable(n, type, wrapper); +} + Hash *JSCEmitter::createNamespaceEntry(const char *name, const char *parent) { - Hash *entry = NewHash(); - String *_name = NewString(name); - Setattr(entry, "name", Swig_scopename_last(_name)); - Setattr(entry, "name_mangled", Swig_name_mangle(_name)); - Setattr(entry, "parent", NewString(parent)); + Hash *entry = JSEmitter::createNamespaceEntry(name, parent); Setattr(entry, "functions", NewString("")); Setattr(entry, "values", NewString("")); - - Delete(_name); return entry; } @@ -1483,93 +1469,62 @@ JSEmitter *swig_javascript_create_JSCEmitter() { return new JSCEmitter(); } -/* class V8Emitter: public JSEmitter { public: - V8Emitter(); + V8Emitter(); - virtual ~V8Emitter(); - - virtual int Initialize(Node *n); + virtual ~V8Emitter(); + + virtual int initialize(Node *n); - virtual int Dump(Node *n); - - virtual int Close(); + virtual int dump(Node *n); + + virtual int close(); + + virtual int enterClass(Node *n); + + virtual int exitClass(Node *n); - virtual int SwitchContext(Node *n); - - virtual int EnterClass(Node *n); - - virtual int ExitClass(Node *n); + virtual int enterVariable(Node *n); - virtual int EnterVariable(Node *n); + virtual int exitVariable(Node *n); - virtual int ExitVariable(Node *n); + virtual int enterFunction(Node *n); - virtual int EnterFunction(Node *n); + virtual int exitFunction(Node *n); - virtual int ExitFunction(Node *n); - protected: - int CreateNamespace(String* scope); + virtual void marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static); - virtual int EmitCtor(Node *n); - - virtual int EmitDtor(Node *n); - - virtual int EmitFunction(Node *n, bool is_member); - - virtual int EmitGetter(Node *n, bool is_member); - - virtual int EmitSetter(Node *n, bool is_member); - - void marshalInputArgs(Node *n, ParmList *parms, int numarg, Wrapper *wrapper); - - void marshalOutput(Node *n, String *actioncode, Wrapper *wrapper); - - Parm *skipIgnoredArgs(Parm *p); + virtual int emitNamespaces(); private: - File *f_runtime; - File *f_header; - File *f_class_templates; - File *f_wrapper; - - File *f_init_namespaces; - File *f_init_class_templates; - File *f_init_wrappers; - File *f_init_inheritance; - File *f_init_class_instances; - File *f_init_static_wrappers; - File *f_init_register_classes; - File *f_init_register_namespaces; - - // the output cpp file - File *f_wrap_cpp; - - // state variables - String* current_context; - String* current_class_type; - String* current_classname_mangled; - String* current_classname_unqualified; - String* current_variable_mangled; - String* current_variable_unqualified; - String* current_getter; - String* current_setter; - String* current_function_mangled; - String* current_function_unqualified; - - String* GLOBAL; - String* NULL_STR; - Hash* namespaces; + File *f_runtime; + File *f_header; + File *f_class_templates; + File *f_wrapper; + File *f_init; + + File *f_init_namespaces; + File *f_init_class_templates; + File *f_init_wrappers; + File *f_init_inheritance; + File *f_init_class_instances; + File *f_init_static_wrappers; + File *f_init_register_classes; + File *f_init_register_namespaces; + + // the output cpp file + File *f_wrap_cpp; + + String* GLOBAL; + String* NULL_STR; }; -*/ -/* // name of templates #define V8_INITIALIZER "v8_initializer" #define V8_DECL_CLASSTEMPLATE "v8_declare_class_template" @@ -1614,151 +1569,301 @@ private: #define KW_LOCALS "${LOCALS}" #define KW_CODE "${CODE}" -#define KW_MARSHAL_INPUT "${MARSHAL_INPUT}" -#define KW_ACTION "${ACTION}" -#define KW_MARSHAL_OUTPUT "${MARSHAL_OUTPUT}" V8Emitter::V8Emitter() - : JSEmitter(), - GLOBAL(NewString("global")), - NULL_STR(NewString("0")), - namespaces(NewHash()) +: JSEmitter(), + GLOBAL(NewString("global")), + NULL_STR(NewString("0")) { } V8Emitter::~V8Emitter() { - Delete(GLOBAL); - Delete(NULL_STR); - Delete(namespaces); + Delete(GLOBAL); + Delete(NULL_STR); } int V8Emitter::initialize(Node *n) { - - // Get the output file name - String *outfile = Getattr(n,"outfile"); - f_wrap_cpp = NewFile(outfile, "w", SWIG_output_files()); - if (!f_wrap_cpp) { - FileErrorDisplay(outfile); - SWIG_exit(EXIT_FAILURE); - } + JSEmitter::initialize(n); + + // Get the output file name + String *outfile = Getattr(n,"outfile"); + f_wrap_cpp = NewFile(outfile, "w", SWIG_output_files()); + if (!f_wrap_cpp) { + FileErrorDisplay(outfile); + SWIG_exit(EXIT_FAILURE); + } - f_runtime = NewString(""); - f_header = NewString(""); - f_class_templates = NewString(""); - f_wrapper = NewString(""); - - f_init_namespaces = NewString(""); - f_init_class_templates = NewString(""); - f_init_wrappers = NewString(""); - f_init_inheritance = NewString(""); - f_init_class_instances = NewString(""); - f_init_static_wrappers = NewString(""); - f_init_register_classes = NewString(""); - f_init_register_namespaces = NewString(""); + f_runtime = NewString(""); + f_header = NewString(""); + f_class_templates = NewString(""); + f_wrapper = NewString(""); + f_init = NewString(""); + + f_init_namespaces = NewString(""); + f_init_class_templates = NewString(""); + f_init_wrappers = NewString(""); + f_init_inheritance = NewString(""); + f_init_class_instances = NewString(""); + f_init_static_wrappers = NewString(""); + f_init_register_classes = NewString(""); + f_init_register_namespaces = NewString(""); - // note: this is necessary for built-in generation of swig runtime code - Swig_register_filebyname("runtime", f_runtime); + // note: this is necessary for built-in generation of swig runtime code + Swig_register_filebyname("runtime", f_runtime); + Swig_register_filebyname("header", f_header); + Swig_register_filebyname("init", f_init); + Swig_register_filebyname("wrapper", f_wrapper); - return SWIG_OK; + return SWIG_OK; } int V8Emitter::dump(Node *n) { - // Get the module name - String* module = Getattr(n,"name"); + // Get the module name + String* module = Getattr(n,"name"); - // write the swig banner - Swig_banner(f_wrap_cpp); + // write the swig banner + Swig_banner(f_wrap_cpp); - Printv(f_wrap_cpp, f_runtime, "\n", 0); - Printv(f_wrap_cpp, f_header, "\n", 0); - Printv(f_wrap_cpp, f_class_templates, "\n", 0); - Printv(f_wrap_cpp, f_wrapper, "\n", 0); + Printv(f_wrap_cpp, f_runtime, "\n", 0); + Printv(f_wrap_cpp, f_header, "\n", 0); + Printv(f_wrap_cpp, f_class_templates, "\n", 0); + Printv(f_wrap_cpp, f_wrapper, "\n", 0); - // compose the initializer function using a template - // filled with sub-parts - Template initializer(GetTemplate(V8_INITIALIZER)); - initializer.Replace(KW_MODULE_NAME, module) - .Replace(KW_NAME_SPACES, f_init_namespaces) - .Replace(KW_CLASS_TEMPLATES, f_init_class_templates) - .Replace(KW_WRAPPERS, f_init_wrappers) - .Replace(KW_INHERITANCE, f_init_inheritance) - .Replace(KW_CLASS_INSTANCES, f_init_class_instances) - .Replace(KW_STATIC_WRAPPERS, f_init_static_wrappers) - .Replace(KW_REGISTER_CLASSES, f_init_register_classes) - .Replace(KW_REGISTER_NS, f_init_register_namespaces); - Wrapper_pretty_print(initializer.str(), f_wrap_cpp); + // compose the initializer function using a template + // filled with sub-parts + Template initializer(getTemplate(V8_INITIALIZER)); + initializer.replace(KW_MODULE_NAME, module) + .replace(KW_NAME_SPACES, f_init_namespaces) + .replace(KW_CLASS_TEMPLATES, f_init_class_templates) + .replace(KW_WRAPPERS, f_init_wrappers) + .replace(KW_INHERITANCE, f_init_inheritance) + .replace(KW_CLASS_INSTANCES, f_init_class_instances) + .replace(KW_STATIC_WRAPPERS, f_init_static_wrappers) + .replace(KW_REGISTER_CLASSES, f_init_register_classes) + .replace(KW_REGISTER_NS, f_init_register_namespaces) + .pretty_print(f_wrap_cpp); - return SWIG_OK; + return SWIG_OK; } int V8Emitter::close() { - // strings - Delete(f_runtime); - Delete(f_header); - Delete(f_class_templates); - Delete(f_wrapper); - Delete(f_init_namespaces); - Delete(f_init_class_templates); - Delete(f_init_wrappers); - Delete(f_init_inheritance); - Delete(f_init_class_instances); - Delete(f_init_static_wrappers); - Delete(f_init_register_classes); - Delete(f_init_register_namespaces); - - // files - Close(f_wrap_cpp); - Delete(f_wrap_cpp); - - return SWIG_OK; + // strings + Delete(f_runtime); + Delete(f_header); + Delete(f_class_templates); + Delete(f_wrapper); + Delete(f_init_namespaces); + Delete(f_init_class_templates); + Delete(f_init_wrappers); + Delete(f_init_inheritance); + Delete(f_init_class_instances); + Delete(f_init_static_wrappers); + Delete(f_init_register_classes); + Delete(f_init_register_namespaces); + + // files + Close(f_wrap_cpp); + Delete(f_wrap_cpp); + + return SWIG_OK; } -int V8Emitter::SwitchContext(Node *n) +int V8Emitter::enterClass(Node *n) { - String* scope = Swig_scopename_prefix(Getattr(n, "name")); + JSEmitter::enterClass(n); - if (scope) { - // if the scope is not yet registered - // create all scopes/namespaces recursively - if(!Getattr(namespaces, scope)) { - CreateNamespace(scope); - } - current_context = Getattr(namespaces, scope); - } else { - current_context = GLOBAL; - } - - return SWIG_OK; + // emit declaration of a v8 class template + Template t_decl_class(getTemplate(V8_DECL_CLASSTEMPLATE)); + t_decl_class.replace(KW_MANGLED_NAME, state.clazz(NAME_MANGLED)) + .pretty_print(f_class_templates); + + // emit definition of v8 class template + Template t_def_class(getTemplate(V8_DEFINE_CLASSTEMPLATE)); + t_def_class.replace(KW_MANGLED_NAME, state.clazz(NAME_MANGLED)) + .replace(KW_UNQUALIFIED_NAME, state.clazz(NAME)) + .pretty_print(f_init_class_templates); + + Template t_class_instance(getTemplate(V8_CREATE_CLASS_INSTANCE)); + t_class_instance.replace(KW_MANGLED_NAME, state.clazz(NAME_MANGLED)) + .pretty_print(f_init_class_instances); + + return SWIG_OK; } -int V8Emitter::CreateNamespace(String* scope) { - String* parent_scope = Swig_scopename_prefix(scope); - String* parent_scope_mangled = 0; +int V8Emitter::exitClass(Node *n) +{ + // emit inheritance setup + Node* baseClass = getBaseClass(n); + if(baseClass) { + Template t_inherit(getTemplate(V8_INHERIT)); + String *base_name_mangled = SwigType_manglestr(Getattr(baseClass, "name")); + t_inherit.replace(KW_MANGLED_NAME, state.clazz(NAME_MANGLED)) + .replace(KW_BASE_CLASS, base_name_mangled) + .pretty_print(f_init_inheritance); + Delete(base_name_mangled); + } + + // emit registeration of class template + Template t_register(getTemplate(V8_REGISTER_CLASS)); + t_register.replace(KW_MANGLED_NAME, state.clazz(NAME_MANGLED)) + .replace(KW_UNQUALIFIED_NAME, state.clazz(NAME)) + .replace(KW_CONTEXT, Getattr(current_namespace, "name_mangled")) + .pretty_print(f_init_register_classes); + + return SWIG_OK; +} - if(!parent_scope) { - parent_scope_mangled = NewString("global"); +int V8Emitter::enterVariable(Node* n) +{ + JSEmitter::enterVariable(n); + + state.variable(GETTER, NULL_STR); + state.variable(SETTER, NULL_STR); + + return SWIG_OK; +} + +int V8Emitter::exitVariable(Node* n) +{ + if(GetFlag(n, "ismember")) { + if(GetFlag(state.variable(), IS_STATIC)) { + Template t_register(getTemplate(V8_REGISTER_GLOBAL_VARIABLE)); + String *class_instance = NewString(""); + Printf(class_instance, "class_%s", state.clazz(NAME_MANGLED)); + t_register.replace(KW_CONTEXT, class_instance) + .replace(KW_UNQUALIFIED_NAME, state.variable(NAME)) + .replace(KW_GETTER, state.variable(GETTER)) + .replace(KW_SETTER, state.variable(SETTER)) + .pretty_print(f_init_static_wrappers); + Delete(class_instance); } else { - parent_scope_mangled = Swig_name_mangle(parent_scope); + Template t_register(getTemplate(V8_REGISTER_MEMBER_VARIABLE)); + t_register.replace(KW_CLASSNAME_MANGLED, state.clazz(NAME_MANGLED)) + .replace(KW_UNQUALIFIED_NAME, state.clazz(NAME)) + .replace(KW_GETTER, state.variable(GETTER)) + .replace(KW_SETTER, state.variable(SETTER)) + .pretty_print(f_init_wrappers); + } + } else { + Template t_register(getTemplate(V8_REGISTER_GLOBAL_VARIABLE)); + t_register.replace(KW_CONTEXT, Getattr(current_namespace, "name")) + .replace(KW_UNQUALIFIED_NAME, state.variable(NAME)) + .replace(KW_GETTER, state.variable(GETTER)) + .replace(KW_SETTER, state.variable(SETTER)) + .pretty_print(f_init_wrappers); + } + + return SWIG_OK; +} +int V8Emitter::enterFunction(Node* n) +{ + JSEmitter::enterFunction(n); + + return SWIG_OK; +} + +int V8Emitter::exitFunction(Node* n) +{ + // register the function at the specific context + if(GetFlag(n, "ismember")) { + if(GetFlag(state.function(), IS_STATIC)) { + Template t_register(getTemplate(V8_REGISTER_GLOBAL_FUNCTION)); + String *class_instance = NewString(""); + Printf(class_instance, "class_%s", state.clazz(NAME_MANGLED)); + t_register.replace(KW_CONTEXT, class_instance) + .replace(KW_UNQUALIFIED_NAME, state.function(NAME)) + .replace(KW_MANGLED_NAME, Getattr(n, "wrap:name")); + Printv(f_init_static_wrappers, t_register.str(), 0); + Delete(class_instance); + } else { + Template t_register(getTemplate(V8_REGISTER_MEMBER_FUNCTION)); + t_register.replace(KW_CLASSNAME_MANGLED, state.clazz(NAME_MANGLED)) + .replace(KW_UNQUALIFIED_NAME, state.function(NAME)) + .replace(KW_MANGLED_NAME, Getattr(n, "wrap:name")); + Printv(f_init_wrappers, t_register.str(), "\n", 0); } - - if (parent_scope && !Getattr(namespaces, parent_scope)) { - CreateNamespace(parent_scope); + } else { + Template t_register(getTemplate(V8_REGISTER_GLOBAL_FUNCTION)); + t_register.replace(KW_CONTEXT, Getattr(current_namespace, "name")) + .replace(KW_UNQUALIFIED_NAME, state.function(NAME)) + .replace(KW_MANGLED_NAME, Getattr(n, "wrap:name")); + Printv(f_init_wrappers, t_register.str(), 0); + } + + return SWIG_OK; +} + +void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) { + String *tm; + Parm *p; + + int startIdx = 0; + if (is_member && !is_static) { + startIdx = 1; + } + + int i = 0; + for (p = parms; p; p = nextSibling(p), i++) { + SwigType *pt = Getattr(p, "type"); + String *arg = NewString(""); + + switch (mode) { + case Getter: + case Function: + if (is_member && !is_static && i == 0) { + Printv(arg, "args[0]", 0); + } else { + Printf(arg, "args[%d]", i - startIdx); + } + + break; + case Setter: + if (is_member && !is_static && i == 0) { + Printv(arg, "args[0]", 0); + } else { + Printv(arg, "value", 0); + } + break; + case Ctor: + Printf(arg, "args[%d]", i); + break; + default: + throw "Illegal state."; } - - String* scope_mangled = Swig_string_mangle(scope); - String* scope_unqualified = Swig_scopename_last(scope); - Setattr(namespaces, scope, scope_mangled); - + + tm = Getattr(p, "tmap:in"); // Get typemap for this argument + if (tm != NULL) { + Replaceall(tm, "$input", arg); + Setattr(p, "emit:input", arg); + + if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) { + Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); + } else { + Replaceall(tm, "$disown", "0"); + } + Replaceall(tm, "$symname", Getattr(n, "sym:name")); + + Printf(wrapper->code, "%s\n", tm); + } else { + Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0)); + } + Delete(arg); + } +} + +int V8Emitter::emitNamespaces() { +// TODO: handle namespaces: +/* // create namespace object and register it to the parent scope - Template t_create_ns(GetTemplate(V8_CREATE_NAMESPACE)); + Template t_create_ns(getTemplate(V8_CREATE_NAMESPACE)); t_create_ns.Replace(KW_MANGLED_NAME, scope_mangled); - Template t_register_ns(GetTemplate(V8_REGISTER_NAMESPACE)); + Template t_register_ns(getTemplate(V8_REGISTER_NAMESPACE)); t_register_ns.Replace(KW_MANGLED_NAME, scope_mangled) .Replace(KW_CONTEXT, parent_scope_mangled) .Replace(KW_UNQUALIFIED_NAME, scope_unqualified); @@ -1766,358 +1871,14 @@ int V8Emitter::CreateNamespace(String* scope) { Printv(f_init_namespaces, t_create_ns.str(), 0); // prepend in order to achieve reversed order of registration statements Insert(f_init_register_namespaces, 0, t_register_ns.str()); - - Delete(parent_scope); - Delete(parent_scope_mangled); - Delete(scope_unqualified); - return SWIG_OK; -} - -int V8Emitter::EnterClass(Node *n) -{ - current_classname_mangled = Swig_string_mangle(Getattr(n, "name")); - current_classname_unqualified = Swig_scopename_last(Getattr(n, "name")); - current_class_type = Getattr(n, "classtype"); - - // emit declaration of a v8 class template - Template t_decl_class(GetTemplate(V8_DECL_CLASSTEMPLATE)); - t_decl_class.Replace(KW_MANGLED_NAME, current_classname_mangled); - Printv(f_class_templates, t_decl_class.str(), 0); - - // emit definition of v8 class template - Template t_def_class(GetTemplate(V8_DEFINE_CLASSTEMPLATE)); - t_def_class.Replace(KW_MANGLED_NAME, current_classname_mangled) - .Replace(KW_UNQUALIFIED_NAME, current_classname_unqualified); - Printv(f_init_class_templates, t_def_class.str(), 0); - - Template t_class_instance(GetTemplate(V8_CREATE_CLASS_INSTANCE)); - t_class_instance.Replace(KW_MANGLED_NAME, current_classname_mangled); - Printv(f_init_class_instances, t_class_instance.str(), 0); - - return SWIG_OK; -} - -int V8Emitter::ExitClass(Node *n) -{ - // emit inheritance setup - Node* baseClass = GetBaseClass(n); - if(baseClass) { - Template t_inherit(GetTemplate(V8_INHERIT)); - t_inherit.Replace(KW_MANGLED_NAME, current_classname_mangled) - .Replace(KW_BASE_CLASS, Swig_string_mangle(Getattr(baseClass, "name"))); - Printv(f_init_inheritance, t_inherit.str(), 0); - } - - // emit registeration of class template - Template t_register(GetTemplate(V8_REGISTER_CLASS)); - t_register.Replace(KW_MANGLED_NAME, current_classname_mangled) - .Replace(KW_UNQUALIFIED_NAME, current_classname_unqualified) - .Replace(KW_CONTEXT, Swig_string_mangle(current_context)); - Printv(f_init_register_classes, t_register.str(), 0); - - Delete(current_classname_mangled); - Delete(current_classname_unqualified); - current_classname_mangled = 0; - current_classname_unqualified = 0; - current_class_type = 0; - - return SWIG_OK; -} - -int V8Emitter::EnterVariable(Node* n) -{ - current_variable_unqualified = Swig_scopename_last(Getattr(n, "name")); - if(GetFlag(n, "ismember")) { - current_variable_mangled = NewString(""); - Printf(current_variable_mangled, "%s_%s", current_classname_mangled, current_variable_unqualified); - } else { - current_variable_mangled = Swig_string_mangle(Getattr(n, "name")); - } - - current_getter = NULL_STR; - current_setter = NULL_STR; - - return SWIG_OK; -} - -int V8Emitter::ExitVariable(Node* n) -{ - if(GetFlag(n, "ismember")) { - if(Equal(Getattr(n, "storage"), "static")) { - Template t_register(GetTemplate(V8_REGISTER_GLOBAL_VARIABLE)); - String *class_instance = NewString(""); - Printf(class_instance, "class_%s", current_classname_mangled); - t_register.Replace(KW_CONTEXT, class_instance) - .Replace(KW_UNQUALIFIED_NAME, current_variable_unqualified) - .Replace(KW_GETTER, current_getter) - .Replace(KW_SETTER, current_setter); - Printv(f_init_static_wrappers, t_register.str(), 0); - Delete(class_instance); - } else { - Template t_register(GetTemplate(V8_REGISTER_MEMBER_VARIABLE)); - t_register.Replace(KW_CLASSNAME_MANGLED, current_classname_mangled) - .Replace(KW_UNQUALIFIED_NAME, current_variable_unqualified) - .Replace(KW_GETTER, current_getter) - .Replace(KW_SETTER, current_setter); - Printv(f_init_wrappers, t_register.str(), 0); - } - } else { - Template t_register(GetTemplate(V8_REGISTER_GLOBAL_VARIABLE)); - t_register.Replace(KW_CONTEXT, current_context) - .Replace(KW_UNQUALIFIED_NAME, current_variable_unqualified) - .Replace(KW_GETTER, current_getter) - .Replace(KW_SETTER, current_setter); - Printv(f_init_wrappers, t_register.str(), 0); - } - - Delete(current_variable_mangled); - Delete(current_variable_unqualified); - current_variable_mangled = 0; - current_variable_unqualified = 0; - - return SWIG_OK; -} - -int V8Emitter::EnterFunction(Node* n) -{ - current_function_unqualified = Swig_scopename_last(Getattr(n, "name")); - if(GetFlag(n, "ismember")) { - current_function_mangled = NewString(""); - Printf(current_function_mangled, "%s_%s", current_classname_mangled, current_function_unqualified); - } else { - current_function_mangled = Swig_string_mangle(Getattr(n, "name")); - } - - return SWIG_OK; -} - -int V8Emitter::ExitFunction(Node* n) -{ - // register the function at the specific context - if(GetFlag(n, "ismember")) { - if(Equal(Getattr(n, "storage"), "static")) { - Template t_register(GetTemplate(V8_REGISTER_GLOBAL_FUNCTION)); - String *class_instance = NewString(""); - Printf(class_instance, "class_%s", current_classname_mangled); - t_register.Replace(KW_CONTEXT, class_instance) - .Replace(KW_UNQUALIFIED_NAME, current_function_unqualified) - .Replace(KW_MANGLED_NAME, Getattr(n, "wrap:name")); - Printv(f_init_static_wrappers, t_register.str(), 0); - Delete(class_instance); - } else { - Template t_register(GetTemplate(V8_REGISTER_MEMBER_FUNCTION)); - t_register.Replace(KW_CLASSNAME_MANGLED, current_classname_mangled) - .Replace(KW_UNQUALIFIED_NAME, current_function_unqualified) - .Replace(KW_MANGLED_NAME, Getattr(n, "wrap:name")); - Printv(f_init_wrappers, t_register.str(), "\n", 0); - } - } else { - Template t_register(GetTemplate(V8_REGISTER_GLOBAL_FUNCTION)); - t_register.Replace(KW_CONTEXT, current_context) - .Replace(KW_UNQUALIFIED_NAME, current_function_unqualified) - .Replace(KW_MANGLED_NAME, Getattr(n, "wrap:name")); - Printv(f_init_wrappers, t_register.str(), 0); - } - - - Delete(current_function_mangled); - Delete(current_function_unqualified); - current_function_mangled = 0; - current_function_unqualified = 0; - - return SWIG_OK; -} - -int V8Emitter::EmitCtor(Node* n) -{ - // TODO: handle overloaded ctors using a dispatcher - Template t(GetTemplate(V8_CTOR_WRAPPER)); - - //HACK: manually add declaration of instance pointer - Printf(wrapper->locals, "%sresult;", SwigType_str(Getattr(n, "type"),0)); - - String* action = emit_action(n); - Printv(wrapper->code, action, 0); - - t.Replace(KW_MANGLED_NAME, current_classname_mangled) - .Replace(KW_UNQUALIFIED_NAME, current_classname_unqualified) - .Replace(KW_LOCALS, wrapper->locals) - .Replace(KW_CODE, wrapper->code); - - Wrapper_pretty_print(t.str(), f_wrapper); - - return SWIG_OK; -} - -int V8Emitter::EmitDtor(Node* n) -{ - // TODO: - // find out how to register a dtor in v8 - return SWIG_OK; -} - -int V8Emitter::EmitGetter(Node *n, bool is_member) { - Template t_getter(GetTemplate(V8_GETTER)); - - current_getter = Getattr(n,"wrap:name"); - - ParmList *params = Getattr(n,"parms"); - emit_parameter_variables(params, wrapper); - emit_attach_parmmaps(params, wrapper); - - int num_args = emit_num_arguments(params); - String* action = emit_action(n); - marshalInputArgs(n, params, num_args, wrapper); - marshalOutput(n, action, wrapper); - - t_getter.Replace(KW_MANGLED_NAME, current_variable_mangled) - .Replace(KW_LOCALS, wrapper->locals) - .Replace(KW_CODE, wrapper->code); - - Wrapper_pretty_print(t_getter.str(), f_wrapper); - - return SWIG_OK; -} - -int V8Emitter::EmitSetter(Node* n, bool is_member) -{ - Template t_setter(GetTemplate(V8_SETTER)); - - current_setter = Getattr(n,"wrap:name"); - - ParmList *params = Getattr(n,"parms"); - emit_parameter_variables(params, wrapper); - emit_attach_parmmaps(params, wrapper); - - int num_args = emit_num_arguments(params); - String* action = emit_action(n); - marshalInputArgs(n, params, num_args, wrapper); - Printv(wrapper->code, action, 0); - - t_setter.Replace(KW_MANGLED_NAME, current_variable_mangled) - .Replace(KW_LOCALS, wrapper->locals) - .Replace(KW_CODE, wrapper->code); - - Wrapper_pretty_print(t_setter.str(), f_wrapper); - - return SWIG_OK; -} - - -int V8Emitter::EmitFunction(Node* n, bool is_member) -{ - Template t_function(GetTemplate(V8_FUNCTION)); - - String* wrap_name = NewString(""); - Printv(wrap_name, current_function_mangled, 0); - Setattr(n, "wrap:name", wrap_name); - - ParmList *params = Getattr(n,"parms"); - emit_parameter_variables(params, wrapper); - emit_attach_parmmaps(params, wrapper); - - int num_args = emit_num_arguments(params); - String* action = emit_action(n); - marshalInputArgs(n, params, num_args, wrapper); - marshalOutput(n, action, wrapper); - - t_function.Replace(KW_MANGLED_NAME, current_function_mangled) - .Replace(KW_LOCALS, wrapper->locals) - .Replace(KW_CODE, wrapper->code); - Wrapper_pretty_print(t_function.str(), f_wrapper); - - return SWIG_OK; -} - -void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, int numarg, Wrapper *wrapper) { - String *tm; - Parm *p; - - bool is_member = (current_class_type != 0); - bool is_setter = IsSetterMethod(n); - bool is_function = (current_function_mangled != 0); - - int start_idx; - if(is_member) { - start_idx = 1; - } else { - start_idx = 0; - } - - // retrieve this pointer for member functions - if(is_member) { - - Template t_selfptr(GetTemplate(V8_THIS_PTR)); - String *type_str = SwigType_strip_qualifiers(SwigType_str(current_class_type,0)); - String *arg_str; - if(is_function) { - arg_str = NewString("args"); - } else { - arg_str = NewString("info"); - } - - t_selfptr.Replace(KW_TYPE, type_str) - .Replace(KW_ARG, arg_str); - Printv(wrapper->code, t_selfptr.str(), 0); - - Delete(type_str); - Delete(arg_str); - } - - int i = 0; - for (i = 0, p = parms; i < numarg; i++) - { - p = skipIgnoredArgs(p); - SwigType *pt = Getattr(p, "type"); - - String *arg = NewString(""); - if (i == 0) { - if(start_idx == 0) { - Printv(arg, is_setter?"value":"args[0]", 0); - } else { - p = Getattr(p, "tmap:in:next"); - Delete(arg); - continue; // special case: skip the typemaps for the first argument - } - } else { - Printf(arg, is_setter?"value":"args[%d]", i - start_idx); - } - - if ((tm = Getattr(p, "tmap:in"))) // Get typemap for this argument - { - Replaceall(tm, "$input", arg); - Setattr(p, "emit:input", arg); - Printf(wrapper->code, "%s\n", tm); - p = Getattr(p, "tmap:in:next"); - } else { - Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0)); - p = nextSibling(p); - } - Delete(arg); - } -} - -void V8Emitter::marshalOutput(Node *n, String *actioncode, Wrapper *wrapper) { - SwigType *type = Getattr(n, "type"); - Setattr(n, "type", type); - String *tm; - if ((tm = Swig_typemap_lookup_out("out", n, "result", wrapper, actioncode))) - { - Replaceall(tm, "$result", "jsresult"); - // TODO: May not be the correct way - Replaceall(tm, "$objecttype", Swig_scopename_last(SwigType_str(SwigType_strip_qualifiers(type), 0))); - Printf(wrapper->code, "%s", tm); - if (Len(tm)) - Printf(wrapper->code, "\n"); - } else { - Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(type, 0), Getattr(n, "name")); - } - emit_return_variable(n, type, wrapper); -} - */ + + return SWIG_OK; +} + + JSEmitter *swig_javascript_create_V8Emitter() { - return 0; + return new V8Emitter(); } From 548287c600e8bd900e6976158ffe9c007a390e5f Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:01:41 +0000 Subject: [PATCH 0104/1048] Update configuration to detect V8 and allow testing with V8. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13777 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/Makefile.in | 22 +++++-- Examples/javascript/class/Makefile | 11 ++-- Examples/javascript/constant/Makefile | 11 ++-- Examples/javascript/enum/Makefile | 11 ++-- Examples/javascript/exception/Makefile | 11 ++-- Examples/javascript/functor/Makefile | 11 ++-- Examples/javascript/namespace/Makefile | 11 ++-- Examples/javascript/operator/Makefile | 11 ++-- Examples/javascript/overload/Makefile | 11 ++-- Examples/javascript/pointer/Makefile | 11 ++-- Examples/javascript/reference/Makefile | 11 ++-- Examples/javascript/simple/Makefile | 11 ++-- Examples/javascript/template/Makefile | 11 ++-- Examples/javascript/variables/Makefile | 11 ++-- configure.in | 82 ++++++++++++++++++++++++-- 15 files changed, 159 insertions(+), 88 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 250ce4e0e..4f20b83b8 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -519,10 +519,22 @@ java_clean: # You need to set this variable to the jscore[or other javascript engine] directories containing the # files "JavaScript.h" and others -JS_INCLUDE= @JSCOREINC@ + +ifeq (,$(V8)) + JS_INCLUDE = @JSCOREINC@ + JS_DLNK = @JSCOREDYNAMICLINKING@ +else + JS_INCLUDE = @JSV8INC@ + JS_DLNK = @JSCOREDYNAMICLINKING@ +endif + +ifeq (,$(V8)) + SWIGJS = $(SWIG) -javascript -jsc +else + SWIGJS = $(SWIG) -javascript -v8 +endif # Extra JAVASCRIPT specific dynamic linking options -JS_DLNK = @JSCOREDYNAMICLINKING@ JS_LIBPREFIX = @JSCORELIBRARYPREFIX@ JSSO =@JSCORESO@ JSLDSHARED = @JSCORELDSHARED@ @@ -535,7 +547,7 @@ JSCXXFLAGS = @JSCXXFLAGS@ # ---------------------------------------------------------------- javascript: $(SRCS) - $(SWIG) -javascript -jsc -debug-codetemplates $(SWIGOPT) $(INTERFACEPATH) + $(SWIGJS) $(SWIGOPT) $(INTERFACEPATH) $(CC) -c $(CCSHARED) $(JSCFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(JS_INCLUDE) $(JSLDSHARED) $(CCSHARED) $(JSCFLAGS) $(OBJS) $(IOBJS) $(JS_DLNK) $(LIBS) -o $(JS_LIBPREFIX)$(TARGET)$(JSSO) @@ -544,7 +556,7 @@ javascript: $(SRCS) # ---------------------------------------------------------------- javascript_cpp: $(SRCS) - $(SWIG) -c++ -javascript -jsc -debug-codetemplates $(SWIGOPT) $(INTERFACEPATH) + $(SWIGJS) -c++ $(SWIGOPT) $(INTERFACEPATH) $(CXX) -c $(CCSHARED) $(JSCXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(JS_INCLUDE) $(JSCXXSHARED) $(CCSHARED) $(OBJS) $(IOBJS) $(JS_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(JS_LIBPREFIX)$(TARGET)$(JSSO) @@ -559,7 +571,7 @@ javascript_exe: $(SRCS) # ---------------------------------------------------------------- javascript_run: $(SRCS) - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(JAVASCRIPT_EXE) -l $(JAVASCRIPT_MODULE) $(JS_SCRIPT) + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(JAVASCRIPT_EXE) -l $(TARGET) $(JS_SCRIPT) # ----------------------------------------------------------------- # Cleaning the javascript examples diff --git a/Examples/javascript/class/Makefile b/Examples/javascript/class/Makefile index ea41e55ce..1ac61ec6b 100755 --- a/Examples/javascript/class/Makefile +++ b/Examples/javascript/class/Makefile @@ -1,17 +1,16 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -SRCS = example.cpp -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript -JAVASCRIPT_MODULE = example +CXXSRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ -SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean @@ -20,5 +19,5 @@ check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/constant/Makefile b/Examples/javascript/constant/Makefile index 4bc75b1a0..1ac61ec6b 100755 --- a/Examples/javascript/constant/Makefile +++ b/Examples/javascript/constant/Makefile @@ -1,17 +1,16 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -SRCS = -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript -JAVASCRIPT_MODULE = example +CXXSRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ -SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean @@ -20,5 +19,5 @@ check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/enum/Makefile b/Examples/javascript/enum/Makefile index ea41e55ce..1ac61ec6b 100755 --- a/Examples/javascript/enum/Makefile +++ b/Examples/javascript/enum/Makefile @@ -1,17 +1,16 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -SRCS = example.cpp -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript -JAVASCRIPT_MODULE = example +CXXSRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ -SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean @@ -20,5 +19,5 @@ check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/exception/Makefile b/Examples/javascript/exception/Makefile index ea41e55ce..1ac61ec6b 100755 --- a/Examples/javascript/exception/Makefile +++ b/Examples/javascript/exception/Makefile @@ -1,17 +1,16 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -SRCS = example.cpp -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript -JAVASCRIPT_MODULE = example +CXXSRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ -SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean @@ -20,5 +19,5 @@ check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/functor/Makefile b/Examples/javascript/functor/Makefile index ea41e55ce..1ac61ec6b 100755 --- a/Examples/javascript/functor/Makefile +++ b/Examples/javascript/functor/Makefile @@ -1,17 +1,16 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -SRCS = example.cpp -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript -JAVASCRIPT_MODULE = example +CXXSRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ -SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean @@ -20,5 +19,5 @@ check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/namespace/Makefile b/Examples/javascript/namespace/Makefile index ea41e55ce..1ac61ec6b 100755 --- a/Examples/javascript/namespace/Makefile +++ b/Examples/javascript/namespace/Makefile @@ -1,17 +1,16 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -SRCS = example.cpp -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript -JAVASCRIPT_MODULE = example +CXXSRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ -SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean @@ -20,5 +19,5 @@ check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/operator/Makefile b/Examples/javascript/operator/Makefile index ea41e55ce..1ac61ec6b 100755 --- a/Examples/javascript/operator/Makefile +++ b/Examples/javascript/operator/Makefile @@ -1,17 +1,16 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -SRCS = example.cpp -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript -JAVASCRIPT_MODULE = example +CXXSRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ -SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean @@ -20,5 +19,5 @@ check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/overload/Makefile b/Examples/javascript/overload/Makefile index ea41e55ce..1ac61ec6b 100755 --- a/Examples/javascript/overload/Makefile +++ b/Examples/javascript/overload/Makefile @@ -1,17 +1,16 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -SRCS = example.cpp -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript -JAVASCRIPT_MODULE = example +CXXSRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ -SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean @@ -20,5 +19,5 @@ check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/pointer/Makefile b/Examples/javascript/pointer/Makefile index ea41e55ce..1ac61ec6b 100755 --- a/Examples/javascript/pointer/Makefile +++ b/Examples/javascript/pointer/Makefile @@ -1,17 +1,16 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -SRCS = example.cpp -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript -JAVASCRIPT_MODULE = example +CXXSRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ -SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean @@ -20,5 +19,5 @@ check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/reference/Makefile b/Examples/javascript/reference/Makefile index ea41e55ce..1ac61ec6b 100755 --- a/Examples/javascript/reference/Makefile +++ b/Examples/javascript/reference/Makefile @@ -1,17 +1,16 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -SRCS = example.cpp -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript -JAVASCRIPT_MODULE = example +CXXSRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ -SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean @@ -20,5 +19,5 @@ check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/simple/Makefile b/Examples/javascript/simple/Makefile index ea41e55ce..1ac61ec6b 100755 --- a/Examples/javascript/simple/Makefile +++ b/Examples/javascript/simple/Makefile @@ -1,17 +1,16 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -SRCS = example.cpp -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript -JAVASCRIPT_MODULE = example +CXXSRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ -SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean @@ -20,5 +19,5 @@ check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/template/Makefile b/Examples/javascript/template/Makefile index ea41e55ce..1ac61ec6b 100755 --- a/Examples/javascript/template/Makefile +++ b/Examples/javascript/template/Makefile @@ -1,17 +1,16 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -SRCS = example.cpp -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript -JAVASCRIPT_MODULE = example +CXXSRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ -SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean @@ -20,5 +19,5 @@ check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/variables/Makefile b/Examples/javascript/variables/Makefile index e80e370e0..1ac61ec6b 100755 --- a/Examples/javascript/variables/Makefile +++ b/Examples/javascript/variables/Makefile @@ -1,17 +1,16 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -SRCS = example.c -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript -JAVASCRIPT_MODULE = example +CXXSRCS = example.cpp +JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ -SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean @@ -20,5 +19,5 @@ check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JAVASCRIPT_MODULE='$(JAVASCRIPT_MODULE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run + JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/configure.in b/configure.in index 92955c4c0..f3d7e4ccd 100644 --- a/configure.in +++ b/configure.in @@ -1088,6 +1088,8 @@ AC_MSG_NOTICE([Disabling Javascript]) JAVASCRIPT= else +### JavascriptCore ### + # check for include files AC_MSG_CHECKING(for include file JavaScriptCore/JavaScript.h) AC_ARG_WITH(javascriptincl, [ --with-javascript=path Set location of Javascript include directory], [JSCOREINCDIR="$withval"], [JSCOREINCDIR=]) @@ -1153,7 +1155,6 @@ else AC_MSG_RESULT($JSCORELIB) fi - # linking options case $host in *-*-darwin*) @@ -1176,10 +1177,9 @@ case $host in *) JSCORELIBRARYPREFIX="lib";; esac -if "$JS_NO_WARNINGS" == "1"; then +if test "$JS_NO_WARNINGS" == "1"; then case $host in *-*-darwin* | *-*-linux* | *-*-cygwin* | *-*-mingw*) - echo "HHHHHHHHHHHHHHHHHHHHHHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" JSCXXFLAGS="`echo $CXXFLAGS | sed 's/-Wall//g'`" ;; *) @@ -1211,6 +1211,78 @@ AC_SUBST(JSCORELDSHARED) AC_SUBST(JSCORECXXSHARED) AC_SUBST(JSCXXFLAGS) +### V8 ### + +# check for include files +AC_MSG_CHECKING(for include file v8.h) +AC_ARG_WITH(javascriptv8incl, [ --with-javascript-v8=path Set location of Javascript include directory], [JSV8INCDIR="$withval"], [JSV8INCDIR=]) + +if test -z "$JSV8INCDIR"; then + JSV8INCDIR="/usr/include/ /usr/local/include/" + + # Add in default directory for JavaScriptCore headers for Linux and MacOSX + case $host in + *-*-linux*) JSV8INCDIR="/usr/include /usr/local/include/ $JSV8INCDIR";; + *-*-darwin*) JSV8INCDIR="$JSV8INCDIR";; #TODO: add configuration for osx + *);; + esac +fi + +for d in $JSV8INCDIR ; do + if test -r "$d/v8.h" ; then + AC_MSG_RESULT($d) + JSV8INCDIR=$d + JSV8INC=-I\"$d\" + break + fi +done + +if test "$JSV8INC" = "" ; then + AC_MSG_RESULT(not found) +fi + + +# check for V8 library +AC_ARG_WITH(jsv8lib,[ --with-jsv8lib =path Set location of V8 library directory],[ + JSV8LIB="-L$withval"], [JSV8LIB=]) +AC_MSG_CHECKING(for V8 library) + +if test -z "$JSV8LIB"; then +dirs="/usr/lib/ /usr/local/lib/" +for i in $dirs ; do + + if test -r $i/libv8.so; then + AC_MSG_RESULT($i) + JSV8LIB="-L$i -lv8" + break + fi +done + +if test "$JSV8LIB" = "" ; then + AC_MSG_RESULT(not found) +fi + +else +AC_MSG_RESULT($JSCORELIB) +fi + + +# linking options +case $host in +*-*-darwin*) + JSV8DYNAMICLINKING="" # TODO: add osx configuration + ;; +*-*-linux*) + JSV8DYNAMICLINKING="$JSV8LIB" + ;; +*) + JSV8DYNAMICLINKING="" + ;; +esac + +AC_SUBST(JSV8INC) +AC_SUBST(JSV8DYNAMICLINKING) + #---------------------------------------------------------------- # Look for gcj #---------------------------------------------------------------- @@ -2372,10 +2444,10 @@ fi AC_SUBST(SKIP_JAVA) SKIP_JAVASCRIPT= -if test -z "$JSCOREINC"; then +if test -z "$JSCOREINC" && test -z "$JSV8INC"; then # Add in default directory for JavaScriptCore headers for Linux and MacOSX case $host in - *-*-linux*) if test -z "$JSCORELIB"; then + *-*-linux*) if test -z "$JSCORELIB" && test -z "$JSV8LIB"; then SKIP_JAVASCRIPT="1" fi ;; From eff094ef3942c026a0711abad56af9a8a54d9b9a Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:01:57 +0000 Subject: [PATCH 0105/1048] Add test "constructor_copy". git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13778 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/constructor_copy.i | 2 +- Examples/test-suite/javascript/Makefile.in | 1 + .../javascript/constructor_copy_runme.js | 41 +++++++++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 Examples/test-suite/javascript/constructor_copy_runme.js diff --git a/Examples/test-suite/constructor_copy.i b/Examples/test-suite/constructor_copy.i index f6bdcb240..6a0e90c71 100644 --- a/Examples/test-suite/constructor_copy.i +++ b/Examples/test-suite/constructor_copy.i @@ -73,7 +73,7 @@ public: %include "std_vector.i" -#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGPYTHON) || defined(SWIGR) || defined(SWIGOCTAVE) || defined(SWIGRUBY) +#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGPYTHON) || defined(SWIGR) || defined(SWIGOCTAVE) || defined(SWIGRUBY) || defined(SWIGJAVASCRIPT) #define SWIG_GOOD_VECTOR %ignore std::vector::vector(size_type); %ignore std::vector::resize(size_type); diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index 38f350cb0..a8e1759f7 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -29,6 +29,7 @@ CPP_TEST_CASES = \ class_scope_weird \ complextest \ constover \ + constructor_copy \ cpp_enum \ cpp_namespace \ cpp_static \ diff --git a/Examples/test-suite/javascript/constructor_copy_runme.js b/Examples/test-suite/javascript/constructor_copy_runme.js new file mode 100644 index 000000000..627b0936b --- /dev/null +++ b/Examples/test-suite/javascript/constructor_copy_runme.js @@ -0,0 +1,41 @@ + +f1 = new constructor_copy.Foo1(3); +f11 = new constructor_copy.Foo1(f1); + +if (f1.x != f11.x) { + throw "error in ctor copy for Foo1"; +} + +var good = 0; + +f8 = new constructor_copy.Foo8() +try { + f81 = new constructor_copy.Foo8(f8); + good = 0; +} catch (err) { + good = 1; +} + +if (good == 0) { + throw "Error: should not allow calling copy ctor for Foo8"; +} + + +bi = new constructor_copy.Bari(5); +bc = new constructor_copy.Bari(bi); + +if (bi.x != bc.x) { + throw "Error in copy ctor of Bari"; +} + +bd = new constructor_copy.Bard(5); +try { + bc = new constructor_copy.Bard(bd); + good = 0; +} catch (err) { + good = 1; +} + +if (good == 0) { + throw "Error: should not allow calling copy ctor for Bard"; +} From 07d5ec24cebcaa7a08425fa4780937b3bca9fae5 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:02:16 +0000 Subject: [PATCH 0106/1048] Add support for type-based dispatching of overloaded functions. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13779 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/jsc/javascriptcode.swg | 50 ++++++++++++++++++--------- Source/Modules/javascript.cxx | 27 +++++++++++---- 2 files changed, 54 insertions(+), 23 deletions(-) diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index dfa51e143..51b49039c 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -58,21 +58,37 @@ JSValueRef ${functionname}(JSContextRef context, JSObjectRef function, JSObjectR } %} -/************************************************************************************** -function_dispatch_case: This template is used for the function which is overloaded -***************************************************************************************/ +%fragment ("JS_functionwrapper_overload", "templates") +%{ +int ${functionname}(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception, JSValueRef* result) +{ + ${LOCALS} + ${CODE} + *result = jsresult; + return SWIG_OK; + + goto fail; + fail: + return SWIG_TypeError; +} +%} + +/*********************************************************************** + * JS_function_dispatch_case: + * This template is used to create a branch for dispatching + * to an overloaded function. + ***********************************************************************/ %fragment ("JS_function_dispatch_case", "templates") %{if(argc == ${argcount}) { - jsresult = ${functionwrapper}(context, function, thisObject, argc, argv, exception); - } else %} + res = ${functionwrapper}(context, function, thisObject, argc, argv, exception, &jsresult); + if(res == SWIG_OK) { *exception = 0; return jsresult; } + } +%} %fragment ("JS_function_dispatch_case_default", "templates") %{ - { - // TODO: throw JS exception - throw "Invalid function arguments."; - } + SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function ${functionname}."); %} /* Added template for function declaration */ @@ -173,18 +189,16 @@ void _wrap_${classname_mangled}_finalize(JSObjectRef thisObject) JSObjectRef _wrap_create_${classname_mangled}(JSContextRef context, JSObjectRef ctorObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { - JSObjectRef thisObject; + JSObjectRef thisObject = NULL; + // switch all cases by means of series of if-returns. ${DISPATCH_CASES} - { - // TODO: handle illegal arguments - SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for contruction of ${classname_mangled}"); - } - return thisObject; + // default: + SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for contruction of ${classname_mangled}"); fail: - return NULL; + return thisObject; } %} @@ -195,7 +209,9 @@ ctor_dispatch_case: This template is used for the constructor which is overloade %fragment ("JS_ctor_dispatch_case", "templates") %{if(argc == ${argcount}) { thisObject = _wrap_create_${classname_mangled}${overloadext}(context, NULL, argc, argv, exception); - } else %} + if(thisObject != NULL) { *exception=0; return thisObject; } /* reset exception and return */ + } +%} %fragment ("JS_ctordefn", "templates") diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 69c5e4adf..72be9b4f0 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -70,6 +70,8 @@ public: Template& replace(const String *pattern, const String *repl); Template& pretty_print(DOH *doh); + + void operator=(const Template& t); private: @@ -1019,8 +1021,8 @@ int JSCEmitter::enterFunction(Node *n) { /* Initialize DOH for collecting function dispatchers */ bool is_overloaded = GetFlag(n, "sym:overloaded"); - if (is_overloaded && state.function(FUNCTION_DISPATCHERS) == 0) { - state.function(FUNCTION_DISPATCHERS, NewString("")); + if (is_overloaded && state.global(FUNCTION_DISPATCHERS) == 0) { + state.global(FUNCTION_DISPATCHERS, NewString("")); } return SWIG_OK; @@ -1333,6 +1335,7 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); if (is_overloaded) { Append(wrap_name, Getattr(n, "sym:overname")); + t_function = getTemplate("JS_functionwrapper_overload"); } Setattr(n, "wrap:name", wrap_name); state.function(WRAPPER_NAME, wrap_name); @@ -1364,7 +1367,7 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { t_dispatch_case.replace("${functionwrapper}", wrap_name) .replace("${argcount}", argcount); - Append(state.function(FUNCTION_DISPATCHERS), t_dispatch_case.str()); + Append(state.global(FUNCTION_DISPATCHERS), t_dispatch_case.str()); Delete(argcount); } @@ -1382,16 +1385,21 @@ int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { String *wrap_name = Swig_name_wrapper(Getattr(n, "name")); Setattr(n, "wrap:name", wrap_name); + Wrapper_add_local(wrapper, "res", "int res"); Wrapper_add_local(wrapper, "jsresult", "JSValueRef jsresult"); - Append(wrapper->code, state.function(FUNCTION_DISPATCHERS)); + Append(wrapper->code, state.global(FUNCTION_DISPATCHERS)); Append(wrapper->code, getTemplate("JS_function_dispatch_case_default").str()); + t_function.replace("${LOCALS}", wrapper->locals) + .replace("${CODE}", wrapper->code); + + // call this here, to replace all variables t_function.replace("${functionname}", wrap_name) - .replace("${LOCALS}", wrapper->locals) - .replace("${CODE}", wrapper->code) .pretty_print(f_wrappers); + // Delete the state variable + state.global(FUNCTION_DISPATCHERS, 0); DelWrapper(wrapper); return SWIG_OK; @@ -2052,3 +2060,10 @@ Template& Template::pretty_print(DOH *doh) { Wrapper_pretty_print(str(), doh); return *this; } + +void Template::operator=(const Template& t) { + Delete(code); + Delete(templateName); + code = NewString(t.code); + templateName = NewString(t.templateName); +} From 52aef2699700c957015c8ce88c5c75f756ffc86f Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:02:30 +0000 Subject: [PATCH 0107/1048] Add examples check list for batch runs. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13780 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/javascript/check.list | 13 +++++++++++++ Makefile.in | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 Examples/javascript/check.list diff --git a/Examples/javascript/check.list b/Examples/javascript/check.list new file mode 100644 index 000000000..146f1800f --- /dev/null +++ b/Examples/javascript/check.list @@ -0,0 +1,13 @@ +class +constant +enum +exception +functor +namespace +operator +overload +pointer +reference +simple +template +variables diff --git a/Makefile.in b/Makefile.in index adc971455..0a485cd33 100644 --- a/Makefile.in +++ b/Makefile.in @@ -175,7 +175,7 @@ cffi_examples := r_examples :=$(shell sed '/^\#/d' $(srcdir)/Examples/r/check.list) go_examples :=$(shell sed '/^\#/d' $(srcdir)/Examples/go/check.list) d_examples :=$(shell sed '/^\#/d' $(srcdir)/Examples/d/check.list) -javascript_examples:= +javascript_examples:=$(shell sed '/^\#/d' $(srcdir)/Examples/javascript/check.list) # all examples check-%-examples : From cbb5b711ab8d3038f993dc77f6397419cb7c1f7e Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:03:00 +0000 Subject: [PATCH 0108/1048] Fix examples after regressions. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13781 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/javascript/constant/Makefile | 4 +- Examples/javascript/pointer/typemaps.i | 0 Examples/javascript/simple/Makefile | 6 +- .../simple/{example.cpp => example.c} | 10 - Examples/javascript/simple/example.i | 8 - Examples/javascript/variables/Makefile | 6 +- Examples/javascript/variables/example_wrap.c | 2593 +++++++++++++++++ 7 files changed, 2601 insertions(+), 26 deletions(-) create mode 100644 Examples/javascript/pointer/typemaps.i rename Examples/javascript/simple/{example.cpp => example.c} (70%) mode change 100755 => 100644 mode change 100755 => 100644 Examples/javascript/simple/example.i create mode 100644 Examples/javascript/variables/example_wrap.c diff --git a/Examples/javascript/constant/Makefile b/Examples/javascript/constant/Makefile index 1ac61ec6b..bebb1f302 100755 --- a/Examples/javascript/constant/Makefile +++ b/Examples/javascript/constant/Makefile @@ -1,7 +1,7 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript -CXXSRCS = example.cpp +CXXSRCS = JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example @@ -10,7 +10,7 @@ SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean diff --git a/Examples/javascript/pointer/typemaps.i b/Examples/javascript/pointer/typemaps.i new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/javascript/simple/Makefile b/Examples/javascript/simple/Makefile index 1ac61ec6b..4fbfa2802 100755 --- a/Examples/javascript/simple/Makefile +++ b/Examples/javascript/simple/Makefile @@ -1,7 +1,7 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript -CXXSRCS = example.cpp +SRCS = example.c JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example @@ -9,8 +9,8 @@ INTERFACE = example.i SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean diff --git a/Examples/javascript/simple/example.cpp b/Examples/javascript/simple/example.c old mode 100755 new mode 100644 similarity index 70% rename from Examples/javascript/simple/example.cpp rename to Examples/javascript/simple/example.c index e7d3b0f11..1c2af789c --- a/Examples/javascript/simple/example.cpp +++ b/Examples/javascript/simple/example.c @@ -1,9 +1,3 @@ -#include -#include -#include -#include -using namespace std; - /* File : example.c */ /* A global variable */ @@ -22,7 +16,3 @@ int gcd(int x, int y) { } - - - - diff --git a/Examples/javascript/simple/example.i b/Examples/javascript/simple/example.i old mode 100755 new mode 100644 index 7c345964c..24093b9bf --- a/Examples/javascript/simple/example.i +++ b/Examples/javascript/simple/example.i @@ -1,15 +1,7 @@ /* File : example.i */ %module example -%include "std_string.i" - %inline %{ extern int gcd(int x, int y); -extern float gcd(float x, float y); -extern char* helloString(char* s); -extern void delete_helloString(char *newstr); -extern std::string helloString(std::string s); -extern void bar(int x, int y = 3, int z = 4); - extern double Foo; %} diff --git a/Examples/javascript/variables/Makefile b/Examples/javascript/variables/Makefile index 1ac61ec6b..4fbfa2802 100755 --- a/Examples/javascript/variables/Makefile +++ b/Examples/javascript/variables/Makefile @@ -1,7 +1,7 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript -CXXSRCS = example.cpp +SRCS = example.c JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example @@ -9,8 +9,8 @@ INTERFACE = example.i SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean diff --git a/Examples/javascript/variables/example_wrap.c b/Examples/javascript/variables/example_wrap.c new file mode 100644 index 000000000..7fc9567cd --- /dev/null +++ b/Examples/javascript/variables/example_wrap.c @@ -0,0 +1,2593 @@ +/* ---------------------------------------------------------------------------- + * This file was automatically generated by SWIG (http://www.swig.org). + * Version 2.0.6 + * + * 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. + * ----------------------------------------------------------------------------- */ +/* ----------------------------------------------------------------------------- + * 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 + + + +#define SWIG_AsCharPtrAndSize(val, cptr, psize, alloc) SWIG_JSC_AsCharPtrAndSize(context, val, cptr, psize, alloc) +#define SWIG_FromCharPtrAndSize(cptr, size) SWIG_JSC_FromCharPtrAndSize(context, cptr, size) +#define SWIG_FromCharPtr(cptr) SWIG_JSC_FromCharPtr(context, cptr) + + + +#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 + + + +#include +#include +#include +#include +#include +#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 + + + + +#define SWIG_Error(code, msg) SWIG_JSC_exception(context, exception, code, msg) +#define SWIG_exception(code, msg) SWIG_JSC_exception(context, exception, code, msg) +#define SWIG_fail goto fail + +#define SWIG_JSC_FROM_DECL_ARGS(arg1) (JSContextRef context, arg1) +#define SWIG_JSC_FROM_CALL_ARGS(arg1) (context, arg1) +#define SWIG_JSC_AS_DECL_ARGS(arg1, arg2) (JSContextRef context, arg1, arg2) +#define SWIG_JSC_AS_CALL_ARGS(arg1, arg2) (context, arg1, arg2) + + +typedef struct { + bool swigCMemOwn; + void *swigCObject; + swig_type_info *info; +}SWIG_PRV_DATA; + + + +void SWIG_Javascript_Raise(JSContextRef context, JSValueRef *exception, const char* type) { + JSStringRef message = JSStringCreateWithUTF8CString(type); + *exception = JSValueMakeString(context, message); + JSStringRelease(message); +} + +void SWIG_JSC_exception(JSContextRef context, JSValueRef *exception, int code, const char* msg) { + SWIG_Javascript_Raise(context, exception, msg); +} + + + + +JSValueRef _wrap_SwigObject_disown(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + JSValueRef jsresult; + + JSObjectRef obj = JSValueToObject(context, thisObject, NULL); + SWIG_PRV_DATA *cdata = (SWIG_PRV_DATA *) JSObjectGetPrivate(obj); + + cdata->swigCMemOwn = false; + + jsresult = JSValueMakeUndefined(context); + return jsresult; +} + +JSValueRef _wrap_SwigObject_getCPtr(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + JSValueRef jsresult; + long result; + + JSObjectRef obj = JSValueToObject(context, thisObject, NULL); + SWIG_PRV_DATA *cdata = (SWIG_PRV_DATA*) JSObjectGetPrivate(obj); + + result = (long) cdata->swigCObject; + jsresult = JSValueMakeNumber(context, result); + + return jsresult; +} + +JSStaticValue _SwigObject_values[] = { + { + 0, 0, 0, 0 + } +}; + +JSStaticFunction _SwigObject_functions[] = { + { + "disown",_wrap_SwigObject_disown, kJSPropertyAttributeNone + },{ + "getCPtr",_wrap_SwigObject_getCPtr, kJSPropertyAttributeNone + }, + { + 0, 0, 0 + } +}; + +JSClassDefinition _SwigObject_objectDefinition; + +JSClassRef _SwigObject_classRef; + + + +int SWIG_JSC_ConvertInstancePtr(JSContextRef context, JSObjectRef objRef, void** ptr, swig_type_info *info, int flags) { + SWIG_PRV_DATA *cdata = (SWIG_PRV_DATA *) JSObjectGetPrivate(objRef); + if(cdata == NULL) { + return SWIG_ERROR; + } + if(cdata->info != info) { + bool type_valid = false; + swig_cast_info *t = info->cast; + while(t != NULL) { + if(t->type == cdata->info) { + type_valid = true; + break; + } + t = t->next; + } + if(!type_valid) { + return SWIG_TypeError; + } + } + + *ptr = cdata->swigCObject; + + if(flags & SWIG_POINTER_DISOWN) { + cdata->swigCMemOwn = false; + } + + return SWIG_OK; +} + +int SWIG_JSC_ConvertPtr(JSContextRef context, JSValueRef valRef, void** ptr, swig_type_info *info, int flags) { + if(!JSValueIsObject(context, valRef)) { + return SWIG_TypeError; + } + + JSObjectRef objRef = JSValueToObject(context, valRef, NULL); + if(objRef == NULL) { + return SWIG_ERROR; + } + + return SWIG_JSC_ConvertInstancePtr(context, objRef, ptr, info, flags); +} + +JSObjectRef SWIG_JSC_NewPointerObj(JSContextRef context, void *ptr, swig_type_info *info, int flags) { + + JSClassRef classRef; + if(info->clientdata == NULL) { + classRef = _SwigObject_classRef; + } else { + classRef = (JSClassRef) info->clientdata; + } + + JSObjectRef result = JSObjectMake(context, classRef, NULL); + + SWIG_PRV_DATA* cdata = (SWIG_PRV_DATA*) malloc(sizeof(SWIG_PRV_DATA)); + cdata->swigCObject = ptr; + cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; + cdata->info = info; + + JSObjectSetPrivate(result, cdata); + + return result; +} + +#define SWIG_ConvertPtr(obj, ptr, info, flags) SWIG_JSC_ConvertPtr(context, obj, ptr, info, flags) +#define SWIG_NewPointerObj(ptr, info, flags) SWIG_JSC_NewPointerObj(context, ptr, info, flags) + +#define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_JSC_ConvertInstancePtr(context, obj, pptr, type, flags) +#define SWIG_NewInstanceObj(thisvalue, type, flags) SWIG_JSC_NewPointerObj(context, thisvalue, type, flags) + + + +/* -------- TYPES TABLE (BEGIN) -------- */ + +#define SWIGTYPE_p_Point swig_types[0] +#define SWIGTYPE_p_char swig_types[1] +#define SWIGTYPE_p_int 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) -------- */ + + + +#define SWIGVERSION 0x020006 +#define SWIG_VERSION SWIGVERSION + + +#define SWIG_as_voidptr(a) (void *)((const void *)(a)) +#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),(void**)(a)) + + +#include "example.h" + + +extern int ivar; +extern short svar; +extern long lvar; +extern unsigned int uivar; +extern unsigned short usvar; +extern unsigned long ulvar; +extern signed char scvar; +extern unsigned char ucvar; +extern char cvar; +extern float fvar; +extern double dvar; +extern char *strvar; +extern const char cstrvar[]; +extern int *iptrvar; +extern char name[256]; + +extern Point *ptptr; +extern Point pt; + + +#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 SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, double *val) +{ + if(!JSValueIsNumber(context, obj)) { + return SWIG_TypeError; + } + if(val) *val = JSValueToNumber(context, obj, NULL); + + return SWIG_OK; +} + + +#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 SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, long* val) +{ + if (!JSValueIsNumber(context, obj)) { + return SWIG_TypeError; + } + if(val) *val = (long) JSValueToNumber(context, obj, NULL); + + return SWIG_OK; +} + + +SWIGINTERN int +SWIG_AsVal_int SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, int *val) +{ + long v; + int res = SWIG_AsVal_long SWIG_JSC_AS_CALL_ARGS(obj, &v); + if (SWIG_IsOK(res)) { + if ((v < INT_MIN || v > INT_MAX)) { + return SWIG_OverflowError; + } else { + if (val) *val = (int)(v); + } + } + return res; +} + + +SWIGINTERNINLINE JSValueRef + SWIG_From_int SWIG_JSC_FROM_DECL_ARGS(int value) +{ + return JSValueMakeNumber(context, value); +} + + +SWIGINTERN int +SWIG_AsVal_short SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, short *val) +{ + long v; + int res = SWIG_AsVal_long SWIG_JSC_AS_CALL_ARGS(obj, &v); + if (SWIG_IsOK(res)) { + if ((v < SHRT_MIN || v > SHRT_MAX)) { + return SWIG_OverflowError; + } else { + if (val) *val = (short)(v); + } + } + return res; +} + + +SWIGINTERNINLINE JSValueRef + SWIG_From_long SWIG_JSC_FROM_DECL_ARGS(long value) +{ + return JSValueMakeNumber(context, value); +} + + +SWIGINTERNINLINE JSValueRef +SWIG_From_short SWIG_JSC_FROM_DECL_ARGS(short value) +{ + return SWIG_From_long SWIG_JSC_FROM_CALL_ARGS(value); +} + + +SWIGINTERN int +SWIG_AsVal_unsigned_SS_long SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, unsigned long *val) +{ + if(!JSValueIsNumber(context, obj)) { + return SWIG_TypeError; + } + + long longVal = (long) JSValueToNumber(context, obj, NULL); + + if(longVal < 0) { + return SWIG_OverflowError; + } + + if(val) *val = longVal; + + return SWIG_OK; +} + + +SWIGINTERN int +SWIG_AsVal_unsigned_SS_int SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, unsigned int *val) +{ + unsigned long v; + int res = SWIG_AsVal_unsigned_SS_long SWIG_JSC_AS_CALL_ARGS(obj, &v); + if (SWIG_IsOK(res)) { + if ((v > UINT_MAX)) { + return SWIG_OverflowError; + } else { + if (val) *val = (unsigned int)(v); + } + } + return res; +} + + +SWIGINTERNINLINE JSValueRef +SWIG_From_unsigned_SS_long SWIG_JSC_FROM_DECL_ARGS(unsigned long value) +{ + return (value > LONG_MAX) ? + JSValueMakeNumber(context, value) : JSValueMakeNumber(context, (long)(value)); +} + + +SWIGINTERNINLINE JSValueRef +SWIG_From_unsigned_SS_int SWIG_JSC_FROM_DECL_ARGS(unsigned int value) +{ + return SWIG_From_unsigned_SS_long SWIG_JSC_FROM_CALL_ARGS(value); +} + + +SWIGINTERN int +SWIG_AsVal_unsigned_SS_short SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, unsigned short *val) +{ + unsigned long v; + int res = SWIG_AsVal_unsigned_SS_long SWIG_JSC_AS_CALL_ARGS(obj, &v); + if (SWIG_IsOK(res)) { + if ((v > USHRT_MAX)) { + return SWIG_OverflowError; + } else { + if (val) *val = (unsigned short)(v); + } + } + return res; +} + + +SWIGINTERNINLINE JSValueRef +SWIG_From_unsigned_SS_short SWIG_JSC_FROM_DECL_ARGS(unsigned short value) +{ + return SWIG_From_unsigned_SS_long SWIG_JSC_FROM_CALL_ARGS(value); +} + + +SWIGINTERN int +SWIG_AsVal_signed_SS_char SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, signed char *val) +{ + long v; + int res = SWIG_AsVal_long SWIG_JSC_AS_CALL_ARGS(obj, &v); + if (SWIG_IsOK(res)) { + if ((v < SCHAR_MIN || v > SCHAR_MAX)) { + return SWIG_OverflowError; + } else { + if (val) *val = (signed char)(v); + } + } + return res; +} + + +SWIGINTERNINLINE JSValueRef +SWIG_From_signed_SS_char SWIG_JSC_FROM_DECL_ARGS(signed char value) +{ + return SWIG_From_long SWIG_JSC_FROM_CALL_ARGS(value); +} + + +SWIGINTERN int +SWIG_AsVal_unsigned_SS_char SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, unsigned char *val) +{ + unsigned long v; + int res = SWIG_AsVal_unsigned_SS_long SWIG_JSC_AS_CALL_ARGS(obj, &v); + if (SWIG_IsOK(res)) { + if ((v > UCHAR_MAX)) { + return SWIG_OverflowError; + } else { + if (val) *val = (unsigned char)(v); + } + } + return res; +} + + +SWIGINTERNINLINE JSValueRef +SWIG_From_unsigned_SS_char SWIG_JSC_FROM_DECL_ARGS(unsigned char value) +{ + return SWIG_From_unsigned_SS_long SWIG_JSC_FROM_CALL_ARGS(value); +} + + +SWIGINTERN swig_type_info* +SWIG_pchar_descriptor(void) +{ + static int init = 0; + static swig_type_info* info = 0; + if (!init) { + info = SWIG_TypeQuery("_p_char"); + init = 1; + } + return info; +} + + +SWIGINTERN int +SWIG_JSC_AsCharPtrAndSize(JSContextRef context, JSValueRef valRef, char** cptr, size_t* psize, int *alloc) +{ + if(JSValueIsString(context, valRef)) { + JSStringRef js_str = JSValueToStringCopy(context, valRef, NULL); + size_t len = JSStringGetMaximumUTF8CStringSize(js_str); + size_t abs_len = JSStringGetLength(js_str); + char* cstr = (char*) malloc(len * sizeof(char)); + JSStringGetUTF8CString(js_str, cstr, len); + + if(alloc) *alloc = SWIG_NEWOBJ; + if(psize) *psize = abs_len + 1; + if(cptr) *cptr = cstr; + + return SWIG_OK; + } else { + if(JSValueIsObject(context, valRef)) { + JSObjectRef obj = JSValueToObject(context, valRef, NULL); + // try if the object is a wrapped char[] + swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); + if (pchar_descriptor) { + void* vptr = 0; + if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { + if (cptr) *cptr = (char *) vptr; + if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; + if (alloc) *alloc = SWIG_OLDOBJ; + return SWIG_OK; + } + } + return SWIG_TypeError; + } else { + return SWIG_TypeError; + } + } +} + + +SWIGINTERN int +SWIG_JSC_AsCharArray(JSContextRef context, JSValueRef obj, char *val, size_t size) +{ + char* cptr = 0; size_t csize = 0; int alloc = SWIG_OLDOBJ; + int res = SWIG_JSC_AsCharPtrAndSize(context, obj, &cptr, &csize, &alloc); + if (SWIG_IsOK(res)) { + if ((csize == size + 1) && cptr && !(cptr[csize-1])) --csize; + if (csize <= size) { + if (val) { + if (csize) memcpy(val, cptr, csize*sizeof(char)); + if (csize < size) memset(val + csize, 0, (size - csize)*sizeof(char)); + } + if (alloc == SWIG_NEWOBJ) { + free((char*)cptr); + res = SWIG_DelNewMask(res); + } + return res; + } + if (alloc == SWIG_NEWOBJ) free((char*)cptr); + } + return SWIG_TypeError; +} + + + + +SWIGINTERN int +SWIG_AsVal_char SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, char *val) +{ + int res = SWIG_JSC_AsCharArray(context, obj, val, 1); + if (!SWIG_IsOK(res)) { + long v; + res = SWIG_AddCast(SWIG_AsVal_long SWIG_JSC_AS_CALL_ARGS(obj, &v)); + if (SWIG_IsOK(res)) { + if ((CHAR_MIN <= v) && (v <= CHAR_MAX)) { + if (val) *val = (char)(v); + } else { + res = SWIG_OverflowError; + } + } + } + return res; +} + + +SWIGINTERNINLINE JSValueRef +SWIG_JSC_FromCharPtrAndSize(JSContextRef context, const char* carray, size_t size) +{ + if (carray) { + if (size > INT_MAX) { + // TODO: handle extra long strings + //swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); + //return pchar_descriptor ? + // SWIG_InternalNewPointerObj(%const_cast(carray,char *), pchar_descriptor, 0) : SWIG_Py_Void(); + return JSValueMakeUndefined(context); + } else { + JSStringRef jsstring = JSStringCreateWithUTF8CString(carray); + JSValueRef result = JSValueMakeString(context, jsstring); + JSStringRelease(jsstring); + return result; + } + } else { + return JSValueMakeUndefined(context); + } +} + + +SWIGINTERNINLINE JSValueRef +SWIG_From_char SWIG_JSC_FROM_DECL_ARGS(char c) +{ + return SWIG_JSC_FromCharPtrAndSize(context, &c,1); +} + + +SWIGINTERN int +SWIG_AsVal_float SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, float *val) +{ + double v; + int res = SWIG_AsVal_double SWIG_JSC_AS_CALL_ARGS(obj, &v); + if (SWIG_IsOK(res)) { + if ((v < -FLT_MAX || v > FLT_MAX)) { + return SWIG_OverflowError; + } else { + if (val) *val = (float)(v); + } + } + return res; +} + + +SWIGINTERN JSValueRef +SWIG_From_double SWIG_JSC_FROM_DECL_ARGS (double val) +{ + return JSValueMakeNumber(context, val); +} + + +SWIGINTERNINLINE JSValueRef +SWIG_From_float SWIG_JSC_FROM_DECL_ARGS(float value) +{ + return SWIG_From_double SWIG_JSC_FROM_CALL_ARGS(value); +} + + + + + +SWIGINTERNINLINE JSValueRef +SWIG_JSC_FromCharPtr(JSContextRef context, const char *cptr) +{ + return SWIG_JSC_FromCharPtrAndSize(context, cptr, (cptr ? strlen(cptr) : 0)); +} + + +extern int status; +extern char path[256]; + + +extern void print_vars(); +extern int *new_int(int value); +extern Point *new_Point(int x, int y); +extern char *Point_print(Point *p); +extern void pt_print(); + + + + +bool JS_registerClass(JSGlobalContextRef context, JSObjectRef parentObject, + const char* className, + JSClassDefinition* definition) { + + JSStringRef js_className = JSStringCreateWithUTF8CString(className); + JSObjectRef classObject = JSObjectMake(context, JSClassCreate(definition), NULL); + JSObjectSetProperty(context, parentObject, + js_className, classObject, + kJSPropertyAttributeNone, NULL); + JSStringRelease(js_className); + + return true; +} + +bool JS_registerNamespace(JSGlobalContextRef context, + JSObjectRef namespaceObj, JSObjectRef parentNamespace, + const char* name) +{ + JSStringRef js_name = JSStringCreateWithUTF8CString(name); + JSObjectSetProperty(context, parentNamespace, + js_name, namespaceObj, + kJSPropertyAttributeNone, NULL); + JSStringRelease(js_name); + + return true; +} + + +bool JS_registerFunction(JSGlobalContextRef context, JSObjectRef object, + const char* functionName, JSObjectCallAsFunctionCallback callback) +{ + JSStringRef js_functionName = JSStringCreateWithUTF8CString(functionName); + JSObjectSetProperty(context, object, js_functionName, + JSObjectMakeFunctionWithCallback(context, js_functionName, callback), + kJSPropertyAttributeNone, NULL); + JSStringRelease(js_functionName); + return true; +} + +bool JS_veto_set_variable(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + char buffer[256]; + char msg[512]; + int res; + + JSStringGetUTF8CString(propertyName, buffer, 256); + res = sprintf(msg, "Tried to write read-only variable: %s.", buffer); + + if(res<0) { + SWIG_exception(SWIG_ERROR, "Tried to write read-only variable."); + } else { + SWIG_exception(SWIG_ERROR, msg); + } + + return false; +} + +JSValueRef JS_CharPtrToJSValue(JSContextRef context, char* cstr) { + JSValueRef val; + + JSStringRef jsstring = JSStringCreateWithUTF8CString((char*) cstr); + val = JSValueMakeString(context, jsstring); + JSStringRelease(jsstring); + + return val; +} + + +bool _wrap_ivar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + int arg1 ; + int val1 ; + int ecode1 = 0 ; + + ecode1 = SWIG_AsVal_int SWIG_JSC_AS_CALL_ARGS(value, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "ivar_set" "', argument " "1"" of type '" "int""'"); + } + arg1 = (int)(val1); + ivar = arg1; + + + return true; + + goto fail; +fail: + return false; +} + + +JSValueRef _wrap_ivar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + int result; + + result = (int)ivar; + jsresult = SWIG_From_int SWIG_JSC_FROM_CALL_ARGS((int)(result)); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +bool _wrap_svar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + short arg1 ; + short val1 ; + int ecode1 = 0 ; + + ecode1 = SWIG_AsVal_short SWIG_JSC_AS_CALL_ARGS(value, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "svar_set" "', argument " "1"" of type '" "short""'"); + } + arg1 = (short)(val1); + svar = arg1; + + + return true; + + goto fail; +fail: + return false; +} + + +JSValueRef _wrap_svar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + short result; + + result = (short)svar; + jsresult = SWIG_From_short SWIG_JSC_FROM_CALL_ARGS((short)(result)); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +bool _wrap_lvar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + long arg1 ; + long val1 ; + int ecode1 = 0 ; + + ecode1 = SWIG_AsVal_long SWIG_JSC_AS_CALL_ARGS(value, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "lvar_set" "', argument " "1"" of type '" "long""'"); + } + arg1 = (long)(val1); + lvar = arg1; + + + return true; + + goto fail; +fail: + return false; +} + + +JSValueRef _wrap_lvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + long result; + + result = (long)lvar; + jsresult = SWIG_From_long SWIG_JSC_FROM_CALL_ARGS((long)(result)); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +bool _wrap_uivar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + unsigned int arg1 ; + unsigned int val1 ; + int ecode1 = 0 ; + + ecode1 = SWIG_AsVal_unsigned_SS_int SWIG_JSC_AS_CALL_ARGS(value, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "uivar_set" "', argument " "1"" of type '" "unsigned int""'"); + } + arg1 = (unsigned int)(val1); + uivar = arg1; + + + return true; + + goto fail; +fail: + return false; +} + + +JSValueRef _wrap_uivar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + unsigned int result; + + result = (unsigned int)uivar; + jsresult = SWIG_From_unsigned_SS_int SWIG_JSC_FROM_CALL_ARGS((unsigned int)(result)); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +bool _wrap_usvar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + unsigned short arg1 ; + unsigned short val1 ; + int ecode1 = 0 ; + + ecode1 = SWIG_AsVal_unsigned_SS_short SWIG_JSC_AS_CALL_ARGS(value, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "usvar_set" "', argument " "1"" of type '" "unsigned short""'"); + } + arg1 = (unsigned short)(val1); + usvar = arg1; + + + return true; + + goto fail; +fail: + return false; +} + + +JSValueRef _wrap_usvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + unsigned short result; + + result = (unsigned short)usvar; + jsresult = SWIG_From_unsigned_SS_short SWIG_JSC_FROM_CALL_ARGS((unsigned short)(result)); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +bool _wrap_ulvar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + unsigned long arg1 ; + unsigned long val1 ; + int ecode1 = 0 ; + + ecode1 = SWIG_AsVal_unsigned_SS_long SWIG_JSC_AS_CALL_ARGS(value, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "ulvar_set" "', argument " "1"" of type '" "unsigned long""'"); + } + arg1 = (unsigned long)(val1); + ulvar = arg1; + + + return true; + + goto fail; +fail: + return false; +} + + +JSValueRef _wrap_ulvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + unsigned long result; + + result = (unsigned long)ulvar; + jsresult = SWIG_From_unsigned_SS_long SWIG_JSC_FROM_CALL_ARGS((unsigned long)(result)); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +bool _wrap_scvar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + signed char arg1 ; + signed char val1 ; + int ecode1 = 0 ; + + ecode1 = SWIG_AsVal_signed_SS_char SWIG_JSC_AS_CALL_ARGS(value, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "scvar_set" "', argument " "1"" of type '" "signed char""'"); + } + arg1 = (signed char)(val1); + scvar = arg1; + + + return true; + + goto fail; +fail: + return false; +} + + +JSValueRef _wrap_scvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + signed char result; + + result = (signed char)scvar; + jsresult = SWIG_From_signed_SS_char SWIG_JSC_FROM_CALL_ARGS((signed char)(result)); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +bool _wrap_ucvar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + unsigned char arg1 ; + unsigned char val1 ; + int ecode1 = 0 ; + + ecode1 = SWIG_AsVal_unsigned_SS_char SWIG_JSC_AS_CALL_ARGS(value, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "ucvar_set" "', argument " "1"" of type '" "unsigned char""'"); + } + arg1 = (unsigned char)(val1); + ucvar = arg1; + + + return true; + + goto fail; +fail: + return false; +} + + +JSValueRef _wrap_ucvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + unsigned char result; + + result = (unsigned char)ucvar; + jsresult = SWIG_From_unsigned_SS_char SWIG_JSC_FROM_CALL_ARGS((unsigned char)(result)); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +bool _wrap_cvar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + char arg1 ; + char val1 ; + int ecode1 = 0 ; + + ecode1 = SWIG_AsVal_char SWIG_JSC_AS_CALL_ARGS(value, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "cvar_set" "', argument " "1"" of type '" "char""'"); + } + arg1 = (char)(val1); + cvar = arg1; + + + return true; + + goto fail; +fail: + return false; +} + + +JSValueRef _wrap_cvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + char result; + + result = (char)cvar; + jsresult = SWIG_From_char SWIG_JSC_FROM_CALL_ARGS((char)(result)); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +bool _wrap_fvar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + float arg1 ; + float val1 ; + int ecode1 = 0 ; + + ecode1 = SWIG_AsVal_float SWIG_JSC_AS_CALL_ARGS(value, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "fvar_set" "', argument " "1"" of type '" "float""'"); + } + arg1 = (float)(val1); + fvar = arg1; + + + return true; + + goto fail; +fail: + return false; +} + + +JSValueRef _wrap_fvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + float result; + + result = (float)fvar; + jsresult = SWIG_From_float SWIG_JSC_FROM_CALL_ARGS((float)(result)); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +bool _wrap_dvar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + double arg1 ; + double val1 ; + int ecode1 = 0 ; + + ecode1 = SWIG_AsVal_double SWIG_JSC_AS_CALL_ARGS(value, &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "dvar_set" "', argument " "1"" of type '" "double""'"); + } + arg1 = (double)(val1); + dvar = arg1; + + + return true; + + goto fail; +fail: + return false; +} + + +JSValueRef _wrap_dvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + double result; + + result = (double)dvar; + jsresult = SWIG_From_double SWIG_JSC_FROM_CALL_ARGS((double)(result)); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +bool _wrap_strvar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + char *arg1 = (char *) 0 ; + int res1 ; + char *buf1 = 0 ; + int alloc1 = 0 ; + + res1 = SWIG_JSC_AsCharPtrAndSize(context, value, &buf1, NULL, &alloc1); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "strvar_set" "', argument " "1"" of type '" "char *""'"); + } + arg1 = (char *)(buf1); + if (strvar) free((char*)strvar); + if (arg1) { + size_t size = strlen((const char *)((const char *)(arg1))) + 1; + strvar = (char *)(char *)memcpy((char *)malloc((size)*sizeof(char)), arg1, sizeof(char)*(size)); + } else { + strvar = 0; + } + + + return true; + + goto fail; +fail: + return false; +} + + +JSValueRef _wrap_strvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + char *result = 0 ; + + result = (char *)strvar; + jsresult = SWIG_FromCharPtr((const char *)result); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +JSValueRef _wrap_cstrvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + char *result = 0 ; + + result = (char *)(char *)cstrvar; + jsresult = SWIG_FromCharPtr((const char *)result); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +bool _wrap_iptrvar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + int *arg1 = (int *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + + res1 = SWIG_ConvertPtr(value, &argp1,SWIGTYPE_p_int, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "iptrvar_set" "', argument " "1"" of type '" "int *""'"); + } + arg1 = (int *)(argp1); + iptrvar = arg1; + + + return true; + + goto fail; +fail: + return false; +} + + +JSValueRef _wrap_iptrvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + int *result = 0 ; + + result = (int *)iptrvar; + jsresult = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_int, 0 | 0 ); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +bool _wrap_name_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + char *arg1 ; + char temp1[256] ; + int res1 ; + + res1 = SWIG_JSC_AsCharArray(context, value, temp1, 256); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "name_set" "', argument " "1"" of type '" "char [256]""'"); + } + arg1 = (char *)(temp1); + if (arg1) memcpy(name,arg1,256*sizeof(char)); + else memset(name,0,256*sizeof(char)); + + + return true; + + goto fail; +fail: + return false; +} + + +JSValueRef _wrap_name_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + char *result = 0 ; + + result = (char *)(char *)name; + { + size_t size = 256; + + while (size && (result[size - 1] == '\0')) --size; + + jsresult = SWIG_FromCharPtrAndSize(result, size); + } + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +bool _wrap_ptptr_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + Point *arg1 = (Point *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + + res1 = SWIG_ConvertPtr(value, &argp1,SWIGTYPE_p_Point, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ptptr_set" "', argument " "1"" of type '" "Point *""'"); + } + arg1 = (Point *)(argp1); + ptptr = arg1; + + + return true; + + goto fail; +fail: + return false; +} + + +JSValueRef _wrap_ptptr_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + Point *result = 0 ; + + result = (Point *)ptptr; + jsresult = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Point, 0 | 0 ); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +bool _wrap_pt_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + Point arg1 ; + void *argp1 ; + int res1 = 0 ; + + { + res1 = SWIG_ConvertPtr(value, &argp1, SWIGTYPE_p_Point, 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pt_set" "', argument " "1"" of type '" "Point""'"); + } + if (!argp1) { + SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "pt_set" "', argument " "1"" of type '" "Point""'"); + } else { + arg1 = *((Point *)(argp1)); + } + } + pt = arg1; + + + return true; + + goto fail; +fail: + return false; +} + + +JSValueRef _wrap_pt_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + Point result; + + result = pt; + jsresult = SWIG_NewPointerObj((Point *)memcpy((Point *)malloc(sizeof(Point)),&result,sizeof(Point)), SWIGTYPE_p_Point, SWIG_POINTER_OWN | 0 ); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +JSValueRef _wrap_status_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + int result; + + result = (int)status; + jsresult = SWIG_From_int SWIG_JSC_FROM_CALL_ARGS((int)(result)); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +JSValueRef _wrap_path_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + char *result = 0 ; + + result = (char *)(char *)path; + { + size_t size = 256; + + while (size && (result[size - 1] == '\0')) --size; + + jsresult = SWIG_FromCharPtrAndSize(result, size); + } + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +JSValueRef _wrap_print_vars(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + JSValueRef jsresult; + + print_vars(); + jsresult = JSValueMakeUndefined(context); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +JSValueRef _wrap_new_int(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + int arg1 ; + int val1 ; + int ecode1 = 0 ; + JSValueRef jsresult; + int *result = 0 ; + + ecode1 = SWIG_AsVal_int SWIG_JSC_AS_CALL_ARGS(argv[0], &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "new_int" "', argument " "1"" of type '" "int""'"); + } + arg1 = (int)(val1); + result = (int *)new_int(arg1); + jsresult = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_int, 0 | 0 ); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +JSValueRef _wrap_new_Point(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + int arg1 ; + int arg2 ; + int val1 ; + int ecode1 = 0 ; + int val2 ; + int ecode2 = 0 ; + JSValueRef jsresult; + Point *result = 0 ; + + ecode1 = SWIG_AsVal_int SWIG_JSC_AS_CALL_ARGS(argv[0], &val1); + if (!SWIG_IsOK(ecode1)) { + SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "new_Point" "', argument " "1"" of type '" "int""'"); + } + arg1 = (int)(val1); + ecode2 = SWIG_AsVal_int SWIG_JSC_AS_CALL_ARGS(argv[1], &val2); + if (!SWIG_IsOK(ecode2)) { + SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "new_Point" "', argument " "2"" of type '" "int""'"); + } + arg2 = (int)(val2); + result = (Point *)new_Point(arg1,arg2); + jsresult = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Point, 0 | 0 ); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +JSValueRef _wrap_Point_print(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + Point *arg1 = (Point *) 0 ; + void *argp1 = 0 ; + int res1 = 0 ; + JSValueRef jsresult; + char *result = 0 ; + + res1 = SWIG_ConvertPtr(argv[0], &argp1,SWIGTYPE_p_Point, 0 | 0 ); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Point_print" "', argument " "1"" of type '" "Point *""'"); + } + arg1 = (Point *)(argp1); + result = (char *)Point_print(arg1); + jsresult = SWIG_FromCharPtr((const char *)result); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +JSValueRef _wrap_pt_print(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + JSValueRef jsresult; + + pt_print(); + jsresult = JSValueMakeUndefined(context); + + return jsresult; + + goto fail; +fail: + return NULL; +} + + +/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ + +static swig_type_info _swigt__p_Point = {"_p_Point", "Point *", 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_int = {"_p_int", "int *", 0, 0, (void*)0, 0}; + +static swig_type_info *swig_type_initial[] = { + &_swigt__p_Point, + &_swigt__p_char, + &_swigt__p_int, +}; + +static swig_cast_info _swigc__p_Point[] = { {&_swigt__p_Point, 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_int[] = { {&_swigt__p_int, 0, 0, 0},{0, 0, 0, 0}}; + +static swig_cast_info *swig_cast_initial[] = { + _swigc__p_Point, + _swigc__p_char, + _swigc__p_int, +}; + + +/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ + + + +JSStaticValue example_values[] = { + { + "ivar",_wrap_ivar_get, _wrap_ivar_set,kJSPropertyAttributeNone + },{ + "svar",_wrap_svar_get, _wrap_svar_set,kJSPropertyAttributeNone + },{ + "lvar",_wrap_lvar_get, _wrap_lvar_set,kJSPropertyAttributeNone + },{ + "uivar",_wrap_uivar_get, _wrap_uivar_set,kJSPropertyAttributeNone + },{ + "usvar",_wrap_usvar_get, _wrap_usvar_set,kJSPropertyAttributeNone + },{ + "ulvar",_wrap_ulvar_get, _wrap_ulvar_set,kJSPropertyAttributeNone + },{ + "scvar",_wrap_scvar_get, _wrap_scvar_set,kJSPropertyAttributeNone + },{ + "ucvar",_wrap_ucvar_get, _wrap_ucvar_set,kJSPropertyAttributeNone + },{ + "cvar",_wrap_cvar_get, _wrap_cvar_set,kJSPropertyAttributeNone + },{ + "fvar",_wrap_fvar_get, _wrap_fvar_set,kJSPropertyAttributeNone + },{ + "dvar",_wrap_dvar_get, _wrap_dvar_set,kJSPropertyAttributeNone + },{ + "strvar",_wrap_strvar_get, _wrap_strvar_set,kJSPropertyAttributeNone + },{ + "cstrvar",_wrap_cstrvar_get, JS_veto_set_variable,kJSPropertyAttributeNone + },{ + "iptrvar",_wrap_iptrvar_get, _wrap_iptrvar_set,kJSPropertyAttributeNone + },{ + "name",_wrap_name_get, _wrap_name_set,kJSPropertyAttributeNone + },{ + "ptptr",_wrap_ptptr_get, _wrap_ptptr_set,kJSPropertyAttributeNone + },{ + "pt",_wrap_pt_get, _wrap_pt_set,kJSPropertyAttributeNone + },{ + "status",_wrap_status_get, JS_veto_set_variable,kJSPropertyAttributeNone + },{ + "path",_wrap_path_get, JS_veto_set_variable,kJSPropertyAttributeNone + }, + { + 0, 0, 0, 0 + } +}; + +JSStaticFunction example_functions[] = { + { + "print_vars",_wrap_print_vars, kJSPropertyAttributeNone + },{ + "new_int",_wrap_new_int, kJSPropertyAttributeNone + },{ + "new_Point",_wrap_new_Point, kJSPropertyAttributeNone + },{ + "Point_print",_wrap_Point_print, kJSPropertyAttributeNone + },{ + "pt_print",_wrap_pt_print, kJSPropertyAttributeNone + }, + { + 0, 0, 0 + } +}; + +JSClassDefinition example_classDefinition; + + +SWIGRUNTIME void +SWIG_JSC_SetModule(swig_module_info *swig_module) {} + +SWIGRUNTIME swig_module_info * +SWIG_JSC_GetModule(void) { + return 0; +} + +#define SWIG_GetModule(clientdata) SWIG_JSC_GetModule() +#define SWIG_SetModule(clientdata, pointer) SWIG_JSC_SetModule(pointer) + + +/* ----------------------------------------------------------------------------- + * 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 + + bool example_initialize(JSGlobalContextRef context) { + SWIG_InitializeModule(0); + + JSObjectRef global_object = JSContextGetGlobalObject(context); + + /* Initialize the base swig type object */ + _SwigObject_objectDefinition.staticFunctions = _SwigObject_functions; + _SwigObject_objectDefinition.staticValues = _SwigObject_values; + _SwigObject_classRef = JSClassCreate(&_SwigObject_objectDefinition); + + /* Create objects for namespaces */ + example_classDefinition.staticFunctions = example_functions; + example_classDefinition.staticValues = example_values; + JSObjectRef example_object = JSObjectMake(context, JSClassCreate(&example_classDefinition), NULL); + + + /* Create classes */ + + + /* Register namespaces */ + + JS_registerNamespace(context, example_object, global_object, "example"); + + return true; + } + +#ifdef __cplusplus +} +#endif + + From 672208d8d20eef3214bf4f48fce009eb3f053a81 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:03:17 +0000 Subject: [PATCH 0109/1048] Adapt overload example to reflect changes in module. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13782 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/javascript/overload/example.i | 4 ---- Examples/javascript/overload/runme.js | 6 +++--- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/Examples/javascript/overload/example.i b/Examples/javascript/overload/example.i index c4f652c0a..b86689f8a 100644 --- a/Examples/javascript/overload/example.i +++ b/Examples/javascript/overload/example.i @@ -11,10 +11,6 @@ for dispatching. To solve the problem one has to rename such conflicting methods. */ - -%rename(f_string) f(const char* s); -%rename(f_bool) f(bool val); -%rename(f_long) f(long val); %rename(f_double) f(double val); %include "example.h" diff --git a/Examples/javascript/overload/runme.js b/Examples/javascript/overload/runme.js index c6d4ef68d..6b822f107 100644 --- a/Examples/javascript/overload/runme.js +++ b/Examples/javascript/overload/runme.js @@ -1,7 +1,7 @@ example.f(); example.f(1); example.f(1, 2); -example.f_string("bla"); -example.f_bool(false); -example.f_long(11111111111); +example.f("bla"); +example.f(false); +example.f(11111111111); example.f_double(1.0); From 10dc758cadc7e0f27eee867a071ba199678e8a0a Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:03:42 +0000 Subject: [PATCH 0110/1048] Refactored javascript shell implementation to support JSC and v8. Also changed configuration in examples Makefile.in to allow switching modes. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13783 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/Makefile.in | 19 ++- Tools/javascript/javascript.cxx | 276 +++++++++----------------------- Tools/javascript/js_shell.cxx | 95 +++++++++++ Tools/javascript/js_shell.h | 49 ++++++ Tools/javascript/jsc_shell.cxx | 171 ++++++++++++++++++++ Tools/javascript/v8_shell.cxx | 222 +++++++++++++++++++++++++ 6 files changed, 632 insertions(+), 200 deletions(-) create mode 100644 Tools/javascript/js_shell.cxx create mode 100644 Tools/javascript/js_shell.h create mode 100644 Tools/javascript/jsc_shell.cxx create mode 100755 Tools/javascript/v8_shell.cxx diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 4f20b83b8..027ce795e 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -525,7 +525,7 @@ ifeq (,$(V8)) JS_DLNK = @JSCOREDYNAMICLINKING@ else JS_INCLUDE = @JSV8INC@ - JS_DLNK = @JSCOREDYNAMICLINKING@ + JS_DLNK = @JSV8DYNAMICLINKING@ endif ifeq (,$(V8)) @@ -542,6 +542,19 @@ JSCXXSHARED = @JSCORECXXSHARED@ JSCFLAGS = @JSCORECFLAGS@ JSCXXFLAGS = @JSCXXFLAGS@ +JSEXE_SRC_DIR = $(TOP)/../Tools/javascript +JSEXE_SRC = $(JSEXE_SRC_DIR)/javascript.cxx $(JSEXE_SRC_DIR)/js_shell.cxx +JSEXE = $(TOP)/../Tools/javascript/javascript +ifeq (,$(V8)) + JSEXE_SRC = $(JSEXE_SRC_DIR)/javascript.cxx $(JSEXE_SRC_DIR)/js_shell.cxx $(JSEXE_SRC_DIR)/jsc_shell.cxx + JSEXE_OPTS = -jsc + JSEXE_FLAGS = -DUSE_JSC +else + JSEXE_SRC = $(JSEXE_SRC_DIR)/javascript.cxx $(JSEXE_SRC_DIR)/js_shell.cxx $(JSEXE_SRC_DIR)/v8_shell.cxx + JSEXE_OPTS = -v8 + JSEXE_FLAG = -DUSE_V8 +endif + # ---------------------------------------------------------------- # Build a javascript dynamically loadable module (C) # ---------------------------------------------------------------- @@ -564,14 +577,14 @@ javascript_cpp: $(SRCS) # Compile a javascript executable # ---------------------------------------------------------------- javascript_exe: $(SRCS) - $(CXX) $(CXXFLAGS) $(JS_INCLUDE) $(JSCXXSRCS) $(LIBS) $(JS_DLNK) -o $(JAVASCRIPT_EXE) + $(CXX) $(CXXFLAGS) $(JSEXE_FLAGS) $(JS_INCLUDE) $(LIBS) $(JSEXE_SRC) $(JS_DLNK) -o $(JSEXE) # ---------------------------------------------------------------- # Run the Compile a javascript executable # ---------------------------------------------------------------- javascript_run: $(SRCS) - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(JAVASCRIPT_EXE) -l $(TARGET) $(JS_SCRIPT) + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(JSEXE) $(JSEXE_OPTS) -l $(TARGET) $(JS_SCRIPT) # ----------------------------------------------------------------- # Cleaning the javascript examples diff --git a/Tools/javascript/javascript.cxx b/Tools/javascript/javascript.cxx index 9e7dd2809..798158ff0 100644 --- a/Tools/javascript/javascript.cxx +++ b/Tools/javascript/javascript.cxx @@ -1,217 +1,99 @@ - -#include #include +#include #include - #include #include #include -#include +#include "js_shell.h" -#include +#ifdef USE_JSC +extern JSShell* create_jsc_shell(); +#endif -using namespace std; - -static JSValueRef jsc_printstring(JSContextRef context,JSObjectRef object, JSObjectRef globalobj, size_t argc, const JSValueRef args[], JSValueRef* ex); -static char* jsccreateStringWithContentsOfFile(const char* fileName); -bool jsc_registerFunction(JSGlobalContextRef context, JSObjectRef object, const char* FunctionName,JSObjectCallAsFunctionCallback cbFunction); - -typedef void* HANDLE; -typedef int (*JSCIntializer)(JSGlobalContextRef context); - -void jsc_printError(JSContextRef, JSValueRef, const std::string&); +#ifdef USE_V8 +extern JSShell* create_v8_shell(); +#endif void print_usage() { - std::cout << "javascript [-l module] " << std::endl; + std::cout << "javascript [-i] [-jsc|-v8] [-l module] " << std::endl; } int main(int argc, char* argv[]) { - std::string scriptPath; - - std::vector module_names; - - std::vector loaded_modules; - std::vector module_initializers; + std::string scriptPath = ""; + std::vector module_names; - for (int idx = 1; idx < argc; ++idx) { - if(strcmp(argv[idx], "-l") == 0) { - idx++; - if(idx > argc) { - print_usage(); - exit(-1); - } - std::string module_name(argv[idx]); - module_names.push_back(module_name); - } else { - scriptPath = argv[idx]; + bool interactive = false; + JSShell* shell = 0; + + for (int idx = 1; idx < argc; ++idx) { + if(strcmp(argv[idx], "-l") == 0) { + idx++; + if(idx > argc) { + print_usage(); + exit(-1); } + std::string module_name(argv[idx]); + module_names.push_back(module_name); + } else if(strcmp(argv[idx], "-v8") == 0) { +#ifdef USE_V8 + shell = create_v8_shell(); +#else + std::cerr << "V8 support is not enabled" << std::endl; + exit(-1); +#endif + } else if(strcmp(argv[idx], "-jsc") == 0) { +#ifdef USE_JSC + shell = create_jsc_shell(); +#else + std::cerr << "JSC support is not enabled" << std::endl; + exit(-1); +#endif + } else if(strcmp(argv[idx], "-i") == 0) { + interactive = true; + } else { + scriptPath = argv[idx]; } - - for(std::vector::iterator it = module_names.begin(); - it != module_names.end(); ++it) { - std::string module_name = *it; - std::string lib_name = std::string("lib").append(module_name).append(".so"); - - HANDLE handle = dlopen(lib_name.c_str(), RTLD_LAZY); - if(handle == 0) { - std::cout << "Could not load library " << lib_name << ":" - << std::endl << dlerror() << std::endl; - continue; - } - - std::string symname; - symname.append(module_name).append("_initialize"); - - JSCIntializer init_function = reinterpret_cast((long) dlsym(handle, symname.c_str())); - if(init_function == 0) { - std::cout << "Could not find initializer function in module " << module_name << std::endl; - dlclose(handle); - continue; - } - - loaded_modules.push_back(handle); - module_initializers.push_back(init_function); - } - - static int failed; - - JSGlobalContextRef context = JSGlobalContextCreate(NULL); - JSObjectRef globalObject = JSContextGetGlobalObject(context); - - jsc_registerFunction(context, globalObject, "print", jsc_printstring); // Utility print function - - // Call module initializers - for(std::vector::iterator it = module_initializers.begin(); - it != module_initializers.end(); ++it) { - JSCIntializer init_function = *it; - init_function(context); - } - - // Evaluate the javascript - char* scriptContent = jsccreateStringWithContentsOfFile(scriptPath.c_str()); - JSStringRef jsScript; - - if(!scriptContent) { - printf("FAIL: runme script could not be loaded.\n"); - failed = 1; - } - else { - JSValueRef ex; - jsScript = JSStringCreateWithUTF8CString(scriptContent); - JSValueRef jsResult = JSEvaluateScript(context, jsScript, 0, 0, 0, &ex); - - if (!jsResult && ex) { - jsc_printError(context, ex, scriptPath); - failed = 1; - } - } - - if (scriptContent != NULL) { - free(scriptContent); - } - - JSStringRelease(jsScript); - - JSGlobalContextRelease(context); - globalObject = 0; - - for(std::vector::iterator it = loaded_modules.begin(); - it != loaded_modules.end(); ++it) { - HANDLE handle = *it; - dlclose(handle); - } - - if (failed) { - printf("FAIL: Some tests failed.\n"); - return 1; - } -} - -static JSValueRef jsc_printstring(JSContextRef context,JSObjectRef object, JSObjectRef globalobj, size_t argc, const JSValueRef args[], JSValueRef* ex) -{ - if (argc > 0) - { - JSStringRef string = JSValueToStringCopy(context, args[0], NULL); - size_t numChars = JSStringGetMaximumUTF8CStringSize(string); - char *stringUTF8 = new char[numChars]; - JSStringGetUTF8CString(string, stringUTF8, numChars); - printf("%s\n", stringUTF8); - - delete[] stringUTF8; - } - - return JSValueMakeUndefined(context); -} - -static char* jsccreateStringWithContentsOfFile(const char* fileName) -{ - char* buffer; - - size_t buffer_size = 0; - size_t buffer_capacity = 1024; - buffer = (char*)malloc(buffer_capacity); - - FILE* f = fopen(fileName, "r"); - if (!f) - { - fprintf(stderr, "Could not open file: %s\n", fileName); - return 0; - } - - while (!feof(f) && !ferror(f)) - { - buffer_size += fread(buffer + buffer_size, 1, buffer_capacity - buffer_size, f); - if (buffer_size == buffer_capacity) - { - // guarantees space for trailing '\0' - buffer_capacity *= 2; - buffer = (char*)realloc(buffer, buffer_capacity); - } - } - fclose(f); - buffer[buffer_size] = '\0'; - - return buffer; -} - -bool jsc_registerFunction(JSGlobalContextRef context, JSObjectRef object, - const char* functionName, JSObjectCallAsFunctionCallback callback) -{ - JSStringRef js_functionName = JSStringCreateWithUTF8CString(functionName); - JSObjectSetProperty(context, object, js_functionName, - JSObjectMakeFunctionWithCallback(context, js_functionName, callback), - kJSPropertyAttributeNone, NULL); - JSStringRelease(js_functionName); - return true; -} - -void jsc_printError(JSContextRef ctx, JSValueRef err, const std::string& sourceUrl) -{ - char *buffer; - - JSStringRef string = JSValueToStringCopy(ctx, err, 0); - size_t length = JSStringGetLength(string); - - buffer = (char*) malloc(length+1); - JSStringGetUTF8CString(string, buffer, length+1); - std::string errMsg(buffer); - JSStringRelease(string); - free(buffer); - - JSObjectRef errObj = JSValueToObject(ctx, err, 0); - - if(errObj == 0) { - return; } - // Note: usually you would also retrieve the property "sourceURL" - // though, it happened that this was always "" - JSStringRef lineKey = JSStringCreateWithUTF8CString("line"); - JSValueRef jsLine = JSObjectGetProperty(ctx, errObj, lineKey, 0); - int line = (int) JSValueToNumber(ctx, jsLine, 0); - JSStringRelease(lineKey); + + if (shell == 0) { +#ifdef USE_JSC + shell = create_jsc_shell(); +#else + std::cerr << "JSC support is not enabled" << std::endl; + exit(-1); +#endif + } + + bool failed = false; + for(std::vector::iterator it = module_names.begin(); + it != module_names.end(); ++it) { + std::string module_name = *it; - std::cerr << sourceUrl << ":" << line << ":" << errMsg << std::endl; - + bool success = shell->ImportModule(module_name); + failed |= !success; + } + + if (failed) { + delete shell; + printf("FAIL: Some modules could not be loaded.\n"); + return -1; + } + + if(interactive) { + failed = !(shell->RunShell()); + } else { + failed = !(shell->RunScript(scriptPath)); + } + + if (failed) { + delete shell; + printf("FAIL: Error during execution of script.\n"); + return 1; + } + + delete shell; + + return 0; } diff --git a/Tools/javascript/js_shell.cxx b/Tools/javascript/js_shell.cxx new file mode 100644 index 000000000..b2b8672a6 --- /dev/null +++ b/Tools/javascript/js_shell.cxx @@ -0,0 +1,95 @@ +#include "js_shell.h" + +#include +#include +#include +#include + +#ifdef __GNUC__ +#include +#define LOAD_LIBRARY(name) dlopen(name, RTLD_LAZY) +#define CLOSE_LIBRARY(handle) dlclose(handle) +#define LIBRARY_ERROR dlerror +#define LIBRARYFILE(name) std::string("lib").append(name).append(".so") +#else +#error "implement dll loading" +#endif + +JSShell::~JSShell() { + + for(std::vector::iterator it = loaded_modules.begin(); + it != loaded_modules.end(); ++it) { + HANDLE handle = *it; + CLOSE_LIBRARY(handle); + } + +} + +bool JSShell::ImportModule(const std::string& name) { + + std::string lib_name = LIBRARYFILE(name); + + HANDLE handle = LOAD_LIBRARY(lib_name.c_str()); + if(handle == 0) { + std::cout << "Could not load library " << lib_name << ":" + << std::endl << LIBRARY_ERROR() << std::endl; + return false; + } + + if(!RegisterModule(handle, name)) { + std::cout << "Could not find initializer function in " << lib_name << std::endl; + CLOSE_LIBRARY(handle); + return false; + } + + loaded_modules.push_back(handle); + + return true; +} + +bool JSShell::RunScript(const std::string& scriptPath) { + std::string source = ReadFile(scriptPath); + if(!InitializeEngine()) return false; + + if(!ExecuteScript(source, scriptPath)) { + return false; + } + + return DisposeEngine(); +} + +bool JSShell::RunShell() { + + if(!InitializeEngine()) return false; + + static const int kBufferSize = 1024; + while (true) { + char buffer[kBufferSize]; + printf("> "); + char* str = fgets(buffer, kBufferSize, stdin); + if (str == NULL) break; + std::string source(str); + ExecuteScript(source, "(shell)"); + } + printf("\n"); +} + +std::string JSShell::ReadFile(const std::string& fileName) +{ + std::string script; + + std::ifstream file(fileName.c_str()); + if (file.is_open()) { + while ( file.good() ) { + std::string line; + getline(file, line); + script.append(line); + script.append("\n"); + } + file.close(); + } else { + std::cout << "Unable to open file " << fileName << "." << std::endl; + } + + return script; +} diff --git a/Tools/javascript/js_shell.h b/Tools/javascript/js_shell.h new file mode 100644 index 000000000..96535a4c0 --- /dev/null +++ b/Tools/javascript/js_shell.h @@ -0,0 +1,49 @@ +#ifndef JS_SHELL_H +#define JS_SHELL_H + +#include +#include + +typedef void* HANDLE; + +class JSShell { + +public: + enum Engine { + JSC, + V8 + }; + +public: + + JSShell() {} + + virtual ~JSShell(); + + bool ImportModule(const std::string& name); + + virtual bool RunScript(const std::string& scriptPath); + + virtual bool RunShell(); + +protected: + + virtual bool RegisterModule(HANDLE library, const std::string& module_name) = 0; + + virtual bool InitializeEngine() = 0; + + virtual bool ExecuteScript(const std::string& source, const std::string& name) = 0; + + virtual bool DisposeEngine() = 0; + + static std::string ReadFile(const std::string& fileName); + +protected: + + std::vector loaded_modules; + +}; + +typedef JSShell* (*JSShellFactory)(); + +#endif // JS_SHELL_H diff --git a/Tools/javascript/jsc_shell.cxx b/Tools/javascript/jsc_shell.cxx new file mode 100644 index 000000000..3fa704440 --- /dev/null +++ b/Tools/javascript/jsc_shell.cxx @@ -0,0 +1,171 @@ +#include + +#include "js_shell.h" + +#include +#include + +#ifdef __GNUC__ +#include +#define LOAD_SYMBOL(handle, name) dlsym(handle, name) +#else +#error "implement dll loading" +#endif + +JSValueRef JSCShell_Print(JSContextRef context, JSObjectRef object, + JSObjectRef globalobj, size_t argc, + const JSValueRef args[], JSValueRef* ex); + +class JSCShell: public JSShell { + +typedef int (*JSCIntializer)(JSGlobalContextRef context); + +public: + + JSCShell() {}; + + virtual ~JSCShell(); + +protected: + + virtual bool RegisterModule(HANDLE library, const std::string& module_name); + + virtual bool InitializeEngine(); + + virtual bool ExecuteScript(const std::string& source, const std::string& name); + + virtual bool DisposeEngine(); + +private: + + //static JSValueRef Print(JSContextRef context,JSObjectRef object, JSObjectRef globalobj, size_t argc, const JSValueRef args[], JSValueRef* ex); + + static bool RegisterFunction(JSGlobalContextRef context, JSObjectRef object, const char* functionName, JSObjectCallAsFunctionCallback cbFunction); + + static void PrintError(JSContextRef, JSValueRef, const std::string&); + +private: + + std::vector module_initializers; + + JSGlobalContextRef context; +}; + +using namespace std; + +JSCShell::~JSCShell() { + if(context != 0) { + JSGlobalContextRelease(context); + context = 0; + } +} + +bool JSCShell::RegisterModule(HANDLE library, const std::string& module_name) { + std::string symname = std::string(module_name).append("_initialize"); + + JSCIntializer init_function = reinterpret_cast((long) LOAD_SYMBOL(library, symname.c_str())); + if(init_function == 0) return false; + + module_initializers.push_back(init_function); + return true; +} + +bool JSCShell::InitializeEngine() { + if(context != 0) { + JSGlobalContextRelease(context); + context = 0; + } + // TODO: check for initialization errors + context = JSGlobalContextCreate(NULL); + if(context == 0) return false; + JSObjectRef globalObject = JSContextGetGlobalObject(context); + JSCShell::RegisterFunction(context, globalObject, "print", JSCShell_Print); + // Call module initializers + for(std::vector::iterator it = module_initializers.begin(); + it != module_initializers.end(); ++it) { + JSCIntializer init_function = *it; + if(!init_function(context)) { + return false; + } + } + return true; +} + +bool JSCShell::ExecuteScript(const std::string& source, const std::string& name) { + JSStringRef jsScript; + JSValueRef ex; + jsScript = JSStringCreateWithUTF8CString(source.c_str()); + JSValueRef jsResult = JSEvaluateScript(context, jsScript, 0, 0, 0, &ex); + JSStringRelease(jsScript); + if (jsResult == NULL && ex != NULL) { + JSCShell::PrintError(context, ex, name); + return false; + } + return true; +} + +bool JSCShell::DisposeEngine() { + JSGlobalContextRelease(context); + context = 0; + return true; +} + +JSValueRef JSCShell_Print(JSContextRef context, JSObjectRef object, + JSObjectRef globalobj, size_t argc, + const JSValueRef args[], JSValueRef* ex) { + if (argc > 0) + { + JSStringRef string = JSValueToStringCopy(context, args[0], NULL); + size_t numChars = JSStringGetMaximumUTF8CStringSize(string); + char *stringUTF8 = new char[numChars]; + JSStringGetUTF8CString(string, stringUTF8, numChars); + printf("%s\n", stringUTF8); + + delete[] stringUTF8; + } + + return JSValueMakeUndefined(context); +} + +bool JSCShell::RegisterFunction(JSGlobalContextRef context, JSObjectRef object, + const char* functionName, JSObjectCallAsFunctionCallback callback) { + JSStringRef js_functionName = JSStringCreateWithUTF8CString(functionName); + JSObjectSetProperty(context, object, js_functionName, + JSObjectMakeFunctionWithCallback(context, js_functionName, callback), + kJSPropertyAttributeNone, NULL); + JSStringRelease(js_functionName); + return true; +} + +void JSCShell::PrintError(JSContextRef ctx, JSValueRef err, const std::string& name) { + char *buffer; + + JSStringRef string = JSValueToStringCopy(ctx, err, 0); + size_t length = JSStringGetLength(string); + + buffer = new char[length+1]; + JSStringGetUTF8CString(string, buffer, length+1); + std::string errMsg(buffer); + JSStringRelease(string); + delete[] buffer; + + JSObjectRef errObj = JSValueToObject(ctx, err, 0); + + if(errObj == 0) { + std::cerr << errMsg << std::endl; + return; + } + + // Note: usually you would also retrieve the property "sourceURL" + // though, it happened that this was always "" + JSStringRef lineKey = JSStringCreateWithUTF8CString("line"); + JSValueRef jsLine = JSObjectGetProperty(ctx, errObj, lineKey, 0); + int line = (int) JSValueToNumber(ctx, jsLine, 0); + JSStringRelease(lineKey); + + std::cerr << name << ":" << line << ":" << errMsg << std::endl; +} + +JSShell* create_jsc_shell() { + return new JSCShell(); +} diff --git a/Tools/javascript/v8_shell.cxx b/Tools/javascript/v8_shell.cxx new file mode 100755 index 000000000..940609ec3 --- /dev/null +++ b/Tools/javascript/v8_shell.cxx @@ -0,0 +1,222 @@ +#include +#include +#include +#include +#include + +#include +#include + +#include "js_shell.h" + +typedef int (*V8ExtensionRegistrar) (v8::Handle); + +class V8Shell: public JSShell { + +public: + V8Shell(); + + virtual ~V8Shell(); + +protected: + + virtual bool RegisterModule(HANDLE library, const std::string& module_name); + + virtual bool InitializeEngine(); + + virtual bool ExecuteScript(const std::string& source, const std::string& name); + + virtual bool DisposeEngine(); + +private: + + v8::Persistent CreateShellContext(); + + void ReportException(v8::TryCatch* handler); + + static v8::Handle Print(const v8::Arguments& args); + + static v8::Handle Quit(const v8::Arguments& args); + + static v8::Handle Version(const v8::Arguments& args); + + static const char* ToCString(const v8::String::Utf8Value& value); + +protected: + + std::vector module_initializers; + + v8::Persistent context; + +}; + +#ifdef __GNUC__ +#include +#define LOAD_SYMBOL(handle, name) dlsym(handle, name) +#else +#error "implement dll loading" +#endif + +// Extracts a C string from a V8 Utf8Value. +const char* V8Shell::ToCString(const v8::String::Utf8Value& value) { + return *value ? *value : ""; +} + +V8Shell::V8Shell() +{ +} + +V8Shell::~V8Shell() { + context.Dispose(); + v8::V8::Dispose(); +} + +bool V8Shell::RegisterModule(HANDLE library, const std::string& module_name) { + std::string symname = std::string(module_name).append("_initialize"); + + V8ExtensionRegistrar init_function = reinterpret_cast((long) LOAD_SYMBOL(library, symname.c_str())); + if(init_function == 0) return false; + + module_initializers.push_back(init_function); + return true; +} + +bool V8Shell::InitializeEngine() { + if (!context.IsEmpty()) { + context.Dispose(); + } + + context = CreateShellContext(); + if (context.IsEmpty()) { + printf("Could not create context.\n"); + return 1; + } + + context->Enter(); +} + +bool V8Shell::ExecuteScript(const std::string& source, const std::string& name) { + // Enter the execution environment before evaluating any code. + v8::Context::Scope context_scope(context); + + v8::HandleScope handle_scope; + v8::TryCatch try_catch; + v8::Handle script = v8::Script::Compile(v8::String::New(source.c_str()), v8::String::New(name.c_str())); + if (script.IsEmpty()) { + // Print errors that happened during compilation. + ReportException(&try_catch); + return false; + } else { + v8::Handle result = script->Run(); + if (result.IsEmpty()) { + assert(try_catch.HasCaught()); + // Print errors that happened during execution. + ReportException(&try_catch); + return false; + } else { + assert(!try_catch.HasCaught()); + if (!result->IsUndefined()) { + // If all went well and the result wasn't undefined then print + // the returned value. + v8::String::Utf8Value str(result); + const char* cstr = V8Shell::ToCString(str); + printf("%s\n", cstr); + } + return true; + } + } +} + +bool V8Shell::DisposeEngine() { + context->Exit(); + context.Dispose(); + v8::V8::Dispose(); +} + +v8::Persistent V8Shell::CreateShellContext() { + // Create a template for the global object. + v8::Handle global = v8::ObjectTemplate::New(); + + // Bind global functions + global->Set(v8::String::New("print"), v8::FunctionTemplate::New(V8Shell::Print)); + global->Set(v8::String::New("quit"), v8::FunctionTemplate::New(V8Shell::Quit)); + global->Set(v8::String::New("version"), v8::FunctionTemplate::New(V8Shell::Version)); + + v8::Persistent _context = v8::Context::New(NULL, global); + + // register extensions + for(std::vector::iterator it=module_initializers.begin(); + it != module_initializers.end(); ++it) { + (*it)(_context); + } + + return _context; +} + + +v8::Handle V8Shell::Print(const v8::Arguments& args) { + bool first = true; + for (int i = 0; i < args.Length(); i++) { + v8::HandleScope handle_scope; + if (first) { + first = false; + } else { + printf(" "); + } + v8::String::Utf8Value str(args[i]); + const char* cstr = V8Shell::ToCString(str); + printf("%s", cstr); + } + printf("\n"); + fflush(stdout); + return v8::Undefined(); +} + +v8::Handle V8Shell::Quit(const v8::Arguments& args) { + int exit_code = args[0]->Int32Value(); + fflush(stdout); + fflush(stderr); + exit(exit_code); + return v8::Undefined(); +} + +v8::Handle V8Shell::Version(const v8::Arguments& args) { + return v8::String::New(v8::V8::GetVersion()); +} + +void V8Shell::ReportException(v8::TryCatch* try_catch) { + v8::HandleScope handle_scope; + v8::String::Utf8Value exception(try_catch->Exception()); + const char* exception_string = V8Shell::ToCString(exception); + v8::Handle message = try_catch->Message(); + if (message.IsEmpty()) { + // V8 didn't provide any extra information about this error; just + // print the exception. + printf("%s\n", exception_string); + } else { + // Print (filename):(line number): (message). + v8::String::Utf8Value filename(message->GetScriptResourceName()); + const char* filename_string = V8Shell::ToCString(filename); + int linenum = message->GetLineNumber(); + printf("%s:%i: %s\n", filename_string, linenum, exception_string); + // Print line of source code. + v8::String::Utf8Value sourceline(message->GetSourceLine()); + const char* sourceline_string = V8Shell::ToCString(sourceline); + printf("%s\n", sourceline_string); + // Print wavy underline (GetUnderline is deprecated). + int start = message->GetStartColumn(); + for (int i = 0; i < start; i++) { + printf(" "); + } + int end = message->GetEndColumn(); + for (int i = start; i < end; i++) { + printf("^"); + } + printf("\n"); + v8::String::Utf8Value stack_trace(try_catch->StackTrace()); + if (stack_trace.length() > 0) { + const char* stack_trace_string = V8Shell::ToCString(stack_trace); + printf("%s\n", stack_trace_string); + } + } +} From 0341e6b14c9f118ca2bfe853385df88779f0521b Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:04:26 +0000 Subject: [PATCH 0111/1048] Clean up example Makefiles. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13784 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/javascript/class/Makefile | 12 +++++------- Examples/javascript/constant/Makefile | 12 +++++------- Examples/javascript/enum/Makefile | 12 +++++------- Examples/javascript/exception/Makefile | 12 +++++------- Examples/javascript/exception/runme.js | 15 +++++++++++++-- Examples/javascript/functor/Makefile | 12 +++++------- Examples/javascript/namespace/Makefile | 12 +++++------- Examples/javascript/operator/Makefile | 12 +++++------- Examples/javascript/overload/Makefile | 12 +++++------- Examples/javascript/pointer/Makefile | 12 +++++------- Examples/javascript/reference/Makefile | 12 +++++------- Examples/javascript/simple/Makefile | 12 +++++------- Examples/javascript/template/Makefile | 12 +++++------- Examples/javascript/variables/Makefile | 12 +++++------- 14 files changed, 78 insertions(+), 93 deletions(-) diff --git a/Examples/javascript/class/Makefile b/Examples/javascript/class/Makefile index 1ac61ec6b..180e99cae 100755 --- a/Examples/javascript/class/Makefile +++ b/Examples/javascript/class/Makefile @@ -1,12 +1,9 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript CXXSRCS = example.cpp -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ @@ -15,9 +12,10 @@ all:: clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean +javascript_exe:: + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' javascript_exe + check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run - + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/constant/Makefile b/Examples/javascript/constant/Makefile index bebb1f302..dbf2f6660 100755 --- a/Examples/javascript/constant/Makefile +++ b/Examples/javascript/constant/Makefile @@ -1,12 +1,9 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript CXXSRCS = -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ @@ -15,9 +12,10 @@ all:: clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean +javascript_exe:: + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' javascript_exe + check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run - + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/enum/Makefile b/Examples/javascript/enum/Makefile index 1ac61ec6b..180e99cae 100755 --- a/Examples/javascript/enum/Makefile +++ b/Examples/javascript/enum/Makefile @@ -1,12 +1,9 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript CXXSRCS = example.cpp -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ @@ -15,9 +12,10 @@ all:: clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean +javascript_exe:: + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' javascript_exe + check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run - + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/exception/Makefile b/Examples/javascript/exception/Makefile index 1ac61ec6b..180e99cae 100755 --- a/Examples/javascript/exception/Makefile +++ b/Examples/javascript/exception/Makefile @@ -1,12 +1,9 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript CXXSRCS = example.cpp -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ @@ -15,9 +12,10 @@ all:: clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean +javascript_exe:: + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' javascript_exe + check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run - + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/exception/runme.js b/Examples/javascript/exception/runme.js index dfa561993..936b37883 100644 --- a/Examples/javascript/exception/runme.js +++ b/Examples/javascript/exception/runme.js @@ -1,6 +1,7 @@ //file: runme.js // Throw a lot of exceptions +print("Trying to catch some exceptions."); t = new example.Test(); try{ t.unknown(); @@ -9,6 +10,8 @@ try{ { if(error == -1) { print("t.unknown() didn't throw"); + } else { + print("successfully catched throw in Test::unknown()."); } } @@ -19,6 +22,8 @@ try{ catch(error){ if(error == -1) { print("t.simple() did not throw"); + } else { + print("successfully catched throw in Test::simple()."); } } @@ -28,6 +33,8 @@ try{ } catch(error){ if(error == -1) { print("t.message() did not throw"); + } else { + print("successfully catched throw in Test::message()."); } } @@ -38,6 +45,8 @@ try{ catch(error){ if(error == -1) { print("t.hosed() did not throw"); + } else { + print("successfully catched throw in Test::hosed()."); } } @@ -48,7 +57,9 @@ for (var i=1; i<4; i++) { } catch(error){ if(error == -1) { - print("t.mulit(" + i + ") did not throw"); + print("t.multi(" + i + ") did not throw"); + } else { + print("successfully catched throw in Test::multi()."); } } -} +} diff --git a/Examples/javascript/functor/Makefile b/Examples/javascript/functor/Makefile index 1ac61ec6b..180e99cae 100755 --- a/Examples/javascript/functor/Makefile +++ b/Examples/javascript/functor/Makefile @@ -1,12 +1,9 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript CXXSRCS = example.cpp -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ @@ -15,9 +12,10 @@ all:: clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean +javascript_exe:: + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' javascript_exe + check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run - + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/namespace/Makefile b/Examples/javascript/namespace/Makefile index 1ac61ec6b..180e99cae 100755 --- a/Examples/javascript/namespace/Makefile +++ b/Examples/javascript/namespace/Makefile @@ -1,12 +1,9 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript CXXSRCS = example.cpp -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ @@ -15,9 +12,10 @@ all:: clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean +javascript_exe:: + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' javascript_exe + check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run - + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/operator/Makefile b/Examples/javascript/operator/Makefile index 1ac61ec6b..180e99cae 100755 --- a/Examples/javascript/operator/Makefile +++ b/Examples/javascript/operator/Makefile @@ -1,12 +1,9 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript CXXSRCS = example.cpp -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ @@ -15,9 +12,10 @@ all:: clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean +javascript_exe:: + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' javascript_exe + check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run - + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/overload/Makefile b/Examples/javascript/overload/Makefile index 1ac61ec6b..180e99cae 100755 --- a/Examples/javascript/overload/Makefile +++ b/Examples/javascript/overload/Makefile @@ -1,12 +1,9 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript CXXSRCS = example.cpp -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ @@ -15,9 +12,10 @@ all:: clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean +javascript_exe:: + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' javascript_exe + check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run - + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/pointer/Makefile b/Examples/javascript/pointer/Makefile index 1ac61ec6b..180e99cae 100755 --- a/Examples/javascript/pointer/Makefile +++ b/Examples/javascript/pointer/Makefile @@ -1,12 +1,9 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript CXXSRCS = example.cpp -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ @@ -15,9 +12,10 @@ all:: clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean +javascript_exe:: + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' javascript_exe + check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run - + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/reference/Makefile b/Examples/javascript/reference/Makefile index 1ac61ec6b..180e99cae 100755 --- a/Examples/javascript/reference/Makefile +++ b/Examples/javascript/reference/Makefile @@ -1,12 +1,9 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript CXXSRCS = example.cpp -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ @@ -15,9 +12,10 @@ all:: clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean +javascript_exe:: + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' javascript_exe + check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run - + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/simple/Makefile b/Examples/javascript/simple/Makefile index 4fbfa2802..fb4669329 100755 --- a/Examples/javascript/simple/Makefile +++ b/Examples/javascript/simple/Makefile @@ -1,12 +1,9 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript SRCS = example.c -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ @@ -15,9 +12,10 @@ all:: clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean +javascript_exe:: + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' javascript_exe + check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run - + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/template/Makefile b/Examples/javascript/template/Makefile index 1ac61ec6b..180e99cae 100755 --- a/Examples/javascript/template/Makefile +++ b/Examples/javascript/template/Makefile @@ -1,12 +1,9 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript CXXSRCS = example.cpp -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ @@ -15,9 +12,10 @@ all:: clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean +javascript_exe:: + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' javascript_exe + check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run - + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/variables/Makefile b/Examples/javascript/variables/Makefile index 4fbfa2802..fb4669329 100755 --- a/Examples/javascript/variables/Makefile +++ b/Examples/javascript/variables/Makefile @@ -1,12 +1,9 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -JAVASCRIPT_EXE = $(TOP)/../Tools/javascript/javascript SRCS = example.c -JSCXXSRCS = $(TOP)/../Tools/javascript/javascript.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -SWIGOPT = -I$(TOP)/../Lib/javascript -I$(TOP)/../Lib/javascript/jsc all:: $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ @@ -15,9 +12,10 @@ all:: clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean +javascript_exe:: + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' javascript_exe + check:: all $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' javascript_exe - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - JAVASCRIPT_EXE='$(JAVASCRIPT_EXE)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run - + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run From 5fab9c8a3857f2c0499790461160bdb4bc9d3602 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:04:40 +0000 Subject: [PATCH 0112/1048] Minor cleanup in javascript shell implementation. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13785 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Tools/javascript/jsc_shell.cxx | 12 +++--------- Tools/javascript/v8_shell.cxx | 10 +++++----- 2 files changed, 8 insertions(+), 14 deletions(-) diff --git a/Tools/javascript/jsc_shell.cxx b/Tools/javascript/jsc_shell.cxx index 3fa704440..a21fb3f1a 100644 --- a/Tools/javascript/jsc_shell.cxx +++ b/Tools/javascript/jsc_shell.cxx @@ -12,10 +12,6 @@ #error "implement dll loading" #endif -JSValueRef JSCShell_Print(JSContextRef context, JSObjectRef object, - JSObjectRef globalobj, size_t argc, - const JSValueRef args[], JSValueRef* ex); - class JSCShell: public JSShell { typedef int (*JSCIntializer)(JSGlobalContextRef context); @@ -38,7 +34,7 @@ protected: private: - //static JSValueRef Print(JSContextRef context,JSObjectRef object, JSObjectRef globalobj, size_t argc, const JSValueRef args[], JSValueRef* ex); + static JSValueRef Print(JSContextRef context,JSObjectRef object, JSObjectRef globalobj, size_t argc, const JSValueRef args[], JSValueRef* ex); static bool RegisterFunction(JSGlobalContextRef context, JSObjectRef object, const char* functionName, JSObjectCallAsFunctionCallback cbFunction); @@ -51,8 +47,6 @@ private: JSGlobalContextRef context; }; -using namespace std; - JSCShell::~JSCShell() { if(context != 0) { JSGlobalContextRelease(context); @@ -79,7 +73,7 @@ bool JSCShell::InitializeEngine() { context = JSGlobalContextCreate(NULL); if(context == 0) return false; JSObjectRef globalObject = JSContextGetGlobalObject(context); - JSCShell::RegisterFunction(context, globalObject, "print", JSCShell_Print); + JSCShell::RegisterFunction(context, globalObject, "print", JSCShell::Print); // Call module initializers for(std::vector::iterator it = module_initializers.begin(); it != module_initializers.end(); ++it) { @@ -110,7 +104,7 @@ bool JSCShell::DisposeEngine() { return true; } -JSValueRef JSCShell_Print(JSContextRef context, JSObjectRef object, +JSValueRef JSCShell::Print(JSContextRef context, JSObjectRef object, JSObjectRef globalobj, size_t argc, const JSValueRef args[], JSValueRef* ex) { if (argc > 0) diff --git a/Tools/javascript/v8_shell.cxx b/Tools/javascript/v8_shell.cxx index 940609ec3..e124ebd7d 100755 --- a/Tools/javascript/v8_shell.cxx +++ b/Tools/javascript/v8_shell.cxx @@ -57,11 +57,6 @@ protected: #error "implement dll loading" #endif -// Extracts a C string from a V8 Utf8Value. -const char* V8Shell::ToCString(const v8::String::Utf8Value& value) { - return *value ? *value : ""; -} - V8Shell::V8Shell() { } @@ -220,3 +215,8 @@ void V8Shell::ReportException(v8::TryCatch* try_catch) { } } } + +// Extracts a C string from a V8 Utf8Value. +const char* V8Shell::ToCString(const v8::String::Utf8Value& value) { + return *value ? *value : ""; +} From cdd450fbe4b9fa9a756cb464dbb3f54e2791106a Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:04:51 +0000 Subject: [PATCH 0113/1048] Delete obsolete source file. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13786 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/Modules/javascript_emitter.cxx | 198 -------------------------- 1 file changed, 198 deletions(-) delete mode 100644 Source/Modules/javascript_emitter.cxx diff --git a/Source/Modules/javascript_emitter.cxx b/Source/Modules/javascript_emitter.cxx deleted file mode 100644 index b9446663a..000000000 --- a/Source/Modules/javascript_emitter.cxx +++ /dev/null @@ -1,198 +0,0 @@ -#include "javascript_emitter.h" - -#include "swigmod.h" - -/* ----------------------------------------------------------------------------- - * JSEmitter() - * ----------------------------------------------------------------------------- */ - -JSEmitter::JSEmitter() - : empty_string(NewString("")) -{ - templates = NewHash(); -} - -/* ----------------------------------------------------------------------------- - * ~JSEmitter() - * ----------------------------------------------------------------------------- */ - -JSEmitter::~JSEmitter() -{ - Delete(empty_string); - Delete(templates); -} - -/* ----------------------------------------------------------------------------- - * JSEmitter::RegisterTemplate() : Registers a code template - * ----------------------------------------------------------------------------- */ - -int JSEmitter::RegisterTemplate(const String *name, const String *code) -{ - return Setattr(templates, name, code); -} - -/* ----------------------------------------------------------------------------- - * JSEmitter::GetTemplate() : Retrieves a registered a code template - * ----------------------------------------------------------------------------- */ - -const String* JSEmitter::GetTemplate(const String *name) -{ - String* templ = Getattr(templates, name); - - if(!templ) { - Printf(stderr, "Could not find template %s\n.", name); - SWIG_exit(EXIT_FAILURE); - } - - return templ; -} - -/* ----------------------------------------------------------------------------- - * JSEmitter::typemapLookup() - * n - for input only and must contain info for Getfile(n) and Getline(n) to work - * tmap_method - typemap method name - * type - typemap type to lookup - * warning - warning number to issue if no typemaps found - * typemap_attributes - the typemap attributes are attached to this node and will - * also be used for temporary storage if non null - * return is never NULL, unlike Swig_typemap_lookup() - * ----------------------------------------------------------------------------- */ - -const String *JSEmitter::typemapLookup(Node *n, const_String_or_char_ptr tmap_method, - SwigType *type, int warning, Node *typemap_attributes) { - Node *node = !typemap_attributes ? NewHash() : typemap_attributes; - Setattr(node, "type", type); - Setfile(node, Getfile(n)); - Setline(node, Getline(n)); - const String *tm = Swig_typemap_lookup(tmap_method, node, "", 0); - if (!tm) { - tm = empty_string; - if (warning != WARN_NONE) { - Swig_warning(warning, Getfile(n), Getline(n), - "No %s typemap defined for %s\n", tmap_method, SwigType_str(type, 0)); - } - } - if (!typemap_attributes) { - Delete(node); - } - return tm; -} - -/* ----------------------------------------------------------------------------- - * JSEmitter::GetBaseClass() : the node of the base class or NULL - * ----------------------------------------------------------------------------- */ - -Node* JSEmitter::GetBaseClass(Node* n) -{ - // retrieve the first base class that is not %ignored - List *baselist = Getattr(n, "bases"); - if (baselist) { - Iterator base = First(baselist); - while (base.item && GetFlag(base.item, "feature:ignore")) { - base = Next(base); - } - - return base.item; - } - - return NULL; -} - -/* ----------------------------------------------------------------------------- - * JSEmitter::EmitWrapperFunction() : dispatches emitter functions - * ----------------------------------------------------------------------------- */ - -int JSEmitter::EmitWrapperFunction(Node* n) -{ - int ret = SWIG_OK; - - current_wrapper = NewWrapper(); - Setattr(n, "wrap:name", NewString(Getattr(n, "sym:name"))); - - String* kind = Getattr(n, "kind"); - - if(kind) { - bool is_member = GetFlag(n, "ismember"); - if( Cmp(kind, "function") == 0 ) { - ret = EmitFunction(n, is_member); - } else if (Cmp(kind, "variable") == 0) { - if(IsSetterMethod(n)) { - ret = EmitSetter(n, is_member); - } else { - ret = EmitGetter(n, is_member); - } - } else { - Printf(stderr, "Warning: unsupported wrapper function type\n"); - Swig_print_node(n); - } - } else { - String *view = Getattr(n, "view"); - - if( Cmp(view, "constructorHandler") == 0 ) { - ret = EmitCtor(n); - - } else if( Cmp(view, "destructorHandler") == 0 ) { - ret = EmitDtor(n); - - } else { - Printf(stderr, "Warning: unsupported wrapper function type"); - Swig_print_node(n); - } - } - - DelWrapper(current_wrapper); - current_wrapper = 0; - - return ret; -} - -/* ----------------------------------------------------------------------------- - * str_ends_with() : c string helper to check suffix match - * ----------------------------------------------------------------------------- */ - -// TODO: shift this to DOH string API -int str_ends_with(const char * str, const char * suffix) { - - if( str == NULL || suffix == NULL ) - return 0; - - size_t str_len = strlen(str); - size_t suffix_len = strlen(suffix); - - if(suffix_len > str_len) - return 0; - - return 0 == strncmp( str + str_len - suffix_len, suffix, suffix_len ); -} - -/* ----------------------------------------------------------------------------- - * JSEmitter::IsSetterMethod() : helper to check if a method is a setter function - * ----------------------------------------------------------------------------- */ - -bool JSEmitter::IsSetterMethod(Node *n) { - String* symname = Getattr(n, "sym:name"); - return ( str_ends_with( (char*) Data(symname), "_set") != 0 ); -} - -Template::Template(const String* code) -{ - if(!code) { - Printf(stdout, "Template code was null. Illegal input for template."); - SWIG_exit(EXIT_FAILURE); - } - - m_code = NewString(code); -} - -Template::~Template() { - Delete(m_code); -} - -String* Template::str() { - return m_code; -} - -Template& Template::Replace(const String* pattern, const String* repl) { - ::Replaceall(m_code, pattern, repl); - return *this; -} From 8d72616e6598dac37109fce3562c32c31188beb1 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:05:11 +0000 Subject: [PATCH 0114/1048] Refactor emitter and code templates to use defined template variables. Also switched from "${...}" to $..., which is swig's common notation of typemap variables. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13787 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/jsc/javascriptcode.swg | 154 +++++++++++----------- Source/Modules/javascript.cxx | 178 +++++++++++++++----------- 2 files changed, 175 insertions(+), 157 deletions(-) diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index 51b49039c..194181125 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -6,10 +6,12 @@ %fragment ("JS_getproperty", "templates") %{ -JSValueRef ${getname}(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +JSValueRef $jsgetter(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) { - ${LOCALS} - ${CODE} + $jslocals + JSValueRef jsresult; + + $jscode return jsresult; goto fail; @@ -26,10 +28,10 @@ JSValueRef ${getname}(JSContextRef context, JSObjectRef thisObject, JSStringRef %fragment ("JS_setproperty", "templates") %{ -bool ${setname}(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +bool $jssetter(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) { - ${LOCALS} - ${CODE} + $jslocals + $jscode return true; @@ -46,10 +48,12 @@ bool ${setname}(JSContextRef context, JSObjectRef thisObject, JSStringRef proper ************************************************************************************/ %fragment ("JS_functionwrapper", "templates") %{ -JSValueRef ${functionname}(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +JSValueRef $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { - ${LOCALS} - ${CODE} + $jslocals + JSValueRef jsresult; + + $jscode return jsresult; goto fail; @@ -60,10 +64,12 @@ JSValueRef ${functionname}(JSContextRef context, JSObjectRef function, JSObjectR %fragment ("JS_functionwrapper_overload", "templates") %{ -int ${functionname}(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception, JSValueRef* result) +int $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception, JSValueRef* result) { - ${LOCALS} - ${CODE} + $jslocals + JSValueRef jsresult; + + $jscode *result = jsresult; return SWIG_OK; @@ -80,83 +86,81 @@ int ${functionname}(JSContextRef context, JSObjectRef function, JSObjectRef this ***********************************************************************/ %fragment ("JS_function_dispatch_case", "templates") -%{if(argc == ${argcount}) { - res = ${functionwrapper}(context, function, thisObject, argc, argv, exception, &jsresult); +%{if(argc == $jsargcount) { + res = $jswrapper(context, function, thisObject, argc, argv, exception, &jsresult); if(res == SWIG_OK) { *exception = 0; return jsresult; } } %} %fragment ("JS_function_dispatch_case_default", "templates") %{ - SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function ${functionname}."); + SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function $jsname."); %} /* Added template for function declaration */ %fragment ("JS_variabledecl", "templates") -%{{"${propertyname}",${getname}, ${setname},kJSPropertyAttributeNone},%} +%{{"$jsname", $jsgetter, $jssetter, kJSPropertyAttributeNone},%} /* Added template for function declaration */ %fragment ("JS_functiondecl", "templates") -%{{"${functionname}",${functionwrapper}, kJSPropertyAttributeNone},%} +%{{"$jsname",$jswrapper, kJSPropertyAttributeNone},%} %fragment ("JS_globaldefn", "templates") %{ -JSStaticValue ${namespace}_values[] = { - ${jsglobalvariables} +JSStaticValue $jsnspace_values[] = { + $jsglobalvariables { 0, 0, 0, 0 } }; -JSStaticFunction ${namespace}_functions[] = { - ${jsglobalfunctions} +JSStaticFunction $jsnspace_functions[] = { + $jsglobalfunctions { 0, 0, 0 } }; -JSClassDefinition ${namespace}_classDefinition; +JSClassDefinition $jsnspace_classDefinition; %} -/****************************************************************************************** - * class_definition: - * This code template is used for wrapper of classes definition. - * ${classname_mangled}:the mangled name of the qualified class name, e.g., foo::A -> foo_A - *****************************************************************************************/ +/*********************************************************************** + * class_definition: + * declarations of javascript class definition objects. + ***********************************************************************/ %fragment ("JS_class_definition", "templates") %{ -JSClassDefinition ${classname_mangled}_classDefinition; +JSClassDefinition $jsmangledname_classDefinition; -JSClassDefinition ${classname_mangled}_objectDefinition; +JSClassDefinition $jsmangledname_objectDefinition; -JSClassRef ${classname_mangled}_classRef; +JSClassRef $jsmangledname_classRef; %} -/********************************************************************* - * class_table: - * This code template is used to add the wrapper for class declaration - * ${classname_mangled}: The mangled name of the qualified class name, e.g., foo::A -> foo_A +/*********************************************************************** + * class_table: + * function and variable tables for class and object creation. ***********************************************************************/ %fragment ("JS_class_tables", "templates") %{ -JSStaticValue ${classname_mangled}_staticValues[] = { - ${jsstaticclassvariables} +JSStaticValue $jsmangledname_staticValues[] = { + $jsstaticclassvariables { 0, 0, 0, 0 } }; -JSStaticFunction ${classname_mangled}_staticFunctions[] = { - ${jsstaticclassfunctions} +JSStaticFunction $jsmangledname_staticFunctions[] = { + $jsstaticclassfunctions { 0, 0, 0 } }; -JSStaticValue ${classname_mangled}_values[] = { - ${jsclassvariables} +JSStaticValue $jsmangledname_values[] = { + $jsclassvariables { 0, 0, 0, 0 } }; -JSStaticFunction ${classname_mangled}_functions[] = { - ${jsclassfunctions} +JSStaticFunction $jsmangledname_functions[] = { + $jsclassfunctions { 0, 0, 0 } }; %} @@ -164,15 +168,14 @@ JSStaticFunction ${classname_mangled}_functions[] = { /********************************************************************* * destructordefn: * This code template is used to adds the destructor wrapper function - * ${classname_mangled}: The mangled name of the qualified class name, e.g., foo::A -> foo_A ***********************************************************************/ %fragment ("JS_destructordefn", "templates") %{ -void _wrap_${classname_mangled}_finalize(JSObjectRef thisObject) +void _wrap_$jsmangledname_finalize(JSObjectRef thisObject) { SWIG_PRV_DATA* t = (SWIG_PRV_DATA*)JSObjectGetPrivate(thisObject); - if(t && t->swigCMemOwn) free ((${type}*)t->swigCObject); + if(t && t->swigCMemOwn) free (($jstype*)t->swigCObject); if(t) free(t); } %} @@ -180,22 +183,21 @@ void _wrap_${classname_mangled}_finalize(JSObjectRef thisObject) /********************************************************************* * constructor_definition: * This code template is used to adds the main constructor wrapper function - * ${classname_mangled}: The mangled name of the qualified class name, e.g., foo::A -> foo_A ***********************************************************************/ %fragment ("JS_mainctordefn", "templates") %{ -JSObjectRef _wrap_create_${classname_mangled}(JSContextRef context, JSObjectRef ctorObject, +JSObjectRef _wrap_create_$jsmangledname(JSContextRef context, JSObjectRef ctorObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { JSObjectRef thisObject = NULL; // switch all cases by means of series of if-returns. - ${DISPATCH_CASES} + $jsdispatchcases // default: - SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for contruction of ${classname_mangled}"); + SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for contruction of $jsmangledname"); fail: return thisObject; @@ -207,8 +209,8 @@ ctor_dispatch_case: This template is used for the constructor which is overloade ***************************************************************************************/ %fragment ("JS_ctor_dispatch_case", "templates") -%{if(argc == ${argcount}) { - thisObject = _wrap_create_${classname_mangled}${overloadext}(context, NULL, argc, argv, exception); +%{if(argc == $jsargcount) { + thisObject = _wrap_create_$jsmangledname$jsoverloadext(context, NULL, argc, argv, exception); if(thisObject != NULL) { *exception=0; return thisObject; } /* reset exception and return */ } %} @@ -216,12 +218,12 @@ ctor_dispatch_case: This template is used for the constructor which is overloade %fragment ("JS_ctordefn", "templates") %{ -JSObjectRef _wrap_create_${classname_mangled}${overloadext}(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +JSObjectRef _wrap_create_$jsmangledname$jsoverloadext(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { - ${LOCALS} - ${CODE} + $jslocals + $jscode - return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_${type_mangled}, SWIG_POINTER_OWN); + return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); goto fail; fail: @@ -237,7 +239,7 @@ initializer:This template is dynamic growing and aggregates everything extern "C" { #endif -bool ${modulename}_initialize(JSGlobalContextRef context) { +bool $jsname_initialize(JSGlobalContextRef context) { SWIG_InitializeModule(0); JSObjectRef global_object = JSContextGetGlobalObject(context); @@ -248,13 +250,13 @@ bool ${modulename}_initialize(JSGlobalContextRef context) { _SwigObject_classRef = JSClassCreate(&_SwigObject_objectDefinition); /* Create objects for namespaces */ - ${create_namespaces} + $jscreatenamespaces /* Create classes */ - ${initializercode} + $jsinitializercode /* Register namespaces */ - ${register_namespaces} + $jsregisternamespaces return true; } @@ -268,41 +270,35 @@ bool ${modulename}_initialize(JSGlobalContextRef context) { /***************************************************************************************** *create_class_template: *This template is used to add a Static references to class templates. - *${classname_mangled}: The mangled name of the qualified class name, e.g., foo::A -> foo_A *****************************************************************************************/ %fragment ("JS_create_class_template", "templates") -%{ ${classname_mangled}_classDefinition.staticFunctions = ${classname_mangled}_staticFunctions; - ${classname_mangled}_classDefinition.staticValues = ${classname_mangled}_staticValues; - ${classname_mangled}_classDefinition.callAsConstructor = _wrap_create_${classname_mangled}; - ${classname_mangled}_objectDefinition.staticValues = ${classname_mangled}_values; - ${classname_mangled}_objectDefinition.staticFunctions = ${classname_mangled}_functions; - ${classname_mangled}_objectDefinition.parentClass = ${base_classname}_classRef; - JSClassRef ${classname_mangled}_classRef = JSClassCreate(&${classname_mangled}_objectDefinition); - SWIGTYPE_${classtype_mangled}->clientdata = ${classname_mangled}_classRef;%} +%{ $jsmangledname_classDefinition.staticFunctions = $jsmangledname_staticFunctions; + $jsmangledname_classDefinition.staticValues = $jsmangledname_staticValues; + $jsmangledname_classDefinition.callAsConstructor = _wrap_create_$jsmangledname; + $jsmangledname_objectDefinition.staticValues = $jsmangledname_values; + $jsmangledname_objectDefinition.staticFunctions = $jsmangledname_functions; + $jsmangledname_objectDefinition.parentClass = $jsbaseclass_classRef; + JSClassRef $jsmangledname_classRef = JSClassCreate(&$jsmangledname_objectDefinition); + SWIGTYPE_$jsmangledtype->clientdata = $jsmangledname_classRef;%} /***************************************************************************************** *register_class: - *This template is used to adds a class registration statement to initializer function - *${classname_mangled}: The mangled name of the qualified class name, e.g., foo::A -> foo_A + * This template is used to adds a class registration statement to initializer function *****************************************************************************************/ %fragment ("JS_register_class", "templates") -%{JS_registerClass(context, ${namespace_mangled}_object, "${classname}", &${classname_mangled}_classDefinition);%} - -/* register global function */ -%fragment ("JS_register_global_function", "templates") -%{JS_registerFunction(${context}, ${context_object}, "${functionname}", ${functionwrapper});%} +%{JS_registerClass(context, $jsnspace_object, "$jsname", &$jsmangledname_classDefinition);%} /* create and register namespaces */ %fragment ("JS_create_namespace", "templates") -%{ ${namespace}_classDefinition.staticFunctions = ${namespace}_functions; - ${namespace}_classDefinition.staticValues = ${namespace}_values; - JSObjectRef ${namespace}_object = JSObjectMake(context, JSClassCreate(&${namespace}_classDefinition), NULL); +%{ $jsmangledname_classDefinition.staticFunctions = $jsmangledname_functions; + $jsmangledname_classDefinition.staticValues = $jsmangledname_values; + JSObjectRef $jsmangledname_object = JSObjectMake(context, JSClassCreate(&$jsmangledname_classDefinition), NULL); %} %fragment ("JS_register_namespace", "templates") %{ -JS_registerNamespace(context, ${namespace_mangled}_object, ${parent_namespace}_object, "${namespace}"); %} +JS_registerNamespace(context, $jsmangledname_object, $jsparent_object, "$jsname"); %} diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 72be9b4f0..f4441f0d9 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -13,6 +13,27 @@ bool js_template_enable_debug = false; #define WRAPPER_NAME "wrapper" #define IS_IMMUTABLE "is_immutable" #define IS_STATIC "is_static" +#define GETTER "getter" +#define SETTER "setter" +#define PARENT "parent" + +// variables used in code templates +// ATTENTION: be aware of prefix collisions when defining those variables +#define T_NAME "$jsname" +#define T_NAME_MANGLED "$jsmangledname" +#define T_TYPE "$jstype" +#define T_TYPE_MANGLED "$jsmangledtype" +#define T_WRAPPER "$jswrapper" +#define T_GETTER "$jsgetter" +#define T_SETTER "$jssetter" +#define T_DISPATCH_CASES "$jsdispatchcases" +#define T_BASECLASS "$jsbaseclass" +#define T_NAMESPACE "$jsnspace" +#define T_PARENT "$jsparent" +#define T_OVERLOAD "$jsoverloadext" +#define T_ARGCOUNT "$jsargcount" +#define T_LOCALS "$jslocals" +#define T_CODE "$jscode" /** * A convenience class to manage state variables for emitters. @@ -569,6 +590,8 @@ JSEmitter::~JSEmitter() { /* ----------------------------------------------------------------------------- * JSEmitter::RegisterTemplate() : Registers a code template + * + * Note: this is used only by JAVASCRIPT::fragmentDirective(). * ----------------------------------------------------------------------------- */ int JSEmitter::registerTemplate(const String *name, const String *code) { @@ -576,7 +599,7 @@ int JSEmitter::registerTemplate(const String *name, const String *code) { } /* ----------------------------------------------------------------------------- - * JSEmitter::getTemplate() : Retrieves a registered a code template + * JSEmitter::getTemplate() : Provides a registered code template * ----------------------------------------------------------------------------- */ Template JSEmitter::getTemplate(const String *name) { @@ -624,6 +647,9 @@ Parm *JSEmitter::skipIgnoredArgs(Parm *p) { /* ----------------------------------------------------------------------------- * JSEmitter::getBaseClass() : the node of the base class or NULL + * + * Note: the first base class is provided. Multiple inheritance is not + * supported. * ----------------------------------------------------------------------------- */ Node *JSEmitter::getBaseClass(Node *n) { @@ -640,7 +666,10 @@ Node *JSEmitter::getBaseClass(Node *n) { } /* ----------------------------------------------------------------------------- - * JSEmitter::emitWrapperFunction() : dispatches emitter functions + * JSEmitter::emitWrapperFunction() : dispatches emitter functions. + * + * This allows to have small sized, dedicated emitting functions. + * All state dependent branching is done here. * ----------------------------------------------------------------------------- */ int JSEmitter::emitWrapperFunction(Node *n) { @@ -737,7 +766,7 @@ int JSEmitter::switchNamespace(Node *n) { String *scope = Swig_scopename_prefix(Getattr(n, "name")); if (scope) { // if the scope is not yet registered - // create all scopes/namespaces recursively + // create (parent) namespaces recursively if (!Getattr(namespaces, scope)) { createNamespace(scope); } @@ -774,9 +803,9 @@ int JSEmitter::createNamespace(String *scope) { Hash *JSEmitter::createNamespaceEntry(const char *_name, const char *parent) { Hash *entry = NewHash(); String *name = NewString(_name); - Setattr(entry, "name", Swig_scopename_last(name)); - Setattr(entry, "name_mangled", Swig_name_mangle(name)); - Setattr(entry, "parent", NewString(parent)); + Setattr(entry, NAME, Swig_scopename_last(name)); + Setattr(entry, NAME_MANGLED, Swig_name_mangle(name)); + Setattr(entry, PARENT, NewString(parent)); Delete(name); return entry; @@ -851,8 +880,6 @@ private: // keys for function scoped state variables #define FUNCTION_DISPATCHERS "function_dispatchers" -#define GETTER "getter" -#define SETTER "setter" JSCEmitter::JSCEmitter() : JSEmitter(), @@ -988,10 +1015,10 @@ int JSCEmitter::dump(Node *n) { // compose the initializer function using a template Template initializer(getTemplate("JS_initializer")); - initializer.replace("${modulename}", module) - .replace("${initializercode}", state.global(INITIALIZER)) - .replace("${create_namespaces}", state.global(CREATE_NAMESPACES)) - .replace("${register_namespaces}", state.global(REGISTER_NAMESPACES)) + initializer.replace(T_NAME, module) + .replace("$jsinitializercode", state.global(INITIALIZER)) + .replace("$jscreatenamespaces", state.global(CREATE_NAMESPACES)) + .replace("$jsregisternamespaces", state.global(REGISTER_NAMESPACES)) .pretty_print(f_init); Printv(f_wrap_cpp, f_init, 0); @@ -1046,8 +1073,8 @@ int JSCEmitter::exitFunction(Node *n) { } } - t_function.replace("${functionname}", state.function(NAME)) - .replace("${functionwrapper}", state.function(WRAPPER_NAME)); + t_function.replace(T_NAME, state.function(NAME)) + .replace(T_WRAPPER, state.function(WRAPPER_NAME)); if (is_member) { if (GetFlag(state.function(), IS_STATIC)) { @@ -1074,9 +1101,9 @@ int JSCEmitter::enterVariable(Node *n) { int JSCEmitter::exitVariable(Node *n) { Template t_variable(getTemplate("JS_variabledecl")); - t_variable.replace("${setname}", state.variable(SETTER)) - .replace("${getname}", state.variable(GETTER)) - .replace("${propertyname}", state.variable(NAME)); + t_variable.replace(T_NAME, state.variable(NAME)) + .replace(T_GETTER, state.variable(GETTER)) + .replace(T_SETTER, state.variable(SETTER)); if (GetFlag(n, "ismember")) { if (GetFlag(state.function(), IS_STATIC) @@ -1103,7 +1130,7 @@ int JSCEmitter::enterClass(Node *n) { state.clazz(CTOR_DISPATCHERS, NewString("")); Template t_class_defn = getTemplate("JS_class_definition"); - t_class_defn.replace("${classname_mangled}", state.clazz(NAME_MANGLED)) + t_class_defn.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .pretty_print(f_wrappers); return SWIG_OK; @@ -1112,11 +1139,11 @@ int JSCEmitter::enterClass(Node *n) { int JSCEmitter::exitClass(Node *n) { Template t_class_tables(getTemplate("JS_class_tables")); - t_class_tables.replace("${classname_mangled}", state.clazz(NAME_MANGLED)) - .replace("${jsclassvariables}", state.clazz(MEMBER_VARIABLES)) - .replace("${jsclassfunctions}", state.clazz(MEMBER_FUNCTIONS)) - .replace("${jsstaticclassfunctions}", state.clazz(STATIC_FUNCTIONS)) - .replace("${jsstaticclassvariables}", state.clazz(STATIC_VARIABLES)) + t_class_tables.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) + .replace("$jsclassvariables", state.clazz(MEMBER_VARIABLES)) + .replace("$jsclassfunctions", state.clazz(MEMBER_FUNCTIONS)) + .replace("$jsstaticclassfunctions", state.clazz(STATIC_FUNCTIONS)) + .replace("$jsstaticclassvariables", state.clazz(STATIC_VARIABLES)) .pretty_print(f_wrappers); /* adds the ctor wrappers at this position */ @@ -1125,8 +1152,8 @@ int JSCEmitter::exitClass(Node *n) { /* adds the main constructor wrapper function */ Template t_mainctor(getTemplate("JS_mainctordefn")); - t_mainctor.replace("${classname_mangled}", state.clazz(NAME_MANGLED)) - .replace("${DISPATCH_CASES}", state.clazz(CTOR_DISPATCHERS)) + t_mainctor.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) + .replace(T_DISPATCH_CASES, state.clazz(CTOR_DISPATCHERS)) .pretty_print(f_wrappers); /* adds a class template statement to initializer function */ @@ -1139,9 +1166,9 @@ int JSCEmitter::exitClass(Node *n) { Delete(base_name_mangled); base_name_mangled = SwigType_manglestr(Getattr(base_class, "name")); } - t_classtemplate.replace("${classname_mangled}", state.clazz(NAME_MANGLED)) - .replace("${classtype_mangled}", state.clazz(TYPE_MANGLED)) - .replace("${base_classname}", base_name_mangled) + t_classtemplate.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) + .replace(T_TYPE_MANGLED, state.clazz(TYPE_MANGLED)) + .replace(T_BASECLASS, base_name_mangled) .pretty_print(state.global(INITIALIZER)); Delete(base_name_mangled); @@ -1150,9 +1177,9 @@ int JSCEmitter::exitClass(Node *n) { /* adds a class registration statement to initializer function */ Template t_registerclass(getTemplate("JS_register_class")); - t_registerclass.replace("${classname}", state.clazz(NAME)) - .replace("${classname_mangled}", state.clazz(NAME_MANGLED)) - .replace("${namespace_mangled}", Getattr(current_namespace, "name_mangled")) + t_registerclass.replace(T_NAME, state.clazz(NAME)) + .replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) + .replace(T_NAMESPACE, Getattr(current_namespace, NAME_MANGLED)) .pretty_print(state.global(INITIALIZER)); return SWIG_OK; @@ -1180,19 +1207,19 @@ int JSEmitter::emitCtor(Node *n) { marshalInputArgs(n, params, wrapper, Ctor, true, false); Printv(wrapper->code, action, "\n", 0); - t_ctor.replace("${classname_mangled}", mangled_name) - .replace("${overloadext}", overname) - .replace("${LOCALS}", wrapper->locals) - .replace("${CODE}", wrapper->code) - .replace("${type_mangled}", state.clazz(TYPE_MANGLED)) + t_ctor.replace(T_NAME_MANGLED, mangled_name) + .replace(T_OVERLOAD, overname) + .replace(T_LOCALS, wrapper->locals) + .replace(T_CODE, wrapper->code) + .replace(T_TYPE_MANGLED, state.clazz(TYPE_MANGLED)) .pretty_print(state.clazz(CTORS)); String *argcount = NewString(""); Printf(argcount, "%d", num_args); Template t_ctor_case(getTemplate("JS_ctor_dispatch_case")); - t_ctor_case.replace("${classname_mangled}", mangled_name) - .replace("${overloadext}", overname) - .replace("${argcount}", argcount); + t_ctor_case.replace(T_NAME_MANGLED, mangled_name) + .replace(T_OVERLOAD, overname) + .replace(T_ARGCOUNT, argcount); Append(state.clazz(CTOR_DISPATCHERS), t_ctor_case.str()); Delete(argcount); @@ -1204,8 +1231,8 @@ int JSEmitter::emitCtor(Node *n) { int JSEmitter::emitDtor(Node *) { Template t_dtor = getTemplate("JS_destructordefn"); - t_dtor.replace("${classname_mangled}", state.clazz(NAME_MANGLED)) - .replace("${type}", state.clazz(TYPE)) + t_dtor.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) + .replace(T_TYPE, state.clazz(TYPE)) .pretty_print(f_wrappers); return SWIG_OK; @@ -1224,16 +1251,15 @@ int JSEmitter::emitGetter(Node *n, bool is_member, bool is_static) { ParmList *params = Getattr(n, "parms"); emit_parameter_variables(params, wrapper); emit_attach_parmmaps(params, wrapper); - Wrapper_add_local(wrapper, "jsresult", "JSValueRef jsresult"); // prepare code part String *action = emit_action(n); marshalInputArgs(n, params, wrapper, Getter, is_member, is_static); marshalOutput(n, action, wrapper); - t_getter.replace("${getname}", wrap_name) - .replace("${LOCALS}", wrapper->locals) - .replace("${CODE}", wrapper->code) + t_getter.replace(T_GETTER, wrap_name) + .replace(T_LOCALS, wrapper->locals) + .replace(T_CODE, wrapper->code) .pretty_print(f_wrappers); DelWrapper(wrapper); @@ -1267,9 +1293,9 @@ int JSEmitter::emitSetter(Node *n, bool is_member, bool is_static) { marshalInputArgs(n, params, wrapper, Setter, is_member, is_static); Append(wrapper->code, action); - t_setter.replace("${setname}", wrap_name) - .replace("${LOCALS}", wrapper->locals) - .replace("${CODE}", wrapper->code) + t_setter.replace(T_SETTER, wrap_name) + .replace(T_LOCALS, wrapper->locals) + .replace(T_CODE, wrapper->code) .pretty_print(f_wrappers); DelWrapper(wrapper); @@ -1296,9 +1322,6 @@ int JSEmitter::emitConstant(Node *n) { state.variable(GETTER, wrap_name); Setattr(n, "wrap:name", wrap_name); - // prepare local variables - Wrapper_add_local(wrapper, "jsresult", "JSValueRef jsresult"); - // prepare code part String *action = NewString(""); String *value = Getattr(n, "rawval"); @@ -1312,9 +1335,9 @@ int JSEmitter::emitConstant(Node *n) { Setattr(n, "wrap:action", action); marshalOutput(n, action, wrapper); - t_getter.replace("${getname}", wrap_name) - .replace("${LOCALS}", wrapper->locals) - .replace("${CODE}", wrapper->code) + t_getter.replace(T_GETTER, wrap_name) + .replace(T_LOCALS, wrapper->locals) + .replace(T_CODE, wrapper->code) .pretty_print(f_wrappers); exitVariable(n); @@ -1334,8 +1357,8 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { // prepare the function wrapper name String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); if (is_overloaded) { - Append(wrap_name, Getattr(n, "sym:overname")); t_function = getTemplate("JS_functionwrapper_overload"); + Append(wrap_name, Getattr(n, "sym:overname")); } Setattr(n, "wrap:name", wrap_name); state.function(WRAPPER_NAME, wrap_name); @@ -1344,16 +1367,15 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { ParmList *params = Getattr(n, "parms"); emit_parameter_variables(params, wrapper); emit_attach_parmmaps(params, wrapper); - Wrapper_add_local(wrapper, "jsresult", "JSValueRef jsresult"); // prepare code part String *action = emit_action(n); marshalInputArgs(n, params, wrapper, Function, is_member, is_static); marshalOutput(n, action, wrapper); - t_function.replace("${functionname}", wrap_name) - .replace("${LOCALS}", wrapper->locals) - .replace("${CODE}", wrapper->code) + t_function.replace(T_WRAPPER, wrap_name) + .replace(T_LOCALS, wrapper->locals) + .replace(T_CODE, wrapper->code) .pretty_print(f_wrappers); // handle function overloading @@ -1364,8 +1386,8 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { String *argcount = NewString(""); Printf(argcount, "%d", argc); - t_dispatch_case.replace("${functionwrapper}", wrap_name) - .replace("${argcount}", argcount); + t_dispatch_case.replace(T_WRAPPER, wrap_name) + .replace(T_ARGCOUNT, argcount); Append(state.global(FUNCTION_DISPATCHERS), t_dispatch_case.str()); @@ -1386,16 +1408,16 @@ int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { Setattr(n, "wrap:name", wrap_name); Wrapper_add_local(wrapper, "res", "int res"); - Wrapper_add_local(wrapper, "jsresult", "JSValueRef jsresult"); Append(wrapper->code, state.global(FUNCTION_DISPATCHERS)); Append(wrapper->code, getTemplate("JS_function_dispatch_case_default").str()); - t_function.replace("${LOCALS}", wrapper->locals) - .replace("${CODE}", wrapper->code); + t_function.replace(T_LOCALS, wrapper->locals) + .replace(T_CODE, wrapper->code); // call this here, to replace all variables - t_function.replace("${functionname}", wrap_name) + t_function.replace(T_WRAPPER, wrap_name) + .replace(T_NAME, state.function(NAME)) .pretty_print(f_wrappers); // Delete the state variable @@ -1446,27 +1468,27 @@ int JSCEmitter::emitNamespaces() { Iterator it; for (it = First(namespaces); it.item; it = Next(it)) { Hash *entry = it.item; - String *name = Getattr(entry, "name"); - String *parent = Getattr(entry, "parent"); + String *name = Getattr(entry, NAME); + String *name_mangled = Getattr(entry, NAME_MANGLED); + String *parent = Getattr(entry, PARENT); + String *parent_mangled = Swig_name_mangle(parent); String *functions = Getattr(entry, "functions"); String *variables = Getattr(entry, "values"); - String *name_mangled = Getattr(entry, "name_mangled"); - String *parent_mangled = Swig_name_mangle(parent); Template namespace_definition(getTemplate("JS_globaldefn")); - namespace_definition.replace("${jsglobalvariables}", variables) - .replace("${jsglobalfunctions}", functions) - .replace("${namespace}", name_mangled) + namespace_definition.replace("$jsglobalvariables", variables) + .replace("$jsglobalfunctions", functions) + .replace(T_NAMESPACE, name_mangled) .pretty_print(f_wrap_cpp); Template t_createNamespace(getTemplate("JS_create_namespace")); - t_createNamespace.replace("${namespace}", name_mangled); + t_createNamespace.replace(T_NAME_MANGLED, name_mangled); Append(state.global(CREATE_NAMESPACES), t_createNamespace.str()); Template t_registerNamespace(getTemplate("JS_register_namespace")); - t_registerNamespace.replace("${namespace_mangled}", name_mangled) - .replace("${namespace}", name) - .replace("${parent_namespace}", parent_mangled); + t_registerNamespace.replace(T_NAME_MANGLED, name_mangled) + .replace(T_NAME, name) + .replace(T_PARENT, parent_mangled); Append(state.global(REGISTER_NAMESPACES), t_registerNamespace.str()); } @@ -1575,8 +1597,8 @@ private: #define KW_REGISTER_CLASSES "${PART_REGISTER_CLASSES}" #define KW_REGISTER_NS "${PART_REGISTER_NS}" -#define KW_LOCALS "${LOCALS}" -#define KW_CODE "${CODE}" +#define KW_LOCALS T_LOCALS +#define KW_CODE T_CODE V8Emitter::V8Emitter() : JSEmitter(), From 78442b27647e2a3d7e45516c709632f8419b7fd6 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:05:37 +0000 Subject: [PATCH 0115/1048] Several adaptations and fixes on the way to get V8 emitter running. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13788 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptcode.swg | 192 +++++++++++--------- Lib/javascript/v8/javascripthelpers.swg | 8 +- Lib/javascript/v8/javascriptprimitives.swg | 2 +- Lib/javascript/v8/javascriptruntime.swg | 12 +- Lib/javascript/v8/javascriptstrings.swg | 0 Source/Modules/javascript.cxx | 201 +++++++++------------ 6 files changed, 209 insertions(+), 206 deletions(-) create mode 100644 Lib/javascript/v8/javascriptstrings.swg diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index e5a1f1eba..59b071c89 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -1,101 +1,131 @@ -%fragment("v8_initializer", "templates") %{ -void ${MODULE}_Initialize(v8::Handle context) +%fragment("JS_ctordefn", "templates") %{ +v8::Handle $jsmangledname_new(const v8::Arguments& args) { + v8::HandleScope scope; + v8::Handle self = args.Holder(); + $jslocals + $jscode + self->SetInternalField(0, v8::External::New(result)); + return scope.Close(self); + goto fail; +fail: + return scope.Close(v8::Undefined); +}%} + +%fragment("JS_getproperty", "templates") %{ +v8::Handle $jsgetter(v8::Local property, const v8::AccessorInfo& info) { + v8::HandleScope scope; + v8::Handle jsresult; + $jslocals + $jscode + return scope.Close(jsresult); + goto fail; +fail: + return scope.Close(v8::Undefined()); +}%} + +%fragment("JS_setproperty", "templates") %{ +void $jssetter(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { + v8::HandleScope scope; + $jslocals + $jscode + goto fail; +fail: + return; +}%} + +%fragment("JS_functionwrapper", "templates") %{ +v8::Handle $jswrapper(const v8::Arguments &args) { + v8::HandleScope scope; + v8::Handle jsresult; + $jslocals + $jscode + return scope.Close(jsresult); + goto fail; +fail: + return scope.Close(v8::Undefined()); +}%} + +// TODO: implement ctor overloading properly! +%fragment ("JS_mainctordefn", "templates") +%{ + // TODO: implement JS_mainctordefn +%} + +%fragment ("JS_ctor_dispatch_case", "templates") +%{ + // TODO: implement JS_ctor_dispatch_case +%} + +%fragment ("JS_destructordefn", "templates") +%{ + // TODO: implement JS_destructordefn +%} + +%fragment("jsv8_declare_class_template", "templates") %{ +v8::Persistent SWIGV8_$jsmangledname;%} + +%fragment("jsv8_define_class_template", "templates") %{ +SWIGV8_$jsmangledname = SWIGV8_CreateClassTemplate("$jsname" , $jsmangledname_new);%} + +%fragment("jsv8_create_class_instance", "templates") %{ +v8::Handle class_$jsmangledname = SWIGV8_$jsmangledname->GetFunction();%} + +%fragment("jsv8_inherit", "templates") %{ +SWIGV8_$jsmangledname->Inherit(SWIGV8_$jsbaseclass);%} + +%fragment("jsv8_register_class", "templates") %{ +$jsparent->Set(v8::String::NewSymbol("$jsname"), class_$jsmangledname);%} + +%fragment("jsv8_create_namespace", "templates") %{ +v8::Handle $jsmangledname = v8::ObjectTemplate::New();%} + +%fragment("jsv8_register_member_function", "templates") %{ +SWIGV8_AddMemberFunction(SWIGV8_$jsmangledname, "$jsname", $jswrapper);%} + +%fragment("jsv8_register_static_function", "templates") %{ +SWIGV8_AddGlobalFunction($jsparent, "$jsname", $jswrapper);%} + +%fragment("jsv8_register_member_variable", "templates") %{ +SWIGV8_AddMemberVariable(SWIGV8_$jsmangledname, "$jsname", $jsgetter, $jssetter);%} + +%fragment("jsv8_register_static_variable", "templates") %{ +SWIGV8_AddGlobalVariable($jsparent, "$jsname", $jsgetter, $jssetter);%} + +%fragment("jsv8_register_namespace", "templates") %{ +$jsparent->Set(v8::String::NewSymbol("$jsname", $jsmangledname->NewInstance()));%} + +%fragment("JS_initializer", "templates") %{ + +extern "C" { + +void $jsname_initialize(v8::Handle context) { v8::HandleScope scope; v8::Local global = context->Global(); /* create object templates for namespaces */ - ${PART_NAMESPACES} + $jsv8nspaces /* create class templates */ - ${PART_CLASS_TEMPLATES} + $jsv8classtemplates /* register wrapper functions */ - ${PART_WRAPPERS} + $jsv8wrappers /* setup inheritances */ - ${PART_INHERITANCE} + $jsv8inheritance /* class instances */ - ${PART_CLASS_INSTANCES} + $jsv8classinstances /* add static class functions and variables */ - ${PART_STATIC_WRAPPERS} + $jsv8staticwrappers /* register classes */ - ${PART_REGISTER_CLASSES} + $jsv8registerclasses /* create and register namespace objects */ - ${PART_REGISTER_NS} + $jsv8registernspaces +} + }%} - -%fragment("v8_declare_class_template", "templates") %{ -v8::Persistent SWIGV8_${NAME_MANGLED};%} - -%fragment("v8_define_class_template", "templates") %{ -SWIGV8_${NAME_MANGLED} = SWIGV8_CreateClassTemplate("${NAME_UNQUALIFIED}" , ${NAME_MANGLED}_new);%} - -%fragment("v8_create_class_instance", "templates") %{ -v8::Handle class_${NAME_MANGLED} = SWIGV8_${NAME_MANGLED}->GetFunction();%} - -%fragment("v8_inherit", "templates") %{ -SWIGV8_${NAME_MANGLED}->Inherit(SWIGV8_${BASE_CLASS});%} - -%fragment("v8_register_class", "templates") %{ -${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}"), class_${NAME_MANGLED});%} - -%fragment("v8_ctor_wrapper", "templates") %{ -v8::Handle ${NAME_MANGLED}_new(const v8::Arguments& args) { - v8::HandleScope scope; - v8::Handle self = args.Holder(); - ${LOCALS} - ${CODE} - self->SetInternalField(0, v8::External::New(result)); - return self; -}%} - -%fragment("v8_getter", "templates") %{ -v8::Handle ${NAME_MANGLED}_get(v8::Local property, const v8::AccessorInfo& info) { - v8::HandleScope scope; - v8::Handle jsresult; - ${LOCALS} - ${CODE} - return scope.Close(jsresult); -}%} - -%fragment("v8_setter", "templates") %{ -void ${NAME_MANGLED}_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { - ${LOCALS} - ${CODE} -}%} - -%fragment("v8_function", "templates") %{ -v8::Handle wrap_${NAME_MANGLED}(const Arguments &args) { - v8::HandleScope scope; - v8::Handle jsresult; - ${LOCALS} - ${CODE} - return scope.Close(jsresult); -}%} - -%fragment("v8_create_namespace", "templates") %{ -v8::Handle ${NAME_MANGLED} = v8::ObjectTemplate::New();%} - -%fragment("v8_register_member_function", "templates") %{ -SWIGV8_AddMemberFunction(SWIGV8_${CLASSNAME_MANGLED}, "${NAME_UNQUALIFIED}", wrap_${NAME_MANGLED});%} - -%fragment("v8_register_global_function", "templates") %{ -SWIGV8_AddGlobalFunction(${CONTEXT}, "${NAME_UNQUALIFIED}", wrap_${NAME_MANGLED});%} - -%fragment("v8_register_member_variable", "templates") %{ -SWIGV8_AddMemberVariable(SWIGV8_${CLASSNAME_MANGLED}, "${NAME_UNQUALIFIED}", ${GETTER}, ${SETTER});%} - -%fragment("v8_register_global_variable", "templates") %{ -SWIGV8_AddGlobalVariable(${CONTEXT}, "${NAME_UNQUALIFIED}", ${GETTER}, ${SETTER});%} - -%fragment("v8_register_namespace", "templates") %{ -${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}", ${NAME_MANGLED}->NewInstance()));%} - -%fragment("v8_this_ptr", "templates") %{ -arg1 = SWIGV8_UnwrapThisPointer<${TYPE}>(${ARG}.Holder()); -%} diff --git a/Lib/javascript/v8/javascripthelpers.swg b/Lib/javascript/v8/javascripthelpers.swg index b5b462b96..1159f7ef3 100644 --- a/Lib/javascript/v8/javascripthelpers.swg +++ b/Lib/javascript/v8/javascripthelpers.swg @@ -13,10 +13,6 @@ v8::Persistent SWIGV8_CreateClassTemplate(const char* symb return v8::Persistent::New(class_templ); } -v8::Handle SWIGV8_CreateNamespace(const char* name, v8::Handle parentContext) { - Handle namespace = ObjectTemplate::New(); -} - /** * Registers a class method with given name for a given class template. */ @@ -29,7 +25,7 @@ void SWIGV8_AddMemberFunction(v8::Handle class_templ, cons * Registers a class method with given name for a given class template. */ void SWIGV8_AddGlobalFunction(v8::Handle obj_templ, const char* symbol, v8::InvocationCallback _func) { - obj_templ->Set(String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)->GetFunction()); + obj_templ->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)->GetFunction()); } /** @@ -44,6 +40,6 @@ void SWIGV8_AddMemberVariable(v8::Handle class_templ, cons * Registers a class method with given name for a given class template. */ void SWIGV8_AddGlobalVariable(v8::Handle obj_templ, const char* symbol, v8::AccessorGetter getter, v8::AccessorSetter setter) { - obj_templ->SetAccessor(String::NewSymbol(symbol), getter, setter); + obj_templ->SetAccessor(v8::String::NewSymbol(symbol), getter, setter); } %} // v8_helper_functions diff --git a/Lib/javascript/v8/javascriptprimitives.swg b/Lib/javascript/v8/javascriptprimitives.swg index 09e1ae9f9..d3dba485d 100644 --- a/Lib/javascript/v8/javascriptprimitives.swg +++ b/Lib/javascript/v8/javascriptprimitives.swg @@ -42,7 +42,7 @@ v8::Handle SWIG_From_dec(long)(long value) SWIGINTERN int SWIG_AsVal_dec(long)(v8::Handle obj, long* val) { - if (!obj->IsInteger()) { + if (!obj->IsNumber()) { return SWIG_TypeError; } if(val) *val = (long) obj->IntegerValue(); diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index 4440fa6d6..15d8a35fc 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -6,6 +6,8 @@ %insert(runtime) %{ #include +#include +#include %} %insert(runtime) "swigrun.swg"; /* SWIG API */ @@ -39,12 +41,12 @@ void SWIG_V8_exception(int code, const char* msg) { %insert(runtime) %{ -int SWIG_JSC_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_type_info *info, int flags) { +int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_type_info *info, int flags) { if(objRef->InternalFieldCount() < 1) { return SWIG_ERROR; } - Handle cdataRef = objRef->GetInternalField(0); + v8::Handle cdataRef = objRef->GetInternalField(0); SWIG_PRV_DATA *cdata = (SWIG_PRV_DATA *) v8::External::Unwrap(cdataRef); if(cdata == NULL) { @@ -80,14 +82,14 @@ int SWIG_V8_ConvertPtr(v8::Handle valRef, void** ptr, swig_type_info return SWIG_TypeError; } - v8::Handle objRef = valRef->ToObject(); + v8::Handle objRef = valRef->ToObject(); - return SWIG_V8_ConvertInstancePtr(context, objRef, ptr, info, flags); + return SWIG_V8_ConvertInstancePtr(objRef, ptr, info, flags); } v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, int flags) { // TODO: wrap ptr into an v8 object - return 0; + return v8::Undefined(); } #define SWIG_ConvertPtr(obj, ptr, info, flags) SWIG_V8_ConvertPtr(obj, ptr, info, flags) diff --git a/Lib/javascript/v8/javascriptstrings.swg b/Lib/javascript/v8/javascriptstrings.swg new file mode 100644 index 000000000..e69de29bb diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index f4441f0d9..c6e48997c 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -16,6 +16,8 @@ bool js_template_enable_debug = false; #define GETTER "getter" #define SETTER "setter" #define PARENT "parent" +#define CTORS "ctors" +#define CTOR_DISPATCHERS "ctor_dispatchers" // variables used in code templates // ATTENTION: be aware of prefix collisions when defining those variables @@ -35,6 +37,16 @@ bool js_template_enable_debug = false; #define T_LOCALS "$jslocals" #define T_CODE "$jscode" +// v8 specific variables used in templates +#define V8_NAME_SPACES "$jsv8nspaces" +#define V8_CLASS_TEMPLATES "$jsv8classtemplates" +#define V8_WRAPPERS "$jsv8wrappers" +#define V8_INHERITANCE "$jsv8inheritance" +#define V8_CLASS_INSTANCES "$jsv8classinstances" +#define V8_STATIC_WRAPPERS "$jsv8staticwrappers" +#define V8_REGISTER_CLASSES "$jsv8registerclasses" +#define V8_REGISTER_NS "$jsv8registernspaces" + /** * A convenience class to manage state variables for emitters. * The implementation delegates to swig Hash DOHs and provides @@ -725,6 +737,9 @@ int JSEmitter::enterClass(Node *n) { Delete(type); state.clazz(TYPE_MANGLED, classtype_mangled); + state.clazz(CTORS, NewString("")); + state.clazz(CTOR_DISPATCHERS, NewString("")); + return SWIG_OK; } @@ -875,8 +890,6 @@ private: #define MEMBER_FUNCTIONS "member_functions" #define STATIC_FUNCTIONS "static_functions" #define STATIC_VARIABLES "static_variables" -#define CTORS "ctors" -#define CTOR_DISPATCHERS "ctor_dispatchers" // keys for function scoped state variables #define FUNCTION_DISPATCHERS "function_dispatchers" @@ -1126,8 +1139,6 @@ int JSCEmitter::enterClass(Node *n) { state.clazz(MEMBER_FUNCTIONS, NewString("")); state.clazz(STATIC_VARIABLES, NewString("")); state.clazz(STATIC_FUNCTIONS, NewString("")); - state.clazz(CTORS, NewString("")); - state.clazz(CTOR_DISPATCHERS, NewString("")); Template t_class_defn = getTemplate("JS_class_definition"); t_class_defn.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) @@ -1536,7 +1547,6 @@ private: File *f_runtime; File *f_header; File *f_class_templates; - File *f_wrapper; File *f_init; File *f_init_namespaces; @@ -1555,51 +1565,6 @@ private: String* NULL_STR; }; -// name of templates -#define V8_INITIALIZER "v8_initializer" -#define V8_DECL_CLASSTEMPLATE "v8_declare_class_template" -#define V8_DEFINE_CLASSTEMPLATE "v8_define_class_template" -#define V8_CREATE_CLASS_INSTANCE "v8_create_class_instance" -#define V8_INHERIT "v8_inherit" -#define V8_REGISTER_CLASS "v8_register_class" -#define V8_CTOR_WRAPPER "v8_ctor_wrapper" -#define V8_GETTER "v8_getter" -#define V8_SETTER "v8_setter" -#define V8_FUNCTION "v8_function" -#define V8_RETRIEVE_THIS "v8_retrieve_this" -#define V8_REGISTER_MEMBER_FUNCTION "v8_register_member_function" -#define V8_REGISTER_GLOBAL_FUNCTION "v8_register_global_function" -#define V8_REGISTER_MEMBER_VARIABLE "v8_register_member_variable" -#define V8_REGISTER_GLOBAL_VARIABLE "v8_register_global_variable" -#define V8_CREATE_NAMESPACE "v8_create_namespace" -#define V8_REGISTER_NAMESPACE "v8_register_namespace" -#define V8_THIS_PTR "v8_this_ptr" - -// keywords used in templates -#define KW_MODULE_NAME "${MODULE}" -#define KW_MANGLED_NAME "${NAME_MANGLED}" -#define KW_UNQUALIFIED_NAME "${NAME_UNQUALIFIED}" -#define KW_CLASSNAME_MANGLED "${CLASSNAME_MANGLED}" -#define KW_BASE_CLASS "${BASE_CLASS}" -#define KW_CONTEXT "${CONTEXT}" -#define KW_TYPE "${TYPE}" -#define KW_ARG "${ARG}" -#define KW_WRAPPER "${WRAPPER}" -#define KW_GETTER "${GETTER}" -#define KW_SETTER "${SETTER}" - -#define KW_NAME_SPACES "${PART_NAMESPACES}" -#define KW_CLASS_TEMPLATES "${PART_CLASS_TEMPLATES}" -#define KW_WRAPPERS "${PART_WRAPPERS}" -#define KW_INHERITANCE "${PART_INHERITANCE}" -#define KW_CLASS_INSTANCES "${PART_CLASS_INSTANCES}" -#define KW_STATIC_WRAPPERS "${PART_STATIC_WRAPPERS}" -#define KW_REGISTER_CLASSES "${PART_REGISTER_CLASSES}" -#define KW_REGISTER_NS "${PART_REGISTER_NS}" - -#define KW_LOCALS T_LOCALS -#define KW_CODE T_CODE - V8Emitter::V8Emitter() : JSEmitter(), GLOBAL(NewString("global")), @@ -1628,7 +1593,6 @@ int V8Emitter::initialize(Node *n) f_runtime = NewString(""); f_header = NewString(""); f_class_templates = NewString(""); - f_wrapper = NewString(""); f_init = NewString(""); f_init_namespaces = NewString(""); @@ -1644,7 +1608,6 @@ int V8Emitter::initialize(Node *n) Swig_register_filebyname("runtime", f_runtime); Swig_register_filebyname("header", f_header); Swig_register_filebyname("init", f_init); - Swig_register_filebyname("wrapper", f_wrapper); return SWIG_OK; } @@ -1657,23 +1620,27 @@ int V8Emitter::dump(Node *n) // write the swig banner Swig_banner(f_wrap_cpp); + SwigType_emit_type_table(f_runtime, f_wrappers); + Printv(f_wrap_cpp, f_runtime, "\n", 0); Printv(f_wrap_cpp, f_header, "\n", 0); Printv(f_wrap_cpp, f_class_templates, "\n", 0); - Printv(f_wrap_cpp, f_wrapper, "\n", 0); + Printv(f_wrap_cpp, f_wrappers, "\n", 0); + + emitNamespaces(); // compose the initializer function using a template // filled with sub-parts - Template initializer(getTemplate(V8_INITIALIZER)); - initializer.replace(KW_MODULE_NAME, module) - .replace(KW_NAME_SPACES, f_init_namespaces) - .replace(KW_CLASS_TEMPLATES, f_init_class_templates) - .replace(KW_WRAPPERS, f_init_wrappers) - .replace(KW_INHERITANCE, f_init_inheritance) - .replace(KW_CLASS_INSTANCES, f_init_class_instances) - .replace(KW_STATIC_WRAPPERS, f_init_static_wrappers) - .replace(KW_REGISTER_CLASSES, f_init_register_classes) - .replace(KW_REGISTER_NS, f_init_register_namespaces) + Template initializer(getTemplate("JS_initializer")); + initializer.replace(T_NAME, module) + .replace(V8_NAME_SPACES, f_init_namespaces) + .replace(V8_CLASS_TEMPLATES, f_init_class_templates) + .replace(V8_WRAPPERS, f_init_wrappers) + .replace(V8_INHERITANCE, f_init_inheritance) + .replace(V8_CLASS_INSTANCES, f_init_class_instances) + .replace(V8_STATIC_WRAPPERS, f_init_static_wrappers) + .replace(V8_REGISTER_CLASSES, f_init_register_classes) + .replace(V8_REGISTER_NS, f_init_register_namespaces) .pretty_print(f_wrap_cpp); return SWIG_OK; @@ -1685,7 +1652,6 @@ int V8Emitter::close() Delete(f_runtime); Delete(f_header); Delete(f_class_templates); - Delete(f_wrapper); Delete(f_init_namespaces); Delete(f_init_class_templates); Delete(f_init_wrappers); @@ -1707,18 +1673,18 @@ int V8Emitter::enterClass(Node *n) JSEmitter::enterClass(n); // emit declaration of a v8 class template - Template t_decl_class(getTemplate(V8_DECL_CLASSTEMPLATE)); - t_decl_class.replace(KW_MANGLED_NAME, state.clazz(NAME_MANGLED)) + Template t_decl_class(getTemplate("jsv8_declare_class_template")); + t_decl_class.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .pretty_print(f_class_templates); // emit definition of v8 class template - Template t_def_class(getTemplate(V8_DEFINE_CLASSTEMPLATE)); - t_def_class.replace(KW_MANGLED_NAME, state.clazz(NAME_MANGLED)) - .replace(KW_UNQUALIFIED_NAME, state.clazz(NAME)) + Template t_def_class(getTemplate("jsv8_define_class_template")); + t_def_class.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) + .replace(T_NAME, state.clazz(NAME)) .pretty_print(f_init_class_templates); - Template t_class_instance(getTemplate(V8_CREATE_CLASS_INSTANCE)); - t_class_instance.replace(KW_MANGLED_NAME, state.clazz(NAME_MANGLED)) + Template t_class_instance(getTemplate("jsv8_create_class_instance")); + t_class_instance.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .pretty_print(f_init_class_instances); return SWIG_OK; @@ -1729,19 +1695,19 @@ int V8Emitter::exitClass(Node *n) // emit inheritance setup Node* baseClass = getBaseClass(n); if(baseClass) { - Template t_inherit(getTemplate(V8_INHERIT)); + Template t_inherit(getTemplate("jsv8_inherit")); String *base_name_mangled = SwigType_manglestr(Getattr(baseClass, "name")); - t_inherit.replace(KW_MANGLED_NAME, state.clazz(NAME_MANGLED)) - .replace(KW_BASE_CLASS, base_name_mangled) + t_inherit.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) + .replace(T_BASECLASS, base_name_mangled) .pretty_print(f_init_inheritance); Delete(base_name_mangled); } // emit registeration of class template - Template t_register(getTemplate(V8_REGISTER_CLASS)); - t_register.replace(KW_MANGLED_NAME, state.clazz(NAME_MANGLED)) - .replace(KW_UNQUALIFIED_NAME, state.clazz(NAME)) - .replace(KW_CONTEXT, Getattr(current_namespace, "name_mangled")) + Template t_register(getTemplate("jsv8_register_class")); + t_register.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) + .replace(T_NAME, state.clazz(NAME)) + .replace(T_PARENT, Getattr(current_namespace, "name_mangled")) .pretty_print(f_init_register_classes); return SWIG_OK; @@ -1761,29 +1727,31 @@ int V8Emitter::exitVariable(Node* n) { if(GetFlag(n, "ismember")) { if(GetFlag(state.variable(), IS_STATIC)) { - Template t_register(getTemplate(V8_REGISTER_GLOBAL_VARIABLE)); + Template t_register(getTemplate("jsv8_register_static_variable")); String *class_instance = NewString(""); Printf(class_instance, "class_%s", state.clazz(NAME_MANGLED)); - t_register.replace(KW_CONTEXT, class_instance) - .replace(KW_UNQUALIFIED_NAME, state.variable(NAME)) - .replace(KW_GETTER, state.variable(GETTER)) - .replace(KW_SETTER, state.variable(SETTER)) + t_register.replace(T_PARENT, class_instance) + .replace(T_NAME, state.variable(NAME)) + .replace(T_GETTER, state.variable(GETTER)) + .replace(T_SETTER, state.variable(SETTER)) .pretty_print(f_init_static_wrappers); Delete(class_instance); } else { - Template t_register(getTemplate(V8_REGISTER_MEMBER_VARIABLE)); - t_register.replace(KW_CLASSNAME_MANGLED, state.clazz(NAME_MANGLED)) - .replace(KW_UNQUALIFIED_NAME, state.clazz(NAME)) - .replace(KW_GETTER, state.variable(GETTER)) - .replace(KW_SETTER, state.variable(SETTER)) + Template t_register(getTemplate("jsv8_register_member_variable")); + t_register.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) + .replace(T_NAME, state.clazz(NAME)) + .replace(T_GETTER, state.variable(GETTER)) + .replace(T_SETTER, state.variable(SETTER)) .pretty_print(f_init_wrappers); } } else { - Template t_register(getTemplate(V8_REGISTER_GLOBAL_VARIABLE)); - t_register.replace(KW_CONTEXT, Getattr(current_namespace, "name")) - .replace(KW_UNQUALIFIED_NAME, state.variable(NAME)) - .replace(KW_GETTER, state.variable(GETTER)) - .replace(KW_SETTER, state.variable(SETTER)) + // Note: a global variable is treated like a static variable + // with the parent being a nspace object (instead of class object) + Template t_register(getTemplate("jsv8_register_static_variable")); + t_register.replace(T_PARENT, Getattr(current_namespace, "name")) + .replace(T_NAME, state.variable(NAME)) + .replace(T_GETTER, state.variable(GETTER)) + .replace(T_SETTER, state.variable(SETTER)) .pretty_print(f_init_wrappers); } @@ -1802,26 +1770,28 @@ int V8Emitter::exitFunction(Node* n) // register the function at the specific context if(GetFlag(n, "ismember")) { if(GetFlag(state.function(), IS_STATIC)) { - Template t_register(getTemplate(V8_REGISTER_GLOBAL_FUNCTION)); + Template t_register(getTemplate("jsv8_register_static_function")); String *class_instance = NewString(""); Printf(class_instance, "class_%s", state.clazz(NAME_MANGLED)); - t_register.replace(KW_CONTEXT, class_instance) - .replace(KW_UNQUALIFIED_NAME, state.function(NAME)) - .replace(KW_MANGLED_NAME, Getattr(n, "wrap:name")); + t_register.replace(T_PARENT, class_instance) + .replace(T_NAME, state.function(NAME)) + .replace(T_WRAPPER, Getattr(n, "wrap:name")); Printv(f_init_static_wrappers, t_register.str(), 0); Delete(class_instance); } else { - Template t_register(getTemplate(V8_REGISTER_MEMBER_FUNCTION)); - t_register.replace(KW_CLASSNAME_MANGLED, state.clazz(NAME_MANGLED)) - .replace(KW_UNQUALIFIED_NAME, state.function(NAME)) - .replace(KW_MANGLED_NAME, Getattr(n, "wrap:name")); + Template t_register(getTemplate("jsv8_register_member_function")); + t_register.replace(T_PARENT, state.clazz(NAME_MANGLED)) + .replace(T_NAME, state.function(NAME)) + .replace(T_WRAPPER, Getattr(n, "wrap:name")); Printv(f_init_wrappers, t_register.str(), "\n", 0); } } else { - Template t_register(getTemplate(V8_REGISTER_GLOBAL_FUNCTION)); - t_register.replace(KW_CONTEXT, Getattr(current_namespace, "name")) - .replace(KW_UNQUALIFIED_NAME, state.function(NAME)) - .replace(KW_MANGLED_NAME, Getattr(n, "wrap:name")); + // Note: a global function is treated like a static function + // with the parent being a nspace object instead of class object + Template t_register(getTemplate("jsv8_register_static_function")); + t_register.replace(T_PARENT, Getattr(current_namespace, "name")) + .replace(T_NAME, state.function(NAME)) + .replace(T_WRAPPER, Getattr(n, "wrap:name")); Printv(f_init_wrappers, t_register.str(), 0); } @@ -1844,17 +1814,22 @@ void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Mar switch (mode) { case Getter: - case Function: if (is_member && !is_static && i == 0) { - Printv(arg, "args[0]", 0); + Printv(arg, "info.Holder()", 0); + } else { + Printf(arg, "args[%d]", i - startIdx); + } + break; + case Function: + if (is_member && !is_static && i == 0) { + Printv(arg, "args.Holder()", 0); } else { Printf(arg, "args[%d]", i - startIdx); } - break; case Setter: if (is_member && !is_static && i == 0) { - Printv(arg, "args[0]", 0); + Printv(arg, "value", 0); } else { Printv(arg, "value", 0); } @@ -1891,12 +1866,12 @@ int V8Emitter::emitNamespaces() { /* // create namespace object and register it to the parent scope Template t_create_ns(getTemplate(V8_CREATE_NAMESPACE)); - t_create_ns.Replace(KW_MANGLED_NAME, scope_mangled); + t_create_ns.Replace(V8_MANGLED_NAME, scope_mangled); Template t_register_ns(getTemplate(V8_REGISTER_NAMESPACE)); - t_register_ns.Replace(KW_MANGLED_NAME, scope_mangled) - .Replace(KW_CONTEXT, parent_scope_mangled) - .Replace(KW_UNQUALIFIED_NAME, scope_unqualified); + t_register_ns.Replace(V8_MANGLED_NAME, scope_mangled) + .Replace(V8_CONTEXT, parent_scope_mangled) + .Replace(V8_UNQUALIFIED_NAME, scope_unqualified); Printv(f_init_namespaces, t_create_ns.str(), 0); // prepend in order to achieve reversed order of registration statements From 72002392770b42c3c1a15a4167426635bf9128db Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:05:51 +0000 Subject: [PATCH 0116/1048] Fix regression in javascript's test-suite configuration. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13789 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/javascript/Makefile.in | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index a8e1759f7..22a3a8a3e 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -3,8 +3,6 @@ ####################################################################### LANGUAGE = javascript -JAVASCRIPT_EXE = ../../../Tools/javascript/javascript -JAVASCRIPT_EXE_SRC = ../../../Tools/javascript/javascript.cxx SCRIPTSUFFIX = _runme.js srcdir = @srcdir@ top_srcdir = @top_srcdir@ @@ -12,6 +10,7 @@ top_builddir = @top_builddir@ JS_INCLUDE = @JSCOREINC@ JS_DLNK = @JSCOREDYNAMICLINKING@ JSCXXFLAGS = @JSCXXFLAGS@ +JAVASCRIPT_EXE = $(top_srcdir)/Tools/javascript/javascript C_TEST_CASES = \ preproc \ @@ -62,7 +61,7 @@ include $(srcdir)/../common.mk # Custom tests - tests with additional commandline options javascript_exe: - $(CXX) $(JSCXXFLAGS) $(JS_INCLUDE) $(JAVASCRIPT_EXE_SRC) $(LIBS) $(JS_DLNK) -o $(JAVASCRIPT_EXE) + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TOP='$(top_builddir)/$(EXAMPLES)' javascript_exe # Rules for the different types of tests %.cpptest: javascript_exe From d5c5f7ebeebeef78bb847dea31bda75e65d5d197 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:06:08 +0000 Subject: [PATCH 0117/1048] Generalize ctor overloading. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13790 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/jsc/javascriptcode.swg | 18 ++++-- Source/Modules/javascript.cxx | 87 ++++++++++++++++----------- 2 files changed, 65 insertions(+), 40 deletions(-) diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index 194181125..68b72e7b8 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -188,7 +188,7 @@ void _wrap_$jsmangledname_finalize(JSObjectRef thisObject) %fragment ("JS_mainctordefn", "templates") %{ -JSObjectRef _wrap_create_$jsmangledname(JSContextRef context, JSObjectRef ctorObject, +JSObjectRef $jswrapper(JSContextRef context, JSObjectRef ctorObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { JSObjectRef thisObject = NULL; @@ -204,13 +204,23 @@ JSObjectRef _wrap_create_$jsmangledname(JSContextRef context, JSObjectRef ctorOb } %} +%fragment ("JS_veto_ctor", "templates") +%{ +JSObjectRef $jsctor(JSContextRef context, JSObjectRef ctorObject, + size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + SWIG_exception(SWIG_ERROR, "Class $jsname can not be instantiated"); + return 0; +} +%} + /************************************************************************************** ctor_dispatch_case: This template is used for the constructor which is overloaded ***************************************************************************************/ %fragment ("JS_ctor_dispatch_case", "templates") %{if(argc == $jsargcount) { - thisObject = _wrap_create_$jsmangledname$jsoverloadext(context, NULL, argc, argv, exception); + thisObject = $jswrapper(context, NULL, argc, argv, exception); if(thisObject != NULL) { *exception=0; return thisObject; } /* reset exception and return */ } %} @@ -218,7 +228,7 @@ ctor_dispatch_case: This template is used for the constructor which is overloade %fragment ("JS_ctordefn", "templates") %{ -JSObjectRef _wrap_create_$jsmangledname$jsoverloadext(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { $jslocals $jscode @@ -275,7 +285,7 @@ bool $jsname_initialize(JSGlobalContextRef context) { %fragment ("JS_create_class_template", "templates") %{ $jsmangledname_classDefinition.staticFunctions = $jsmangledname_staticFunctions; $jsmangledname_classDefinition.staticValues = $jsmangledname_staticValues; - $jsmangledname_classDefinition.callAsConstructor = _wrap_create_$jsmangledname; + $jsmangledname_classDefinition.callAsConstructor = $jsctor; $jsmangledname_objectDefinition.staticValues = $jsmangledname_values; $jsmangledname_objectDefinition.staticFunctions = $jsmangledname_functions; $jsmangledname_objectDefinition.parentClass = $jsbaseclass_classRef; diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index c6e48997c..bab7d8b88 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -13,11 +13,14 @@ bool js_template_enable_debug = false; #define WRAPPER_NAME "wrapper" #define IS_IMMUTABLE "is_immutable" #define IS_STATIC "is_static" +#define IS_ABSTRACT "is_abstract" #define GETTER "getter" #define SETTER "setter" #define PARENT "parent" -#define CTORS "ctors" +#define CTOR "ctor" +#define CTOR_WRAPPERS "ctor_wrappers" #define CTOR_DISPATCHERS "ctor_dispatchers" +#define ARGCOUNT "wrap:argc" // variables used in code templates // ATTENTION: be aware of prefix collisions when defining those variables @@ -26,6 +29,7 @@ bool js_template_enable_debug = false; #define T_TYPE "$jstype" #define T_TYPE_MANGLED "$jsmangledtype" #define T_WRAPPER "$jswrapper" +#define T_CTOR "$jsctor" #define T_GETTER "$jsgetter" #define T_SETTER "$jssetter" #define T_DISPATCH_CASES "$jsdispatchcases" @@ -737,9 +741,15 @@ int JSEmitter::enterClass(Node *n) { Delete(type); state.clazz(TYPE_MANGLED, classtype_mangled); - state.clazz(CTORS, NewString("")); + String *ctor_wrapper = NewString("_wrap_new_veto_"); + Append(ctor_wrapper, state.clazz(NAME)); + state.clazz(CTOR, ctor_wrapper); state.clazz(CTOR_DISPATCHERS, NewString("")); + // HACK: assume that a class is abstract + // this is resolved by emitCtor (which is only called for non abstract classes) + SetFlag(state.clazz(), IS_ABSTRACT); + return SWIG_OK; } @@ -924,6 +934,11 @@ void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Ma String *tm; Parm *p; + int num_args = emit_num_arguments(parms); + String *argcount = NewString(""); + Printf(argcount, "%d", num_args); + Setattr(n, ARGCOUNT, argcount); + int startIdx = 0; if (is_member && !is_static) { startIdx = 1; @@ -1104,10 +1119,8 @@ int JSCEmitter::exitFunction(Node *n) { int JSCEmitter::enterVariable(Node *n) { JSEmitter::enterVariable(n); - state.variable(GETTER, NULL_STR); state.variable(SETTER, VETO_SET); - return SWIG_OK; } @@ -1134,7 +1147,6 @@ int JSCEmitter::exitVariable(Node *n) { int JSCEmitter::enterClass(Node *n) { JSEmitter::enterClass(n); - state.clazz(MEMBER_VARIABLES, NewString("")); state.clazz(MEMBER_FUNCTIONS, NewString("")); state.clazz(STATIC_VARIABLES, NewString("")); @@ -1148,7 +1160,6 @@ int JSCEmitter::enterClass(Node *n) { } int JSCEmitter::exitClass(Node *n) { - Template t_class_tables(getTemplate("JS_class_tables")); t_class_tables.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .replace("$jsclassvariables", state.clazz(MEMBER_VARIABLES)) @@ -1159,13 +1170,15 @@ int JSCEmitter::exitClass(Node *n) { /* adds the ctor wrappers at this position */ // Note: this is necessary to avoid extra forward declarations. - Append(f_wrappers, state.clazz(CTORS)); + //Append(f_wrappers, state.clazz(CTOR_WRAPPERS)); - /* adds the main constructor wrapper function */ - Template t_mainctor(getTemplate("JS_mainctordefn")); - t_mainctor.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) - .replace(T_DISPATCH_CASES, state.clazz(CTOR_DISPATCHERS)) + // for abstract classes add a vetoing ctor + if(GetFlag(state.clazz(), IS_ABSTRACT)) { + Template t_veto_ctor(getTemplate("JS_veto_ctor")); + t_veto_ctor.replace(T_CTOR, state.clazz(CTOR)) + .replace(T_NAME, state.clazz(NAME)) .pretty_print(f_wrappers); + } /* adds a class template statement to initializer function */ Template t_classtemplate(getTemplate("JS_create_class_template")); @@ -1180,6 +1193,7 @@ int JSCEmitter::exitClass(Node *n) { t_classtemplate.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .replace(T_TYPE_MANGLED, state.clazz(TYPE_MANGLED)) .replace(T_BASECLASS, base_name_mangled) + .replace(T_CTOR, state.clazz(CTOR)) .pretty_print(state.global(INITIALIZER)); Delete(base_name_mangled); @@ -1197,15 +1211,18 @@ int JSCEmitter::exitClass(Node *n) { } int JSEmitter::emitCtor(Node *n) { - + Wrapper *wrapper = NewWrapper(); - + Template t_ctor(getTemplate("JS_ctordefn")); - String *mangled_name = SwigType_manglestr(Getattr(n, "name")); - String *overname = Getattr(n, "sym:overname"); - String *wrap_name = Swig_name_wrapper(Getattr(n, "name")); + //String *mangled_name = SwigType_manglestr(Getattr(n, "name")); + String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); + Append(wrap_name, Getattr(n, "sym:overname")); Setattr(n, "wrap:name", wrap_name); + // note: removing the is_abstract flag, as this emitter + // is supposed to be called for non-abstract classes only. + Setattr(state.clazz(), IS_ABSTRACT, 0); ParmList *params = Getattr(n, "parms"); emit_parameter_variables(params, wrapper); @@ -1213,29 +1230,35 @@ int JSEmitter::emitCtor(Node *n) { Printf(wrapper->locals, "%sresult;", SwigType_str(Getattr(n, "type"), 0)); - int num_args = emit_num_arguments(params); String *action = emit_action(n); marshalInputArgs(n, params, wrapper, Ctor, true, false); Printv(wrapper->code, action, "\n", 0); - t_ctor.replace(T_NAME_MANGLED, mangled_name) - .replace(T_OVERLOAD, overname) + t_ctor.replace(T_WRAPPER, wrap_name) + .replace(T_TYPE_MANGLED, state.clazz(TYPE_MANGLED)) .replace(T_LOCALS, wrapper->locals) .replace(T_CODE, wrapper->code) - .replace(T_TYPE_MANGLED, state.clazz(TYPE_MANGLED)) - .pretty_print(state.clazz(CTORS)); + .pretty_print(f_wrappers); - String *argcount = NewString(""); - Printf(argcount, "%d", num_args); Template t_ctor_case(getTemplate("JS_ctor_dispatch_case")); - t_ctor_case.replace(T_NAME_MANGLED, mangled_name) - .replace(T_OVERLOAD, overname) - .replace(T_ARGCOUNT, argcount); + t_ctor_case.replace(T_WRAPPER, wrap_name) + .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)); Append(state.clazz(CTOR_DISPATCHERS), t_ctor_case.str()); - Delete(argcount); DelWrapper(wrapper); + // create a dispatching ctor (if necessary) + if (!Getattr(n, "sym:nextSibling")) { + String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); + Template t_mainctor(getTemplate("JS_mainctordefn")); + t_mainctor.replace(T_WRAPPER, wrap_name) + .replace(T_DISPATCH_CASES, state.clazz(CTOR_DISPATCHERS)) + .pretty_print(f_wrappers); + state.clazz(CTOR, wrap_name); + } else { + state.clazz(CTOR, wrap_name); + } + return SWIG_OK; } @@ -1392,17 +1415,9 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { // handle function overloading if (is_overloaded) { Template t_dispatch_case = getTemplate("JS_function_dispatch_case"); - - int argc = emit_num_arguments(params); - String *argcount = NewString(""); - Printf(argcount, "%d", argc); - t_dispatch_case.replace(T_WRAPPER, wrap_name) - .replace(T_ARGCOUNT, argcount); - + .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)); Append(state.global(FUNCTION_DISPATCHERS), t_dispatch_case.str()); - - Delete(argcount); } DelWrapper(wrapper); From 9b0c8dae839def6e83b447230923630e819b64b4 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:06:26 +0000 Subject: [PATCH 0118/1048] Add argcount checking to functions and ctors. Before argument counts were only checked for overloaded functions/ctors. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13791 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/jsc/javascriptcode.swg | 8 +++++ Source/Modules/javascript.cxx | 43 +++++++++++++++++---------- 2 files changed, 35 insertions(+), 16 deletions(-) diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index 68b72e7b8..7f425c44a 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -52,6 +52,8 @@ JSValueRef $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef th { $jslocals JSValueRef jsresult; + + if(argc != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); $jscode return jsresult; @@ -68,6 +70,8 @@ int $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObjec { $jslocals JSValueRef jsresult; + + if(argc != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); $jscode *result = jsresult; @@ -231,6 +235,9 @@ ctor_dispatch_case: This template is used for the constructor which is overloade JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { $jslocals + + if(argc != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); + $jscode return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); @@ -240,6 +247,7 @@ JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size_t argc return NULL; } %} + /********************************************************************** initializer:This template is dynamic growing and aggregates everything **********************************************************************/ diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index bab7d8b88..de43af246 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -934,16 +934,20 @@ void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Ma String *tm; Parm *p; - int num_args = emit_num_arguments(parms); + // determine an offset index, as members have an extra 'this' argument + // except: static members and ctors. + int startIdx = 0; + if (is_member && !is_static && mode!=Ctor) { + startIdx = 1; + } + + // store number of arguments for argument checks + int num_args = emit_num_arguments(parms) - startIdx; String *argcount = NewString(""); Printf(argcount, "%d", num_args); Setattr(n, ARGCOUNT, argcount); - int startIdx = 0; - if (is_member && !is_static) { - startIdx = 1; - } - + // process arguments int i = 0; for (p = parms; p; p = nextSibling(p), i++) { SwigType *pt = Getattr(p, "type"); @@ -957,7 +961,6 @@ void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Ma } else { Printf(arg, "argv[%d]", i - startIdx); } - break; case Setter: if (is_member && !is_static && i == 0) { @@ -1213,12 +1216,16 @@ int JSCEmitter::exitClass(Node *n) { int JSEmitter::emitCtor(Node *n) { Wrapper *wrapper = NewWrapper(); + + bool is_overloaded = GetFlag(n, "sym:overloaded"); Template t_ctor(getTemplate("JS_ctordefn")); //String *mangled_name = SwigType_manglestr(Getattr(n, "name")); String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); - Append(wrap_name, Getattr(n, "sym:overname")); + if(is_overloaded) { + Append(wrap_name, Getattr(n, "sym:overname")); + } Setattr(n, "wrap:name", wrap_name); // note: removing the is_abstract flag, as this emitter // is supposed to be called for non-abstract classes only. @@ -1238,6 +1245,7 @@ int JSEmitter::emitCtor(Node *n) { .replace(T_TYPE_MANGLED, state.clazz(TYPE_MANGLED)) .replace(T_LOCALS, wrapper->locals) .replace(T_CODE, wrapper->code) + .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)) .pretty_print(f_wrappers); Template t_ctor_case(getTemplate("JS_ctor_dispatch_case")); @@ -1247,14 +1255,16 @@ int JSEmitter::emitCtor(Node *n) { DelWrapper(wrapper); - // create a dispatching ctor (if necessary) - if (!Getattr(n, "sym:nextSibling")) { - String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); - Template t_mainctor(getTemplate("JS_mainctordefn")); - t_mainctor.replace(T_WRAPPER, wrap_name) - .replace(T_DISPATCH_CASES, state.clazz(CTOR_DISPATCHERS)) - .pretty_print(f_wrappers); - state.clazz(CTOR, wrap_name); + // create a dispatching ctor + if(is_overloaded) { + if (!Getattr(n, "sym:nextSibling")) { + String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); + Template t_mainctor(getTemplate("JS_mainctordefn")); + t_mainctor.replace(T_WRAPPER, wrap_name) + .replace(T_DISPATCH_CASES, state.clazz(CTOR_DISPATCHERS)) + .pretty_print(f_wrappers); + state.clazz(CTOR, wrap_name); + } } else { state.clazz(CTOR, wrap_name); } @@ -1410,6 +1420,7 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { t_function.replace(T_WRAPPER, wrap_name) .replace(T_LOCALS, wrapper->locals) .replace(T_CODE, wrapper->code) + .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)) .pretty_print(f_wrappers); // handle function overloading From 0cae8fccd0cfdbcc6dc426c75102ac8a08430b5d Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:06:39 +0000 Subject: [PATCH 0119/1048] Minor refactor of marshalInputArgs for generalization. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13792 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/Modules/javascript.cxx | 71 ++++++++++++++++------------------- 1 file changed, 32 insertions(+), 39 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index de43af246..3ccc9ffa4 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -261,6 +261,8 @@ protected: virtual int emitSetter(Node *n, bool is_member, bool is_static); virtual void marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) = 0; + + virtual void emitInputTypemap(Node *n, Parm *p, Wrapper *wrapper, String *arg); virtual void marshalOutput(Node *n, String *actioncode, Wrapper *wrapper); @@ -931,7 +933,6 @@ JSCEmitter::~JSCEmitter() { * --------------------------------------------------------------------- */ void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) { - String *tm; Parm *p; // determine an offset index, as members have an extra 'this' argument @@ -950,9 +951,7 @@ void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Ma // process arguments int i = 0; for (p = parms; p; p = nextSibling(p), i++) { - SwigType *pt = Getattr(p, "type"); String *arg = NewString(""); - switch (mode) { case Getter: case Function: @@ -975,23 +974,7 @@ void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Ma default: throw "Illegal state."; } - - tm = Getattr(p, "tmap:in"); // Get typemap for this argument - if (tm != NULL) { - Replaceall(tm, "$input", arg); - Setattr(p, "emit:input", arg); - - if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) { - Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); - } else { - Replaceall(tm, "$disown", "0"); - } - Replaceall(tm, "$symname", Getattr(n, "sym:name")); - - Printf(wrapper->code, "%s\n", tm); - } else { - Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0)); - } + emitInputTypemap(n, p, wrapper, arg); Delete(arg); } } @@ -1464,6 +1447,28 @@ int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { return SWIG_OK; } +void JSEmitter::emitInputTypemap(Node *n, Parm *p, Wrapper *wrapper, String *arg) { + // Get input typemap for current param + String *tm = Getattr(p, "tmap:in"); + SwigType *pt = Getattr(p, "type"); + + if (tm != NULL) { + Replaceall(tm, "$input", arg); + Setattr(p, "emit:input", arg); + + // do replacements for built-in variables + if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) { + Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); + } else { + Replaceall(tm, "$disown", "0"); + } + Replaceall(tm, "$symname", Getattr(n, "sym:name")); + Printf(wrapper->code, "%s\n", tm); + } else { + Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0)); + } +} + void JSEmitter::marshalOutput(Node *n, String *actioncode, Wrapper *wrapper) { SwigType *type = Getattr(n, "type"); Setattr(n, "type", type); @@ -1825,7 +1830,6 @@ int V8Emitter::exitFunction(Node* n) } void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) { - String *tm; Parm *p; int startIdx = 0; @@ -1833,9 +1837,14 @@ void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Mar startIdx = 1; } + // store number of arguments for argument checks + int num_args = emit_num_arguments(parms) - startIdx; + String *argcount = NewString(""); + Printf(argcount, "%d", num_args); + Setattr(n, ARGCOUNT, argcount); + int i = 0; for (p = parms; p; p = nextSibling(p), i++) { - SwigType *pt = Getattr(p, "type"); String *arg = NewString(""); switch (mode) { @@ -1866,23 +1875,7 @@ void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Mar default: throw "Illegal state."; } - - tm = Getattr(p, "tmap:in"); // Get typemap for this argument - if (tm != NULL) { - Replaceall(tm, "$input", arg); - Setattr(p, "emit:input", arg); - - if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) { - Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); - } else { - Replaceall(tm, "$disown", "0"); - } - Replaceall(tm, "$symname", Getattr(n, "sym:name")); - - Printf(wrapper->code, "%s\n", tm); - } else { - Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0)); - } + emitInputTypemap(n, p, wrapper, arg); Delete(arg); } } From cda09239ad4b7f5367ea3382e4497cc8d830338b Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:06:58 +0000 Subject: [PATCH 0120/1048] Several fixes in v8 emitter and code templates. Achieves first compile of example "class" after re-integration. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13793 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptcode.swg | 71 ++++++++++++---------- Lib/javascript/v8/javascripthelpers.swg | 11 ++-- Lib/javascript/v8/javascriptruntime.swg | 25 +++++++- Source/Modules/javascript.cxx | 80 ++++++++++++++----------- 4 files changed, 112 insertions(+), 75 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 59b071c89..c2b6819d3 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -1,5 +1,5 @@ %fragment("JS_ctordefn", "templates") %{ -v8::Handle $jsmangledname_new(const v8::Arguments& args) { +v8::Handle $jswrapper(const v8::Arguments& args) { v8::HandleScope scope; v8::Handle self = args.Holder(); $jslocals @@ -8,13 +8,21 @@ v8::Handle $jsmangledname_new(const v8::Arguments& args) { return scope.Close(self); goto fail; fail: - return scope.Close(v8::Undefined); + return scope.Close(v8::Undefined()); +}%} + +%fragment ("JS_veto_ctor", "templates") +%{ +v8::Handle $jsctor(const v8::Arguments& args) { + v8::HandleScope scope; + SWIG_exception(SWIG_ERROR, "Class $jsname can not be instantiated"); + return scope.Close(v8::Undefined()); }%} %fragment("JS_getproperty", "templates") %{ v8::Handle $jsgetter(v8::Local property, const v8::AccessorInfo& info) { v8::HandleScope scope; - v8::Handle jsresult; + v8::Handle jsresult; $jslocals $jscode return scope.Close(jsresult); @@ -36,7 +44,7 @@ fail: %fragment("JS_functionwrapper", "templates") %{ v8::Handle $jswrapper(const v8::Arguments &args) { v8::HandleScope scope; - v8::Handle jsresult; + v8::Handle jsresult; $jslocals $jscode return scope.Close(jsresult); @@ -45,7 +53,6 @@ fail: return scope.Close(v8::Undefined()); }%} -// TODO: implement ctor overloading properly! %fragment ("JS_mainctordefn", "templates") %{ // TODO: implement JS_mainctordefn @@ -61,41 +68,41 @@ fail: // TODO: implement JS_destructordefn %} -%fragment("jsv8_declare_class_template", "templates") %{ -v8::Persistent SWIGV8_$jsmangledname;%} +%fragment("jsv8_declare_class_template", "templates") +%{v8::Persistent SWIGV8_$jsmangledname;%} -%fragment("jsv8_define_class_template", "templates") %{ -SWIGV8_$jsmangledname = SWIGV8_CreateClassTemplate("$jsname" , $jsmangledname_new);%} +%fragment("jsv8_define_class_template", "templates") +%{SWIGV8_$jsmangledname = SWIGV8_CreateClassTemplate("$jsname" , $jsctor);%} -%fragment("jsv8_create_class_instance", "templates") %{ -v8::Handle class_$jsmangledname = SWIGV8_$jsmangledname->GetFunction();%} +%fragment("jsv8_create_class_instance", "templates") +%{v8::Handle class_$jsmangledname = SWIGV8_$jsmangledname->GetFunction();%} -%fragment("jsv8_inherit", "templates") %{ -SWIGV8_$jsmangledname->Inherit(SWIGV8_$jsbaseclass);%} +%fragment("jsv8_inherit", "templates") +%{SWIGV8_$jsmangledname->Inherit(SWIGV8_$jsbaseclass);%} -%fragment("jsv8_register_class", "templates") %{ -$jsparent->Set(v8::String::NewSymbol("$jsname"), class_$jsmangledname);%} +%fragment("jsv8_register_class", "templates") +%{$jsparent->Set(v8::String::NewSymbol("$jsname"), class_$jsmangledname);%} -%fragment("jsv8_create_namespace", "templates") %{ -v8::Handle $jsmangledname = v8::ObjectTemplate::New();%} +%fragment("jsv8_create_namespace", "templates") +%{v8::Handle $jsmangledname = v8::ObjectTemplate::New();%} -%fragment("jsv8_register_member_function", "templates") %{ -SWIGV8_AddMemberFunction(SWIGV8_$jsmangledname, "$jsname", $jswrapper);%} +%fragment("jsv8_register_member_function", "templates") +%{SWIGV8_AddMemberFunction(SWIGV8_$jsmangledname, "$jsname", $jswrapper);%} -%fragment("jsv8_register_static_function", "templates") %{ -SWIGV8_AddGlobalFunction($jsparent, "$jsname", $jswrapper);%} +%fragment("jsv8_register_static_function", "templates") +%{SWIGV8_AddGlobalFunction(SWIGV8_$jsparent, "$jsname", $jswrapper);%} -%fragment("jsv8_register_member_variable", "templates") %{ -SWIGV8_AddMemberVariable(SWIGV8_$jsmangledname, "$jsname", $jsgetter, $jssetter);%} +%fragment("jsv8_register_member_variable", "templates") +%{SWIGV8_AddMemberVariable(SWIGV8_$jsmangledname, "$jsname", $jsgetter, $jssetter);%} -%fragment("jsv8_register_static_variable", "templates") %{ -SWIGV8_AddGlobalVariable($jsparent, "$jsname", $jsgetter, $jssetter);%} +%fragment("jsv8_register_static_variable", "templates") +%{SWIGV8_AddGlobalVariable(SWIGV8_$jsparent, "$jsname", $jsgetter, $jssetter);%} -%fragment("jsv8_register_namespace", "templates") %{ -$jsparent->Set(v8::String::NewSymbol("$jsname", $jsmangledname->NewInstance()));%} - -%fragment("JS_initializer", "templates") %{ +%fragment("jsv8_register_namespace", "templates") +%{$jsparent->Set(v8::String::NewSymbol("$jsname"), $jsmangledname->NewInstance());%} +%fragment("JS_initializer", "templates") +%{ extern "C" { void $jsname_initialize(v8::Handle context) @@ -115,12 +122,12 @@ void $jsname_initialize(v8::Handle context) /* setup inheritances */ $jsv8inheritance - /* class instances */ - $jsv8classinstances - /* add static class functions and variables */ $jsv8staticwrappers + /* class instances */ + $jsv8classinstances + /* register classes */ $jsv8registerclasses diff --git a/Lib/javascript/v8/javascripthelpers.swg b/Lib/javascript/v8/javascripthelpers.swg index 1159f7ef3..bd103702c 100644 --- a/Lib/javascript/v8/javascripthelpers.swg +++ b/Lib/javascript/v8/javascripthelpers.swg @@ -24,10 +24,12 @@ void SWIGV8_AddMemberFunction(v8::Handle class_templ, cons /** * Registers a class method with given name for a given class template. */ -void SWIGV8_AddGlobalFunction(v8::Handle obj_templ, const char* symbol, v8::InvocationCallback _func) { - obj_templ->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)->GetFunction()); +void SWIGV8_AddGlobalFunction(v8::Handle class_templ, const char* symbol, v8::InvocationCallback _func) { + v8::Handle obj_templ = class_templ->InstanceTemplate(); + obj_templ->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)->GetFunction()); } + /** * Registers a class property with given name for a given class template. */ @@ -39,7 +41,8 @@ void SWIGV8_AddMemberVariable(v8::Handle class_templ, cons /** * Registers a class method with given name for a given class template. */ -void SWIGV8_AddGlobalVariable(v8::Handle obj_templ, const char* symbol, v8::AccessorGetter getter, v8::AccessorSetter setter) { - obj_templ->SetAccessor(v8::String::NewSymbol(symbol), getter, setter); +void SWIGV8_AddGlobalVariable(v8::Handle class_templ, const char* symbol, v8::AccessorGetter getter, v8::AccessorSetter setter) { + v8::Handle obj_templ = class_templ->InstanceTemplate(); + obj_templ->SetAccessor(v8::String::NewSymbol(symbol), getter, setter); } %} // v8_helper_functions diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index 15d8a35fc..e8b26892c 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -24,7 +24,7 @@ typedef struct { bool swigCMemOwn; void *swigCObject; swig_type_info *info; -}SWIG_PRV_DATA; +} SWIG_PRV_DATA; %} %insert(runtime) %{ @@ -88,8 +88,27 @@ int SWIG_V8_ConvertPtr(v8::Handle valRef, void** ptr, swig_type_info } v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, int flags) { - // TODO: wrap ptr into an v8 object - return v8::Undefined(); + v8::HandleScope scope; + + v8::Local class_templ; + if(info->clientdata == NULL) { + // TODO: get class template for unknown types + //class_templ = _SwigObject_classRef; + } else { + class_templ = *((v8::Local*) info->clientdata); + } + + v8::Handle inst_templ = class_templ->InstanceTemplate(); + v8::Local result = inst_templ->NewInstance(); + + SWIG_PRV_DATA* cdata = (SWIG_PRV_DATA*) new SWIG_PRV_DATA; + cdata->swigCObject = ptr; + cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; + cdata->info = info; + + result->SetInternalField(0, v8::External::New(cdata)); + + return scope.Close(result); } #define SWIG_ConvertPtr(obj, ptr, info, flags) SWIG_V8_ConvertPtr(obj, ptr, info, flags) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 3ccc9ffa4..14b2e7859 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1708,21 +1708,29 @@ int V8Emitter::enterClass(Node *n) t_decl_class.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .pretty_print(f_class_templates); - // emit definition of v8 class template - Template t_def_class(getTemplate("jsv8_define_class_template")); - t_def_class.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) - .replace(T_NAME, state.clazz(NAME)) - .pretty_print(f_init_class_templates); - - Template t_class_instance(getTemplate("jsv8_create_class_instance")); - t_class_instance.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) - .pretty_print(f_init_class_instances); - return SWIG_OK; } int V8Emitter::exitClass(Node *n) { + if(GetFlag(state.clazz(), IS_ABSTRACT)) { + Template t_veto_ctor(getTemplate("JS_veto_ctor")); + t_veto_ctor.replace(T_CTOR, state.clazz(CTOR)) + .replace(T_NAME, state.clazz(NAME)) + .pretty_print(f_wrappers); + } + + // emit definition of v8 class template + Template t_def_class(getTemplate("jsv8_define_class_template")); + t_def_class.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) + .replace(T_NAME, state.clazz(NAME)) + .replace(T_CTOR, state.clazz(CTOR)) + .pretty_print(f_init_class_templates); + + Template t_class_instance(getTemplate("jsv8_create_class_instance")); + t_class_instance.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) + .pretty_print(f_init_class_instances); + // emit inheritance setup Node* baseClass = getBaseClass(n); if(baseClass) { @@ -1759,14 +1767,11 @@ int V8Emitter::exitVariable(Node* n) if(GetFlag(n, "ismember")) { if(GetFlag(state.variable(), IS_STATIC)) { Template t_register(getTemplate("jsv8_register_static_variable")); - String *class_instance = NewString(""); - Printf(class_instance, "class_%s", state.clazz(NAME_MANGLED)); - t_register.replace(T_PARENT, class_instance) + t_register.replace(T_PARENT, state.clazz(NAME_MANGLED)) .replace(T_NAME, state.variable(NAME)) .replace(T_GETTER, state.variable(GETTER)) .replace(T_SETTER, state.variable(SETTER)) .pretty_print(f_init_static_wrappers); - Delete(class_instance); } else { Template t_register(getTemplate("jsv8_register_member_variable")); t_register.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) @@ -1779,7 +1784,7 @@ int V8Emitter::exitVariable(Node* n) // Note: a global variable is treated like a static variable // with the parent being a nspace object (instead of class object) Template t_register(getTemplate("jsv8_register_static_variable")); - t_register.replace(T_PARENT, Getattr(current_namespace, "name")) + t_register.replace(T_PARENT, Getattr(current_namespace, NAME)) .replace(T_NAME, state.variable(NAME)) .replace(T_GETTER, state.variable(GETTER)) .replace(T_SETTER, state.variable(SETTER)) @@ -1802,16 +1807,13 @@ int V8Emitter::exitFunction(Node* n) if(GetFlag(n, "ismember")) { if(GetFlag(state.function(), IS_STATIC)) { Template t_register(getTemplate("jsv8_register_static_function")); - String *class_instance = NewString(""); - Printf(class_instance, "class_%s", state.clazz(NAME_MANGLED)); - t_register.replace(T_PARENT, class_instance) + t_register.replace(T_PARENT, state.clazz(NAME_MANGLED)) .replace(T_NAME, state.function(NAME)) .replace(T_WRAPPER, Getattr(n, "wrap:name")); Printv(f_init_static_wrappers, t_register.str(), 0); - Delete(class_instance); } else { Template t_register(getTemplate("jsv8_register_member_function")); - t_register.replace(T_PARENT, state.clazz(NAME_MANGLED)) + t_register.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .replace(T_NAME, state.function(NAME)) .replace(T_WRAPPER, Getattr(n, "wrap:name")); Printv(f_init_wrappers, t_register.str(), "\n", 0); @@ -1820,7 +1822,7 @@ int V8Emitter::exitFunction(Node* n) // Note: a global function is treated like a static function // with the parent being a nspace object instead of class object Template t_register(getTemplate("jsv8_register_static_function")); - t_register.replace(T_PARENT, Getattr(current_namespace, "name")) + t_register.replace(T_PARENT, Getattr(current_namespace, NAME)) .replace(T_NAME, state.function(NAME)) .replace(T_WRAPPER, Getattr(n, "wrap:name")); Printv(f_init_wrappers, t_register.str(), 0); @@ -1881,21 +1883,27 @@ void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Mar } int V8Emitter::emitNamespaces() { -// TODO: handle namespaces: -/* - // create namespace object and register it to the parent scope - Template t_create_ns(getTemplate(V8_CREATE_NAMESPACE)); - t_create_ns.Replace(V8_MANGLED_NAME, scope_mangled); - - Template t_register_ns(getTemplate(V8_REGISTER_NAMESPACE)); - t_register_ns.Replace(V8_MANGLED_NAME, scope_mangled) - .Replace(V8_CONTEXT, parent_scope_mangled) - .Replace(V8_UNQUALIFIED_NAME, scope_unqualified); + Iterator it; + for (it = First(namespaces); it.item; it = Next(it)) { + Hash *entry = it.item; + String *name = Getattr(entry, NAME); + String *name_mangled = Getattr(entry, NAME_MANGLED); + String *parent = Getattr(entry, PARENT); + String *parent_mangled = Swig_name_mangle(parent); - Printv(f_init_namespaces, t_create_ns.str(), 0); + // create namespace object and register it to the parent scope + Template t_create_ns(getTemplate("jsv8_create_namespace")); + t_create_ns.replace(T_NAME_MANGLED, name_mangled) + .pretty_print(f_init_namespaces); + + Template t_register_ns(getTemplate("jsv8_register_namespace")); + t_register_ns.replace(T_NAME_MANGLED, name_mangled) + .replace(T_NAME, name) + .replace(T_PARENT, parent_mangled); + // prepend in order to achieve reversed order of registration statements Insert(f_init_register_namespaces, 0, t_register_ns.str()); -*/ + } return SWIG_OK; } @@ -2044,9 +2052,9 @@ String *Template::str() { String *pre_code = NewString(""); String *post_code = NewString(""); String *debug_code = NewString(""); - Printf(pre_code, "//begin fragment(\"%s\")\n", templateName); - Printf(post_code, "//end fragment(\"%s\")\n", templateName); - Printf(debug_code, "%s\n%s\n%s", pre_code, code, post_code); + Printf(pre_code, "/* begin fragment(\"%s\") */", templateName); + Printf(post_code, "/* end fragment(\"%s\") */", templateName); + Printf(debug_code, "%s\n%s\n%s\n", pre_code, code, post_code); Delete(code); Delete(pre_code); From 022c274256d5f61daa6a880d781b903cb82af677 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:07:21 +0000 Subject: [PATCH 0121/1048] Minor fixes in v8 javascript shell. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13794 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/Makefile.in | 2 +- Tools/javascript/v8_shell.cxx | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 027ce795e..8bf1f1498 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -552,7 +552,7 @@ ifeq (,$(V8)) else JSEXE_SRC = $(JSEXE_SRC_DIR)/javascript.cxx $(JSEXE_SRC_DIR)/js_shell.cxx $(JSEXE_SRC_DIR)/v8_shell.cxx JSEXE_OPTS = -v8 - JSEXE_FLAG = -DUSE_V8 + JSEXE_FLAGS = -DUSE_V8 endif # ---------------------------------------------------------------- diff --git a/Tools/javascript/v8_shell.cxx b/Tools/javascript/v8_shell.cxx index e124ebd7d..c4cbcecc5 100755 --- a/Tools/javascript/v8_shell.cxx +++ b/Tools/javascript/v8_shell.cxx @@ -220,3 +220,7 @@ void V8Shell::ReportException(v8::TryCatch* try_catch) { const char* V8Shell::ToCString(const v8::String::Utf8Value& value) { return *value ? *value : ""; } + +JSShell* create_v8_shell() { + return new V8Shell(); +} From 78f5b46381e4c93f3d1227a702761a8eda01f4ca Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:07:43 +0000 Subject: [PATCH 0122/1048] Fix class example. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13795 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/javascript/class/{example.cpp => example.cxx} | 0 Examples/javascript/class/example.h | 1 - 2 files changed, 1 deletion(-) rename Examples/javascript/class/{example.cpp => example.cxx} (100%) diff --git a/Examples/javascript/class/example.cpp b/Examples/javascript/class/example.cxx similarity index 100% rename from Examples/javascript/class/example.cpp rename to Examples/javascript/class/example.cxx diff --git a/Examples/javascript/class/example.h b/Examples/javascript/class/example.h index 9d19e340a..64b7684fa 100755 --- a/Examples/javascript/class/example.h +++ b/Examples/javascript/class/example.h @@ -12,7 +12,6 @@ public: void move(double dx, double dy); virtual double area(void) = 0; virtual double perimeter(void) = 0; - static void printMe(void); static int nshapes; }; From 46cff47ada4ec3197798359425c165e09d4498a5 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:08:03 +0000 Subject: [PATCH 0123/1048] Several fixes in generator for v8 initializer function. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13796 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptcode.swg | 76 ++++++++++++------------- Lib/javascript/v8/javascripthelpers.swg | 28 +++++---- Source/Modules/javascript.cxx | 17 +++--- 3 files changed, 60 insertions(+), 61 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index c2b6819d3..8ba811354 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -69,37 +69,37 @@ fail: %} %fragment("jsv8_declare_class_template", "templates") -%{v8::Persistent SWIGV8_$jsmangledname;%} +%{v8::Persistent $jsmangledname_class;%} %fragment("jsv8_define_class_template", "templates") -%{SWIGV8_$jsmangledname = SWIGV8_CreateClassTemplate("$jsname" , $jsctor);%} +%{$jsmangledname_class = SWIGV8_CreateClassTemplate("$jsname" , $jsctor);%} %fragment("jsv8_create_class_instance", "templates") -%{v8::Handle class_$jsmangledname = SWIGV8_$jsmangledname->GetFunction();%} +%{v8::Handle $jsmangledname = $jsmangledname_class->GetFunction();%} %fragment("jsv8_inherit", "templates") -%{SWIGV8_$jsmangledname->Inherit(SWIGV8_$jsbaseclass);%} +%{$jsmangledname_class->Inherit($jsbaseclass_class);%} %fragment("jsv8_register_class", "templates") -%{$jsparent->Set(v8::String::NewSymbol("$jsname"), class_$jsmangledname);%} +%{$jsparent->Set(v8::String::NewSymbol("$jsname"), $jsmangledname);%} %fragment("jsv8_create_namespace", "templates") -%{v8::Handle $jsmangledname = v8::ObjectTemplate::New();%} +%{v8::Handle $jsmangledname = v8::Object::New();%} %fragment("jsv8_register_member_function", "templates") -%{SWIGV8_AddMemberFunction(SWIGV8_$jsmangledname, "$jsname", $jswrapper);%} - -%fragment("jsv8_register_static_function", "templates") -%{SWIGV8_AddGlobalFunction(SWIGV8_$jsparent, "$jsname", $jswrapper);%} +%{SWIGV8_AddMemberFunction($jsmangledname_class, "$jsname", $jswrapper);%} %fragment("jsv8_register_member_variable", "templates") -%{SWIGV8_AddMemberVariable(SWIGV8_$jsmangledname, "$jsname", $jsgetter, $jssetter);%} +%{SWIGV8_AddMemberVariable($jsmangledname_class, "$jsname", $jsgetter, $jssetter);%} + +%fragment("jsv8_register_static_function", "templates") +%{SWIGV8_AddStaticFunction($jsparent, "$jsname", $jswrapper);%} %fragment("jsv8_register_static_variable", "templates") -%{SWIGV8_AddGlobalVariable(SWIGV8_$jsparent, "$jsname", $jsgetter, $jssetter);%} +%{SWIGV8_AddStaticVariable($jsparent, "$jsname", $jsgetter, $jssetter);%} %fragment("jsv8_register_namespace", "templates") -%{$jsparent->Set(v8::String::NewSymbol("$jsname"), $jsmangledname->NewInstance());%} +%{$jsparent->Set(v8::String::NewSymbol("$jsname"), $jsmangledname);%} %fragment("JS_initializer", "templates") %{ @@ -107,32 +107,32 @@ extern "C" { void $jsname_initialize(v8::Handle context) { - v8::HandleScope scope; - v8::Local global = context->Global(); + v8::HandleScope scope; + v8::Local global = context->Global(); - /* create object templates for namespaces */ - $jsv8nspaces - - /* create class templates */ - $jsv8classtemplates - - /* register wrapper functions */ - $jsv8wrappers - - /* setup inheritances */ - $jsv8inheritance - - /* add static class functions and variables */ - $jsv8staticwrappers - - /* class instances */ - $jsv8classinstances - - /* register classes */ - $jsv8registerclasses - - /* create and register namespace objects */ - $jsv8registernspaces + /* create objects for namespaces */ + $jsv8nspaces + + /* create class templates */ + $jsv8classtemplates + + /* register wrapper functions */ + $jsv8wrappers + + /* setup inheritances */ + $jsv8inheritance + + /* class instances */ + $jsv8classinstances + + /* add static class functions and variables */ + $jsv8staticwrappers + + /* register classes */ + $jsv8registerclasses + + /* create and register namespace objects */ + $jsv8registernspaces } }%} diff --git a/Lib/javascript/v8/javascripthelpers.swg b/Lib/javascript/v8/javascripthelpers.swg index bd103702c..5de11feb3 100644 --- a/Lib/javascript/v8/javascripthelpers.swg +++ b/Lib/javascript/v8/javascripthelpers.swg @@ -21,28 +21,26 @@ void SWIGV8_AddMemberFunction(v8::Handle class_templ, cons proto_templ->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)); } -/** - * Registers a class method with given name for a given class template. - */ -void SWIGV8_AddGlobalFunction(v8::Handle class_templ, const char* symbol, v8::InvocationCallback _func) { - v8::Handle obj_templ = class_templ->InstanceTemplate(); - obj_templ->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)->GetFunction()); -} - - /** * Registers a class property with given name for a given class template. */ void SWIGV8_AddMemberVariable(v8::Handle class_templ, const char* symbol, v8::AccessorGetter getter, v8::AccessorSetter setter) { - v8::Handle proto_templ = class_templ->InstanceTemplate(); - proto_templ->SetAccessor(v8::String::NewSymbol(symbol), getter, setter); + v8::Handle proto_templ = class_templ->InstanceTemplate(); + proto_templ->SetAccessor(v8::String::NewSymbol(symbol), getter, setter); } /** - * Registers a class method with given name for a given class template. + * Registers a class method with given name for a given object. */ -void SWIGV8_AddGlobalVariable(v8::Handle class_templ, const char* symbol, v8::AccessorGetter getter, v8::AccessorSetter setter) { - v8::Handle obj_templ = class_templ->InstanceTemplate(); - obj_templ->SetAccessor(v8::String::NewSymbol(symbol), getter, setter); +void SWIGV8_AddStaticFunction(v8::Handle obj, const char* symbol, v8::InvocationCallback _func) { + obj->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)->GetFunction()); } + +/** + * Registers a class method with given name for a given object. + */ +void SWIGV8_AddStaticVariable(v8::Handle obj, const char* symbol, v8::AccessorGetter getter, v8::AccessorSetter setter) { + obj->SetAccessor(v8::String::NewSymbol(symbol), getter, setter); +} + %} // v8_helper_functions diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 14b2e7859..a415e8371 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1728,7 +1728,8 @@ int V8Emitter::exitClass(Node *n) .pretty_print(f_init_class_templates); Template t_class_instance(getTemplate("jsv8_create_class_instance")); - t_class_instance.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) + t_class_instance.replace(T_NAME, state.clazz(NAME)) + .replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .pretty_print(f_init_class_instances); // emit inheritance setup @@ -1790,7 +1791,7 @@ int V8Emitter::exitVariable(Node* n) .replace(T_SETTER, state.variable(SETTER)) .pretty_print(f_init_wrappers); } - + return SWIG_OK; } @@ -1809,14 +1810,14 @@ int V8Emitter::exitFunction(Node* n) Template t_register(getTemplate("jsv8_register_static_function")); t_register.replace(T_PARENT, state.clazz(NAME_MANGLED)) .replace(T_NAME, state.function(NAME)) - .replace(T_WRAPPER, Getattr(n, "wrap:name")); - Printv(f_init_static_wrappers, t_register.str(), 0); + .replace(T_WRAPPER, Getattr(n, "wrap:name")) + .pretty_print(f_init_static_wrappers); } else { Template t_register(getTemplate("jsv8_register_member_function")); t_register.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .replace(T_NAME, state.function(NAME)) - .replace(T_WRAPPER, Getattr(n, "wrap:name")); - Printv(f_init_wrappers, t_register.str(), "\n", 0); + .replace(T_WRAPPER, Getattr(n, "wrap:name")) + .pretty_print(f_init_wrappers); } } else { // Note: a global function is treated like a static function @@ -1824,8 +1825,8 @@ int V8Emitter::exitFunction(Node* n) Template t_register(getTemplate("jsv8_register_static_function")); t_register.replace(T_PARENT, Getattr(current_namespace, NAME)) .replace(T_NAME, state.function(NAME)) - .replace(T_WRAPPER, Getattr(n, "wrap:name")); - Printv(f_init_wrappers, t_register.str(), 0); + .replace(T_WRAPPER, Getattr(n, "wrap:name")) + .pretty_print(f_init_wrappers); } return SWIG_OK; From 9a914af2b787b336228f779c519b39147e536a68 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:08:16 +0000 Subject: [PATCH 0124/1048] Fix v8 shell to initialize v8 context in proper order. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13797 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Tools/javascript/v8_shell.cxx | 91 ++++++++++++++++++++++++++++------- 1 file changed, 74 insertions(+), 17 deletions(-) diff --git a/Tools/javascript/v8_shell.cxx b/Tools/javascript/v8_shell.cxx index c4cbcecc5..62620a72a 100755 --- a/Tools/javascript/v8_shell.cxx +++ b/Tools/javascript/v8_shell.cxx @@ -14,9 +14,14 @@ typedef int (*V8ExtensionRegistrar) (v8::Handle); class V8Shell: public JSShell { public: - V8Shell(); - - virtual ~V8Shell(); + V8Shell(); + + virtual ~V8Shell(); + + virtual bool RunScript(const std::string& scriptPath); + + virtual bool RunShell(); + protected: @@ -41,6 +46,8 @@ private: static v8::Handle Version(const v8::Arguments& args); static const char* ToCString(const v8::String::Utf8Value& value); + + void ExtendEngine(); protected: @@ -76,24 +83,81 @@ bool V8Shell::RegisterModule(HANDLE library, const std::string& module_name) { return true; } -bool V8Shell::InitializeEngine() { +bool V8Shell::RunScript(const std::string& scriptPath) { + if (!context.IsEmpty()) { context.Dispose(); } + + std::string source = ReadFile(scriptPath); context = CreateShellContext(); if (context.IsEmpty()) { printf("Could not create context.\n"); - return 1; + return false; + } + context->Enter(); + + v8::Context::Scope context_scope(context); + ExtendEngine(); + + if(!ExecuteScript(source, scriptPath)) { + return false; + } + + context->Exit(); + context.Dispose(); + v8::V8::Dispose(); +} + +bool V8Shell::RunShell() { + + if (!context.IsEmpty()) { + context.Dispose(); + } + + context = CreateShellContext(); + if (context.IsEmpty()) { + printf("Could not create context.\n"); + return false; } context->Enter(); + + v8::Context::Scope context_scope(context); + ExtendEngine(); + + static const int kBufferSize = 1024; + while (true) { + char buffer[kBufferSize]; + printf("> "); + char* str = fgets(buffer, kBufferSize, stdin); + if (str == NULL) break; + std::string source(str); + ExecuteScript(source, "(shell)"); + } + printf("\n"); + + context->Exit(); + context.Dispose(); + v8::V8::Dispose(); +} + + +bool V8Shell::InitializeEngine() { +} + +void V8Shell::ExtendEngine() { + + // register extensions + for(std::vector::iterator it=module_initializers.begin(); + it != module_initializers.end(); ++it) { + (*it)(context); + } + } bool V8Shell::ExecuteScript(const std::string& source, const std::string& name) { - // Enter the execution environment before evaluating any code. - v8::Context::Scope context_scope(context); - v8::HandleScope handle_scope; v8::TryCatch try_catch; v8::Handle script = v8::Script::Compile(v8::String::New(source.c_str()), v8::String::New(name.c_str())); @@ -123,12 +187,11 @@ bool V8Shell::ExecuteScript(const std::string& source, const std::string& name) } bool V8Shell::DisposeEngine() { - context->Exit(); - context.Dispose(); - v8::V8::Dispose(); } v8::Persistent V8Shell::CreateShellContext() { + v8::HandleScope scope; + // Create a template for the global object. v8::Handle global = v8::ObjectTemplate::New(); @@ -139,12 +202,6 @@ v8::Persistent V8Shell::CreateShellContext() { v8::Persistent _context = v8::Context::New(NULL, global); - // register extensions - for(std::vector::iterator it=module_initializers.begin(); - it != module_initializers.end(); ++it) { - (*it)(_context); - } - return _context; } From 21bdb78f1ca2f016afb73c84b4286312f47d3175 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:08:33 +0000 Subject: [PATCH 0125/1048] Activate SwigModuleInitializer for in v8 emitter. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13798 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptcode.swg | 2 ++ Source/Modules/javascript.cxx | 32 +++++++++++++++++----------- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 8ba811354..ef16478d8 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -107,6 +107,8 @@ extern "C" { void $jsname_initialize(v8::Handle context) { + SWIG_InitializeModule(0); + v8::HandleScope scope; v8::Local global = context->Global(); diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index a415e8371..f114c74c9 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1575,19 +1575,23 @@ protected: private: - File *f_runtime; - File *f_header; - File *f_class_templates; - File *f_init; + /* built-in parts */ + String *f_runtime; + String *f_header; + String *f_init; - File *f_init_namespaces; - File *f_init_class_templates; - File *f_init_wrappers; - File *f_init_inheritance; - File *f_init_class_instances; - File *f_init_static_wrappers; - File *f_init_register_classes; - File *f_init_register_namespaces; + /* part for class templates */ + String *f_class_templates; + + /* parts for initilizer */ + String *f_init_namespaces; + String *f_init_class_templates; + String *f_init_wrappers; + String *f_init_inheritance; + String *f_init_class_instances; + String *f_init_static_wrappers; + String *f_init_register_classes; + String *f_init_register_namespaces; // the output cpp file File *f_wrap_cpp; @@ -1672,7 +1676,9 @@ int V8Emitter::dump(Node *n) .replace(V8_STATIC_WRAPPERS, f_init_static_wrappers) .replace(V8_REGISTER_CLASSES, f_init_register_classes) .replace(V8_REGISTER_NS, f_init_register_namespaces) - .pretty_print(f_wrap_cpp); + .pretty_print(f_init); + + Printv(f_wrap_cpp, f_init, 0); return SWIG_OK; } From f1e9b21dfd63df4b694bac471daa1f9359c88378 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:08:50 +0000 Subject: [PATCH 0126/1048] Add missing swig_type_info registration in v8 emitter. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13799 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptcode.swg | 8 +- Source/Modules/javascript.cxx | 626 +++++++++++++-------------- 2 files changed, 314 insertions(+), 320 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index ef16478d8..2adbd1307 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -4,8 +4,9 @@ v8::Handle $jswrapper(const v8::Arguments& args) { v8::Handle self = args.Holder(); $jslocals $jscode - self->SetInternalField(0, v8::External::New(result)); - return scope.Close(self); + + return SWIG_V8_NewPointerObj(result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); + goto fail; fail: return scope.Close(v8::Undefined()); @@ -72,7 +73,8 @@ fail: %{v8::Persistent $jsmangledname_class;%} %fragment("jsv8_define_class_template", "templates") -%{$jsmangledname_class = SWIGV8_CreateClassTemplate("$jsname" , $jsctor);%} +%{$jsmangledname_class = SWIGV8_CreateClassTemplate("$jsname" , $jsctor); + SWIGTYPE_$jsmangledtype->clientdata = &$jsmangledname_class;%} %fragment("jsv8_create_class_instance", "templates") %{v8::Handle $jsmangledname = $jsmangledname_class->GetFunction();%} diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index f114c74c9..388f037e7 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -21,6 +21,7 @@ bool js_template_enable_debug = false; #define CTOR_WRAPPERS "ctor_wrappers" #define CTOR_DISPATCHERS "ctor_dispatchers" #define ARGCOUNT "wrap:argc" +#define FUNCTION_DISPATCHERS "function_dispatchers" // variables used in code templates // ATTENTION: be aware of prefix collisions when defining those variables @@ -785,6 +786,309 @@ int JSEmitter::enterVariable(Node *n) { return SWIG_OK; } +int JSEmitter::emitCtor(Node *n) { + + Wrapper *wrapper = NewWrapper(); + + bool is_overloaded = GetFlag(n, "sym:overloaded"); + + Template t_ctor(getTemplate("JS_ctordefn")); + + //String *mangled_name = SwigType_manglestr(Getattr(n, "name")); + String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); + if(is_overloaded) { + Append(wrap_name, Getattr(n, "sym:overname")); + } + Setattr(n, "wrap:name", wrap_name); + // note: removing the is_abstract flag, as this emitter + // is supposed to be called for non-abstract classes only. + Setattr(state.clazz(), IS_ABSTRACT, 0); + + ParmList *params = Getattr(n, "parms"); + emit_parameter_variables(params, wrapper); + emit_attach_parmmaps(params, wrapper); + + Printf(wrapper->locals, "%sresult;", SwigType_str(Getattr(n, "type"), 0)); + + String *action = emit_action(n); + marshalInputArgs(n, params, wrapper, Ctor, true, false); + + Printv(wrapper->code, action, "\n", 0); + t_ctor.replace(T_WRAPPER, wrap_name) + .replace(T_TYPE_MANGLED, state.clazz(TYPE_MANGLED)) + .replace(T_LOCALS, wrapper->locals) + .replace(T_CODE, wrapper->code) + .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)) + .pretty_print(f_wrappers); + + Template t_ctor_case(getTemplate("JS_ctor_dispatch_case")); + t_ctor_case.replace(T_WRAPPER, wrap_name) + .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)); + Append(state.clazz(CTOR_DISPATCHERS), t_ctor_case.str()); + + DelWrapper(wrapper); + + // create a dispatching ctor + if(is_overloaded) { + if (!Getattr(n, "sym:nextSibling")) { + String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); + Template t_mainctor(getTemplate("JS_mainctordefn")); + t_mainctor.replace(T_WRAPPER, wrap_name) + .replace(T_DISPATCH_CASES, state.clazz(CTOR_DISPATCHERS)) + .pretty_print(f_wrappers); + state.clazz(CTOR, wrap_name); + } + } else { + state.clazz(CTOR, wrap_name); + } + + return SWIG_OK; +} + +int JSEmitter::emitDtor(Node *) { + + Template t_dtor = getTemplate("JS_destructordefn"); + t_dtor.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) + .replace(T_TYPE, state.clazz(TYPE)) + .pretty_print(f_wrappers); + + return SWIG_OK; +} + +int JSEmitter::emitGetter(Node *n, bool is_member, bool is_static) { + Wrapper *wrapper = NewWrapper(); + Template t_getter(getTemplate("JS_getproperty")); + + // prepare wrapper name + String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); + Setattr(n, "wrap:name", wrap_name); + state.variable(GETTER, wrap_name); + + // prepare local variables + ParmList *params = Getattr(n, "parms"); + emit_parameter_variables(params, wrapper); + emit_attach_parmmaps(params, wrapper); + + // prepare code part + String *action = emit_action(n); + marshalInputArgs(n, params, wrapper, Getter, is_member, is_static); + marshalOutput(n, action, wrapper); + + t_getter.replace(T_GETTER, wrap_name) + .replace(T_LOCALS, wrapper->locals) + .replace(T_CODE, wrapper->code) + .pretty_print(f_wrappers); + + DelWrapper(wrapper); + + return SWIG_OK; +} + +int JSEmitter::emitSetter(Node *n, bool is_member, bool is_static) { + + // skip variables that are immutable + if (State::IsSet(state.variable(IS_IMMUTABLE))) { + return SWIG_OK; + } + + Wrapper *wrapper = NewWrapper(); + + Template t_setter(getTemplate("JS_setproperty")); + + // prepare wrapper name + String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); + Setattr(n, "wrap:name", wrap_name); + state.variable(SETTER, wrap_name); + + // prepare local variables + ParmList *params = Getattr(n, "parms"); + emit_parameter_variables(params, wrapper); + emit_attach_parmmaps(params, wrapper); + + // prepare code part + String *action = emit_action(n); + marshalInputArgs(n, params, wrapper, Setter, is_member, is_static); + Append(wrapper->code, action); + + t_setter.replace(T_SETTER, wrap_name) + .replace(T_LOCALS, wrapper->locals) + .replace(T_CODE, wrapper->code) + .pretty_print(f_wrappers); + + DelWrapper(wrapper); + + return SWIG_OK; +} + +/* ----------------------------------------------------------------------------- + * JSEmitter::emitConstant() : triggers code generation for constants + * ----------------------------------------------------------------------------- */ + +int JSEmitter::emitConstant(Node *n) { + + Wrapper *wrapper = NewWrapper(); + + Template t_getter(getTemplate("JS_getproperty")); + + // call the variable methods as a constants are + // registred in same way + enterVariable(n); + + // prepare function wrapper name + String *wrap_name = Swig_name_wrapper(Getattr(n, "name")); + state.variable(GETTER, wrap_name); + Setattr(n, "wrap:name", wrap_name); + + // prepare code part + String *action = NewString(""); + String *value = Getattr(n, "rawval"); + if (value == NULL) { + value = Getattr(n, "rawvalue"); + } + if (value == NULL) { + value = Getattr(n, "value"); + } + Printf(action, "result = %s;\n", value); + Setattr(n, "wrap:action", action); + marshalOutput(n, action, wrapper); + + t_getter.replace(T_GETTER, wrap_name) + .replace(T_LOCALS, wrapper->locals) + .replace(T_CODE, wrapper->code) + .pretty_print(f_wrappers); + + exitVariable(n); + + DelWrapper(wrapper); + + return SWIG_OK; +} + +int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { + + Wrapper *wrapper = NewWrapper(); + Template t_function(getTemplate("JS_functionwrapper")); + + bool is_overloaded = GetFlag(n, "sym:overloaded"); + + // prepare the function wrapper name + String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); + if (is_overloaded) { + t_function = getTemplate("JS_functionwrapper_overload"); + Append(wrap_name, Getattr(n, "sym:overname")); + } + Setattr(n, "wrap:name", wrap_name); + state.function(WRAPPER_NAME, wrap_name); + + // prepare local variables + ParmList *params = Getattr(n, "parms"); + emit_parameter_variables(params, wrapper); + emit_attach_parmmaps(params, wrapper); + + // prepare code part + String *action = emit_action(n); + marshalInputArgs(n, params, wrapper, Function, is_member, is_static); + marshalOutput(n, action, wrapper); + + t_function.replace(T_WRAPPER, wrap_name) + .replace(T_LOCALS, wrapper->locals) + .replace(T_CODE, wrapper->code) + .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)) + .pretty_print(f_wrappers); + + // handle function overloading + if (is_overloaded) { + Template t_dispatch_case = getTemplate("JS_function_dispatch_case"); + t_dispatch_case.replace(T_WRAPPER, wrap_name) + .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)); + Append(state.global(FUNCTION_DISPATCHERS), t_dispatch_case.str()); + } + + DelWrapper(wrapper); + + return SWIG_OK; +} + +int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { + + Template t_function(getTemplate("JS_functionwrapper")); + + Wrapper *wrapper = NewWrapper(); + String *wrap_name = Swig_name_wrapper(Getattr(n, "name")); + Setattr(n, "wrap:name", wrap_name); + + Wrapper_add_local(wrapper, "res", "int res"); + + Append(wrapper->code, state.global(FUNCTION_DISPATCHERS)); + Append(wrapper->code, getTemplate("JS_function_dispatch_case_default").str()); + + t_function.replace(T_LOCALS, wrapper->locals) + .replace(T_CODE, wrapper->code); + + // call this here, to replace all variables + t_function.replace(T_WRAPPER, wrap_name) + .replace(T_NAME, state.function(NAME)) + .pretty_print(f_wrappers); + + // Delete the state variable + state.global(FUNCTION_DISPATCHERS, 0); + DelWrapper(wrapper); + + return SWIG_OK; +} + +void JSEmitter::emitInputTypemap(Node *n, Parm *p, Wrapper *wrapper, String *arg) { + // Get input typemap for current param + String *tm = Getattr(p, "tmap:in"); + SwigType *pt = Getattr(p, "type"); + + if (tm != NULL) { + Replaceall(tm, "$input", arg); + Setattr(p, "emit:input", arg); + + // do replacements for built-in variables + if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) { + Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); + } else { + Replaceall(tm, "$disown", "0"); + } + Replaceall(tm, "$symname", Getattr(n, "sym:name")); + Printf(wrapper->code, "%s\n", tm); + } else { + Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0)); + } +} + +void JSEmitter::marshalOutput(Node *n, String *actioncode, Wrapper *wrapper) { + SwigType *type = Getattr(n, "type"); + Setattr(n, "type", type); + String *tm; + + // HACK: output types are not registered as swig_types automatically + if (SwigType_ispointer(type)) { + SwigType_remember_clientdata(type, NewString("0")); + } + + if ((tm = Swig_typemap_lookup_out("out", n, "result", wrapper, actioncode))) { + Replaceall(tm, "$result", "jsresult"); + Replaceall(tm, "$objecttype", Swig_scopename_last(SwigType_str(SwigType_strip_qualifiers(type), 0))); + + if (GetFlag(n, "feature:new")) { + Replaceall(tm, "$owner", "SWIG_POINTER_OWN"); + } else { + Replaceall(tm, "$owner", "0"); + } + Append(wrapper->code, tm); + + if (Len(tm) > 0) { + Printf(wrapper->code, "\n"); + } + } else { + Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(type, 0), Getattr(n, "name")); + } + emit_return_variable(n, type, wrapper); +} + int JSEmitter::switchNamespace(Node *n) { if (!GetFlag(n, "feature:nspace")) { @@ -903,9 +1207,6 @@ private: #define STATIC_FUNCTIONS "static_functions" #define STATIC_VARIABLES "static_variables" -// keys for function scoped state variables -#define FUNCTION_DISPATCHERS "function_dispatchers" - JSCEmitter::JSCEmitter() : JSEmitter(), NULL_STR(NewString("NULL")), @@ -1196,309 +1497,6 @@ int JSCEmitter::exitClass(Node *n) { return SWIG_OK; } -int JSEmitter::emitCtor(Node *n) { - - Wrapper *wrapper = NewWrapper(); - - bool is_overloaded = GetFlag(n, "sym:overloaded"); - - Template t_ctor(getTemplate("JS_ctordefn")); - - //String *mangled_name = SwigType_manglestr(Getattr(n, "name")); - String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); - if(is_overloaded) { - Append(wrap_name, Getattr(n, "sym:overname")); - } - Setattr(n, "wrap:name", wrap_name); - // note: removing the is_abstract flag, as this emitter - // is supposed to be called for non-abstract classes only. - Setattr(state.clazz(), IS_ABSTRACT, 0); - - ParmList *params = Getattr(n, "parms"); - emit_parameter_variables(params, wrapper); - emit_attach_parmmaps(params, wrapper); - - Printf(wrapper->locals, "%sresult;", SwigType_str(Getattr(n, "type"), 0)); - - String *action = emit_action(n); - marshalInputArgs(n, params, wrapper, Ctor, true, false); - - Printv(wrapper->code, action, "\n", 0); - t_ctor.replace(T_WRAPPER, wrap_name) - .replace(T_TYPE_MANGLED, state.clazz(TYPE_MANGLED)) - .replace(T_LOCALS, wrapper->locals) - .replace(T_CODE, wrapper->code) - .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)) - .pretty_print(f_wrappers); - - Template t_ctor_case(getTemplate("JS_ctor_dispatch_case")); - t_ctor_case.replace(T_WRAPPER, wrap_name) - .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)); - Append(state.clazz(CTOR_DISPATCHERS), t_ctor_case.str()); - - DelWrapper(wrapper); - - // create a dispatching ctor - if(is_overloaded) { - if (!Getattr(n, "sym:nextSibling")) { - String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); - Template t_mainctor(getTemplate("JS_mainctordefn")); - t_mainctor.replace(T_WRAPPER, wrap_name) - .replace(T_DISPATCH_CASES, state.clazz(CTOR_DISPATCHERS)) - .pretty_print(f_wrappers); - state.clazz(CTOR, wrap_name); - } - } else { - state.clazz(CTOR, wrap_name); - } - - return SWIG_OK; -} - -int JSEmitter::emitDtor(Node *) { - - Template t_dtor = getTemplate("JS_destructordefn"); - t_dtor.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) - .replace(T_TYPE, state.clazz(TYPE)) - .pretty_print(f_wrappers); - - return SWIG_OK; -} - -int JSEmitter::emitGetter(Node *n, bool is_member, bool is_static) { - Wrapper *wrapper = NewWrapper(); - Template t_getter(getTemplate("JS_getproperty")); - - // prepare wrapper name - String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); - Setattr(n, "wrap:name", wrap_name); - state.variable(GETTER, wrap_name); - - // prepare local variables - ParmList *params = Getattr(n, "parms"); - emit_parameter_variables(params, wrapper); - emit_attach_parmmaps(params, wrapper); - - // prepare code part - String *action = emit_action(n); - marshalInputArgs(n, params, wrapper, Getter, is_member, is_static); - marshalOutput(n, action, wrapper); - - t_getter.replace(T_GETTER, wrap_name) - .replace(T_LOCALS, wrapper->locals) - .replace(T_CODE, wrapper->code) - .pretty_print(f_wrappers); - - DelWrapper(wrapper); - - return SWIG_OK; -} - -int JSEmitter::emitSetter(Node *n, bool is_member, bool is_static) { - - // skip variables that are immutable - if (State::IsSet(state.variable(IS_IMMUTABLE))) { - return SWIG_OK; - } - - Wrapper *wrapper = NewWrapper(); - - Template t_setter(getTemplate("JS_setproperty")); - - // prepare wrapper name - String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); - Setattr(n, "wrap:name", wrap_name); - state.variable(SETTER, wrap_name); - - // prepare local variables - ParmList *params = Getattr(n, "parms"); - emit_parameter_variables(params, wrapper); - emit_attach_parmmaps(params, wrapper); - - // prepare code part - String *action = emit_action(n); - marshalInputArgs(n, params, wrapper, Setter, is_member, is_static); - Append(wrapper->code, action); - - t_setter.replace(T_SETTER, wrap_name) - .replace(T_LOCALS, wrapper->locals) - .replace(T_CODE, wrapper->code) - .pretty_print(f_wrappers); - - DelWrapper(wrapper); - - return SWIG_OK; -} - -/* ----------------------------------------------------------------------------- - * JSCEmitter::emitConstant() : triggers code generation for constants - * ----------------------------------------------------------------------------- */ - -int JSEmitter::emitConstant(Node *n) { - - Wrapper *wrapper = NewWrapper(); - - Template t_getter(getTemplate("JS_getproperty")); - - // call the variable methods as a constants are - // registred in same way - enterVariable(n); - - // prepare function wrapper name - String *wrap_name = Swig_name_wrapper(Getattr(n, "name")); - state.variable(GETTER, wrap_name); - Setattr(n, "wrap:name", wrap_name); - - // prepare code part - String *action = NewString(""); - String *value = Getattr(n, "rawval"); - if (value == NULL) { - value = Getattr(n, "rawvalue"); - } - if (value == NULL) { - value = Getattr(n, "value"); - } - Printf(action, "result = %s;\n", value); - Setattr(n, "wrap:action", action); - marshalOutput(n, action, wrapper); - - t_getter.replace(T_GETTER, wrap_name) - .replace(T_LOCALS, wrapper->locals) - .replace(T_CODE, wrapper->code) - .pretty_print(f_wrappers); - - exitVariable(n); - - DelWrapper(wrapper); - - return SWIG_OK; -} - -int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { - - Wrapper *wrapper = NewWrapper(); - Template t_function(getTemplate("JS_functionwrapper")); - - bool is_overloaded = GetFlag(n, "sym:overloaded"); - - // prepare the function wrapper name - String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); - if (is_overloaded) { - t_function = getTemplate("JS_functionwrapper_overload"); - Append(wrap_name, Getattr(n, "sym:overname")); - } - Setattr(n, "wrap:name", wrap_name); - state.function(WRAPPER_NAME, wrap_name); - - // prepare local variables - ParmList *params = Getattr(n, "parms"); - emit_parameter_variables(params, wrapper); - emit_attach_parmmaps(params, wrapper); - - // prepare code part - String *action = emit_action(n); - marshalInputArgs(n, params, wrapper, Function, is_member, is_static); - marshalOutput(n, action, wrapper); - - t_function.replace(T_WRAPPER, wrap_name) - .replace(T_LOCALS, wrapper->locals) - .replace(T_CODE, wrapper->code) - .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)) - .pretty_print(f_wrappers); - - // handle function overloading - if (is_overloaded) { - Template t_dispatch_case = getTemplate("JS_function_dispatch_case"); - t_dispatch_case.replace(T_WRAPPER, wrap_name) - .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)); - Append(state.global(FUNCTION_DISPATCHERS), t_dispatch_case.str()); - } - - DelWrapper(wrapper); - - return SWIG_OK; -} - -int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { - - Template t_function(getTemplate("JS_functionwrapper")); - - Wrapper *wrapper = NewWrapper(); - String *wrap_name = Swig_name_wrapper(Getattr(n, "name")); - Setattr(n, "wrap:name", wrap_name); - - Wrapper_add_local(wrapper, "res", "int res"); - - Append(wrapper->code, state.global(FUNCTION_DISPATCHERS)); - Append(wrapper->code, getTemplate("JS_function_dispatch_case_default").str()); - - t_function.replace(T_LOCALS, wrapper->locals) - .replace(T_CODE, wrapper->code); - - // call this here, to replace all variables - t_function.replace(T_WRAPPER, wrap_name) - .replace(T_NAME, state.function(NAME)) - .pretty_print(f_wrappers); - - // Delete the state variable - state.global(FUNCTION_DISPATCHERS, 0); - DelWrapper(wrapper); - - return SWIG_OK; -} - -void JSEmitter::emitInputTypemap(Node *n, Parm *p, Wrapper *wrapper, String *arg) { - // Get input typemap for current param - String *tm = Getattr(p, "tmap:in"); - SwigType *pt = Getattr(p, "type"); - - if (tm != NULL) { - Replaceall(tm, "$input", arg); - Setattr(p, "emit:input", arg); - - // do replacements for built-in variables - if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) { - Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); - } else { - Replaceall(tm, "$disown", "0"); - } - Replaceall(tm, "$symname", Getattr(n, "sym:name")); - Printf(wrapper->code, "%s\n", tm); - } else { - Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0)); - } -} - -void JSEmitter::marshalOutput(Node *n, String *actioncode, Wrapper *wrapper) { - SwigType *type = Getattr(n, "type"); - Setattr(n, "type", type); - String *tm; - - // HACK: output types are not registered as swig_types automatically - if (SwigType_ispointer(type)) { - SwigType_remember_clientdata(type, NewString("0")); - } - - if ((tm = Swig_typemap_lookup_out("out", n, "result", wrapper, actioncode))) { - Replaceall(tm, "$result", "jsresult"); - Replaceall(tm, "$objecttype", Swig_scopename_last(SwigType_str(SwigType_strip_qualifiers(type), 0))); - - if (GetFlag(n, "feature:new")) { - Replaceall(tm, "$owner", "SWIG_POINTER_OWN"); - } else { - Replaceall(tm, "$owner", "0"); - } - Append(wrapper->code, tm); - - if (Len(tm) > 0) { - Printf(wrapper->code, "\n"); - } - } else { - Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(type, 0), Getattr(n, "name")); - } - emit_return_variable(n, type, wrapper); -} - Hash *JSCEmitter::createNamespaceEntry(const char *name, const char *parent) { Hash *entry = JSEmitter::createNamespaceEntry(name, parent); Setattr(entry, "functions", NewString("")); @@ -1541,6 +1539,10 @@ JSEmitter *swig_javascript_create_JSCEmitter() { return new JSCEmitter(); } +/********************************************************************** + * V8: JSEmitter implementation for V8 engine + **********************************************************************/ + class V8Emitter: public JSEmitter { public: @@ -1548,29 +1550,19 @@ public: V8Emitter(); virtual ~V8Emitter(); - virtual int initialize(Node *n); - virtual int dump(Node *n); - virtual int close(); - virtual int enterClass(Node *n); - virtual int exitClass(Node *n); - virtual int enterVariable(Node *n); - virtual int exitVariable(Node *n); - virtual int enterFunction(Node *n); - virtual int exitFunction(Node *n); protected: virtual void marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static); - virtual int emitNamespaces(); private: @@ -1731,6 +1723,7 @@ int V8Emitter::exitClass(Node *n) t_def_class.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .replace(T_NAME, state.clazz(NAME)) .replace(T_CTOR, state.clazz(CTOR)) + .replace(T_TYPE_MANGLED, state.clazz(TYPE_MANGLED)) .pretty_print(f_init_class_templates); Template t_class_instance(getTemplate("jsv8_create_class_instance")); @@ -1804,7 +1797,6 @@ int V8Emitter::exitVariable(Node* n) int V8Emitter::enterFunction(Node* n) { JSEmitter::enterFunction(n); - return SWIG_OK; } From 1862f43cfcd93a3f79cf652da70f22a438de4cf9 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:09:05 +0000 Subject: [PATCH 0127/1048] Minor clean up in class example. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13800 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/javascript/class/Makefile | 2 +- Examples/javascript/class/runme.js | 5 ----- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/Examples/javascript/class/Makefile b/Examples/javascript/class/Makefile index 180e99cae..507289ed1 100755 --- a/Examples/javascript/class/Makefile +++ b/Examples/javascript/class/Makefile @@ -1,6 +1,6 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cpp +CXXSRCS = example.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i diff --git a/Examples/javascript/class/runme.js b/Examples/javascript/class/runme.js index 922876fc5..50261d868 100755 --- a/Examples/javascript/class/runme.js +++ b/Examples/javascript/class/runme.js @@ -21,15 +21,10 @@ c.y = 30; s.x = -10; s.y = 5; -print("\nHere is their current position:"); -print("Circle = (" + c.x + "," + c.y + ")"); -print("Square = (" + s.x + "," + s.y + ")"); - print("\nHere is their new position:"); print("Circle = (" + c.x + "," + c.y + ")"); print("Square = (" + s.x + "," + s.y + ")"); - // ----- Call some methods ----- print("\nHere are some properties of the shapes:"); print("Circle:"); From bd752ff86b94a082235d0ff424729c7d5e043715 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:09:18 +0000 Subject: [PATCH 0128/1048] In example Makefiles for v8 forward to CPP target. As v8 is C++ it is not possible to build wrappers in C. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13801 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/Makefile.in | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 8bf1f1498..008ae817f 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -559,10 +559,15 @@ endif # Build a javascript dynamically loadable module (C) # ---------------------------------------------------------------- +# Note: for v8 there is no C support, so forwarding to javascript_cpp +ifeq (,$(V8)) javascript: $(SRCS) $(SWIGJS) $(SWIGOPT) $(INTERFACEPATH) $(CC) -c $(CCSHARED) $(JSCFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(JS_INCLUDE) $(JSLDSHARED) $(CCSHARED) $(JSCFLAGS) $(OBJS) $(IOBJS) $(JS_DLNK) $(LIBS) -o $(JS_LIBPREFIX)$(TARGET)$(JSSO) +else +javascript: $(SRCS) javascript_cpp +endif # ---------------------------------------------------------------- # Build a javascript dynamically loadable module (C++) From c3918f3f822a09b297f30ef060c9269dc97e0f39 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:09:31 +0000 Subject: [PATCH 0129/1048] Add string support to v8 typemaps. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13802 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptstrings.swg | 64 +++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/Lib/javascript/v8/javascriptstrings.swg b/Lib/javascript/v8/javascriptstrings.swg index e69de29bb..6bba0436e 100644 --- a/Lib/javascript/v8/javascriptstrings.swg +++ b/Lib/javascript/v8/javascriptstrings.swg @@ -0,0 +1,64 @@ + +/* ------------------------------------------------------------ + * utility methods for char strings + * ------------------------------------------------------------ */ +%fragment("SWIG_AsCharPtrAndSize","header",fragment="SWIG_pchar_descriptor") { +SWIGINTERN int +SWIG_AsCharPtrAndSize(v8::Handle valRef, char** cptr, size_t* psize, int *alloc) +{ + if(valRef->IsString()) { + v8::Handle js_str = valRef->toString(); + + size_t len = js_str->Utf8Length(); + size_t abs_len = js_str->Length(); + char* cstr = new char[len]; + js_str->WriteUtf8(cstr, len); + JSStringGetUTF8CString(js_str, cstr, len); + + if(alloc) *alloc = SWIG_NEWOBJ; + if(psize) *psize = abs_len + 1; + if(cptr) *cptr = cstr; + + return SWIG_OK; + } else { + if(valRef->IsObject()) { + v8::Handle obj = valRef->ToObject(); + // try if the object is a wrapped char[] + swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); + if (pchar_descriptor) { + void* vptr = 0; + if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { + if (cptr) *cptr = (char *) vptr; + if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; + if (alloc) *alloc = SWIG_OLDOBJ; + return SWIG_OK; + } + } + return SWIG_TypeError; + } else { + return SWIG_TypeError; + } + } +} +} + +%fragment("SWIG_FromCharPtrAndSize","header",fragment="SWIG_pchar_descriptor") { +SWIGINTERNINLINE v8::Handle +SWIG_FromCharPtrAndSize(const char* carray, size_t size) +{ + if (carray) { + if (size > INT_MAX) { + // TODO: handle extra long strings + //swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); + //return pchar_descriptor ? + // SWIG_InternalNewPointerObj(%const_cast(carray,char *), pchar_descriptor, 0) : SWIG_Py_Void(); + return v8::Undefined(); + } else { + v8::Handle js_str = v8::String::New(carray, size); + return js_str; + } + } else { + return v8::Undefined(); + } +} +} From 915e65135cdf90a484bd1078eb3cfe15f192e50e Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:09:43 +0000 Subject: [PATCH 0130/1048] Minor fix in v8 shell. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13803 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Tools/javascript/v8_shell.cxx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Tools/javascript/v8_shell.cxx b/Tools/javascript/v8_shell.cxx index 62620a72a..6c84fe758 100755 --- a/Tools/javascript/v8_shell.cxx +++ b/Tools/javascript/v8_shell.cxx @@ -108,6 +108,8 @@ bool V8Shell::RunScript(const std::string& scriptPath) { context->Exit(); context.Dispose(); v8::V8::Dispose(); + + return true; } bool V8Shell::RunShell() { @@ -141,6 +143,8 @@ bool V8Shell::RunShell() { context->Exit(); context.Dispose(); v8::V8::Dispose(); + + return true; } From 58e4f9703c78052ee60f3021724bc3274f3d329a Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:09:57 +0000 Subject: [PATCH 0131/1048] Fix handling of Char constants in JSC typemaps. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13804 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/jsc/javascriptstrings.swg | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/Lib/javascript/jsc/javascriptstrings.swg b/Lib/javascript/jsc/javascriptstrings.swg index f97e84cd0..f83c7533d 100644 --- a/Lib/javascript/jsc/javascriptstrings.swg +++ b/Lib/javascript/jsc/javascriptstrings.swg @@ -51,7 +51,18 @@ SWIG_JSC_FromCharPtrAndSize(JSContextRef context, const char* carray, size_t siz // SWIG_InternalNewPointerObj(%const_cast(carray,char *), pchar_descriptor, 0) : SWIG_Py_Void(); return JSValueMakeUndefined(context); } else { - JSStringRef jsstring = JSStringCreateWithUTF8CString(carray); + JSStringRef jsstring; + if(size < 2) { + char c[size+1]; + int i; + for(i=0;i Date: Sat, 8 Sep 2012 01:10:10 +0000 Subject: [PATCH 0132/1048] Fix string warnings of for char* constants in CPP wrappers. This has been done by changing the implementation of marshalOutputArgs, which now does not create a local result variable in this case, and uses the constant inline in the output typemap. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13805 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/Modules/javascript.cxx | 37 +++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 388f037e7..b268223df 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -265,7 +265,7 @@ protected: virtual void emitInputTypemap(Node *n, Parm *p, Wrapper *wrapper, String *arg); - virtual void marshalOutput(Node *n, String *actioncode, Wrapper *wrapper); + virtual void marshalOutput(Node *n, Wrapper *wrapper, String *actioncode, const String *cresult=0, bool emitReturnVariable = true); /** * Helper function to retrieve the first parent class node. @@ -291,6 +291,8 @@ protected: // which are switched on namespace change Hash *namespaces; Hash *current_namespace; + + String *defaultResultName; File *f_wrappers; @@ -595,6 +597,7 @@ JSEmitter::JSEmitter() : templates(NewHash()), namespaces(NULL), current_namespace(NULL), + defaultResultName(NewString("result")), f_wrappers(NULL) { } @@ -872,7 +875,7 @@ int JSEmitter::emitGetter(Node *n, bool is_member, bool is_static) { // prepare code part String *action = emit_action(n); marshalInputArgs(n, params, wrapper, Getter, is_member, is_static); - marshalOutput(n, action, wrapper); + marshalOutput(n, wrapper, action); t_getter.replace(T_GETTER, wrap_name) .replace(T_LOCALS, wrapper->locals) @@ -927,7 +930,7 @@ int JSEmitter::emitSetter(Node *n, bool is_member, bool is_static) { int JSEmitter::emitConstant(Node *n) { Wrapper *wrapper = NewWrapper(); - + Template t_getter(getTemplate("JS_getproperty")); // call the variable methods as a constants are @@ -944,13 +947,10 @@ int JSEmitter::emitConstant(Node *n) { String *value = Getattr(n, "rawval"); if (value == NULL) { value = Getattr(n, "rawvalue"); + if (value == NULL) value = Getattr(n, "value"); } - if (value == NULL) { - value = Getattr(n, "value"); - } - Printf(action, "result = %s;\n", value); - Setattr(n, "wrap:action", action); - marshalOutput(n, action, wrapper); + assert(value != NULL); + marshalOutput(n, wrapper, action, value, false); t_getter.replace(T_GETTER, wrap_name) .replace(T_LOCALS, wrapper->locals) @@ -988,7 +988,7 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { // prepare code part String *action = emit_action(n); marshalInputArgs(n, params, wrapper, Function, is_member, is_static); - marshalOutput(n, action, wrapper); + marshalOutput(n, wrapper, action); t_function.replace(T_WRAPPER, wrap_name) .replace(T_LOCALS, wrapper->locals) @@ -1059,17 +1059,21 @@ void JSEmitter::emitInputTypemap(Node *n, Parm *p, Wrapper *wrapper, String *arg } } -void JSEmitter::marshalOutput(Node *n, String *actioncode, Wrapper *wrapper) { +void JSEmitter::marshalOutput(Node *n, Wrapper *wrapper, String *actioncode, const String *cresult, bool emitReturnVariable) { SwigType *type = Getattr(n, "type"); Setattr(n, "type", type); String *tm; - + // HACK: output types are not registered as swig_types automatically - if (SwigType_ispointer(type)) { - SwigType_remember_clientdata(type, NewString("0")); - } + if (SwigType_ispointer(type)) SwigType_remember_clientdata(type, NewString("0")); - if ((tm = Swig_typemap_lookup_out("out", n, "result", wrapper, actioncode))) { + // adds a declaration for the result variable + if(emitReturnVariable) emit_return_variable(n, type, wrapper); + + // if not given, use default result identifier ('result') for output typemap + if(cresult == 0) cresult = defaultResultName; + + if ((tm = Swig_typemap_lookup_out("out", n, cresult, wrapper, actioncode))) { Replaceall(tm, "$result", "jsresult"); Replaceall(tm, "$objecttype", Swig_scopename_last(SwigType_str(SwigType_strip_qualifiers(type), 0))); @@ -1086,7 +1090,6 @@ void JSEmitter::marshalOutput(Node *n, String *actioncode, Wrapper *wrapper) { } else { Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(type, 0), Getattr(n, "name")); } - emit_return_variable(n, type, wrapper); } int JSEmitter::switchNamespace(Node *n) { From 2893df9f7394ef48424f0b88e44af702a11fdd95 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:10:27 +0000 Subject: [PATCH 0133/1048] Several fixes in v8 emitter. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13806 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptruntime.swg | 9 ++++++--- Source/Modules/javascript.cxx | 9 ++++++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index e8b26892c..d94587419 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -91,14 +91,17 @@ v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, in v8::HandleScope scope; v8::Local class_templ; + v8::Handle inst_templ; if(info->clientdata == NULL) { - // TODO: get class template for unknown types - //class_templ = _SwigObject_classRef; + class_templ = v8::FunctionTemplate::New(); + class_templ->SetClassName(v8::String::NewSymbol(info->name)); + inst_templ = class_templ->InstanceTemplate(); + inst_templ->SetInternalFieldCount(1); } else { class_templ = *((v8::Local*) info->clientdata); + inst_templ = class_templ->InstanceTemplate(); } - v8::Handle inst_templ = class_templ->InstanceTemplate(); v8::Local result = inst_templ->NewInstance(); SWIG_PRV_DATA* cdata = (SWIG_PRV_DATA*) new SWIG_PRV_DATA; diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index b268223df..e7fa8801a 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1720,6 +1720,9 @@ int V8Emitter::exitClass(Node *n) .replace(T_NAME, state.clazz(NAME)) .pretty_print(f_wrappers); } + + /* Note: this makes sure that there is a swig_type added for this class */ + SwigType_remember_clientdata(state.clazz(TYPE_MANGLED), NewString("0")); // emit definition of v8 class template Template t_def_class(getTemplate("jsv8_define_class_template")); @@ -1768,7 +1771,7 @@ int V8Emitter::enterVariable(Node* n) int V8Emitter::exitVariable(Node* n) { if(GetFlag(n, "ismember")) { - if(GetFlag(state.variable(), IS_STATIC)) { + if(GetFlag(state.variable(), IS_STATIC) || Equal(Getattr(n, "nodeType"), "enumitem") ) { Template t_register(getTemplate("jsv8_register_static_variable")); t_register.replace(T_PARENT, state.clazz(NAME_MANGLED)) .replace(T_NAME, state.variable(NAME)) @@ -1778,7 +1781,7 @@ int V8Emitter::exitVariable(Node* n) } else { Template t_register(getTemplate("jsv8_register_member_variable")); t_register.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) - .replace(T_NAME, state.clazz(NAME)) + .replace(T_NAME, state.variable(NAME)) .replace(T_GETTER, state.variable(GETTER)) .replace(T_SETTER, state.variable(SETTER)) .pretty_print(f_init_wrappers); @@ -1868,7 +1871,7 @@ void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Mar break; case Setter: if (is_member && !is_static && i == 0) { - Printv(arg, "value", 0); + Printv(arg, "info.Holder()", 0); } else { Printv(arg, "value", 0); } From a4f8e4c1c3bbcd36a771313f2516717aa113b771 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:10:42 +0000 Subject: [PATCH 0134/1048] Fix bug in v8 ctor emitter. This bug leaded to flaky crashes of v8 engine. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13807 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptcode.swg | 5 ++++- Lib/javascript/v8/javascriptruntime.swg | 18 +++++++++++------- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 2adbd1307..070ef2e2d 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -5,7 +5,8 @@ v8::Handle $jswrapper(const v8::Arguments& args) { $jslocals $jscode - return SWIG_V8_NewPointerObj(result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); + SWIG_V8_SetPrivateData(self, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); + return scope.Close(self); goto fail; fail: @@ -54,10 +55,12 @@ fail: return scope.Close(v8::Undefined()); }%} +/* %fragment ("JS_mainctordefn", "templates") %{ // TODO: implement JS_mainctordefn %} +*/ %fragment ("JS_ctor_dispatch_case", "templates") %{ diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index d94587419..ce1367070 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -77,6 +77,15 @@ int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_t return SWIG_OK; } +void SWIG_V8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info *info, int flags) { + SWIG_PRV_DATA* cdata = (SWIG_PRV_DATA*) new SWIG_PRV_DATA; + cdata->swigCObject = ptr; + cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; + cdata->info = info; + + obj->SetInternalField(0, v8::External::New(cdata)); +} + int SWIG_V8_ConvertPtr(v8::Handle valRef, void** ptr, swig_type_info *info, int flags) { if(!valRef->IsObject()) { return SWIG_TypeError; @@ -103,14 +112,9 @@ v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, in } v8::Local result = inst_templ->NewInstance(); - - SWIG_PRV_DATA* cdata = (SWIG_PRV_DATA*) new SWIG_PRV_DATA; - cdata->swigCObject = ptr; - cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; - cdata->info = info; - - result->SetInternalField(0, v8::External::New(cdata)); + SWIG_V8_SetPrivateData(result, ptr, info, flags); + return scope.Close(result); } From 84e5476147cd141d1178cd25be35df6b01c5b92e Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:10:57 +0000 Subject: [PATCH 0135/1048] Add std::string support to v8 typemaps. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13808 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptstrings.swg | 3 +- Lib/javascript/v8/std_string.i | 68 +++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 2 deletions(-) create mode 100755 Lib/javascript/v8/std_string.i diff --git a/Lib/javascript/v8/javascriptstrings.swg b/Lib/javascript/v8/javascriptstrings.swg index 6bba0436e..14a96c63e 100644 --- a/Lib/javascript/v8/javascriptstrings.swg +++ b/Lib/javascript/v8/javascriptstrings.swg @@ -7,13 +7,12 @@ SWIGINTERN int SWIG_AsCharPtrAndSize(v8::Handle valRef, char** cptr, size_t* psize, int *alloc) { if(valRef->IsString()) { - v8::Handle js_str = valRef->toString(); + v8::Handle js_str = valRef->ToString(); size_t len = js_str->Utf8Length(); size_t abs_len = js_str->Length(); char* cstr = new char[len]; js_str->WriteUtf8(cstr, len); - JSStringGetUTF8CString(js_str, cstr, len); if(alloc) *alloc = SWIG_NEWOBJ; if(psize) *psize = abs_len + 1; diff --git a/Lib/javascript/v8/std_string.i b/Lib/javascript/v8/std_string.i new file mode 100755 index 000000000..0d6143319 --- /dev/null +++ b/Lib/javascript/v8/std_string.i @@ -0,0 +1,68 @@ +/* ----------------------------------------------------------------------------- + * std_string.i + * + * Typemaps for std::string and const std::string& + * These are mapped to a JSCore String and are passed around by value. + * + * To use non-const std::string references use the following %apply. Note + * that they are passed by value. + * %apply const std::string & {std::string &}; + * ----------------------------------------------------------------------------- */ + +%{ +#include +%} + +namespace std { + +%naturalvar string; + +class string; + +// string + +%typemap(in) string +%{ + if(!$input->IsString()) { + // TODO: Throw exception? + return NULL; + } + + size_t $1_strsize = js_str->Utf8Length(); + char* 1_cstr = new char[1_strsize]; + js_str->WriteUtf8(1_cstr, 1_strsize); + $1 = std::string($1_cstr); +%} + +%typemap(out) string %{ + $result = v8::String::New($1.c_str(), $1.size()); +%} + +%typemap(freearg) string +%{%} + +// const string & +%typemap(in) const string & +%{ + + if(!$input->IsString()) { + // TODO: Throw exception? + return NULL; + } + + size_t $1_strsize = js_str->Utf8Length(); + char* 1_cstr = new char[1_strsize]; + js_str->WriteUtf8(1_cstr, 1_strsize); + $1 = newstd::string($1_cstr); +%} + +%typemap(out) const string & %{ + $result = v8::String::New($1.c_str(), $1.size()); +%} + +%typemap(freearg) const string & //TODO: Not working: A memory leak +%{ free($1_cstr); %} + +//%typemap(typecheck) const string & = char *; + +} From 70383a1b61aacfb475f72652cf120515f11de2c1 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:11:11 +0000 Subject: [PATCH 0136/1048] Enable string exceptions in v8. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13809 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptruntime.swg | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index ce1367070..3305bd6ad 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -29,8 +29,8 @@ typedef struct { %insert(runtime) %{ -void SWIG_V8_Raise(const char* type) { - // TODO: throw v8 exception +void SWIG_V8_Raise(const char* msg) { + v8::ThrowException(v8::Exception::Error(v8::String::New(msg))); } void SWIG_V8_exception(int code, const char* msg) { From da6307a19ea5668757ab59f95e670f99bd64b61a Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:11:32 +0000 Subject: [PATCH 0137/1048] Enable overloading ctors for v8. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13810 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptcode.swg | 28 +++++++++++++++++++++------- Source/Modules/javascript.cxx | 3 ++- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 070ef2e2d..527efe115 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -55,16 +55,30 @@ fail: return scope.Close(v8::Undefined()); }%} -/* -%fragment ("JS_mainctordefn", "templates") -%{ - // TODO: implement JS_mainctordefn +%fragment ("JS_mainctordefn", "templates") %{ +v8::Handle $jswrapper(const v8::Arguments& args) { + v8::HandleScope scope; + + v8::TryCatch tryCatch; + // switch all cases by means of series of if-returns. + $jsdispatchcases + + // default: + if(!tryCatch.HasCaught()) + SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for contruction of $jsmangledname"); + +fail: + scope.Close(v8::Undefined()); +} %} -*/ %fragment ("JS_ctor_dispatch_case", "templates") -%{ - // TODO: implement JS_ctor_dispatch_case +%{if(args.Length() == $jsargcount) { + v8::Handle self = $jswrapper(args); + if(!self->IsUndefined()) { + tryCatch.Reset(); return scope.Close(self); /* reset exception and return */ + } + } %} %fragment ("JS_destructordefn", "templates") diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index e7fa8801a..a6261394f 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -837,6 +837,7 @@ int JSEmitter::emitCtor(Node *n) { String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); Template t_mainctor(getTemplate("JS_mainctordefn")); t_mainctor.replace(T_WRAPPER, wrap_name) + .replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .replace(T_DISPATCH_CASES, state.clazz(CTOR_DISPATCHERS)) .pretty_print(f_wrappers); state.clazz(CTOR, wrap_name); @@ -1845,7 +1846,7 @@ void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Mar } // store number of arguments for argument checks - int num_args = emit_num_arguments(parms) - startIdx; + int num_args = emit_num_arguments(parms); String *argcount = NewString(""); Printf(argcount, "%d", num_args); Setattr(n, ARGCOUNT, argcount); From 68f0f859f887f7be4c61d53b37ec8989c02833b9 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:11:51 +0000 Subject: [PATCH 0138/1048] Fix name collision in generated v8 initializer. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13811 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptcode.swg | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 527efe115..497392780 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -94,16 +94,16 @@ fail: SWIGTYPE_$jsmangledtype->clientdata = &$jsmangledname_class;%} %fragment("jsv8_create_class_instance", "templates") -%{v8::Handle $jsmangledname = $jsmangledname_class->GetFunction();%} +%{v8::Handle $jsmangledname_obj = $jsmangledname_class->GetFunction();%} %fragment("jsv8_inherit", "templates") %{$jsmangledname_class->Inherit($jsbaseclass_class);%} %fragment("jsv8_register_class", "templates") -%{$jsparent->Set(v8::String::NewSymbol("$jsname"), $jsmangledname);%} +%{$jsparent_obj->Set(v8::String::NewSymbol("$jsname"), $jsmangledname_obj);%} %fragment("jsv8_create_namespace", "templates") -%{v8::Handle $jsmangledname = v8::Object::New();%} +%{v8::Handle $jsmangledname_obj = v8::Object::New();%} %fragment("jsv8_register_member_function", "templates") %{SWIGV8_AddMemberFunction($jsmangledname_class, "$jsname", $jswrapper);%} @@ -112,13 +112,13 @@ fail: %{SWIGV8_AddMemberVariable($jsmangledname_class, "$jsname", $jsgetter, $jssetter);%} %fragment("jsv8_register_static_function", "templates") -%{SWIGV8_AddStaticFunction($jsparent, "$jsname", $jswrapper);%} +%{SWIGV8_AddStaticFunction($jsparent_obj, "$jsname", $jswrapper);%} %fragment("jsv8_register_static_variable", "templates") -%{SWIGV8_AddStaticVariable($jsparent, "$jsname", $jsgetter, $jssetter);%} +%{SWIGV8_AddStaticVariable($jsparent_obj, "$jsname", $jsgetter, $jssetter);%} %fragment("jsv8_register_namespace", "templates") -%{$jsparent->Set(v8::String::NewSymbol("$jsname"), $jsmangledname);%} +%{$jsparent_obj->Set(v8::String::NewSymbol("$jsname"), $jsmangledname_obj);%} %fragment("JS_initializer", "templates") %{ @@ -129,7 +129,7 @@ void $jsname_initialize(v8::Handle context) SWIG_InitializeModule(0); v8::HandleScope scope; - v8::Local global = context->Global(); + v8::Local global_obj = context->Global(); /* create objects for namespaces */ $jsv8nspaces From d13289cc918061b9ffea6aeb9fe1dba9990727e5 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:12:18 +0000 Subject: [PATCH 0139/1048] Fix function dispatching for v8. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13812 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/jsc/javascriptcode.swg | 23 ++++-- Lib/javascript/v8/javascriptcode.swg | 99 ++++++++++++++++++------- Lib/javascript/v8/javascriptruntime.swg | 55 ++++++++++---- Source/Modules/javascript.cxx | 43 +++++++---- 4 files changed, 160 insertions(+), 60 deletions(-) diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index 7f425c44a..4a83b87d2 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -64,6 +64,24 @@ JSValueRef $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef th } %} +%fragment ("JS_function_dispatcher", "templates") +%{ +JSValueRef $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + $jslocals + JSValueRef jsresult; + int res; + $jscode + + SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function $jsname."); + return jsresult; + + goto fail; + fail: + return NULL; +} +%} + %fragment ("JS_functionwrapper_overload", "templates") %{ int $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception, JSValueRef* result) @@ -96,11 +114,6 @@ int $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObjec } %} -%fragment ("JS_function_dispatch_case_default", "templates") -%{ - SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function $jsname."); -%} - /* Added template for function declaration */ %fragment ("JS_variabledecl", "templates") diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 497392780..b7b2c195f 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -19,7 +19,38 @@ v8::Handle $jsctor(const v8::Arguments& args) { v8::HandleScope scope; SWIG_exception(SWIG_ERROR, "Class $jsname can not be instantiated"); return scope.Close(v8::Undefined()); -}%} +} +%} + +%fragment ("JS_mainctordefn", "templates") %{ +v8::Handle $jswrapper(const v8::Arguments& args) { + v8::HandleScope scope; + + // switch all cases by means of series of if-returns. + $jsdispatchcases + + // default: + SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for contruction of $jsmangledname"); + +fail: + scope.Close(v8::Undefined()); +} +%} + +%fragment ("JS_ctor_dispatch_case", "templates") +%{if(args.Length() == $jsargcount) { + v8::Handle self = $jswrapper(args); + if(!self->IsUndefined()) { + return scope.Close(self); + } + } +%} + +%fragment ("JS_destructordefn", "templates") +%{ + // TODO: implement JS_destructordefn +%} + %fragment("JS_getproperty", "templates") %{ v8::Handle $jsgetter(v8::Local property, const v8::AccessorInfo& info) { @@ -53,37 +84,55 @@ v8::Handle $jswrapper(const v8::Arguments &args) { goto fail; fail: return scope.Close(v8::Undefined()); -}%} - -%fragment ("JS_mainctordefn", "templates") %{ -v8::Handle $jswrapper(const v8::Arguments& args) { - v8::HandleScope scope; - - v8::TryCatch tryCatch; - // switch all cases by means of series of if-returns. - $jsdispatchcases - - // default: - if(!tryCatch.HasCaught()) - SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for contruction of $jsmangledname"); - -fail: - scope.Close(v8::Undefined()); } %} -%fragment ("JS_ctor_dispatch_case", "templates") -%{if(args.Length() == $jsargcount) { - v8::Handle self = $jswrapper(args); - if(!self->IsUndefined()) { - tryCatch.Reset(); return scope.Close(self); /* reset exception and return */ - } +%fragment("JS_function_dispatcher", "templates") %{ +v8::Handle $jswrapper(const v8::Arguments &args) { + v8::HandleScope scope; + v8::Handle jsresult; + OverloadErrorHandler errorHandler; + $jscode + + SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function $jsname."); + + goto fail; +fail: + return scope.Close(v8::Undefined()); +} +%} + +%fragment ("JS_functionwrapper_overload", "templates") +%{ +v8::Handle $jswrapper(const v8::Arguments &args, V8ErrorHandler& SWIGV8_ErrorHandler) +{ + v8::HandleScope scope; + + v8::Handle jsresult; + $jslocals + if(args.Length() != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); + $jscode + return scope.Close(jsresult); + goto fail; +fail: + return scope.Close(jsresult); +} +%} + +%fragment ("JS_function_dispatch_case", "templates") +%{ + if(args.Length() == $jsargcount) { + errorHandler.err.Clear(); + jsresult = $jswrapper(args, errorHandler); + if(errorHandler.err.IsEmpty()) { + return scope.Close(jsresult); + } } %} -%fragment ("JS_destructordefn", "templates") +%fragment ("JS_function_dispatch_case_default", "templates") %{ - // TODO: implement JS_destructordefn + SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function $jsname."); %} %fragment("jsv8_declare_class_template", "templates") diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index 3305bd6ad..2eb9c82cc 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -14,9 +14,48 @@ %insert(runtime) "swigerrors.swg"; /* SWIG errors */ %insert(runtime) %{ -#define SWIG_Error(code, msg) SWIG_V8_exception(code, msg) -#define SWIG_exception(code, msg) SWIG_V8_exception(code, msg) +#define SWIG_Error(code, msg) SWIGV8_ErrorHandler.error(code, msg) +#define SWIG_exception(code, msg) SWIGV8_ErrorHandler.error(code, msg) #define SWIG_fail goto fail +#define SWIGV8_OVERLOAD false + +void SWIG_V8_Raise(const char* msg) { + v8::ThrowException(v8::Exception::Error(v8::String::New(msg))); +} + +/* + Note: There are two contexts for handling errors. + A static V8ErrorHandler is used in not overloaded methods. + For overloaded methods the throwing type checking mechanism is used + during dispatching. As V8 exceptions can not be resetted properly + the trick is to use a dynamic ErrorHandler with same local name as the global + one. + + - See defintion of SWIG_Error above. + - See code templates 'JS_function_dispatcher', 'JS_functionwrapper_overload', + and 'JS_function_dispatch_case' in javascriptcode.swg + +*/ +class V8ErrorHandler { +public: + virtual void error(int code, const char* msg) { + SWIG_V8_Raise(msg); + } +}; +// this is used in usually +V8ErrorHandler SWIGV8_ErrorHandler; + +// instances of this are used in overloaded functions +class OverloadErrorHandler: public V8ErrorHandler { +public: + virtual void error(int code, const char* msg) { + err = v8::Exception::Error(v8::String::New(msg)); + if(code != SWIG_TypeError) { + v8::ThrowException(err); + } + } + v8::Handle err; +}; %} %insert(runtime) %{ @@ -27,18 +66,6 @@ typedef struct { } SWIG_PRV_DATA; %} -%insert(runtime) %{ - -void SWIG_V8_Raise(const char* msg) { - v8::ThrowException(v8::Exception::Error(v8::String::New(msg))); -} - -void SWIG_V8_exception(int code, const char* msg) { - SWIG_V8_Raise(msg); -} - -%} - %insert(runtime) %{ int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_type_info *info, int flags) { diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index a6261394f..5f3e01a42 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -766,6 +766,12 @@ int JSEmitter::enterFunction(Node *n) { if(Equal(Getattr(n, "storage"), "static")) { SetFlag(state.function(), IS_STATIC); } + + /* Initialize DOH for collecting function dispatchers */ + bool is_overloaded = GetFlag(n, "sym:overloaded"); + if (is_overloaded && state.global(FUNCTION_DISPATCHERS) == 0) { + state.global(FUNCTION_DISPATCHERS, NewString("")); + } return SWIG_OK; } @@ -1012,16 +1018,13 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { - Template t_function(getTemplate("JS_functionwrapper")); + Template t_function(getTemplate("JS_function_dispatcher")); Wrapper *wrapper = NewWrapper(); String *wrap_name = Swig_name_wrapper(Getattr(n, "name")); Setattr(n, "wrap:name", wrap_name); - Wrapper_add_local(wrapper, "res", "int res"); - Append(wrapper->code, state.global(FUNCTION_DISPATCHERS)); - Append(wrapper->code, getTemplate("JS_function_dispatch_case_default").str()); t_function.replace(T_LOCALS, wrapper->locals) .replace(T_CODE, wrapper->code); @@ -1365,12 +1368,6 @@ int JSCEmitter::enterFunction(Node *n) { JSEmitter::enterFunction(n); - /* Initialize DOH for collecting function dispatchers */ - bool is_overloaded = GetFlag(n, "sym:overloaded"); - if (is_overloaded && state.global(FUNCTION_DISPATCHERS) == 0) { - state.global(FUNCTION_DISPATCHERS, NewString("")); - } - return SWIG_OK; } @@ -1808,20 +1805,34 @@ int V8Emitter::enterFunction(Node* n) } int V8Emitter::exitFunction(Node* n) -{ +{ + bool is_member = GetFlag(n, "ismember"); + + // create a dispatcher for overloaded functions + bool is_overloaded = GetFlag(n, "sym:overloaded"); + if (is_overloaded) { + if (!Getattr(n, "sym:nextSibling")) { + state.function(WRAPPER_NAME, Swig_name_wrapper(Getattr(n, "name"))); + emitFunctionDispatcher(n, is_member); + } else { + //don't register wrappers of overloaded functions in function tables + return SWIG_OK; + } + } + // register the function at the specific context - if(GetFlag(n, "ismember")) { + if(is_member) { if(GetFlag(state.function(), IS_STATIC)) { Template t_register(getTemplate("jsv8_register_static_function")); t_register.replace(T_PARENT, state.clazz(NAME_MANGLED)) .replace(T_NAME, state.function(NAME)) - .replace(T_WRAPPER, Getattr(n, "wrap:name")) + .replace(T_WRAPPER, state.function(WRAPPER_NAME)) .pretty_print(f_init_static_wrappers); } else { Template t_register(getTemplate("jsv8_register_member_function")); t_register.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .replace(T_NAME, state.function(NAME)) - .replace(T_WRAPPER, Getattr(n, "wrap:name")) + .replace(T_WRAPPER, state.function(WRAPPER_NAME)) .pretty_print(f_init_wrappers); } } else { @@ -1830,8 +1841,8 @@ int V8Emitter::exitFunction(Node* n) Template t_register(getTemplate("jsv8_register_static_function")); t_register.replace(T_PARENT, Getattr(current_namespace, NAME)) .replace(T_NAME, state.function(NAME)) - .replace(T_WRAPPER, Getattr(n, "wrap:name")) - .pretty_print(f_init_wrappers); + .replace(T_WRAPPER, state.function(WRAPPER_NAME)) + .pretty_print(f_init_static_wrappers); } return SWIG_OK; From 843c8a408cb76e22efc10ede577f17e2e5b7deb2 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:12:33 +0000 Subject: [PATCH 0140/1048] Fix AsVal macros of long and int for v8. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13813 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptprimitives.swg | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/Lib/javascript/v8/javascriptprimitives.swg b/Lib/javascript/v8/javascriptprimitives.swg index d3dba485d..bd0295478 100644 --- a/Lib/javascript/v8/javascriptprimitives.swg +++ b/Lib/javascript/v8/javascriptprimitives.swg @@ -29,11 +29,25 @@ v8::Handle SWIG_From_dec(int)(int value) } } +%fragment(SWIG_AsVal_frag(int),"header") { +SWIGINTERN +int SWIG_AsVal_dec(int)(v8::Handle valRef, int* val) +{ + if (!valRef->IsInt32()) { + return SWIG_TypeError; + } + if(val) *val = valRef->IntegerValue(); + + return SWIG_OK; +} +} + + %fragment(SWIG_From_frag(long),"header") { SWIGINTERNINLINE v8::Handle SWIG_From_dec(long)(long value) { - return v8::Integer::New(value); + return v8::Number::New(value); } } From a82e0a6e8f7ba258f29de6f8680e406a8b102ae5 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:12:46 +0000 Subject: [PATCH 0141/1048] Fix c++ linking problem in example 'variables'. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13814 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/javascript/variables/example.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Examples/javascript/variables/example.c b/Examples/javascript/variables/example.c index aa4ffe9b3..3ad4c2323 100755 --- a/Examples/javascript/variables/example.c +++ b/Examples/javascript/variables/example.c @@ -23,7 +23,12 @@ char cvar = 0; float fvar = 0; double dvar = 0; char *strvar = 0; -const char cstrvar[] = "Goodbye"; +#ifdef __cplusplus // Note: for v8 this must be linkable with g++, without extern cstrvar is mangled +extern const char cstrvar[] = "Goodbye"; +#else +const char cstrvar[] = "Goodbye"; +#endif +const int *iptrvar = 0; char name[256] = "Dave"; char path[256] = "/home/beazley"; From 91fc0ff205f6f6679a0cb51716adc91a21524929 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:13:03 +0000 Subject: [PATCH 0142/1048] Use a throwing default setter in v8 emitter. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13815 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascripthelpers.swg | 16 ++++++++++++++++ Source/Modules/javascript.cxx | 8 ++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/Lib/javascript/v8/javascripthelpers.swg b/Lib/javascript/v8/javascripthelpers.swg index 5de11feb3..9a80a6552 100644 --- a/Lib/javascript/v8/javascripthelpers.swg +++ b/Lib/javascript/v8/javascripthelpers.swg @@ -43,4 +43,20 @@ void SWIGV8_AddStaticVariable(v8::Handle obj, const char* symbol, v8 obj->SetAccessor(v8::String::NewSymbol(symbol), getter, setter); } +void JS_veto_set_variable(v8::Local property, v8::Local value, const v8::AccessorInfo& info) +{ + char buffer[256]; + char msg[512]; + int res; + + property->WriteUtf8(buffer, 256); + res = sprintf(msg, "Tried to write read-only variable: %s.", buffer); + + if(res<0) { + SWIG_exception(SWIG_ERROR, "Tried to write read-only variable."); + } else { + SWIG_exception(SWIG_ERROR, msg); + } +} + %} // v8_helper_functions diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 5f3e01a42..28c4b96b7 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1591,12 +1591,15 @@ private: String* GLOBAL; String* NULL_STR; + String *VETO_SET; + }; V8Emitter::V8Emitter() : JSEmitter(), GLOBAL(NewString("global")), - NULL_STR(NewString("0")) + NULL_STR(NewString("0")), + VETO_SET(NewString("JS_veto_set_variable")) { } @@ -1604,6 +1607,7 @@ V8Emitter::~V8Emitter() { Delete(GLOBAL); Delete(NULL_STR); + Delete(VETO_SET); } int V8Emitter::initialize(Node *n) @@ -1761,7 +1765,7 @@ int V8Emitter::enterVariable(Node* n) JSEmitter::enterVariable(n); state.variable(GETTER, NULL_STR); - state.variable(SETTER, NULL_STR); + state.variable(SETTER, VETO_SET); return SWIG_OK; } From da109ee764b0c48f93554f4cc093997fe530ec28 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:13:17 +0000 Subject: [PATCH 0143/1048] Fix input string handling in v8 typemaps. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13816 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptstrings.swg | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Lib/javascript/v8/javascriptstrings.swg b/Lib/javascript/v8/javascriptstrings.swg index 14a96c63e..e955bee3a 100644 --- a/Lib/javascript/v8/javascriptstrings.swg +++ b/Lib/javascript/v8/javascriptstrings.swg @@ -9,13 +9,12 @@ SWIG_AsCharPtrAndSize(v8::Handle valRef, char** cptr, size_t* psize, if(valRef->IsString()) { v8::Handle js_str = valRef->ToString(); - size_t len = js_str->Utf8Length(); - size_t abs_len = js_str->Length(); + size_t len = js_str->Utf8Length() + 1; char* cstr = new char[len]; js_str->WriteUtf8(cstr, len); if(alloc) *alloc = SWIG_NEWOBJ; - if(psize) *psize = abs_len + 1; + if(psize) *psize = len; if(cptr) *cptr = cstr; return SWIG_OK; From 5425edc50894d32724b7cde8d11bce9fbd3fcdf8 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:13:29 +0000 Subject: [PATCH 0144/1048] Add library flag for building v8 shell. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13817 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/Makefile.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 008ae817f..a6ed5157e 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -582,7 +582,7 @@ javascript_cpp: $(SRCS) # Compile a javascript executable # ---------------------------------------------------------------- javascript_exe: $(SRCS) - $(CXX) $(CXXFLAGS) $(JSEXE_FLAGS) $(JS_INCLUDE) $(LIBS) $(JSEXE_SRC) $(JS_DLNK) -o $(JSEXE) + $(CXX) $(CXXFLAGS) $(JSEXE_FLAGS) $(JS_INCLUDE) $(LIBS) $(JSEXE_SRC) $(JS_DLNK) -ldl -o $(JSEXE) # ---------------------------------------------------------------- # Run the Compile a javascript executable From 8db76ddee10085765c41be3c5829ec0cce1e0933 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:13:42 +0000 Subject: [PATCH 0145/1048] Remove generated file from repository. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13818 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/javascript/variables/example_wrap.c | 2593 ------------------ 1 file changed, 2593 deletions(-) delete mode 100644 Examples/javascript/variables/example_wrap.c diff --git a/Examples/javascript/variables/example_wrap.c b/Examples/javascript/variables/example_wrap.c deleted file mode 100644 index 7fc9567cd..000000000 --- a/Examples/javascript/variables/example_wrap.c +++ /dev/null @@ -1,2593 +0,0 @@ -/* ---------------------------------------------------------------------------- - * This file was automatically generated by SWIG (http://www.swig.org). - * Version 2.0.6 - * - * 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. - * ----------------------------------------------------------------------------- */ -/* ----------------------------------------------------------------------------- - * 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 - - - -#define SWIG_AsCharPtrAndSize(val, cptr, psize, alloc) SWIG_JSC_AsCharPtrAndSize(context, val, cptr, psize, alloc) -#define SWIG_FromCharPtrAndSize(cptr, size) SWIG_JSC_FromCharPtrAndSize(context, cptr, size) -#define SWIG_FromCharPtr(cptr) SWIG_JSC_FromCharPtr(context, cptr) - - - -#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 - - - -#include -#include -#include -#include -#include -#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 - - - - -#define SWIG_Error(code, msg) SWIG_JSC_exception(context, exception, code, msg) -#define SWIG_exception(code, msg) SWIG_JSC_exception(context, exception, code, msg) -#define SWIG_fail goto fail - -#define SWIG_JSC_FROM_DECL_ARGS(arg1) (JSContextRef context, arg1) -#define SWIG_JSC_FROM_CALL_ARGS(arg1) (context, arg1) -#define SWIG_JSC_AS_DECL_ARGS(arg1, arg2) (JSContextRef context, arg1, arg2) -#define SWIG_JSC_AS_CALL_ARGS(arg1, arg2) (context, arg1, arg2) - - -typedef struct { - bool swigCMemOwn; - void *swigCObject; - swig_type_info *info; -}SWIG_PRV_DATA; - - - -void SWIG_Javascript_Raise(JSContextRef context, JSValueRef *exception, const char* type) { - JSStringRef message = JSStringCreateWithUTF8CString(type); - *exception = JSValueMakeString(context, message); - JSStringRelease(message); -} - -void SWIG_JSC_exception(JSContextRef context, JSValueRef *exception, int code, const char* msg) { - SWIG_Javascript_Raise(context, exception, msg); -} - - - - -JSValueRef _wrap_SwigObject_disown(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) -{ - JSValueRef jsresult; - - JSObjectRef obj = JSValueToObject(context, thisObject, NULL); - SWIG_PRV_DATA *cdata = (SWIG_PRV_DATA *) JSObjectGetPrivate(obj); - - cdata->swigCMemOwn = false; - - jsresult = JSValueMakeUndefined(context); - return jsresult; -} - -JSValueRef _wrap_SwigObject_getCPtr(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) -{ - JSValueRef jsresult; - long result; - - JSObjectRef obj = JSValueToObject(context, thisObject, NULL); - SWIG_PRV_DATA *cdata = (SWIG_PRV_DATA*) JSObjectGetPrivate(obj); - - result = (long) cdata->swigCObject; - jsresult = JSValueMakeNumber(context, result); - - return jsresult; -} - -JSStaticValue _SwigObject_values[] = { - { - 0, 0, 0, 0 - } -}; - -JSStaticFunction _SwigObject_functions[] = { - { - "disown",_wrap_SwigObject_disown, kJSPropertyAttributeNone - },{ - "getCPtr",_wrap_SwigObject_getCPtr, kJSPropertyAttributeNone - }, - { - 0, 0, 0 - } -}; - -JSClassDefinition _SwigObject_objectDefinition; - -JSClassRef _SwigObject_classRef; - - - -int SWIG_JSC_ConvertInstancePtr(JSContextRef context, JSObjectRef objRef, void** ptr, swig_type_info *info, int flags) { - SWIG_PRV_DATA *cdata = (SWIG_PRV_DATA *) JSObjectGetPrivate(objRef); - if(cdata == NULL) { - return SWIG_ERROR; - } - if(cdata->info != info) { - bool type_valid = false; - swig_cast_info *t = info->cast; - while(t != NULL) { - if(t->type == cdata->info) { - type_valid = true; - break; - } - t = t->next; - } - if(!type_valid) { - return SWIG_TypeError; - } - } - - *ptr = cdata->swigCObject; - - if(flags & SWIG_POINTER_DISOWN) { - cdata->swigCMemOwn = false; - } - - return SWIG_OK; -} - -int SWIG_JSC_ConvertPtr(JSContextRef context, JSValueRef valRef, void** ptr, swig_type_info *info, int flags) { - if(!JSValueIsObject(context, valRef)) { - return SWIG_TypeError; - } - - JSObjectRef objRef = JSValueToObject(context, valRef, NULL); - if(objRef == NULL) { - return SWIG_ERROR; - } - - return SWIG_JSC_ConvertInstancePtr(context, objRef, ptr, info, flags); -} - -JSObjectRef SWIG_JSC_NewPointerObj(JSContextRef context, void *ptr, swig_type_info *info, int flags) { - - JSClassRef classRef; - if(info->clientdata == NULL) { - classRef = _SwigObject_classRef; - } else { - classRef = (JSClassRef) info->clientdata; - } - - JSObjectRef result = JSObjectMake(context, classRef, NULL); - - SWIG_PRV_DATA* cdata = (SWIG_PRV_DATA*) malloc(sizeof(SWIG_PRV_DATA)); - cdata->swigCObject = ptr; - cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; - cdata->info = info; - - JSObjectSetPrivate(result, cdata); - - return result; -} - -#define SWIG_ConvertPtr(obj, ptr, info, flags) SWIG_JSC_ConvertPtr(context, obj, ptr, info, flags) -#define SWIG_NewPointerObj(ptr, info, flags) SWIG_JSC_NewPointerObj(context, ptr, info, flags) - -#define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_JSC_ConvertInstancePtr(context, obj, pptr, type, flags) -#define SWIG_NewInstanceObj(thisvalue, type, flags) SWIG_JSC_NewPointerObj(context, thisvalue, type, flags) - - - -/* -------- TYPES TABLE (BEGIN) -------- */ - -#define SWIGTYPE_p_Point swig_types[0] -#define SWIGTYPE_p_char swig_types[1] -#define SWIGTYPE_p_int 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) -------- */ - - - -#define SWIGVERSION 0x020006 -#define SWIG_VERSION SWIGVERSION - - -#define SWIG_as_voidptr(a) (void *)((const void *)(a)) -#define SWIG_as_voidptrptr(a) ((void)SWIG_as_voidptr(*a),(void**)(a)) - - -#include "example.h" - - -extern int ivar; -extern short svar; -extern long lvar; -extern unsigned int uivar; -extern unsigned short usvar; -extern unsigned long ulvar; -extern signed char scvar; -extern unsigned char ucvar; -extern char cvar; -extern float fvar; -extern double dvar; -extern char *strvar; -extern const char cstrvar[]; -extern int *iptrvar; -extern char name[256]; - -extern Point *ptptr; -extern Point pt; - - -#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 SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, double *val) -{ - if(!JSValueIsNumber(context, obj)) { - return SWIG_TypeError; - } - if(val) *val = JSValueToNumber(context, obj, NULL); - - return SWIG_OK; -} - - -#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 SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, long* val) -{ - if (!JSValueIsNumber(context, obj)) { - return SWIG_TypeError; - } - if(val) *val = (long) JSValueToNumber(context, obj, NULL); - - return SWIG_OK; -} - - -SWIGINTERN int -SWIG_AsVal_int SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, int *val) -{ - long v; - int res = SWIG_AsVal_long SWIG_JSC_AS_CALL_ARGS(obj, &v); - if (SWIG_IsOK(res)) { - if ((v < INT_MIN || v > INT_MAX)) { - return SWIG_OverflowError; - } else { - if (val) *val = (int)(v); - } - } - return res; -} - - -SWIGINTERNINLINE JSValueRef - SWIG_From_int SWIG_JSC_FROM_DECL_ARGS(int value) -{ - return JSValueMakeNumber(context, value); -} - - -SWIGINTERN int -SWIG_AsVal_short SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, short *val) -{ - long v; - int res = SWIG_AsVal_long SWIG_JSC_AS_CALL_ARGS(obj, &v); - if (SWIG_IsOK(res)) { - if ((v < SHRT_MIN || v > SHRT_MAX)) { - return SWIG_OverflowError; - } else { - if (val) *val = (short)(v); - } - } - return res; -} - - -SWIGINTERNINLINE JSValueRef - SWIG_From_long SWIG_JSC_FROM_DECL_ARGS(long value) -{ - return JSValueMakeNumber(context, value); -} - - -SWIGINTERNINLINE JSValueRef -SWIG_From_short SWIG_JSC_FROM_DECL_ARGS(short value) -{ - return SWIG_From_long SWIG_JSC_FROM_CALL_ARGS(value); -} - - -SWIGINTERN int -SWIG_AsVal_unsigned_SS_long SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, unsigned long *val) -{ - if(!JSValueIsNumber(context, obj)) { - return SWIG_TypeError; - } - - long longVal = (long) JSValueToNumber(context, obj, NULL); - - if(longVal < 0) { - return SWIG_OverflowError; - } - - if(val) *val = longVal; - - return SWIG_OK; -} - - -SWIGINTERN int -SWIG_AsVal_unsigned_SS_int SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, unsigned int *val) -{ - unsigned long v; - int res = SWIG_AsVal_unsigned_SS_long SWIG_JSC_AS_CALL_ARGS(obj, &v); - if (SWIG_IsOK(res)) { - if ((v > UINT_MAX)) { - return SWIG_OverflowError; - } else { - if (val) *val = (unsigned int)(v); - } - } - return res; -} - - -SWIGINTERNINLINE JSValueRef -SWIG_From_unsigned_SS_long SWIG_JSC_FROM_DECL_ARGS(unsigned long value) -{ - return (value > LONG_MAX) ? - JSValueMakeNumber(context, value) : JSValueMakeNumber(context, (long)(value)); -} - - -SWIGINTERNINLINE JSValueRef -SWIG_From_unsigned_SS_int SWIG_JSC_FROM_DECL_ARGS(unsigned int value) -{ - return SWIG_From_unsigned_SS_long SWIG_JSC_FROM_CALL_ARGS(value); -} - - -SWIGINTERN int -SWIG_AsVal_unsigned_SS_short SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, unsigned short *val) -{ - unsigned long v; - int res = SWIG_AsVal_unsigned_SS_long SWIG_JSC_AS_CALL_ARGS(obj, &v); - if (SWIG_IsOK(res)) { - if ((v > USHRT_MAX)) { - return SWIG_OverflowError; - } else { - if (val) *val = (unsigned short)(v); - } - } - return res; -} - - -SWIGINTERNINLINE JSValueRef -SWIG_From_unsigned_SS_short SWIG_JSC_FROM_DECL_ARGS(unsigned short value) -{ - return SWIG_From_unsigned_SS_long SWIG_JSC_FROM_CALL_ARGS(value); -} - - -SWIGINTERN int -SWIG_AsVal_signed_SS_char SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, signed char *val) -{ - long v; - int res = SWIG_AsVal_long SWIG_JSC_AS_CALL_ARGS(obj, &v); - if (SWIG_IsOK(res)) { - if ((v < SCHAR_MIN || v > SCHAR_MAX)) { - return SWIG_OverflowError; - } else { - if (val) *val = (signed char)(v); - } - } - return res; -} - - -SWIGINTERNINLINE JSValueRef -SWIG_From_signed_SS_char SWIG_JSC_FROM_DECL_ARGS(signed char value) -{ - return SWIG_From_long SWIG_JSC_FROM_CALL_ARGS(value); -} - - -SWIGINTERN int -SWIG_AsVal_unsigned_SS_char SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, unsigned char *val) -{ - unsigned long v; - int res = SWIG_AsVal_unsigned_SS_long SWIG_JSC_AS_CALL_ARGS(obj, &v); - if (SWIG_IsOK(res)) { - if ((v > UCHAR_MAX)) { - return SWIG_OverflowError; - } else { - if (val) *val = (unsigned char)(v); - } - } - return res; -} - - -SWIGINTERNINLINE JSValueRef -SWIG_From_unsigned_SS_char SWIG_JSC_FROM_DECL_ARGS(unsigned char value) -{ - return SWIG_From_unsigned_SS_long SWIG_JSC_FROM_CALL_ARGS(value); -} - - -SWIGINTERN swig_type_info* -SWIG_pchar_descriptor(void) -{ - static int init = 0; - static swig_type_info* info = 0; - if (!init) { - info = SWIG_TypeQuery("_p_char"); - init = 1; - } - return info; -} - - -SWIGINTERN int -SWIG_JSC_AsCharPtrAndSize(JSContextRef context, JSValueRef valRef, char** cptr, size_t* psize, int *alloc) -{ - if(JSValueIsString(context, valRef)) { - JSStringRef js_str = JSValueToStringCopy(context, valRef, NULL); - size_t len = JSStringGetMaximumUTF8CStringSize(js_str); - size_t abs_len = JSStringGetLength(js_str); - char* cstr = (char*) malloc(len * sizeof(char)); - JSStringGetUTF8CString(js_str, cstr, len); - - if(alloc) *alloc = SWIG_NEWOBJ; - if(psize) *psize = abs_len + 1; - if(cptr) *cptr = cstr; - - return SWIG_OK; - } else { - if(JSValueIsObject(context, valRef)) { - JSObjectRef obj = JSValueToObject(context, valRef, NULL); - // try if the object is a wrapped char[] - swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); - if (pchar_descriptor) { - void* vptr = 0; - if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { - if (cptr) *cptr = (char *) vptr; - if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; - if (alloc) *alloc = SWIG_OLDOBJ; - return SWIG_OK; - } - } - return SWIG_TypeError; - } else { - return SWIG_TypeError; - } - } -} - - -SWIGINTERN int -SWIG_JSC_AsCharArray(JSContextRef context, JSValueRef obj, char *val, size_t size) -{ - char* cptr = 0; size_t csize = 0; int alloc = SWIG_OLDOBJ; - int res = SWIG_JSC_AsCharPtrAndSize(context, obj, &cptr, &csize, &alloc); - if (SWIG_IsOK(res)) { - if ((csize == size + 1) && cptr && !(cptr[csize-1])) --csize; - if (csize <= size) { - if (val) { - if (csize) memcpy(val, cptr, csize*sizeof(char)); - if (csize < size) memset(val + csize, 0, (size - csize)*sizeof(char)); - } - if (alloc == SWIG_NEWOBJ) { - free((char*)cptr); - res = SWIG_DelNewMask(res); - } - return res; - } - if (alloc == SWIG_NEWOBJ) free((char*)cptr); - } - return SWIG_TypeError; -} - - - - -SWIGINTERN int -SWIG_AsVal_char SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, char *val) -{ - int res = SWIG_JSC_AsCharArray(context, obj, val, 1); - if (!SWIG_IsOK(res)) { - long v; - res = SWIG_AddCast(SWIG_AsVal_long SWIG_JSC_AS_CALL_ARGS(obj, &v)); - if (SWIG_IsOK(res)) { - if ((CHAR_MIN <= v) && (v <= CHAR_MAX)) { - if (val) *val = (char)(v); - } else { - res = SWIG_OverflowError; - } - } - } - return res; -} - - -SWIGINTERNINLINE JSValueRef -SWIG_JSC_FromCharPtrAndSize(JSContextRef context, const char* carray, size_t size) -{ - if (carray) { - if (size > INT_MAX) { - // TODO: handle extra long strings - //swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); - //return pchar_descriptor ? - // SWIG_InternalNewPointerObj(%const_cast(carray,char *), pchar_descriptor, 0) : SWIG_Py_Void(); - return JSValueMakeUndefined(context); - } else { - JSStringRef jsstring = JSStringCreateWithUTF8CString(carray); - JSValueRef result = JSValueMakeString(context, jsstring); - JSStringRelease(jsstring); - return result; - } - } else { - return JSValueMakeUndefined(context); - } -} - - -SWIGINTERNINLINE JSValueRef -SWIG_From_char SWIG_JSC_FROM_DECL_ARGS(char c) -{ - return SWIG_JSC_FromCharPtrAndSize(context, &c,1); -} - - -SWIGINTERN int -SWIG_AsVal_float SWIG_JSC_AS_DECL_ARGS(JSValueRef obj, float *val) -{ - double v; - int res = SWIG_AsVal_double SWIG_JSC_AS_CALL_ARGS(obj, &v); - if (SWIG_IsOK(res)) { - if ((v < -FLT_MAX || v > FLT_MAX)) { - return SWIG_OverflowError; - } else { - if (val) *val = (float)(v); - } - } - return res; -} - - -SWIGINTERN JSValueRef -SWIG_From_double SWIG_JSC_FROM_DECL_ARGS (double val) -{ - return JSValueMakeNumber(context, val); -} - - -SWIGINTERNINLINE JSValueRef -SWIG_From_float SWIG_JSC_FROM_DECL_ARGS(float value) -{ - return SWIG_From_double SWIG_JSC_FROM_CALL_ARGS(value); -} - - - - - -SWIGINTERNINLINE JSValueRef -SWIG_JSC_FromCharPtr(JSContextRef context, const char *cptr) -{ - return SWIG_JSC_FromCharPtrAndSize(context, cptr, (cptr ? strlen(cptr) : 0)); -} - - -extern int status; -extern char path[256]; - - -extern void print_vars(); -extern int *new_int(int value); -extern Point *new_Point(int x, int y); -extern char *Point_print(Point *p); -extern void pt_print(); - - - - -bool JS_registerClass(JSGlobalContextRef context, JSObjectRef parentObject, - const char* className, - JSClassDefinition* definition) { - - JSStringRef js_className = JSStringCreateWithUTF8CString(className); - JSObjectRef classObject = JSObjectMake(context, JSClassCreate(definition), NULL); - JSObjectSetProperty(context, parentObject, - js_className, classObject, - kJSPropertyAttributeNone, NULL); - JSStringRelease(js_className); - - return true; -} - -bool JS_registerNamespace(JSGlobalContextRef context, - JSObjectRef namespaceObj, JSObjectRef parentNamespace, - const char* name) -{ - JSStringRef js_name = JSStringCreateWithUTF8CString(name); - JSObjectSetProperty(context, parentNamespace, - js_name, namespaceObj, - kJSPropertyAttributeNone, NULL); - JSStringRelease(js_name); - - return true; -} - - -bool JS_registerFunction(JSGlobalContextRef context, JSObjectRef object, - const char* functionName, JSObjectCallAsFunctionCallback callback) -{ - JSStringRef js_functionName = JSStringCreateWithUTF8CString(functionName); - JSObjectSetProperty(context, object, js_functionName, - JSObjectMakeFunctionWithCallback(context, js_functionName, callback), - kJSPropertyAttributeNone, NULL); - JSStringRelease(js_functionName); - return true; -} - -bool JS_veto_set_variable(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) -{ - char buffer[256]; - char msg[512]; - int res; - - JSStringGetUTF8CString(propertyName, buffer, 256); - res = sprintf(msg, "Tried to write read-only variable: %s.", buffer); - - if(res<0) { - SWIG_exception(SWIG_ERROR, "Tried to write read-only variable."); - } else { - SWIG_exception(SWIG_ERROR, msg); - } - - return false; -} - -JSValueRef JS_CharPtrToJSValue(JSContextRef context, char* cstr) { - JSValueRef val; - - JSStringRef jsstring = JSStringCreateWithUTF8CString((char*) cstr); - val = JSValueMakeString(context, jsstring); - JSStringRelease(jsstring); - - return val; -} - - -bool _wrap_ivar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) -{ - int arg1 ; - int val1 ; - int ecode1 = 0 ; - - ecode1 = SWIG_AsVal_int SWIG_JSC_AS_CALL_ARGS(value, &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "ivar_set" "', argument " "1"" of type '" "int""'"); - } - arg1 = (int)(val1); - ivar = arg1; - - - return true; - - goto fail; -fail: - return false; -} - - -JSValueRef _wrap_ivar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) -{ - JSValueRef jsresult; - int result; - - result = (int)ivar; - jsresult = SWIG_From_int SWIG_JSC_FROM_CALL_ARGS((int)(result)); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -bool _wrap_svar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) -{ - short arg1 ; - short val1 ; - int ecode1 = 0 ; - - ecode1 = SWIG_AsVal_short SWIG_JSC_AS_CALL_ARGS(value, &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "svar_set" "', argument " "1"" of type '" "short""'"); - } - arg1 = (short)(val1); - svar = arg1; - - - return true; - - goto fail; -fail: - return false; -} - - -JSValueRef _wrap_svar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) -{ - JSValueRef jsresult; - short result; - - result = (short)svar; - jsresult = SWIG_From_short SWIG_JSC_FROM_CALL_ARGS((short)(result)); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -bool _wrap_lvar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) -{ - long arg1 ; - long val1 ; - int ecode1 = 0 ; - - ecode1 = SWIG_AsVal_long SWIG_JSC_AS_CALL_ARGS(value, &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "lvar_set" "', argument " "1"" of type '" "long""'"); - } - arg1 = (long)(val1); - lvar = arg1; - - - return true; - - goto fail; -fail: - return false; -} - - -JSValueRef _wrap_lvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) -{ - JSValueRef jsresult; - long result; - - result = (long)lvar; - jsresult = SWIG_From_long SWIG_JSC_FROM_CALL_ARGS((long)(result)); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -bool _wrap_uivar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) -{ - unsigned int arg1 ; - unsigned int val1 ; - int ecode1 = 0 ; - - ecode1 = SWIG_AsVal_unsigned_SS_int SWIG_JSC_AS_CALL_ARGS(value, &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "uivar_set" "', argument " "1"" of type '" "unsigned int""'"); - } - arg1 = (unsigned int)(val1); - uivar = arg1; - - - return true; - - goto fail; -fail: - return false; -} - - -JSValueRef _wrap_uivar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) -{ - JSValueRef jsresult; - unsigned int result; - - result = (unsigned int)uivar; - jsresult = SWIG_From_unsigned_SS_int SWIG_JSC_FROM_CALL_ARGS((unsigned int)(result)); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -bool _wrap_usvar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) -{ - unsigned short arg1 ; - unsigned short val1 ; - int ecode1 = 0 ; - - ecode1 = SWIG_AsVal_unsigned_SS_short SWIG_JSC_AS_CALL_ARGS(value, &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "usvar_set" "', argument " "1"" of type '" "unsigned short""'"); - } - arg1 = (unsigned short)(val1); - usvar = arg1; - - - return true; - - goto fail; -fail: - return false; -} - - -JSValueRef _wrap_usvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) -{ - JSValueRef jsresult; - unsigned short result; - - result = (unsigned short)usvar; - jsresult = SWIG_From_unsigned_SS_short SWIG_JSC_FROM_CALL_ARGS((unsigned short)(result)); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -bool _wrap_ulvar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) -{ - unsigned long arg1 ; - unsigned long val1 ; - int ecode1 = 0 ; - - ecode1 = SWIG_AsVal_unsigned_SS_long SWIG_JSC_AS_CALL_ARGS(value, &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "ulvar_set" "', argument " "1"" of type '" "unsigned long""'"); - } - arg1 = (unsigned long)(val1); - ulvar = arg1; - - - return true; - - goto fail; -fail: - return false; -} - - -JSValueRef _wrap_ulvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) -{ - JSValueRef jsresult; - unsigned long result; - - result = (unsigned long)ulvar; - jsresult = SWIG_From_unsigned_SS_long SWIG_JSC_FROM_CALL_ARGS((unsigned long)(result)); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -bool _wrap_scvar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) -{ - signed char arg1 ; - signed char val1 ; - int ecode1 = 0 ; - - ecode1 = SWIG_AsVal_signed_SS_char SWIG_JSC_AS_CALL_ARGS(value, &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "scvar_set" "', argument " "1"" of type '" "signed char""'"); - } - arg1 = (signed char)(val1); - scvar = arg1; - - - return true; - - goto fail; -fail: - return false; -} - - -JSValueRef _wrap_scvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) -{ - JSValueRef jsresult; - signed char result; - - result = (signed char)scvar; - jsresult = SWIG_From_signed_SS_char SWIG_JSC_FROM_CALL_ARGS((signed char)(result)); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -bool _wrap_ucvar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) -{ - unsigned char arg1 ; - unsigned char val1 ; - int ecode1 = 0 ; - - ecode1 = SWIG_AsVal_unsigned_SS_char SWIG_JSC_AS_CALL_ARGS(value, &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "ucvar_set" "', argument " "1"" of type '" "unsigned char""'"); - } - arg1 = (unsigned char)(val1); - ucvar = arg1; - - - return true; - - goto fail; -fail: - return false; -} - - -JSValueRef _wrap_ucvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) -{ - JSValueRef jsresult; - unsigned char result; - - result = (unsigned char)ucvar; - jsresult = SWIG_From_unsigned_SS_char SWIG_JSC_FROM_CALL_ARGS((unsigned char)(result)); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -bool _wrap_cvar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) -{ - char arg1 ; - char val1 ; - int ecode1 = 0 ; - - ecode1 = SWIG_AsVal_char SWIG_JSC_AS_CALL_ARGS(value, &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "cvar_set" "', argument " "1"" of type '" "char""'"); - } - arg1 = (char)(val1); - cvar = arg1; - - - return true; - - goto fail; -fail: - return false; -} - - -JSValueRef _wrap_cvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) -{ - JSValueRef jsresult; - char result; - - result = (char)cvar; - jsresult = SWIG_From_char SWIG_JSC_FROM_CALL_ARGS((char)(result)); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -bool _wrap_fvar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) -{ - float arg1 ; - float val1 ; - int ecode1 = 0 ; - - ecode1 = SWIG_AsVal_float SWIG_JSC_AS_CALL_ARGS(value, &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "fvar_set" "', argument " "1"" of type '" "float""'"); - } - arg1 = (float)(val1); - fvar = arg1; - - - return true; - - goto fail; -fail: - return false; -} - - -JSValueRef _wrap_fvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) -{ - JSValueRef jsresult; - float result; - - result = (float)fvar; - jsresult = SWIG_From_float SWIG_JSC_FROM_CALL_ARGS((float)(result)); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -bool _wrap_dvar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) -{ - double arg1 ; - double val1 ; - int ecode1 = 0 ; - - ecode1 = SWIG_AsVal_double SWIG_JSC_AS_CALL_ARGS(value, &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "dvar_set" "', argument " "1"" of type '" "double""'"); - } - arg1 = (double)(val1); - dvar = arg1; - - - return true; - - goto fail; -fail: - return false; -} - - -JSValueRef _wrap_dvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) -{ - JSValueRef jsresult; - double result; - - result = (double)dvar; - jsresult = SWIG_From_double SWIG_JSC_FROM_CALL_ARGS((double)(result)); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -bool _wrap_strvar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) -{ - char *arg1 = (char *) 0 ; - int res1 ; - char *buf1 = 0 ; - int alloc1 = 0 ; - - res1 = SWIG_JSC_AsCharPtrAndSize(context, value, &buf1, NULL, &alloc1); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "strvar_set" "', argument " "1"" of type '" "char *""'"); - } - arg1 = (char *)(buf1); - if (strvar) free((char*)strvar); - if (arg1) { - size_t size = strlen((const char *)((const char *)(arg1))) + 1; - strvar = (char *)(char *)memcpy((char *)malloc((size)*sizeof(char)), arg1, sizeof(char)*(size)); - } else { - strvar = 0; - } - - - return true; - - goto fail; -fail: - return false; -} - - -JSValueRef _wrap_strvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) -{ - JSValueRef jsresult; - char *result = 0 ; - - result = (char *)strvar; - jsresult = SWIG_FromCharPtr((const char *)result); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -JSValueRef _wrap_cstrvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) -{ - JSValueRef jsresult; - char *result = 0 ; - - result = (char *)(char *)cstrvar; - jsresult = SWIG_FromCharPtr((const char *)result); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -bool _wrap_iptrvar_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) -{ - int *arg1 = (int *) 0 ; - void *argp1 = 0 ; - int res1 = 0 ; - - res1 = SWIG_ConvertPtr(value, &argp1,SWIGTYPE_p_int, 0 | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "iptrvar_set" "', argument " "1"" of type '" "int *""'"); - } - arg1 = (int *)(argp1); - iptrvar = arg1; - - - return true; - - goto fail; -fail: - return false; -} - - -JSValueRef _wrap_iptrvar_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) -{ - JSValueRef jsresult; - int *result = 0 ; - - result = (int *)iptrvar; - jsresult = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_int, 0 | 0 ); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -bool _wrap_name_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) -{ - char *arg1 ; - char temp1[256] ; - int res1 ; - - res1 = SWIG_JSC_AsCharArray(context, value, temp1, 256); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "name_set" "', argument " "1"" of type '" "char [256]""'"); - } - arg1 = (char *)(temp1); - if (arg1) memcpy(name,arg1,256*sizeof(char)); - else memset(name,0,256*sizeof(char)); - - - return true; - - goto fail; -fail: - return false; -} - - -JSValueRef _wrap_name_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) -{ - JSValueRef jsresult; - char *result = 0 ; - - result = (char *)(char *)name; - { - size_t size = 256; - - while (size && (result[size - 1] == '\0')) --size; - - jsresult = SWIG_FromCharPtrAndSize(result, size); - } - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -bool _wrap_ptptr_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) -{ - Point *arg1 = (Point *) 0 ; - void *argp1 = 0 ; - int res1 = 0 ; - - res1 = SWIG_ConvertPtr(value, &argp1,SWIGTYPE_p_Point, 0 | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ptptr_set" "', argument " "1"" of type '" "Point *""'"); - } - arg1 = (Point *)(argp1); - ptptr = arg1; - - - return true; - - goto fail; -fail: - return false; -} - - -JSValueRef _wrap_ptptr_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) -{ - JSValueRef jsresult; - Point *result = 0 ; - - result = (Point *)ptptr; - jsresult = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Point, 0 | 0 ); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -bool _wrap_pt_set(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) -{ - Point arg1 ; - void *argp1 ; - int res1 = 0 ; - - { - res1 = SWIG_ConvertPtr(value, &argp1, SWIGTYPE_p_Point, 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "pt_set" "', argument " "1"" of type '" "Point""'"); - } - if (!argp1) { - SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in method '" "pt_set" "', argument " "1"" of type '" "Point""'"); - } else { - arg1 = *((Point *)(argp1)); - } - } - pt = arg1; - - - return true; - - goto fail; -fail: - return false; -} - - -JSValueRef _wrap_pt_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) -{ - JSValueRef jsresult; - Point result; - - result = pt; - jsresult = SWIG_NewPointerObj((Point *)memcpy((Point *)malloc(sizeof(Point)),&result,sizeof(Point)), SWIGTYPE_p_Point, SWIG_POINTER_OWN | 0 ); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -JSValueRef _wrap_status_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) -{ - JSValueRef jsresult; - int result; - - result = (int)status; - jsresult = SWIG_From_int SWIG_JSC_FROM_CALL_ARGS((int)(result)); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -JSValueRef _wrap_path_get(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) -{ - JSValueRef jsresult; - char *result = 0 ; - - result = (char *)(char *)path; - { - size_t size = 256; - - while (size && (result[size - 1] == '\0')) --size; - - jsresult = SWIG_FromCharPtrAndSize(result, size); - } - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -JSValueRef _wrap_print_vars(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) -{ - JSValueRef jsresult; - - print_vars(); - jsresult = JSValueMakeUndefined(context); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -JSValueRef _wrap_new_int(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) -{ - int arg1 ; - int val1 ; - int ecode1 = 0 ; - JSValueRef jsresult; - int *result = 0 ; - - ecode1 = SWIG_AsVal_int SWIG_JSC_AS_CALL_ARGS(argv[0], &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "new_int" "', argument " "1"" of type '" "int""'"); - } - arg1 = (int)(val1); - result = (int *)new_int(arg1); - jsresult = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_int, 0 | 0 ); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -JSValueRef _wrap_new_Point(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) -{ - int arg1 ; - int arg2 ; - int val1 ; - int ecode1 = 0 ; - int val2 ; - int ecode2 = 0 ; - JSValueRef jsresult; - Point *result = 0 ; - - ecode1 = SWIG_AsVal_int SWIG_JSC_AS_CALL_ARGS(argv[0], &val1); - if (!SWIG_IsOK(ecode1)) { - SWIG_exception_fail(SWIG_ArgError(ecode1), "in method '" "new_Point" "', argument " "1"" of type '" "int""'"); - } - arg1 = (int)(val1); - ecode2 = SWIG_AsVal_int SWIG_JSC_AS_CALL_ARGS(argv[1], &val2); - if (!SWIG_IsOK(ecode2)) { - SWIG_exception_fail(SWIG_ArgError(ecode2), "in method '" "new_Point" "', argument " "2"" of type '" "int""'"); - } - arg2 = (int)(val2); - result = (Point *)new_Point(arg1,arg2); - jsresult = SWIG_NewPointerObj(SWIG_as_voidptr(result), SWIGTYPE_p_Point, 0 | 0 ); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -JSValueRef _wrap_Point_print(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) -{ - Point *arg1 = (Point *) 0 ; - void *argp1 = 0 ; - int res1 = 0 ; - JSValueRef jsresult; - char *result = 0 ; - - res1 = SWIG_ConvertPtr(argv[0], &argp1,SWIGTYPE_p_Point, 0 | 0 ); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "Point_print" "', argument " "1"" of type '" "Point *""'"); - } - arg1 = (Point *)(argp1); - result = (char *)Point_print(arg1); - jsresult = SWIG_FromCharPtr((const char *)result); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -JSValueRef _wrap_pt_print(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) -{ - JSValueRef jsresult; - - pt_print(); - jsresult = JSValueMakeUndefined(context); - - return jsresult; - - goto fail; -fail: - return NULL; -} - - -/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (BEGIN) -------- */ - -static swig_type_info _swigt__p_Point = {"_p_Point", "Point *", 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_int = {"_p_int", "int *", 0, 0, (void*)0, 0}; - -static swig_type_info *swig_type_initial[] = { - &_swigt__p_Point, - &_swigt__p_char, - &_swigt__p_int, -}; - -static swig_cast_info _swigc__p_Point[] = { {&_swigt__p_Point, 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_int[] = { {&_swigt__p_int, 0, 0, 0},{0, 0, 0, 0}}; - -static swig_cast_info *swig_cast_initial[] = { - _swigc__p_Point, - _swigc__p_char, - _swigc__p_int, -}; - - -/* -------- TYPE CONVERSION AND EQUIVALENCE RULES (END) -------- */ - - - -JSStaticValue example_values[] = { - { - "ivar",_wrap_ivar_get, _wrap_ivar_set,kJSPropertyAttributeNone - },{ - "svar",_wrap_svar_get, _wrap_svar_set,kJSPropertyAttributeNone - },{ - "lvar",_wrap_lvar_get, _wrap_lvar_set,kJSPropertyAttributeNone - },{ - "uivar",_wrap_uivar_get, _wrap_uivar_set,kJSPropertyAttributeNone - },{ - "usvar",_wrap_usvar_get, _wrap_usvar_set,kJSPropertyAttributeNone - },{ - "ulvar",_wrap_ulvar_get, _wrap_ulvar_set,kJSPropertyAttributeNone - },{ - "scvar",_wrap_scvar_get, _wrap_scvar_set,kJSPropertyAttributeNone - },{ - "ucvar",_wrap_ucvar_get, _wrap_ucvar_set,kJSPropertyAttributeNone - },{ - "cvar",_wrap_cvar_get, _wrap_cvar_set,kJSPropertyAttributeNone - },{ - "fvar",_wrap_fvar_get, _wrap_fvar_set,kJSPropertyAttributeNone - },{ - "dvar",_wrap_dvar_get, _wrap_dvar_set,kJSPropertyAttributeNone - },{ - "strvar",_wrap_strvar_get, _wrap_strvar_set,kJSPropertyAttributeNone - },{ - "cstrvar",_wrap_cstrvar_get, JS_veto_set_variable,kJSPropertyAttributeNone - },{ - "iptrvar",_wrap_iptrvar_get, _wrap_iptrvar_set,kJSPropertyAttributeNone - },{ - "name",_wrap_name_get, _wrap_name_set,kJSPropertyAttributeNone - },{ - "ptptr",_wrap_ptptr_get, _wrap_ptptr_set,kJSPropertyAttributeNone - },{ - "pt",_wrap_pt_get, _wrap_pt_set,kJSPropertyAttributeNone - },{ - "status",_wrap_status_get, JS_veto_set_variable,kJSPropertyAttributeNone - },{ - "path",_wrap_path_get, JS_veto_set_variable,kJSPropertyAttributeNone - }, - { - 0, 0, 0, 0 - } -}; - -JSStaticFunction example_functions[] = { - { - "print_vars",_wrap_print_vars, kJSPropertyAttributeNone - },{ - "new_int",_wrap_new_int, kJSPropertyAttributeNone - },{ - "new_Point",_wrap_new_Point, kJSPropertyAttributeNone - },{ - "Point_print",_wrap_Point_print, kJSPropertyAttributeNone - },{ - "pt_print",_wrap_pt_print, kJSPropertyAttributeNone - }, - { - 0, 0, 0 - } -}; - -JSClassDefinition example_classDefinition; - - -SWIGRUNTIME void -SWIG_JSC_SetModule(swig_module_info *swig_module) {} - -SWIGRUNTIME swig_module_info * -SWIG_JSC_GetModule(void) { - return 0; -} - -#define SWIG_GetModule(clientdata) SWIG_JSC_GetModule() -#define SWIG_SetModule(clientdata, pointer) SWIG_JSC_SetModule(pointer) - - -/* ----------------------------------------------------------------------------- - * 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 - - bool example_initialize(JSGlobalContextRef context) { - SWIG_InitializeModule(0); - - JSObjectRef global_object = JSContextGetGlobalObject(context); - - /* Initialize the base swig type object */ - _SwigObject_objectDefinition.staticFunctions = _SwigObject_functions; - _SwigObject_objectDefinition.staticValues = _SwigObject_values; - _SwigObject_classRef = JSClassCreate(&_SwigObject_objectDefinition); - - /* Create objects for namespaces */ - example_classDefinition.staticFunctions = example_functions; - example_classDefinition.staticValues = example_values; - JSObjectRef example_object = JSObjectMake(context, JSClassCreate(&example_classDefinition), NULL); - - - /* Create classes */ - - - /* Register namespaces */ - - JS_registerNamespace(context, example_object, global_object, "example"); - - return true; - } - -#ifdef __cplusplus -} -#endif - - From f814a8e702dcfe2ae2f2480de372e78c5a997eb5 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:14:02 +0000 Subject: [PATCH 0146/1048] Fix errors concerning object wrapping and cleanup in v8 emitter. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13819 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptcode.swg | 30 ++++++++--- Lib/javascript/v8/javascripthelpers.swg | 4 +- Lib/javascript/v8/javascriptinit.swg | 2 + Lib/javascript/v8/javascriptruntime.swg | 71 +++++++++++++------------ Source/Modules/javascript.cxx | 64 +++++++++++++++++++--- 5 files changed, 122 insertions(+), 49 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index b7b2c195f..8f3d8cff2 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -5,7 +5,7 @@ v8::Handle $jswrapper(const v8::Arguments& args) { $jslocals $jscode - SWIG_V8_SetPrivateData(self, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); + SWIGV8_SetPrivateData(self, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); return scope.Close(self); goto fail; @@ -48,7 +48,14 @@ fail: %fragment ("JS_destructordefn", "templates") %{ - // TODO: implement JS_destructordefn +void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) { + SWIGV8_Proxy* proxy = (SWIGV8_Proxy*) parameter; + if(proxy->swigCMemOwn && proxy->swigCObject) { + std::cout << "Deleting wrapped instance: " << proxy->info->name << std::endl; + delete ($jstype*) proxy->swigCObject; + } + delete proxy; +} %} @@ -136,18 +143,25 @@ fail: %} %fragment("jsv8_declare_class_template", "templates") -%{v8::Persistent $jsmangledname_class;%} +%{SWIGV8_ClientData $jsmangledname_clientData; +%} %fragment("jsv8_define_class_template", "templates") -%{$jsmangledname_class = SWIGV8_CreateClassTemplate("$jsname" , $jsctor); - SWIGTYPE_$jsmangledtype->clientdata = &$jsmangledname_class;%} - -%fragment("jsv8_create_class_instance", "templates") -%{v8::Handle $jsmangledname_obj = $jsmangledname_class->GetFunction();%} +%{v8::Handle $jsmangledname_class = SWIGV8_CreateClassTemplate("$jsmangledname"); + $jsmangledname_clientData.class_templ = $jsmangledname_class; + $jsmangledname_clientData.dtor = $jsdtor; + SWIGTYPE_p$jsmangledtype->clientdata = &$jsmangledname_clientData;%} %fragment("jsv8_inherit", "templates") %{$jsmangledname_class->Inherit($jsbaseclass_class);%} +%fragment("jsv8_create_class_instance", "templates") +%{v8::Handle $jsmangledname_class_0 = SWIGV8_CreateClassTemplate("$jsname"); + $jsmangledname_class_0->SetCallHandler($jsctor); + $jsmangledname_class_0->Inherit($jsmangledname_class); + $jsmangledname_class_0->SetHiddenPrototype(true); + v8::Handle $jsmangledname_obj = $jsmangledname_class_0->GetFunction();%} + %fragment("jsv8_register_class", "templates") %{$jsparent_obj->Set(v8::String::NewSymbol("$jsname"), $jsmangledname_obj);%} diff --git a/Lib/javascript/v8/javascripthelpers.swg b/Lib/javascript/v8/javascripthelpers.swg index 9a80a6552..4fcf0e447 100644 --- a/Lib/javascript/v8/javascripthelpers.swg +++ b/Lib/javascript/v8/javascripthelpers.swg @@ -3,8 +3,8 @@ /** * Creates a class template for a class with specified initialization function. */ -v8::Persistent SWIGV8_CreateClassTemplate(const char* symbol, v8::InvocationCallback _func) { - v8::Local class_templ = v8::FunctionTemplate::New(_func); +v8::Persistent SWIGV8_CreateClassTemplate(const char* symbol) { + v8::Local class_templ = v8::FunctionTemplate::New(); class_templ->SetClassName(v8::String::NewSymbol(symbol)); v8::Handle inst_templ = class_templ->InstanceTemplate(); diff --git a/Lib/javascript/v8/javascriptinit.swg b/Lib/javascript/v8/javascriptinit.swg index 1186b33bc..1bca4c244 100644 --- a/Lib/javascript/v8/javascriptinit.swg +++ b/Lib/javascript/v8/javascriptinit.swg @@ -12,4 +12,6 @@ SWIG_V8_GetModule(void) { %} +%insert(init) %{/************ BEGIN: "swiginit.swg" *******************/ %} %insert(init) "swiginit.swg" +%insert(init) %{/************ END: "swiginit.swg" *******************/ %} diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index 2eb9c82cc..b9f24a562 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -8,6 +8,7 @@ #include #include #include +#include %} %insert(runtime) "swigrun.swg"; /* SWIG API */ @@ -59,27 +60,45 @@ public: %} %insert(runtime) %{ -typedef struct { + +// Note: to trigger the c8 gc more often one can tell v8 about the memory consumption +// TODO: we could add a v8 specific parameter to control this value +#define SWIGV8_AVG_OBJ_SIZE 1000 + +class SWIGV8_Proxy { +public: + SWIGV8_Proxy(): swigCMemOwn(false), swigCObject(0), info(0) { + v8::V8::AdjustAmountOfExternalAllocatedMemory(SWIGV8_AVG_OBJ_SIZE); + }; + + ~SWIGV8_Proxy() { + v8::V8::AdjustAmountOfExternalAllocatedMemory(-SWIGV8_AVG_OBJ_SIZE); + } + bool swigCMemOwn; void *swigCObject; swig_type_info *info; -} SWIG_PRV_DATA; +}; + +class SWIGV8_ClientData { +public: + v8::Handle class_templ; + void (*dtor) (v8::Persistent< v8::Value > object, void *parameter); +}; + %} %insert(runtime) %{ int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_type_info *info, int flags) { + v8::HandleScope scope; - if(objRef->InternalFieldCount() < 1) { - return SWIG_ERROR; - } + if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; v8::Handle cdataRef = objRef->GetInternalField(0); - - SWIG_PRV_DATA *cdata = (SWIG_PRV_DATA *) v8::External::Unwrap(cdataRef); + SWIGV8_Proxy *cdata = (SWIGV8_Proxy *) v8::External::Unwrap(cdataRef); if(cdata == NULL) { return SWIG_ERROR; } - if(cdata->info != info) { bool type_valid = false; swig_cast_info *t = info->cast; @@ -94,53 +113,39 @@ int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_t return SWIG_TypeError; } } - *ptr = cdata->swigCObject; - if(flags & SWIG_POINTER_DISOWN) { cdata->swigCMemOwn = false; } - return SWIG_OK; } -void SWIG_V8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info *info, int flags) { - SWIG_PRV_DATA* cdata = (SWIG_PRV_DATA*) new SWIG_PRV_DATA; +void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info *info, int flags) { + SWIGV8_Proxy* cdata = new SWIGV8_Proxy(); cdata->swigCObject = ptr; cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; cdata->info = info; - - obj->SetInternalField(0, v8::External::New(cdata)); + obj->SetPointerInInternalField(0, cdata); + v8::Persistent weakptr = v8::Persistent::New(obj); + weakptr.MakeWeak(cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); } int SWIG_V8_ConvertPtr(v8::Handle valRef, void** ptr, swig_type_info *info, int flags) { + v8::HandleScope scope; + if(!valRef->IsObject()) { return SWIG_TypeError; } - v8::Handle objRef = valRef->ToObject(); - return SWIG_V8_ConvertInstancePtr(objRef, ptr, info, flags); } v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, int flags) { v8::HandleScope scope; - - v8::Local class_templ; - v8::Handle inst_templ; - if(info->clientdata == NULL) { - class_templ = v8::FunctionTemplate::New(); - class_templ->SetClassName(v8::String::NewSymbol(info->name)); - inst_templ = class_templ->InstanceTemplate(); - inst_templ->SetInternalFieldCount(1); - } else { - class_templ = *((v8::Local*) info->clientdata); - inst_templ = class_templ->InstanceTemplate(); - } - - v8::Local result = inst_templ->NewInstance(); - - SWIG_V8_SetPrivateData(result, ptr, info, flags); + + v8::Handle class_templ = ((SWIGV8_ClientData*) info->clientdata)->class_templ; + v8::Handle result = class_templ->InstanceTemplate()->NewInstance(); + SWIGV8_SetPrivateData(result, ptr, info, flags); return scope.Close(result); } diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 28c4b96b7..f54d470f1 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -20,6 +20,7 @@ bool js_template_enable_debug = false; #define CTOR "ctor" #define CTOR_WRAPPERS "ctor_wrappers" #define CTOR_DISPATCHERS "ctor_dispatchers" +#define DTOR "dtor" #define ARGCOUNT "wrap:argc" #define FUNCTION_DISPATCHERS "function_dispatchers" @@ -31,6 +32,7 @@ bool js_template_enable_debug = false; #define T_TYPE_MANGLED "$jsmangledtype" #define T_WRAPPER "$jswrapper" #define T_CTOR "$jsctor" +#define T_DTOR "$jsdtor" #define T_GETTER "$jsgetter" #define T_SETTER "$jssetter" #define T_DISPATCH_CASES "$jsdispatchcases" @@ -292,6 +294,8 @@ protected: Hash *namespaces; Hash *current_namespace; + Hash *undefined_types; + String *defaultResultName; File *f_wrappers; @@ -597,6 +601,7 @@ JSEmitter::JSEmitter() : templates(NewHash()), namespaces(NULL), current_namespace(NULL), + undefined_types(NewHash()), defaultResultName(NewString("result")), f_wrappers(NULL) { @@ -751,6 +756,7 @@ int JSEmitter::enterClass(Node *n) { Append(ctor_wrapper, state.clazz(NAME)); state.clazz(CTOR, ctor_wrapper); state.clazz(CTOR_DISPATCHERS, NewString("")); + state.clazz(DTOR, NewString("0")); // HACK: assume that a class is abstract // this is resolved by emitCtor (which is only called for non abstract classes) @@ -855,10 +861,13 @@ int JSEmitter::emitCtor(Node *n) { return SWIG_OK; } -int JSEmitter::emitDtor(Node *) { +int JSEmitter::emitDtor(Node *n) { Template t_dtor = getTemplate("JS_destructordefn"); + String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); + state.clazz(DTOR, wrap_name); t_dtor.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) + .replace(T_WRAPPER, wrap_name) .replace(T_TYPE, state.clazz(TYPE)) .pretty_print(f_wrappers); @@ -1068,8 +1077,11 @@ void JSEmitter::marshalOutput(Node *n, Wrapper *wrapper, String *actioncode, co Setattr(n, "type", type); String *tm; - // HACK: output types are not registered as swig_types automatically - if (SwigType_ispointer(type)) SwigType_remember_clientdata(type, NewString("0")); + // register undefined wrappers + if (SwigType_ispointer(type) && !Language::instance()->classLookup(type)) { + SwigType_remember_clientdata(type, 0); + Setattr(undefined_types, SwigType_manglestr(type), type); + } // adds a declaration for the result variable if(emitReturnVariable) emit_return_variable(n, type, wrapper); @@ -1565,6 +1577,7 @@ protected: virtual void marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static); virtual int emitNamespaces(); + virtual void emitUndefined(); private: @@ -1654,6 +1667,8 @@ int V8Emitter::dump(Node *n) SwigType_emit_type_table(f_runtime, f_wrappers); + emitUndefined(); + Printv(f_wrap_cpp, f_runtime, "\n", 0); Printv(f_wrap_cpp, f_header, "\n", 0); Printv(f_wrap_cpp, f_class_templates, "\n", 0); @@ -1724,19 +1739,22 @@ int V8Emitter::exitClass(Node *n) } /* Note: this makes sure that there is a swig_type added for this class */ - SwigType_remember_clientdata(state.clazz(TYPE_MANGLED), NewString("0")); + String *clientData = NewString(""); + Printf(clientData, "&%s_clientData", state.clazz(NAME_MANGLED)); + SwigType_remember_clientdata(state.clazz(TYPE_MANGLED), clientData); // emit definition of v8 class template Template t_def_class(getTemplate("jsv8_define_class_template")); t_def_class.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .replace(T_NAME, state.clazz(NAME)) - .replace(T_CTOR, state.clazz(CTOR)) - .replace(T_TYPE_MANGLED, state.clazz(TYPE_MANGLED)) + .replace(T_TYPE_MANGLED, SwigType_manglestr(Getattr(n, "classtype"))) + .replace(T_DTOR, state.clazz(DTOR)) .pretty_print(f_init_class_templates); Template t_class_instance(getTemplate("jsv8_create_class_instance")); t_class_instance.replace(T_NAME, state.clazz(NAME)) .replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) + .replace(T_CTOR, state.clazz(CTOR)) .pretty_print(f_init_class_instances); // emit inheritance setup @@ -1929,6 +1947,40 @@ int V8Emitter::emitNamespaces() { return SWIG_OK; } +void V8Emitter::emitUndefined() { + Iterator ki; + for (ki = First(undefined_types); ki.item; ki = Next(ki)) { + String *mangled_name = ki.key; + String *dtor = Swig_name_destroy("", mangled_name); + SwigType *deref = SwigType_del_pointer(ki.item); + String *type_mangled = SwigType_manglestr(ki.item); + + // emit clientData declaration + Template clientDataDecl = getTemplate("jsv8_declare_class_template"); + clientDataDecl.replace(T_NAME_MANGLED, mangled_name) + .pretty_print(f_class_templates); + + // emit an extra dtor for unknown types + Template t_dtor = getTemplate("JS_destructordefn"); + t_dtor.replace(T_NAME_MANGLED, mangled_name) + .replace(T_WRAPPER, dtor) + .replace(T_TYPE, deref) + .pretty_print(f_wrappers); + + // create a class template and initialize clientData + Template clientDataDef = getTemplate("jsv8_define_class_template"); + clientDataDef.replace(T_NAME_MANGLED, mangled_name) + .replace(T_NAME, mangled_name) + .replace(T_TYPE_MANGLED, type_mangled) + .replace(T_DTOR, dtor) + .pretty_print(f_init_class_templates); + + Delete(dtor); + Delete(deref); + Delete(type_mangled); + + } +} JSEmitter *swig_javascript_create_V8Emitter() { return new V8Emitter(); From 20927938681c14e4f812879973f8e677c08d77b0 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:14:14 +0000 Subject: [PATCH 0147/1048] Make v8 shell more quiet. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13820 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Tools/javascript/v8_shell.cxx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Tools/javascript/v8_shell.cxx b/Tools/javascript/v8_shell.cxx index 6c84fe758..27923dd86 100755 --- a/Tools/javascript/v8_shell.cxx +++ b/Tools/javascript/v8_shell.cxx @@ -181,9 +181,9 @@ bool V8Shell::ExecuteScript(const std::string& source, const std::string& name) if (!result->IsUndefined()) { // If all went well and the result wasn't undefined then print // the returned value. - v8::String::Utf8Value str(result); - const char* cstr = V8Shell::ToCString(str); - printf("%s\n", cstr); + //v8::String::Utf8Value str(result); + //const char* cstr = V8Shell::ToCString(str); + //printf("%s\n", cstr); } return true; } From 8948360725e853f2232188edd38a834ac1f87666 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:14:23 +0000 Subject: [PATCH 0148/1048] Fix configuration_in for detecting v8 include and lib. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13821 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- configure.in | 30 +++++++++++------------------- 1 file changed, 11 insertions(+), 19 deletions(-) diff --git a/configure.in b/configure.in index f3d7e4ccd..5a00636a2 100644 --- a/configure.in +++ b/configure.in @@ -1215,11 +1215,9 @@ AC_SUBST(JSCXXFLAGS) # check for include files AC_MSG_CHECKING(for include file v8.h) -AC_ARG_WITH(javascriptv8incl, [ --with-javascript-v8=path Set location of Javascript include directory], [JSV8INCDIR="$withval"], [JSV8INCDIR=]) +AC_ARG_WITH(v8inc, [ --with-v8inc=path Set location of Javascript include directory], [JSV8INCDIR="$withval"]) if test -z "$JSV8INCDIR"; then - JSV8INCDIR="/usr/include/ /usr/local/include/" - # Add in default directory for JavaScriptCore headers for Linux and MacOSX case $host in *-*-linux*) JSV8INCDIR="/usr/include /usr/local/include/ $JSV8INCDIR";; @@ -1243,27 +1241,21 @@ fi # check for V8 library -AC_ARG_WITH(jsv8lib,[ --with-jsv8lib =path Set location of V8 library directory],[ - JSV8LIB="-L$withval"], [JSV8LIB=]) -AC_MSG_CHECKING(for V8 library) +AC_MSG_CHECKING(for v8 library) +AC_ARG_WITH(v8lib,[ --with-v8lib=path Set location of V8 library directory],[JSV8LIBDIR="$withval"], [JSV8LIB=]) -if test -z "$JSV8LIB"; then -dirs="/usr/lib/ /usr/local/lib/" -for i in $dirs ; do - - if test -r $i/libv8.so; then - AC_MSG_RESULT($i) - JSV8LIB="-L$i -lv8" - break - fi +v8libdirs="$JSV8LIBDIR /usr/lib/ /usr/local/lib/" +for i in $v8libdirs ; do + if test -r $i/libv8.so; then + JSV8LIB="-L$i -lv8" + break + fi done if test "$JSV8LIB" = "" ; then - AC_MSG_RESULT(not found) -fi - + AC_MSG_RESULT(not found) else -AC_MSG_RESULT($JSCORELIB) + AC_MSG_RESULT($JSV8LIB) fi From 4616f9643ff5ce8aefe0594289c9a97230cabf09 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:14:37 +0000 Subject: [PATCH 0149/1048] Adapt test-suite configuration to allow switching between js engines. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13822 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/test-suite/javascript/Makefile.in | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index 22a3a8a3e..d59f3d60e 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -56,6 +56,12 @@ SKIP_MULTI_CPP_CASES = @SKIP_MULTI_CPP_CASES@ include $(srcdir)/../common.mk +ifeq (,$(V8)) +JSENGINEFLAG = -jsc +else +JSENGINEFLAG = -v8 +endif + # Overridden variables here # Custom tests - tests with additional commandline options @@ -83,7 +89,7 @@ javascript_exe: # a file is found which has _runme.js appended after the testcase name. run_testcase = \ if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(JAVASCRIPT_EXE) -l $* $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(JAVASCRIPT_EXE) $(JSENGINEFLAG) -l $* $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ fi # Clean From 296a5d028547c0a0a013a24e65cdcb9c3086fb52 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:14:48 +0000 Subject: [PATCH 0150/1048] Minor change in javascript example Makefile configuration. Propagate global CFLAGS and CXXFLAGS to inner javascript targets. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13823 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Examples/Makefile.in | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index a6ed5157e..bf9fe5cd8 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -543,8 +543,7 @@ JSCFLAGS = @JSCORECFLAGS@ JSCXXFLAGS = @JSCXXFLAGS@ JSEXE_SRC_DIR = $(TOP)/../Tools/javascript -JSEXE_SRC = $(JSEXE_SRC_DIR)/javascript.cxx $(JSEXE_SRC_DIR)/js_shell.cxx -JSEXE = $(TOP)/../Tools/javascript/javascript +JSEXE = $(JSEXE_SRC_DIR)/javascript ifeq (,$(V8)) JSEXE_SRC = $(JSEXE_SRC_DIR)/javascript.cxx $(JSEXE_SRC_DIR)/js_shell.cxx $(JSEXE_SRC_DIR)/jsc_shell.cxx JSEXE_OPTS = -jsc @@ -563,8 +562,8 @@ endif ifeq (,$(V8)) javascript: $(SRCS) $(SWIGJS) $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(JSCFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(JS_INCLUDE) - $(JSLDSHARED) $(CCSHARED) $(JSCFLAGS) $(OBJS) $(IOBJS) $(JS_DLNK) $(LIBS) -o $(JS_LIBPREFIX)$(TARGET)$(JSSO) + $(CC) -c $(CCSHARED) $(CFLAGS) $(JSCFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(JS_INCLUDE) + $(JSLDSHARED) $(CCSHARED) $(OBJS) $(IOBJS) $(JS_DLNK) $(LIBS) -o $(JS_LIBPREFIX)$(TARGET)$(JSSO) else javascript: $(SRCS) javascript_cpp endif @@ -575,7 +574,7 @@ endif javascript_cpp: $(SRCS) $(SWIGJS) -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(JSCXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(JS_INCLUDE) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(JSCXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(JS_INCLUDE) $(JSCXXSHARED) $(CCSHARED) $(OBJS) $(IOBJS) $(JS_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(JS_LIBPREFIX)$(TARGET)$(JSSO) # ---------------------------------------------------------------- From 7c7d1cf3b9e8a1dfd92b3ca199e2ee0b8bf1cc6f Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:15:12 +0000 Subject: [PATCH 0151/1048] Fix errors related to wrapping and destruction of (undefined) SWIG_TYPES. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13824 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptcode.swg | 6 +- Lib/javascript/v8/javascriptruntime.swg | 28 +++++++-- Source/Modules/javascript.cxx | 81 +++++++++++++++++++------ 3 files changed, 87 insertions(+), 28 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 8f3d8cff2..b46bacfa9 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -52,7 +52,7 @@ void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) { SWIGV8_Proxy* proxy = (SWIGV8_Proxy*) parameter; if(proxy->swigCMemOwn && proxy->swigCObject) { std::cout << "Deleting wrapped instance: " << proxy->info->name << std::endl; - delete ($jstype*) proxy->swigCObject; + $jsfree proxy->swigCObject; } delete proxy; } @@ -150,7 +150,7 @@ fail: %{v8::Handle $jsmangledname_class = SWIGV8_CreateClassTemplate("$jsmangledname"); $jsmangledname_clientData.class_templ = $jsmangledname_class; $jsmangledname_clientData.dtor = $jsdtor; - SWIGTYPE_p$jsmangledtype->clientdata = &$jsmangledname_clientData;%} + SWIGTYPE$jsmangledtype->clientdata = &$jsmangledname_clientData;%} %fragment("jsv8_inherit", "templates") %{$jsmangledname_class->Inherit($jsbaseclass_class);%} @@ -194,6 +194,8 @@ void $jsname_initialize(v8::Handle context) v8::HandleScope scope; v8::Local global_obj = context->Global(); + SWIGV8_SWIGTYPE_Proxy_class_templ = SWIGV8_CreateClassTemplate("SwigProxy"); + /* create objects for namespaces */ $jsv8nspaces diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index b9f24a562..b6ef55d90 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -86,10 +86,8 @@ public: void (*dtor) (v8::Persistent< v8::Value > object, void *parameter); }; -%} +v8::Persistent SWIGV8_SWIGTYPE_Proxy_class_templ; - -%insert(runtime) %{ int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_type_info *info, int flags) { v8::HandleScope scope; @@ -120,14 +118,27 @@ int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_t return SWIG_OK; } +void SWIGV8_Proxy_DefaultDtor(v8::Persistent< v8::Value > object, void *parameter) { + SWIGV8_Proxy* proxy = (SWIGV8_Proxy*) parameter; + if(proxy) { + delete proxy; + } +} + void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info *info, int flags) { SWIGV8_Proxy* cdata = new SWIGV8_Proxy(); cdata->swigCObject = ptr; cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; cdata->info = info; obj->SetPointerInInternalField(0, cdata); + v8::Persistent weakptr = v8::Persistent::New(obj); - weakptr.MakeWeak(cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); + // clientdata must be set for owned data as we need to register the dtor + if(cdata->swigCMemOwn) { + weakptr.MakeWeak(cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); + } else { + weakptr.MakeWeak(cdata, SWIGV8_Proxy_DefaultDtor); + } } int SWIG_V8_ConvertPtr(v8::Handle valRef, void** ptr, swig_type_info *info, int flags) { @@ -142,8 +153,13 @@ int SWIG_V8_ConvertPtr(v8::Handle valRef, void** ptr, swig_type_info v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, int flags) { v8::HandleScope scope; - - v8::Handle class_templ = ((SWIGV8_ClientData*) info->clientdata)->class_templ; + + v8::Handle class_templ; + if(info->clientdata != 0) { + class_templ = ((SWIGV8_ClientData*) info->clientdata)->class_templ; + } else { + class_templ = SWIGV8_SWIGTYPE_Proxy_class_templ; + } v8::Handle result = class_templ->InstanceTemplate()->NewInstance(); SWIGV8_SetPrivateData(result, ptr, info, flags); diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index f54d470f1..db4972310 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -43,6 +43,7 @@ bool js_template_enable_debug = false; #define T_ARGCOUNT "$jsargcount" #define T_LOCALS "$jslocals" #define T_CODE "$jscode" +#define T_FREE "$jsfree" // v8 specific variables used in templates #define V8_NAME_SPACES "$jsv8nspaces" @@ -269,6 +270,8 @@ protected: virtual void marshalOutput(Node *n, Wrapper *wrapper, String *actioncode, const String *cresult=0, bool emitReturnVariable = true); + void registerProxyType(SwigType* type); + /** * Helper function to retrieve the first parent class node. */ @@ -281,6 +284,7 @@ protected: virtual Hash *createNamespaceEntry(const char *name, const char *parent); virtual int emitNamespaces() = 0; + protected: @@ -865,12 +869,27 @@ int JSEmitter::emitDtor(Node *n) { Template t_dtor = getTemplate("JS_destructordefn"); String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); + + SwigType *type = state.clazz(TYPE); + String *p_classtype = SwigType_add_pointer(state.clazz(TYPE)); + String *ctype = SwigType_lstr(p_classtype, ""); + String *free = NewString(""); + if(SwigType_isarray(type)) { + Printf(free, "delete [] (%s)", ctype); + } else { + Printf(free, "delete (%s)", ctype); + } + state.clazz(DTOR, wrap_name); t_dtor.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .replace(T_WRAPPER, wrap_name) - .replace(T_TYPE, state.clazz(TYPE)) + .replace(T_FREE, free) .pretty_print(f_wrappers); + Delete(p_classtype); + Delete(ctype); + Delete(free); + return SWIG_OK; } @@ -1050,15 +1069,30 @@ int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { return SWIG_OK; } +void JSEmitter::registerProxyType(SwigType* type) { + SwigType *ftype = SwigType_typedef_resolve_all(type); + + // register undefined wrappers + int needs_proxy= (SwigType_ispointer(ftype) + || SwigType_isarray(ftype) || SwigType_isreference(ftype)) + && !(Language::instance()->classLookup(ftype)); + if (needs_proxy) { + SwigType_remember_clientdata(ftype, 0); + Setattr(undefined_types, SwigType_manglestr(ftype), ftype); + } else { + Delete(ftype); + } + +} + void JSEmitter::emitInputTypemap(Node *n, Parm *p, Wrapper *wrapper, String *arg) { // Get input typemap for current param String *tm = Getattr(p, "tmap:in"); - SwigType *pt = Getattr(p, "type"); - + SwigType *type = Getattr(p, "type"); + if (tm != NULL) { Replaceall(tm, "$input", arg); Setattr(p, "emit:input", arg); - // do replacements for built-in variables if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) { Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); @@ -1068,28 +1102,24 @@ void JSEmitter::emitInputTypemap(Node *n, Parm *p, Wrapper *wrapper, String *arg Replaceall(tm, "$symname", Getattr(n, "sym:name")); Printf(wrapper->code, "%s\n", tm); } else { - Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0)); + Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(type, 0)); } } void JSEmitter::marshalOutput(Node *n, Wrapper *wrapper, String *actioncode, const String *cresult, bool emitReturnVariable) { SwigType *type = Getattr(n, "type"); - Setattr(n, "type", type); String *tm; - - // register undefined wrappers - if (SwigType_ispointer(type) && !Language::instance()->classLookup(type)) { - SwigType_remember_clientdata(type, 0); - Setattr(undefined_types, SwigType_manglestr(type), type); - } - // adds a declaration for the result variable if(emitReturnVariable) emit_return_variable(n, type, wrapper); - // if not given, use default result identifier ('result') for output typemap if(cresult == 0) cresult = defaultResultName; - if ((tm = Swig_typemap_lookup_out("out", n, cresult, wrapper, actioncode))) { + tm = Swig_typemap_lookup_out("out", n, cresult, wrapper, actioncode); + if(GetFlag(n, "feature:new")) { + registerProxyType(type); + } + + if (tm) { Replaceall(tm, "$result", "jsresult"); Replaceall(tm, "$objecttype", Swig_scopename_last(SwigType_str(SwigType_strip_qualifiers(type), 0))); @@ -1744,10 +1774,12 @@ int V8Emitter::exitClass(Node *n) SwigType_remember_clientdata(state.clazz(TYPE_MANGLED), clientData); // emit definition of v8 class template + String *p_classtype = state.clazz(TYPE); + String *p_classtype_str = SwigType_manglestr(p_classtype); Template t_def_class(getTemplate("jsv8_define_class_template")); t_def_class.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .replace(T_NAME, state.clazz(NAME)) - .replace(T_TYPE_MANGLED, SwigType_manglestr(Getattr(n, "classtype"))) + .replace(T_TYPE_MANGLED, p_classtype_str) .replace(T_DTOR, state.clazz(DTOR)) .pretty_print(f_init_class_templates); @@ -1951,9 +1983,17 @@ void V8Emitter::emitUndefined() { Iterator ki; for (ki = First(undefined_types); ki.item; ki = Next(ki)) { String *mangled_name = ki.key; + SwigType *type = ki.item; String *dtor = Swig_name_destroy("", mangled_name); - SwigType *deref = SwigType_del_pointer(ki.item); - String *type_mangled = SwigType_manglestr(ki.item); + String *type_mangled = SwigType_manglestr(type); + String *ctype = SwigType_lstr(type, ""); + + String *free = NewString(""); + if(SwigType_isarray(type)) { + Printf(free, "delete [] (%s)", ctype); + } else { + Printf(free, "delete (%s)", ctype); + } // emit clientData declaration Template clientDataDecl = getTemplate("jsv8_declare_class_template"); @@ -1964,7 +2004,7 @@ void V8Emitter::emitUndefined() { Template t_dtor = getTemplate("JS_destructordefn"); t_dtor.replace(T_NAME_MANGLED, mangled_name) .replace(T_WRAPPER, dtor) - .replace(T_TYPE, deref) + .replace(T_FREE, free) .pretty_print(f_wrappers); // create a class template and initialize clientData @@ -1976,8 +2016,9 @@ void V8Emitter::emitUndefined() { .pretty_print(f_init_class_templates); Delete(dtor); - Delete(deref); + Delete(free); Delete(type_mangled); + Delete(ctype); } } From 8b7a9fec2519aa5faac9c3bb26f7612ee1f5aefb Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:15:29 +0000 Subject: [PATCH 0152/1048] Add complex support to v8 module. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13825 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptcomplex.swg | 79 +++++++++---------------- 1 file changed, 28 insertions(+), 51 deletions(-) diff --git a/Lib/javascript/v8/javascriptcomplex.swg b/Lib/javascript/v8/javascriptcomplex.swg index 7d165dce4..70c5baffb 100644 --- a/Lib/javascript/v8/javascriptcomplex.swg +++ b/Lib/javascript/v8/javascriptcomplex.swg @@ -12,13 +12,15 @@ %fragment(SWIG_From_frag(Type),"header", fragment=SWIG_From_frag(double)) { -SWIGINTERNINLINE JSObjectRef +SWIGINTERNINLINE v8::Handle SWIG_From_dec(Type)(%ifcplusplus(const Type&, Type) c) { - JSValueRef vals[2]; - vals[0] = SWIG_From(double)(Real(c)); - vals[1] = SWIG_From(double)(Imag(c)); - return JSObjectMakeArray(context, 2, vals, NULL); + v8::HandleScope scope; + v8::Local vals = v8::Array::New(2); + + vals->Set(0, SWIG_From(double)(Real(c))); + vals->Set(1, SWIG_From(double)(Imag(c))); + return scope.Close(vals); } } %enddef @@ -29,42 +31,30 @@ SWIG_From_dec(Type)(%ifcplusplus(const Type&, Type) c) fragment=SWIG_AsVal_frag(double)) { SWIGINTERN int -SWIG_AsVal_dec(Type) (JSValueRef o, Type* val) +SWIG_AsVal_dec(Type) (v8::Handle o, Type* val) { - if (JSValueIsObject(context, o)) { - JSObjectRef array; - JSValueRef exception, js_re, js_im; + v8::HandleScope scope; + + if (o->IsArray()) { + v8::Handle array = v8::Handle::Cast(o); + + if(array->Length() != 2) SWIG_Error(SWIG_TypeError, "Illegal argument for complex: must be array[2]."); double re, im; int res; - - exception = 0; - res = 0; - array = JSValueToObject(context, o, &exception); - if(exception != 0) - return SWIG_TypeError; - - js_re = JSObjectGetPropertyAtIndex(context, array, 0, &exception); - if(exception != 0) - return SWIG_TypeError; - - js_im = JSObjectGetPropertyAtIndex(context, array, 1, &exception); - if(exception != 0) - return SWIG_TypeError; - - res = SWIG_AsVal(double)(js_re, &re); + res = SWIG_AsVal(double)(array->Get(0), &re); if(!SWIG_IsOK(res)) { return SWIG_TypeError; } - res = SWIG_AsVal(double)(js_im, &im); + res = SWIG_AsVal(double)(array->Get(1), &im); if(!SWIG_IsOK(res)) { return SWIG_TypeError; } if (val) *val = Constructor(re, im); return SWIG_OK; - } else { + } else if(o->IsNumber()){ double d; int res = SWIG_AddCast(SWIG_AsVal(double)(o, &d)); if (SWIG_IsOK(res)) { @@ -83,39 +73,27 @@ SWIG_AsVal_dec(Type) (JSValueRef o, Type* val) %fragment(SWIG_AsVal_frag(Type),"header", fragment=SWIG_AsVal_frag(float)) { SWIGINTERN int -SWIG_AsVal_dec(Type)(JSValueRef o, Type *val) +SWIG_AsVal_dec(Type) (v8::Handle o, Type* val) { - if (JSValueIsObject(context, o)) { - JSObjectRef array; - JSValueRef exception, js_re, js_im; + v8::HandleScope scope; + + if (o->IsArray()) { + v8::Handle array = v8::Handle::Cast(o); + + if(array->Length() != 2) SWIG_Error(SWIG_TypeError, "Illegal argument for complex: must be array[2]."); double re, im; int res; - - exception = 0; - res = 0; - array = JSValueToObject(context, o, &exception); - if(exception != 0) - return SWIG_TypeError; - - js_re = JSObjectGetPropertyAtIndex(context, array, 0, &exception); - if(exception != 0) - return SWIG_TypeError; - - js_im = JSObjectGetPropertyAtIndex(context, array, 1, &exception); - if(exception != 0) - return SWIG_TypeError; - - res = SWIG_AsVal(double)(js_re, &re); + res = SWIG_AsVal(double)(array->Get(0), &re); if(!SWIG_IsOK(res)) { return SWIG_TypeError; } - res = SWIG_AsVal(double)(js_im, &im); + res = SWIG_AsVal(double)(array->Get(1), &im); if(!SWIG_IsOK(res)) { return SWIG_TypeError; } - + if ((-FLT_MAX <= re && re <= FLT_MAX) && (-FLT_MAX <= im && im <= FLT_MAX)) { if (val) *val = Constructor(%numeric_cast(re, float), %numeric_cast(im, float)); @@ -123,7 +101,7 @@ SWIG_AsVal_dec(Type)(JSValueRef o, Type *val) } else { return SWIG_OverflowError; } - } else { + } else if(o->IsNumber()){ float re; int res = SWIG_AddCast(SWIG_AsVal(float)(o, &re)); if (SWIG_IsOK(res)) { @@ -134,7 +112,6 @@ SWIG_AsVal_dec(Type)(JSValueRef o, Type *val) return SWIG_TypeError; } } - %swig_fromcplx_conv(Type, Real, Imag); %enddef From 131a106204e060ac15bd2474c8a5501f82868284 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:15:51 +0000 Subject: [PATCH 0153/1048] Improve names and comments of code templates for javascript emitters. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13826 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/jsc/javascriptcode.swg | 471 +++++++++++++++----------- Lib/javascript/v8/javascriptcode.swg | 120 ++++--- Source/Modules/javascript.cxx | 113 +++--- 3 files changed, 428 insertions(+), 276 deletions(-) diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index 4a83b87d2..9a91c874a 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -1,12 +1,108 @@ -/********************************************************************* - *getproperty: This template gives name to generated wrapper for the getproperty - *{LOCALS}: declarations for input arguments - *{CODE}: contains input marshalling, and the action -*********************************************************************/ - -%fragment ("JS_getproperty", "templates") +/* ----------------------------------------------------------------------------- + * js_ctor: template for wrapping a ctor. + * - $jswrapper: wrapper of called ctor + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * - $jsargcount: number of arguments + * - $jsmangledtype: mangled type of class + * ----------------------------------------------------------------------------- */ +%fragment ("js_ctor", "templates") %{ -JSValueRef $jsgetter(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + $jslocals + + if(argc != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); + + $jscode + + return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); + + goto fail; + fail: + return NULL; +} +%} + +/* ----------------------------------------------------------------------------- + * js_veto_ctor: a vetoing ctor for abstract classes + * - $jswrapper: name of wrapper + * - $jsname: class name + * ----------------------------------------------------------------------------- */ +%fragment ("js_veto_ctor", "templates") +%{ +JSObjectRef $jswrapper(JSContextRef context, JSObjectRef ctorObject, + size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + SWIG_exception(SWIG_ERROR, "Class $jsname can not be instantiated"); + return 0; +} +%} + +/* ----------------------------------------------------------------------------- + * js_ctor_dispatcher: dispatcher for overloaded constructors + * - $jswrapper: name of wrapper + * - $jsname: class name + * - $jsdispatchcases: part containing code for dispatching + * ----------------------------------------------------------------------------- */ +%fragment ("js_ctor_dispatcher", "templates") +%{ +JSObjectRef $jswrapper(JSContextRef context, JSObjectRef ctorObject, + size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + JSObjectRef thisObject = NULL; + + // switch all cases by means of series of if-returns. + $jsdispatchcases + + // default: + SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for contruction of $jsname"); + + fail: + return thisObject; +} +%} + +/* ----------------------------------------------------------------------------- + * js_ctor_dispatch_case: template for a dispatch case for calling an overloaded ctor. + * - $jsargcount: number of arguments of called ctor + * - $jswrapper: wrapper of called ctor + * + * Note: a try-catch-like mechanism is used to switch cases + * ----------------------------------------------------------------------------- */ +%fragment ("js_ctor_dispatch_case", "templates") +%{ + if(argc == $jsargcount) { + thisObject = $jswrapper(context, NULL, argc, argv, exception); + if(thisObject != NULL) { *exception=0; return thisObject; } /* reset exception and return */ + } +%} + + +/* ----------------------------------------------------------------------------- + * js_dtor: template for a destructor wrapper + * - $jsmangledname: mangled class name + * - $jstype: class type + * ----------------------------------------------------------------------------- */ +%fragment ("js_dtor", "templates") +%{ +void $jswrapper(JSObjectRef thisObject) +{ + SWIG_PRV_DATA* t = (SWIG_PRV_DATA*) JSObjectGetPrivate(thisObject); + if(t && t->swigCMemOwn) free (($jstype*)t->swigCObject); + if(t) free(t); +} +%} + +/* ----------------------------------------------------------------------------- + * js_getter: template for getter function wrappers + * - $jswrapper: wrapper function name + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ +%fragment ("js_getter", "templates") +%{ +JSValueRef $jswrapper(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) { $jslocals JSValueRef jsresult; @@ -20,15 +116,15 @@ JSValueRef $jsgetter(JSContextRef context, JSObjectRef thisObject, JSStringRef p } %} -/********************************************************************** - *setproperty: This template gives name to generated wrapper for the setproperty - *{LOCALS}: declarations for input arguments - *{CODE}: contains input marshalling, and the action -**********************************************************************/ - -%fragment ("JS_setproperty", "templates") +/* ----------------------------------------------------------------------------- + * js_setter: template for setter function wrappers + * - $jswrapper: wrapper function name + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ +%fragment ("js_setter", "templates") %{ -bool $jssetter(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +bool $jswrapper(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) { $jslocals $jscode @@ -41,12 +137,13 @@ bool $jssetter(JSContextRef context, JSObjectRef thisObject, JSStringRef propert } %} -/************************************************************************************ - *functionwrapper: This template gives name to generated wrapper for the function - *{LOCALS}: declarations for input arguments - *{CODE} contains input marshalling, and the action -************************************************************************************/ -%fragment ("JS_functionwrapper", "templates") +/* ----------------------------------------------------------------------------- + * js_function: template for function wrappers + * - $jswrapper: wrapper function name + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ +%fragment ("js_function", "templates") %{ JSValueRef $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { @@ -64,7 +161,14 @@ JSValueRef $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef th } %} -%fragment ("JS_function_dispatcher", "templates") +/* ----------------------------------------------------------------------------- + * js_function_dispatcher: template for a function dispatcher for overloaded functions + * - $jswrapper: wrapper function name + * - $jsname: name of the wrapped function + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ +%fragment ("js_function_dispatcher", "templates") %{ JSValueRef $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { @@ -82,7 +186,13 @@ JSValueRef $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef th } %} -%fragment ("JS_functionwrapper_overload", "templates") +/* ----------------------------------------------------------------------------- + * js_overloaded_function: template for a overloaded function + * - $jswrapper: wrapper function name + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ +%fragment ("js_overloaded_function", "templates") %{ int $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception, JSValueRef* result) { @@ -101,51 +211,87 @@ int $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObjec } %} -/*********************************************************************** - * JS_function_dispatch_case: - * This template is used to create a branch for dispatching - * to an overloaded function. - ***********************************************************************/ - -%fragment ("JS_function_dispatch_case", "templates") -%{if(argc == $jsargcount) { +/* ----------------------------------------------------------------------------- + * js_function_dispatch_case: template for a case used in the function dispatcher + * - $jswrapper: wrapper function name + * - $jsargcount: number of arguments of overloaded function + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ +%fragment ("js_function_dispatch_case", "templates") +%{ + if(argc == $jsargcount) { res = $jswrapper(context, function, thisObject, argc, argv, exception, &jsresult); if(res == SWIG_OK) { *exception = 0; return jsresult; } } %} -/* Added template for function declaration */ +/* ----------------------------------------------------------------------------- + * js_initializer: template for the module initializer function + * - $jsname: module name + * - $jscreatenamespaces: part with code for creating namespace objects + * - $jscreateclasses: part with code for creating classes + * - $jsregisternamespaces: part with code for registration of namespaces + * ----------------------------------------------------------------------------- */ +%fragment ("js_initializer", "templates") %{ +#ifdef __cplusplus +extern "C" { +#endif -%fragment ("JS_variabledecl", "templates") -%{{"$jsname", $jsgetter, $jssetter, kJSPropertyAttributeNone},%} +bool $jsname_initialize(JSGlobalContextRef context) { + SWIG_InitializeModule(0); + JSObjectRef global_object = JSContextGetGlobalObject(context); + + /* Initialize the base swig type object */ + _SwigObject_objectDefinition.staticFunctions = _SwigObject_functions; + _SwigObject_objectDefinition.staticValues = _SwigObject_values; + _SwigObject_classRef = JSClassCreate(&_SwigObject_objectDefinition); + + /* Create objects for namespaces */ + $jscreatenamespaces -/* Added template for function declaration */ + /* Register classes */ + $jsregisterclasses -%fragment ("JS_functiondecl", "templates") -%{{"$jsname",$jswrapper, kJSPropertyAttributeNone},%} + /* Register namespaces */ + $jsregisternamespaces -%fragment ("JS_globaldefn", "templates") -%{ -JSStaticValue $jsnspace_values[] = { - $jsglobalvariables - { 0, 0, 0, 0 } -}; + return true; +} -JSStaticFunction $jsnspace_functions[] = { - $jsglobalfunctions - { 0, 0, 0 } -}; +#ifdef __cplusplus +} +#endif -JSClassDefinition $jsnspace_classDefinition; %} -/*********************************************************************** - * class_definition: - * declarations of javascript class definition objects. - ***********************************************************************/ +/* ----------------------------------------------------------------------------- + * jsc_variable_declaration: template for a variable table entry + * - $jsname: name of the variable + * - $jsgetter: wrapper of getter function + * - $jssetter: wrapper of setter function + * ----------------------------------------------------------------------------- */ +%fragment ("jsc_variable_declaration", "templates") +%{ + {"$jsname", $jsgetter, $jssetter, kJSPropertyAttributeNone}, +%} -%fragment ("JS_class_definition", "templates") + +/* ----------------------------------------------------------------------------- + * jsc_function_declaration: template for a function table entry + * - $jsname: name of the variable + * - $jswrapper: wrapper function + * ----------------------------------------------------------------------------- */ +%fragment ("jsc_function_declaration", "templates") +%{ + {"$jsname", $jswrapper, kJSPropertyAttributeNone}, +%} + +/* ----------------------------------------------------------------------------- + * jsc_classtemplate_declaration: template for a namespace declaration + * - $jsmangledname: mangled class name + * ----------------------------------------------------------------------------- */ +%fragment ("jsc_class_declaration", "templates") %{ JSClassDefinition $jsmangledname_classDefinition; @@ -154,12 +300,15 @@ JSClassDefinition $jsmangledname_objectDefinition; JSClassRef $jsmangledname_classRef; %} -/*********************************************************************** - * class_table: - * function and variable tables for class and object creation. -***********************************************************************/ - -%fragment ("JS_class_tables", "templates") +/* ----------------------------------------------------------------------------- + * jsc_class_tables: template for a namespace declaration + * - $jsmangledname: mangled class name + * - $jsstaticclassvariables: list of static variable entries + * - $jsstaticclassfunctions: list of static function entries + * - $jsclassvariables: list of member variable entries + * - $jsclassfunctions: list of member function entries + * ----------------------------------------------------------------------------- */ +%fragment ("jsc_class_tables", "templates") %{ JSStaticValue $jsmangledname_staticValues[] = { $jsstaticclassvariables @@ -182,154 +331,76 @@ JSStaticFunction $jsmangledname_functions[] = { }; %} -/********************************************************************* - * destructordefn: - * This code template is used to adds the destructor wrapper function -***********************************************************************/ +/* ----------------------------------------------------------------------------- + * jsc_define_class_template: template for defining a class template + * - $jsmangledname: mangled class name + * - $jsmangledtype: mangled class type + * - $jsctor: wrapper of ctor + * - $jsbaseclass: mangled name of base class + * ----------------------------------------------------------------------------- */ +%fragment ("jsc_class_definition", "templates") +%{ + $jsmangledname_classDefinition.staticFunctions = $jsmangledname_staticFunctions; + $jsmangledname_classDefinition.staticValues = $jsmangledname_staticValues; + $jsmangledname_classDefinition.callAsConstructor = $jsctor; + $jsmangledname_objectDefinition.staticValues = $jsmangledname_values; + $jsmangledname_objectDefinition.staticFunctions = $jsmangledname_functions; + $jsmangledname_objectDefinition.parentClass = $jsbaseclass_classRef; + JSClassRef $jsmangledname_classRef = JSClassCreate(&$jsmangledname_objectDefinition); + SWIGTYPE_$jsmangledtype->clientdata = $jsmangledname_classRef; +%} -%fragment ("JS_destructordefn", "templates") +/* ----------------------------------------------------------------------------- + * jsc_register_class: template for registration of a class + * - $jsname: class name + * - $jsmangledname: mangled class name + * - $jsnspace: mangled name of namespace + * ----------------------------------------------------------------------------- */ +%fragment ("jsc_class_registration", "templates") %{ -void _wrap_$jsmangledname_finalize(JSObjectRef thisObject) -{ - SWIG_PRV_DATA* t = (SWIG_PRV_DATA*)JSObjectGetPrivate(thisObject); - if(t && t->swigCMemOwn) free (($jstype*)t->swigCObject); - if(t) free(t); -} + JS_registerClass(context, $jsnspace_object, "$jsname", &$jsmangledname_classDefinition); %} -/********************************************************************* - * constructor_definition: - * This code template is used to adds the main constructor wrapper function -***********************************************************************/ - -%fragment ("JS_mainctordefn", "templates") +/* ----------------------------------------------------------------------------- + * jsc_nspace_declaration: template for a namespace declaration + * - $jsnspace: mangled name of the namespace + * - $jsglobalvariables: list of variable entries + * - $jsglobalfunctions: list if fuction entries + * ----------------------------------------------------------------------------- */ +%fragment ("jsc_nspace_declaration", "templates") %{ -JSObjectRef $jswrapper(JSContextRef context, JSObjectRef ctorObject, - size_t argc, const JSValueRef argv[], JSValueRef* exception) -{ - JSObjectRef thisObject = NULL; - - // switch all cases by means of series of if-returns. - $jsdispatchcases +JSStaticValue $jsnspace_values[] = { + $jsglobalvariables + { 0, 0, 0, 0 } +}; - // default: - SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for contruction of $jsmangledname"); - - fail: - return thisObject; -} +JSStaticFunction $jsnspace_functions[] = { + $jsglobalfunctions + { 0, 0, 0 } +}; + +JSClassDefinition $jsnspace_classDefinition; %} -%fragment ("JS_veto_ctor", "templates") +/* ----------------------------------------------------------------------------- + * jsc_nspace_definition: template for definition of a namespace object + * - $jsmangledname: mangled name of namespace + * ----------------------------------------------------------------------------- */ +%fragment ("jsc_nspace_definition", "templates") +%{ + $jsmangledname_classDefinition.staticFunctions = $jsmangledname_functions; + $jsmangledname_classDefinition.staticValues = $jsmangledname_values; + JSObjectRef $jsmangledname_object = JSObjectMake(context, JSClassCreate(&$jsmangledname_classDefinition), NULL); +%} + +/* ----------------------------------------------------------------------------- + * jsc_nspace_registration: template for registration of a namespace object + * - $jsname: name of namespace + * - $jsmangledname: mangled name of namespace + * - $jsparent: mangled name of parent namespace + * ----------------------------------------------------------------------------- */ +%fragment ("jsc_nspace_registration", "templates") %{ -JSObjectRef $jsctor(JSContextRef context, JSObjectRef ctorObject, - size_t argc, const JSValueRef argv[], JSValueRef* exception) -{ - SWIG_exception(SWIG_ERROR, "Class $jsname can not be instantiated"); - return 0; -} + JS_registerNamespace(context, $jsmangledname_object, $jsparent_object, "$jsname"); %} - -/************************************************************************************** -ctor_dispatch_case: This template is used for the constructor which is overloaded -***************************************************************************************/ - -%fragment ("JS_ctor_dispatch_case", "templates") -%{if(argc == $jsargcount) { - thisObject = $jswrapper(context, NULL, argc, argv, exception); - if(thisObject != NULL) { *exception=0; return thisObject; } /* reset exception and return */ - } -%} - - -%fragment ("JS_ctordefn", "templates") -%{ -JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) -{ - $jslocals - - if(argc != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); - - $jscode - - return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); - - goto fail; - fail: - return NULL; -} -%} - -/********************************************************************** -initializer:This template is dynamic growing and aggregates everything -**********************************************************************/ - -%fragment ("JS_initializer", "templates") %{ -#ifdef __cplusplus -extern "C" { -#endif - -bool $jsname_initialize(JSGlobalContextRef context) { - SWIG_InitializeModule(0); - - JSObjectRef global_object = JSContextGetGlobalObject(context); - - /* Initialize the base swig type object */ - _SwigObject_objectDefinition.staticFunctions = _SwigObject_functions; - _SwigObject_objectDefinition.staticValues = _SwigObject_values; - _SwigObject_classRef = JSClassCreate(&_SwigObject_objectDefinition); - - /* Create objects for namespaces */ - $jscreatenamespaces - - /* Create classes */ - $jsinitializercode - - /* Register namespaces */ - $jsregisternamespaces - - return true; -} - -#ifdef __cplusplus -} -#endif - -%} - -/***************************************************************************************** - *create_class_template: - *This template is used to add a Static references to class templates. -*****************************************************************************************/ - -%fragment ("JS_create_class_template", "templates") -%{ $jsmangledname_classDefinition.staticFunctions = $jsmangledname_staticFunctions; - $jsmangledname_classDefinition.staticValues = $jsmangledname_staticValues; - $jsmangledname_classDefinition.callAsConstructor = $jsctor; - $jsmangledname_objectDefinition.staticValues = $jsmangledname_values; - $jsmangledname_objectDefinition.staticFunctions = $jsmangledname_functions; - $jsmangledname_objectDefinition.parentClass = $jsbaseclass_classRef; - JSClassRef $jsmangledname_classRef = JSClassCreate(&$jsmangledname_objectDefinition); - SWIGTYPE_$jsmangledtype->clientdata = $jsmangledname_classRef;%} - -/***************************************************************************************** - *register_class: - * This template is used to adds a class registration statement to initializer function -*****************************************************************************************/ - -%fragment ("JS_register_class", "templates") -%{JS_registerClass(context, $jsnspace_object, "$jsname", &$jsmangledname_classDefinition);%} - - -/* create and register namespaces */ - -%fragment ("JS_create_namespace", "templates") -%{ $jsmangledname_classDefinition.staticFunctions = $jsmangledname_functions; - $jsmangledname_classDefinition.staticValues = $jsmangledname_values; - JSObjectRef $jsmangledname_object = JSObjectMake(context, JSClassCreate(&$jsmangledname_classDefinition), NULL); -%} - -%fragment ("JS_register_namespace", "templates") -%{ -JS_registerNamespace(context, $jsmangledname_object, $jsparent_object, "$jsname"); %} diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index b46bacfa9..5e092528b 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -1,4 +1,4 @@ -%fragment("JS_ctordefn", "templates") %{ +%fragment("js_ctor", "templates") %{ v8::Handle $jswrapper(const v8::Arguments& args) { v8::HandleScope scope; v8::Handle self = args.Holder(); @@ -11,18 +11,36 @@ v8::Handle $jswrapper(const v8::Arguments& args) { goto fail; fail: return scope.Close(v8::Undefined()); -}%} +} +%} -%fragment ("JS_veto_ctor", "templates") +%fragment ("js_veto_ctor", "templates") %{ -v8::Handle $jsctor(const v8::Arguments& args) { +v8::Handle $jswrapper(const v8::Arguments& args) { v8::HandleScope scope; SWIG_exception(SWIG_ERROR, "Class $jsname can not be instantiated"); return scope.Close(v8::Undefined()); } %} -%fragment ("JS_mainctordefn", "templates") %{ +%fragment("js_overloaded_ctor", "templates") %{ +v8::Handle $jswrapper(const v8::Arguments& args) { + v8::HandleScope scope; + v8::Handle self = args.Holder(); + $jslocals + $jscode + + SWIGV8_SetPrivateData(self, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); + return scope.Close(self); + + goto fail; +fail: + return scope.Close(v8::Undefined()); +} +%} + +%fragment ("js_ctor_dispatcher", "templates") +%{ v8::Handle $jswrapper(const v8::Arguments& args) { v8::HandleScope scope; @@ -37,8 +55,9 @@ fail: } %} -%fragment ("JS_ctor_dispatch_case", "templates") -%{if(args.Length() == $jsargcount) { +%fragment ("js_ctor_dispatch_case", "templates") +%{ + if(args.Length() == $jsargcount) { v8::Handle self = $jswrapper(args); if(!self->IsUndefined()) { return scope.Close(self); @@ -46,7 +65,7 @@ fail: } %} -%fragment ("JS_destructordefn", "templates") +%fragment ("js_dtor", "templates") %{ void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) { SWIGV8_Proxy* proxy = (SWIGV8_Proxy*) parameter; @@ -59,8 +78,9 @@ void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) { %} -%fragment("JS_getproperty", "templates") %{ -v8::Handle $jsgetter(v8::Local property, const v8::AccessorInfo& info) { +%fragment("js_getter", "templates") +%{ +v8::Handle $jswrapper(v8::Local property, const v8::AccessorInfo& info) { v8::HandleScope scope; v8::Handle jsresult; $jslocals @@ -69,19 +89,23 @@ v8::Handle $jsgetter(v8::Local property, const v8::Access goto fail; fail: return scope.Close(v8::Undefined()); -}%} +} +%} -%fragment("JS_setproperty", "templates") %{ -void $jssetter(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { +%fragment("js_setter", "templates") +%{ +void $jswrapper(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { v8::HandleScope scope; $jslocals $jscode goto fail; fail: return; -}%} +} +%} -%fragment("JS_functionwrapper", "templates") %{ +%fragment("js_function", "templates") +%{ v8::Handle $jswrapper(const v8::Arguments &args) { v8::HandleScope scope; v8::Handle jsresult; @@ -94,7 +118,8 @@ fail: } %} -%fragment("JS_function_dispatcher", "templates") %{ +%fragment("js_function_dispatcher", "templates") +%{ v8::Handle $jswrapper(const v8::Arguments &args) { v8::HandleScope scope; v8::Handle jsresult; @@ -109,7 +134,7 @@ fail: } %} -%fragment ("JS_functionwrapper_overload", "templates") +%fragment ("js_overloaded_function", "templates") %{ v8::Handle $jswrapper(const v8::Arguments &args, V8ErrorHandler& SWIGV8_ErrorHandler) { @@ -126,7 +151,7 @@ fail: } %} -%fragment ("JS_function_dispatch_case", "templates") +%fragment ("js_function_dispatch_case", "templates") %{ if(args.Length() == $jsargcount) { errorHandler.err.Clear(); @@ -137,53 +162,69 @@ fail: } %} -%fragment ("JS_function_dispatch_case_default", "templates") -%{ - SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function $jsname."); -%} - %fragment("jsv8_declare_class_template", "templates") -%{SWIGV8_ClientData $jsmangledname_clientData; +%{ + SWIGV8_ClientData $jsmangledname_clientData; %} %fragment("jsv8_define_class_template", "templates") -%{v8::Handle $jsmangledname_class = SWIGV8_CreateClassTemplate("$jsmangledname"); +%{ + v8::Handle $jsmangledname_class = SWIGV8_CreateClassTemplate("$jsmangledname"); $jsmangledname_clientData.class_templ = $jsmangledname_class; $jsmangledname_clientData.dtor = $jsdtor; - SWIGTYPE$jsmangledtype->clientdata = &$jsmangledname_clientData;%} + SWIGTYPE$jsmangledtype->clientdata = &$jsmangledname_clientData; +%} %fragment("jsv8_inherit", "templates") -%{$jsmangledname_class->Inherit($jsbaseclass_class);%} +%{ + $jsmangledname_class->Inherit($jsbaseclass_class); +%} %fragment("jsv8_create_class_instance", "templates") -%{v8::Handle $jsmangledname_class_0 = SWIGV8_CreateClassTemplate("$jsname"); +%{ + v8::Handle $jsmangledname_class_0 = SWIGV8_CreateClassTemplate("$jsname"); $jsmangledname_class_0->SetCallHandler($jsctor); $jsmangledname_class_0->Inherit($jsmangledname_class); $jsmangledname_class_0->SetHiddenPrototype(true); - v8::Handle $jsmangledname_obj = $jsmangledname_class_0->GetFunction();%} + v8::Handle $jsmangledname_obj = $jsmangledname_class_0->GetFunction(); +%} %fragment("jsv8_register_class", "templates") -%{$jsparent_obj->Set(v8::String::NewSymbol("$jsname"), $jsmangledname_obj);%} +%{ + $jsparent_obj->Set(v8::String::NewSymbol("$jsname"), $jsmangledname_obj); +%} %fragment("jsv8_create_namespace", "templates") -%{v8::Handle $jsmangledname_obj = v8::Object::New();%} +%{ + v8::Handle $jsmangledname_obj = v8::Object::New(); +%} %fragment("jsv8_register_member_function", "templates") -%{SWIGV8_AddMemberFunction($jsmangledname_class, "$jsname", $jswrapper);%} +%{ + SWIGV8_AddMemberFunction($jsmangledname_class, "$jsname", $jswrapper); +%} %fragment("jsv8_register_member_variable", "templates") -%{SWIGV8_AddMemberVariable($jsmangledname_class, "$jsname", $jsgetter, $jssetter);%} +%{ + SWIGV8_AddMemberVariable($jsmangledname_class, "$jsname", $jsgetter, $jssetter); +%} %fragment("jsv8_register_static_function", "templates") -%{SWIGV8_AddStaticFunction($jsparent_obj, "$jsname", $jswrapper);%} +%{ + SWIGV8_AddStaticFunction($jsparent_obj, "$jsname", $jswrapper); +%} %fragment("jsv8_register_static_variable", "templates") -%{SWIGV8_AddStaticVariable($jsparent_obj, "$jsname", $jsgetter, $jssetter);%} +%{ + SWIGV8_AddStaticVariable($jsparent_obj, "$jsname", $jsgetter, $jssetter); +%} %fragment("jsv8_register_namespace", "templates") -%{$jsparent_obj->Set(v8::String::NewSymbol("$jsname"), $jsmangledname_obj);%} +%{ + $jsparent_obj->Set(v8::String::NewSymbol("$jsname"), $jsmangledname_obj); +%} -%fragment("JS_initializer", "templates") +%fragment("js_initializer", "templates") %{ extern "C" { @@ -194,6 +235,7 @@ void $jsname_initialize(v8::Handle context) v8::HandleScope scope; v8::Local global_obj = context->Global(); + // a class template for creating proxies of undefined types SWIGV8_SWIGTYPE_Proxy_class_templ = SWIGV8_CreateClassTemplate("SwigProxy"); /* create objects for namespaces */ @@ -219,6 +261,8 @@ void $jsname_initialize(v8::Handle context) /* create and register namespace objects */ $jsv8registernspaces + } -}%} +} // extern "C" +%} diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index db4972310..76d8b389d 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -114,6 +114,10 @@ public: void operator=(const Template& t); +protected: + + void trim(); + private: String *code; @@ -518,7 +522,6 @@ void JAVASCRIPT::main(int argc, char *argv[]) { int mode = -1; - bool debug_templates = false; for (int i = 1; i < argc; i++) { if (argv[i]) { if (strcmp(argv[i], "-v8") == 0) { @@ -535,7 +538,7 @@ void JAVASCRIPT::main(int argc, char *argv[]) { SWIG_library_directory("javascript/qt"); } else if (strcmp(argv[i], "-debug-codetemplates") == 0) { Swig_mark_arg(i); - debug_templates = true; + js_template_enable_debug = true; } } } @@ -565,10 +568,6 @@ void JAVASCRIPT::main(int argc, char *argv[]) { } } - if (debug_templates) { - js_template_enable_debug = true; - } - // Add a symbol to the parser for conditional compilation Preprocessor_define("SWIGJAVASCRIPT 1", 0); @@ -811,7 +810,7 @@ int JSEmitter::emitCtor(Node *n) { bool is_overloaded = GetFlag(n, "sym:overloaded"); - Template t_ctor(getTemplate("JS_ctordefn")); + Template t_ctor(getTemplate("js_ctor")); //String *mangled_name = SwigType_manglestr(Getattr(n, "name")); String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); @@ -840,7 +839,7 @@ int JSEmitter::emitCtor(Node *n) { .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)) .pretty_print(f_wrappers); - Template t_ctor_case(getTemplate("JS_ctor_dispatch_case")); + Template t_ctor_case(getTemplate("js_ctor_dispatch_case")); t_ctor_case.replace(T_WRAPPER, wrap_name) .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)); Append(state.clazz(CTOR_DISPATCHERS), t_ctor_case.str()); @@ -851,7 +850,7 @@ int JSEmitter::emitCtor(Node *n) { if(is_overloaded) { if (!Getattr(n, "sym:nextSibling")) { String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); - Template t_mainctor(getTemplate("JS_mainctordefn")); + Template t_mainctor(getTemplate("js_ctor_dispatcher")); t_mainctor.replace(T_WRAPPER, wrap_name) .replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .replace(T_DISPATCH_CASES, state.clazz(CTOR_DISPATCHERS)) @@ -867,13 +866,16 @@ int JSEmitter::emitCtor(Node *n) { int JSEmitter::emitDtor(Node *n) { - Template t_dtor = getTemplate("JS_destructordefn"); + Template t_dtor = getTemplate("js_dtor"); String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); SwigType *type = state.clazz(TYPE); String *p_classtype = SwigType_add_pointer(state.clazz(TYPE)); String *ctype = SwigType_lstr(p_classtype, ""); String *free = NewString(""); + + // HACK: this is only for the v8 emitter. maybe set an attribute wrap:action of node + // TODO: generate dtors more similar to other wrappers if(SwigType_isarray(type)) { Printf(free, "delete [] (%s)", ctype); } else { @@ -884,6 +886,7 @@ int JSEmitter::emitDtor(Node *n) { t_dtor.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .replace(T_WRAPPER, wrap_name) .replace(T_FREE, free) + .replace(T_TYPE, ctype) .pretty_print(f_wrappers); Delete(p_classtype); @@ -895,7 +898,7 @@ int JSEmitter::emitDtor(Node *n) { int JSEmitter::emitGetter(Node *n, bool is_member, bool is_static) { Wrapper *wrapper = NewWrapper(); - Template t_getter(getTemplate("JS_getproperty")); + Template t_getter(getTemplate("js_getter")); // prepare wrapper name String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); @@ -912,7 +915,7 @@ int JSEmitter::emitGetter(Node *n, bool is_member, bool is_static) { marshalInputArgs(n, params, wrapper, Getter, is_member, is_static); marshalOutput(n, wrapper, action); - t_getter.replace(T_GETTER, wrap_name) + t_getter.replace(T_WRAPPER, wrap_name) .replace(T_LOCALS, wrapper->locals) .replace(T_CODE, wrapper->code) .pretty_print(f_wrappers); @@ -931,7 +934,7 @@ int JSEmitter::emitSetter(Node *n, bool is_member, bool is_static) { Wrapper *wrapper = NewWrapper(); - Template t_setter(getTemplate("JS_setproperty")); + Template t_setter(getTemplate("js_setter")); // prepare wrapper name String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); @@ -948,7 +951,7 @@ int JSEmitter::emitSetter(Node *n, bool is_member, bool is_static) { marshalInputArgs(n, params, wrapper, Setter, is_member, is_static); Append(wrapper->code, action); - t_setter.replace(T_SETTER, wrap_name) + t_setter.replace(T_WRAPPER, wrap_name) .replace(T_LOCALS, wrapper->locals) .replace(T_CODE, wrapper->code) .pretty_print(f_wrappers); @@ -966,7 +969,7 @@ int JSEmitter::emitConstant(Node *n) { Wrapper *wrapper = NewWrapper(); - Template t_getter(getTemplate("JS_getproperty")); + Template t_getter(getTemplate("js_getter")); // call the variable methods as a constants are // registred in same way @@ -987,7 +990,7 @@ int JSEmitter::emitConstant(Node *n) { assert(value != NULL); marshalOutput(n, wrapper, action, value, false); - t_getter.replace(T_GETTER, wrap_name) + t_getter.replace(T_WRAPPER, wrap_name) .replace(T_LOCALS, wrapper->locals) .replace(T_CODE, wrapper->code) .pretty_print(f_wrappers); @@ -1002,14 +1005,14 @@ int JSEmitter::emitConstant(Node *n) { int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { Wrapper *wrapper = NewWrapper(); - Template t_function(getTemplate("JS_functionwrapper")); + Template t_function(getTemplate("js_function")); bool is_overloaded = GetFlag(n, "sym:overloaded"); // prepare the function wrapper name String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); if (is_overloaded) { - t_function = getTemplate("JS_functionwrapper_overload"); + t_function = getTemplate("js_overloaded_function"); Append(wrap_name, Getattr(n, "sym:overname")); } Setattr(n, "wrap:name", wrap_name); @@ -1033,7 +1036,7 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { // handle function overloading if (is_overloaded) { - Template t_dispatch_case = getTemplate("JS_function_dispatch_case"); + Template t_dispatch_case = getTemplate("js_function_dispatch_case"); t_dispatch_case.replace(T_WRAPPER, wrap_name) .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)); Append(state.global(FUNCTION_DISPATCHERS), t_dispatch_case.str()); @@ -1046,7 +1049,7 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { - Template t_function(getTemplate("JS_function_dispatcher")); + Template t_function(getTemplate("js_function_dispatcher")); Wrapper *wrapper = NewWrapper(); String *wrap_name = Swig_name_wrapper(Getattr(n, "name")); @@ -1378,9 +1381,9 @@ int JSCEmitter::dump(Node *n) { emitNamespaces(); // compose the initializer function using a template - Template initializer(getTemplate("JS_initializer")); + Template initializer(getTemplate("js_initializer")); initializer.replace(T_NAME, module) - .replace("$jsinitializercode", state.global(INITIALIZER)) + .replace("$jsregisterclasses", state.global(INITIALIZER)) .replace("$jscreatenamespaces", state.global(CREATE_NAMESPACES)) .replace("$jsregisternamespaces", state.global(REGISTER_NAMESPACES)) .pretty_print(f_init); @@ -1414,7 +1417,7 @@ int JSCEmitter::enterFunction(Node *n) { } int JSCEmitter::exitFunction(Node *n) { - Template t_function = getTemplate("JS_functiondecl"); + Template t_function = getTemplate("jsc_function_declaration"); bool is_member = GetFlag(n, "ismember"); bool is_overloaded = GetFlag(n, "sym:overloaded"); @@ -1456,7 +1459,7 @@ int JSCEmitter::enterVariable(Node *n) { int JSCEmitter::exitVariable(Node *n) { - Template t_variable(getTemplate("JS_variabledecl")); + Template t_variable(getTemplate("jsc_variable_declaration")); t_variable.replace(T_NAME, state.variable(NAME)) .replace(T_GETTER, state.variable(GETTER)) .replace(T_SETTER, state.variable(SETTER)); @@ -1482,15 +1485,15 @@ int JSCEmitter::enterClass(Node *n) { state.clazz(STATIC_VARIABLES, NewString("")); state.clazz(STATIC_FUNCTIONS, NewString("")); - Template t_class_defn = getTemplate("JS_class_definition"); - t_class_defn.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) + Template t_class_decl = getTemplate("jsc_class_declaration"); + t_class_decl.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .pretty_print(f_wrappers); return SWIG_OK; } int JSCEmitter::exitClass(Node *n) { - Template t_class_tables(getTemplate("JS_class_tables")); + Template t_class_tables(getTemplate("jsc_class_tables")); t_class_tables.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .replace("$jsclassvariables", state.clazz(MEMBER_VARIABLES)) .replace("$jsclassfunctions", state.clazz(MEMBER_FUNCTIONS)) @@ -1504,14 +1507,14 @@ int JSCEmitter::exitClass(Node *n) { // for abstract classes add a vetoing ctor if(GetFlag(state.clazz(), IS_ABSTRACT)) { - Template t_veto_ctor(getTemplate("JS_veto_ctor")); - t_veto_ctor.replace(T_CTOR, state.clazz(CTOR)) + Template t_veto_ctor(getTemplate("js_veto_ctor")); + t_veto_ctor.replace(T_WRAPPER, state.clazz(CTOR)) .replace(T_NAME, state.clazz(NAME)) .pretty_print(f_wrappers); } /* adds a class template statement to initializer function */ - Template t_classtemplate(getTemplate("JS_create_class_template")); + Template t_classtemplate(getTemplate("jsc_class_definition")); /* prepare registration of base class */ String *base_name_mangled = NewString("_SwigObject"); @@ -1531,7 +1534,7 @@ int JSCEmitter::exitClass(Node *n) { SwigType_remember_clientdata(state.clazz(TYPE_MANGLED), NewString("0")); /* adds a class registration statement to initializer function */ - Template t_registerclass(getTemplate("JS_register_class")); + Template t_registerclass(getTemplate("jsc_class_registration")); t_registerclass.replace(T_NAME, state.clazz(NAME)) .replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .replace(T_NAMESPACE, Getattr(current_namespace, NAME_MANGLED)) @@ -1558,17 +1561,17 @@ int JSCEmitter::emitNamespaces() { String *functions = Getattr(entry, "functions"); String *variables = Getattr(entry, "values"); - Template namespace_definition(getTemplate("JS_globaldefn")); + Template namespace_definition(getTemplate("jsc_nspace_declaration")); namespace_definition.replace("$jsglobalvariables", variables) .replace("$jsglobalfunctions", functions) .replace(T_NAMESPACE, name_mangled) .pretty_print(f_wrap_cpp); - Template t_createNamespace(getTemplate("JS_create_namespace")); + Template t_createNamespace(getTemplate("jsc_nspace_definition")); t_createNamespace.replace(T_NAME_MANGLED, name_mangled); Append(state.global(CREATE_NAMESPACES), t_createNamespace.str()); - Template t_registerNamespace(getTemplate("JS_register_namespace")); + Template t_registerNamespace(getTemplate("jsc_nspace_registration")); t_registerNamespace.replace(T_NAME_MANGLED, name_mangled) .replace(T_NAME, name) .replace(T_PARENT, parent_mangled); @@ -1708,7 +1711,7 @@ int V8Emitter::dump(Node *n) // compose the initializer function using a template // filled with sub-parts - Template initializer(getTemplate("JS_initializer")); + Template initializer(getTemplate("js_initializer")); initializer.replace(T_NAME, module) .replace(V8_NAME_SPACES, f_init_namespaces) .replace(V8_CLASS_TEMPLATES, f_init_class_templates) @@ -1762,8 +1765,8 @@ int V8Emitter::enterClass(Node *n) int V8Emitter::exitClass(Node *n) { if(GetFlag(state.clazz(), IS_ABSTRACT)) { - Template t_veto_ctor(getTemplate("JS_veto_ctor")); - t_veto_ctor.replace(T_CTOR, state.clazz(CTOR)) + Template t_veto_ctor(getTemplate("js_veto_ctor")); + t_veto_ctor.replace(T_WRAPPER, state.clazz(CTOR)) .replace(T_NAME, state.clazz(NAME)) .pretty_print(f_wrappers); } @@ -2001,7 +2004,7 @@ void V8Emitter::emitUndefined() { .pretty_print(f_class_templates); // emit an extra dtor for unknown types - Template t_dtor = getTemplate("JS_destructordefn"); + Template t_dtor = getTemplate("js_dtor"); t_dtor.replace(T_NAME_MANGLED, mangled_name) .replace(T_WRAPPER, dtor) .replace(T_FREE, free) @@ -2134,6 +2137,8 @@ Template::Template(const String *code_) { } code = NewString(code_); templateName = NewString(""); + + trim(); } Template::Template(const String *code_, const String *templateName_) { @@ -2145,6 +2150,8 @@ Template::Template(const String *code_, const String *templateName_) { code = NewString(code_); templateName = NewString(templateName_); + + trim(); } @@ -2179,6 +2186,36 @@ String *Template::str() { return code; } +void Template::trim() { + const char* str = Char(code); + if (str == 0) return; + + int length = Len(code); + if (length == 0) return; + + int idx; + for(idx=0; idx < length; ++idx) { + if (str[idx] == ' ' || str[idx] == '\t' || str[idx] == '\r' || str[idx] == '\n') + break; + } + int start_pos = idx; + + for(idx=length-1; idx >= start_pos; --idx) { + if (str[idx] == ' ' || str[idx] == '\t' || str[idx] == '\r' || str[idx] == '\n') + break; + } + int end_pos = idx; + + int new_length = end_pos-start_pos+1; + char* newstr = new char[new_length+1]; + memcpy(newstr, str+start_pos, new_length); + newstr[new_length] = 0; + + Delete(code); + code = NewString(newstr); + delete[] newstr; +} + /* ----------------------------------------------------------------------------- * Template& Template::replace(const String* pattern, const String* repl) : * From 9b06144d39f3f1b820ee90ad0bf1c2cf96cbaf6a Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:16:09 +0000 Subject: [PATCH 0154/1048] Fix handling of overloaded ctors in v8 emitter. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13827 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/v8/javascriptcode.swg | 49 +++++++++++++++------------- Source/Modules/javascript.cxx | 6 ++-- 2 files changed, 30 insertions(+), 25 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 5e092528b..78316c80b 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -3,6 +3,7 @@ v8::Handle $jswrapper(const v8::Arguments& args) { v8::HandleScope scope; v8::Handle self = args.Holder(); $jslocals + if(args.Length() != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); $jscode SWIGV8_SetPrivateData(self, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); @@ -23,11 +24,30 @@ v8::Handle $jswrapper(const v8::Arguments& args) { } %} -%fragment("js_overloaded_ctor", "templates") %{ +%fragment ("js_ctor_dispatcher", "templates") +%{ v8::Handle $jswrapper(const v8::Arguments& args) { + v8::HandleScope scope; + OverloadErrorHandler errorHandler; + v8::Handle self; + + // switch all cases by means of series of if-returns. + $jsdispatchcases + + // default: + SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for contruction of $jsmangledname"); + +fail: + scope.Close(v8::Undefined()); +} +%} + +%fragment("js_overloaded_ctor", "templates") %{ +v8::Handle $jswrapper(const v8::Arguments& args, V8ErrorHandler& SWIGV8_ErrorHandler) { v8::HandleScope scope; v8::Handle self = args.Holder(); $jslocals + if(args.Length() != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); $jscode SWIGV8_SetPrivateData(self, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); @@ -39,27 +59,12 @@ fail: } %} -%fragment ("js_ctor_dispatcher", "templates") -%{ -v8::Handle $jswrapper(const v8::Arguments& args) { - v8::HandleScope scope; - - // switch all cases by means of series of if-returns. - $jsdispatchcases - - // default: - SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for contruction of $jsmangledname"); - -fail: - scope.Close(v8::Undefined()); -} -%} - %fragment ("js_ctor_dispatch_case", "templates") %{ if(args.Length() == $jsargcount) { - v8::Handle self = $jswrapper(args); - if(!self->IsUndefined()) { + errorHandler.err.Clear(); + self = $jswrapper(args, errorHandler); + if(errorHandler.err.IsEmpty()) { return scope.Close(self); } } @@ -110,6 +115,8 @@ v8::Handle $jswrapper(const v8::Arguments &args) { v8::HandleScope scope; v8::Handle jsresult; $jslocals + if(args.Length() != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); + $jscode return scope.Close(jsresult); goto fail; @@ -138,11 +145,9 @@ fail: %{ v8::Handle $jswrapper(const v8::Arguments &args, V8ErrorHandler& SWIGV8_ErrorHandler) { - v8::HandleScope scope; - + v8::HandleScope scope; v8::Handle jsresult; $jslocals - if(args.Length() != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); $jscode return scope.Close(jsresult); goto fail; diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 76d8b389d..a713d8fa7 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -815,6 +815,7 @@ int JSEmitter::emitCtor(Node *n) { //String *mangled_name = SwigType_manglestr(Getattr(n, "name")); String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); if(is_overloaded) { + t_ctor = getTemplate("js_overloaded_ctor"); Append(wrap_name, Getattr(n, "sym:overname")); } Setattr(n, "wrap:name", wrap_name); @@ -1909,12 +1910,12 @@ void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Mar Parm *p; int startIdx = 0; - if (is_member && !is_static) { + if (is_member && !is_static && mode!=Ctor) { startIdx = 1; } // store number of arguments for argument checks - int num_args = emit_num_arguments(parms); + int num_args = emit_num_arguments(parms) - startIdx; String *argcount = NewString(""); Printf(argcount, "%d", num_args); Setattr(n, ARGCOUNT, argcount); @@ -1922,7 +1923,6 @@ void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Mar int i = 0; for (p = parms; p; p = nextSibling(p), i++) { String *arg = NewString(""); - switch (mode) { case Getter: if (is_member && !is_static && i == 0) { From 217ffb11d0cbcfbcfbaa679bd815a80b897b1c8b Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:16:26 +0000 Subject: [PATCH 0155/1048] Fix regressions of latest commits. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13828 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/jsc/javascriptcode.swg | 17 +++++++++++++--- Source/Modules/javascript.cxx | 28 +++++++++++++-------------- 2 files changed, 28 insertions(+), 17 deletions(-) diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index 9a91c874a..73c127103 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -11,13 +11,10 @@ JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { $jslocals - if(argc != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); $jscode - return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); - goto fail; fail: return NULL; @@ -63,6 +60,20 @@ JSObjectRef $jswrapper(JSContextRef context, JSObjectRef ctorObject, } %} +%fragment ("js_overloaded_ctor", "templates") +%{ +JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + $jslocals + $jscode + return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); + + goto fail; + fail: + return NULL; +} +%} + /* ----------------------------------------------------------------------------- * js_ctor_dispatch_case: template for a dispatch case for calling an overloaded ctor. * - $jsargcount: number of arguments of called ctor diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index a713d8fa7..3c2c872c8 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1075,18 +1075,16 @@ int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { void JSEmitter::registerProxyType(SwigType* type) { SwigType *ftype = SwigType_typedef_resolve_all(type); + if(Language::instance()->classLookup(ftype)) return; + + // TODO: confused... more try and error... understand and fix eventually + SwigType *p_ftype = SwigType_add_pointer(ftype); // register undefined wrappers - int needs_proxy= (SwigType_ispointer(ftype) - || SwigType_isarray(ftype) || SwigType_isreference(ftype)) - && !(Language::instance()->classLookup(ftype)); - if (needs_proxy) { - SwigType_remember_clientdata(ftype, 0); - Setattr(undefined_types, SwigType_manglestr(ftype), ftype); - } else { - Delete(ftype); - } + SwigType_remember_clientdata(p_ftype, 0); + Setattr(undefined_types, SwigType_manglestr(p_ftype), p_ftype); + Delete(ftype); } void JSEmitter::emitInputTypemap(Node *n, Parm *p, Wrapper *wrapper, String *arg) { @@ -1119,7 +1117,9 @@ void JSEmitter::marshalOutput(Node *n, Wrapper *wrapper, String *actioncode, co if(cresult == 0) cresult = defaultResultName; tm = Swig_typemap_lookup_out("out", n, cresult, wrapper, actioncode); - if(GetFlag(n, "feature:new")) { + bool should_own = GetFlag(n, "feature:new"); + bool needs_proxy = GetFlag(n, "tmap:out:SWIGTYPE"); + if(needs_proxy) { registerProxyType(type); } @@ -1127,7 +1127,7 @@ void JSEmitter::marshalOutput(Node *n, Wrapper *wrapper, String *actioncode, co Replaceall(tm, "$result", "jsresult"); Replaceall(tm, "$objecttype", Swig_scopename_last(SwigType_str(SwigType_strip_qualifiers(type), 0))); - if (GetFlag(n, "feature:new")) { + if (should_own) { Replaceall(tm, "$owner", "SWIG_POINTER_OWN"); } else { Replaceall(tm, "$owner", "0"); @@ -1985,10 +1985,10 @@ int V8Emitter::emitNamespaces() { void V8Emitter::emitUndefined() { Iterator ki; for (ki = First(undefined_types); ki.item; ki = Next(ki)) { - String *mangled_name = ki.key; + String *mangled_name = NewStringf("SWIGTYPE%s", ki.key); SwigType *type = ki.item; String *dtor = Swig_name_destroy("", mangled_name); - String *type_mangled = SwigType_manglestr(type); + String *type_mangled = ki.key; String *ctype = SwigType_lstr(type, ""); String *free = NewString(""); @@ -2018,9 +2018,9 @@ void V8Emitter::emitUndefined() { .replace(T_DTOR, dtor) .pretty_print(f_init_class_templates); + Delete(mangled_name); Delete(dtor); Delete(free); - Delete(type_mangled); Delete(ctype); } From 86cb62146661f89f9cd3dd76c721ddfed529b99d Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:16:42 +0000 Subject: [PATCH 0156/1048] Add comments to v8 code templates. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13829 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Lib/javascript/jsc/javascriptcode.swg | 8 ++ Lib/javascript/v8/javascriptcode.swg | 195 +++++++++++++++++++++++--- 2 files changed, 182 insertions(+), 21 deletions(-) diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index 73c127103..34245ed14 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -60,6 +60,14 @@ JSObjectRef $jswrapper(JSContextRef context, JSObjectRef ctorObject, } %} +/* ----------------------------------------------------------------------------- + * js_overloaded_ctor: template for wrapping a ctor. + * - $jswrapper: wrapper of called ctor + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * - $jsargcount: number of arguments + * - $jsmangledtype: mangled type of class + * ----------------------------------------------------------------------------- */ %fragment ("js_overloaded_ctor", "templates") %{ JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 78316c80b..eb95cb1bf 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -1,3 +1,11 @@ +/* ----------------------------------------------------------------------------- + * js_ctor: template for wrapping a ctor. + * - $jswrapper: wrapper of called ctor + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * - $jsargcount: number of arguments + * - $jsmangledtype: mangled type of class + * ----------------------------------------------------------------------------- */ %fragment("js_ctor", "templates") %{ v8::Handle $jswrapper(const v8::Arguments& args) { v8::HandleScope scope; @@ -15,6 +23,11 @@ fail: } %} +/* ----------------------------------------------------------------------------- + * js_veto_ctor: a vetoing ctor for abstract classes + * - $jswrapper: name of wrapper + * - $jsname: class name + * ----------------------------------------------------------------------------- */ %fragment ("js_veto_ctor", "templates") %{ v8::Handle $jswrapper(const v8::Arguments& args) { @@ -24,6 +37,12 @@ v8::Handle $jswrapper(const v8::Arguments& args) { } %} +/* ----------------------------------------------------------------------------- + * js_ctor_dispatcher: dispatcher for overloaded constructors + * - $jswrapper: name of wrapper + * - $jsname: class name + * - $jsdispatchcases: part containing code for dispatching + * ----------------------------------------------------------------------------- */ %fragment ("js_ctor_dispatcher", "templates") %{ v8::Handle $jswrapper(const v8::Arguments& args) { @@ -42,6 +61,14 @@ fail: } %} +/* ----------------------------------------------------------------------------- + * js_overloaded_ctor: template for wrapping a ctor. + * - $jswrapper: wrapper of called ctor + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * - $jsargcount: number of arguments + * - $jsmangledtype: mangled type of class + * ----------------------------------------------------------------------------- */ %fragment("js_overloaded_ctor", "templates") %{ v8::Handle $jswrapper(const v8::Arguments& args, V8ErrorHandler& SWIGV8_ErrorHandler) { v8::HandleScope scope; @@ -59,6 +86,13 @@ fail: } %} +/* ----------------------------------------------------------------------------- + * js_ctor_dispatch_case: template for a dispatch case for calling an overloaded ctor. + * - $jsargcount: number of arguments of called ctor + * - $jswrapper: wrapper of called ctor + * + * Note: a try-catch-like mechanism is used to switch cases + * ----------------------------------------------------------------------------- */ %fragment ("js_ctor_dispatch_case", "templates") %{ if(args.Length() == $jsargcount) { @@ -70,6 +104,11 @@ fail: } %} +/* ----------------------------------------------------------------------------- + * js_dtor: template for a destructor wrapper + * - $jsmangledname: mangled class name + * - $jstype: class type + * ----------------------------------------------------------------------------- */ %fragment ("js_dtor", "templates") %{ void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) { @@ -82,7 +121,12 @@ void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) { } %} - +/* ----------------------------------------------------------------------------- + * js_getter: template for getter function wrappers + * - $jswrapper: wrapper function name + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ %fragment("js_getter", "templates") %{ v8::Handle $jswrapper(v8::Local property, const v8::AccessorInfo& info) { @@ -97,6 +141,12 @@ fail: } %} +/* ----------------------------------------------------------------------------- + * js_setter: template for setter function wrappers + * - $jswrapper: wrapper function name + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ %fragment("js_setter", "templates") %{ void $jswrapper(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { @@ -109,6 +159,12 @@ fail: } %} +/* ----------------------------------------------------------------------------- + * js_function: template for function wrappers + * - $jswrapper: wrapper function name + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ %fragment("js_function", "templates") %{ v8::Handle $jswrapper(const v8::Arguments &args) { @@ -125,6 +181,13 @@ fail: } %} +/* ----------------------------------------------------------------------------- + * js_function_dispatcher: template for a function dispatcher for overloaded functions + * - $jswrapper: wrapper function name + * - $jsname: name of the wrapped function + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ %fragment("js_function_dispatcher", "templates") %{ v8::Handle $jswrapper(const v8::Arguments &args) { @@ -141,6 +204,12 @@ fail: } %} +/* ----------------------------------------------------------------------------- + * js_overloaded_function: template for a overloaded function + * - $jswrapper: wrapper function name + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ %fragment ("js_overloaded_function", "templates") %{ v8::Handle $jswrapper(const v8::Arguments &args, V8ErrorHandler& SWIGV8_ErrorHandler) @@ -156,6 +225,12 @@ fail: } %} +/* ----------------------------------------------------------------------------- + * js_function_dispatch_case: template for a case used in the function dispatcher + * - $jswrapper: wrapper function name + * - $jsargcount: number of arguments of overloaded function + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ %fragment ("js_function_dispatch_case", "templates") %{ if(args.Length() == $jsargcount) { @@ -167,11 +242,21 @@ fail: } %} +/* ----------------------------------------------------------------------------- + * jsv8_declare_class_template: template for a class template declaration. + * - $jsmangledname: mangled class name + * ----------------------------------------------------------------------------- */ %fragment("jsv8_declare_class_template", "templates") %{ SWIGV8_ClientData $jsmangledname_clientData; %} +/* ----------------------------------------------------------------------------- + * jsv8_define_class_template: template for a class template definition. + * - $jsmangledname: mangled class name + * - $jsmangledtype: mangled class type + * - $jsdtor: the dtor wrapper + * ----------------------------------------------------------------------------- */ %fragment("jsv8_define_class_template", "templates") %{ v8::Handle $jsmangledname_class = SWIGV8_CreateClassTemplate("$jsmangledname"); @@ -180,11 +265,21 @@ fail: SWIGTYPE$jsmangledtype->clientdata = &$jsmangledname_clientData; %} +/* ----------------------------------------------------------------------------- + * jsv8_inherit: template for an class inherit statement. + * - $jsmangledname: mangled class name + * - $jsbaseclass: mangled name of the base class + * ----------------------------------------------------------------------------- */ %fragment("jsv8_inherit", "templates") %{ $jsmangledname_class->Inherit($jsbaseclass_class); %} +/* ----------------------------------------------------------------------------- + * jsv8_create_class_instance: template for creating an class object. + * - $jsname: class name + * - $jsmangledname: mangled class name + * ----------------------------------------------------------------------------- */ %fragment("jsv8_create_class_instance", "templates") %{ v8::Handle $jsmangledname_class_0 = SWIGV8_CreateClassTemplate("$jsname"); @@ -194,41 +289,99 @@ fail: v8::Handle $jsmangledname_obj = $jsmangledname_class_0->GetFunction(); %} +/* ----------------------------------------------------------------------------- + * jsv8_register_class: template for a statement that registers a class in a parent namespace. + * - $jsname: class name + * - $jsmangledname: mangled class name + * - $jsparent: mangled name of parent namespace + * ----------------------------------------------------------------------------- */ %fragment("jsv8_register_class", "templates") %{ $jsparent_obj->Set(v8::String::NewSymbol("$jsname"), $jsmangledname_obj); %} +/* ----------------------------------------------------------------------------- + * jsv8_create_namespace: template for a statement that creates a namespace object. + * - $jsmangledname: mangled namespace name + * ----------------------------------------------------------------------------- */ %fragment("jsv8_create_namespace", "templates") %{ v8::Handle $jsmangledname_obj = v8::Object::New(); %} -%fragment("jsv8_register_member_function", "templates") -%{ - SWIGV8_AddMemberFunction($jsmangledname_class, "$jsname", $jswrapper); -%} - -%fragment("jsv8_register_member_variable", "templates") -%{ - SWIGV8_AddMemberVariable($jsmangledname_class, "$jsname", $jsgetter, $jssetter); -%} - -%fragment("jsv8_register_static_function", "templates") -%{ - SWIGV8_AddStaticFunction($jsparent_obj, "$jsname", $jswrapper); -%} - -%fragment("jsv8_register_static_variable", "templates") -%{ - SWIGV8_AddStaticVariable($jsparent_obj, "$jsname", $jsgetter, $jssetter); -%} - +/* ----------------------------------------------------------------------------- + * jsv8_register_namespace: template for a statement that registers a namespace in a parent namespace. + * - $jsname: name of namespace + * - $jsmangledname: mangled name of namespace + * - $jsparent: mangled name of parent namespace + * ----------------------------------------------------------------------------- */ %fragment("jsv8_register_namespace", "templates") %{ $jsparent_obj->Set(v8::String::NewSymbol("$jsname"), $jsmangledname_obj); %} +/* ----------------------------------------------------------------------------- + * jsv8_register_member_function: template for a statement that registers a member function. + * - $jsmangledname: mangled class name + * - $jsname: name of the function + * - $jswrapper: wrapper of the member function + * ----------------------------------------------------------------------------- */ +%fragment("jsv8_register_member_function", "templates") +%{ + SWIGV8_AddMemberFunction($jsmangledname_class, "$jsname", $jswrapper); +%} + +/* ----------------------------------------------------------------------------- + * jsv8_register_member_variable: template for a statement that registers a member variable. + * - $jsmangledname: mangled class name + * - $jsname: name of the function + * - $jsgetter: wrapper of the getter function + * - $jssetter: wrapper of the setter function + * ----------------------------------------------------------------------------- */ +%fragment("jsv8_register_member_variable", "templates") +%{ + SWIGV8_AddMemberVariable($jsmangledname_class, "$jsname", $jsgetter, $jssetter); +%} + +/* ----------------------------------------------------------------------------- + * jsv8_register_static_function: template for a statement that registers a static class function. + * - $jsname: function name + * - $jswrapper: wrapper of the function + * - $jsparent: mangled name of parent namespace + * + * Note: this template is also used for global functions. + * ----------------------------------------------------------------------------- */ +%fragment("jsv8_register_static_function", "templates") +%{ + SWIGV8_AddStaticFunction($jsparent_obj, "$jsname", $jswrapper); +%} + +/* ----------------------------------------------------------------------------- + * jsv8_register_static_variable: template for a statement that registers a static variable. + * - $jsname: variable name + * - $jsparent: mangled name of parent namespace + * - $jsgetter: wrapper of the getter function + * - $jssetter: wrapper of the setter function + * + * Note: this template is also used for global variables. + * ----------------------------------------------------------------------------- */ +%fragment("jsv8_register_static_variable", "templates") +%{ + SWIGV8_AddStaticVariable($jsparent_obj, "$jsname", $jsgetter, $jssetter); +%} + +/* ----------------------------------------------------------------------------- + * js_initializer: template for the module initializer function + * - $jsname: module name + * - $jsv8nspaces: part with code creating namespace objects + * - $jsv8classtemplates: part with code creating class templates + * - $jsv8wrappers: part with code that registers wrapper functions + * - $jsv8inheritance: part with inherit statements + * - $jsv8classinstances: part with code creating class objects + * - $jsv8staticwrappers: part with code adding static functions to class objects + * - $jsv8registerclasses: part with code that registers class objects in namespaces + * - $jsv8registernspaces: part with code that registers namespaces in parent namespaces + * ----------------------------------------------------------------------------- */ %fragment("js_initializer", "templates") %{ extern "C" { From 94730dad7a5d00468d4b2798c7cbd04db6b1d30d Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 8 Sep 2012 01:16:54 +0000 Subject: [PATCH 0157/1048] Beautify output of v8 emitter. Trimming some of the code templates. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13830 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- Source/Modules/javascript.cxx | 69 +++++++++++++++++++---------------- 1 file changed, 37 insertions(+), 32 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 3c2c872c8..ea1172c67 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -114,9 +114,7 @@ public: void operator=(const Template& t); -protected: - - void trim(); + Template& trim(); private: @@ -1604,7 +1602,6 @@ public: virtual int exitClass(Node *n); virtual int enterVariable(Node *n); virtual int exitVariable(Node *n); - virtual int enterFunction(Node *n); virtual int exitFunction(Node *n); protected: @@ -1758,6 +1755,7 @@ int V8Emitter::enterClass(Node *n) // emit declaration of a v8 class template Template t_decl_class(getTemplate("jsv8_declare_class_template")); t_decl_class.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) + .trim() .pretty_print(f_class_templates); return SWIG_OK; @@ -1780,35 +1778,39 @@ int V8Emitter::exitClass(Node *n) // emit definition of v8 class template String *p_classtype = state.clazz(TYPE); String *p_classtype_str = SwigType_manglestr(p_classtype); - Template t_def_class(getTemplate("jsv8_define_class_template")); + Template t_def_class = getTemplate("jsv8_define_class_template"); t_def_class.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .replace(T_NAME, state.clazz(NAME)) .replace(T_TYPE_MANGLED, p_classtype_str) .replace(T_DTOR, state.clazz(DTOR)) + .trim() .pretty_print(f_init_class_templates); - Template t_class_instance(getTemplate("jsv8_create_class_instance")); + Template t_class_instance = getTemplate("jsv8_create_class_instance"); t_class_instance.replace(T_NAME, state.clazz(NAME)) .replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .replace(T_CTOR, state.clazz(CTOR)) + .trim() .pretty_print(f_init_class_instances); // emit inheritance setup Node* baseClass = getBaseClass(n); if(baseClass) { - Template t_inherit(getTemplate("jsv8_inherit")); + Template t_inherit = getTemplate("jsv8_inherit"); String *base_name_mangled = SwigType_manglestr(Getattr(baseClass, "name")); t_inherit.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .replace(T_BASECLASS, base_name_mangled) + .trim() .pretty_print(f_init_inheritance); Delete(base_name_mangled); } // emit registeration of class template - Template t_register(getTemplate("jsv8_register_class")); + Template t_register = getTemplate("jsv8_register_class"); t_register.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .replace(T_NAME, state.clazz(NAME)) .replace(T_PARENT, Getattr(current_namespace, "name_mangled")) + .trim() .pretty_print(f_init_register_classes); return SWIG_OK; @@ -1828,40 +1830,37 @@ int V8Emitter::exitVariable(Node* n) { if(GetFlag(n, "ismember")) { if(GetFlag(state.variable(), IS_STATIC) || Equal(Getattr(n, "nodeType"), "enumitem") ) { - Template t_register(getTemplate("jsv8_register_static_variable")); + Template t_register = getTemplate("jsv8_register_static_variable"); t_register.replace(T_PARENT, state.clazz(NAME_MANGLED)) .replace(T_NAME, state.variable(NAME)) .replace(T_GETTER, state.variable(GETTER)) .replace(T_SETTER, state.variable(SETTER)) + .trim() .pretty_print(f_init_static_wrappers); } else { - Template t_register(getTemplate("jsv8_register_member_variable")); + Template t_register = getTemplate("jsv8_register_member_variable"); t_register.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .replace(T_NAME, state.variable(NAME)) .replace(T_GETTER, state.variable(GETTER)) .replace(T_SETTER, state.variable(SETTER)) + .trim() .pretty_print(f_init_wrappers); } } else { // Note: a global variable is treated like a static variable // with the parent being a nspace object (instead of class object) - Template t_register(getTemplate("jsv8_register_static_variable")); + Template t_register = getTemplate("jsv8_register_static_variable"); t_register.replace(T_PARENT, Getattr(current_namespace, NAME)) .replace(T_NAME, state.variable(NAME)) .replace(T_GETTER, state.variable(GETTER)) .replace(T_SETTER, state.variable(SETTER)) + .trim() .pretty_print(f_init_wrappers); } return SWIG_OK; } -int V8Emitter::enterFunction(Node* n) -{ - JSEmitter::enterFunction(n); - return SWIG_OK; -} - int V8Emitter::exitFunction(Node* n) { bool is_member = GetFlag(n, "ismember"); @@ -1881,25 +1880,28 @@ int V8Emitter::exitFunction(Node* n) // register the function at the specific context if(is_member) { if(GetFlag(state.function(), IS_STATIC)) { - Template t_register(getTemplate("jsv8_register_static_function")); + Template t_register = getTemplate("jsv8_register_static_function"); t_register.replace(T_PARENT, state.clazz(NAME_MANGLED)) .replace(T_NAME, state.function(NAME)) .replace(T_WRAPPER, state.function(WRAPPER_NAME)) + .trim() .pretty_print(f_init_static_wrappers); } else { - Template t_register(getTemplate("jsv8_register_member_function")); + Template t_register = getTemplate("jsv8_register_member_function"); t_register.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .replace(T_NAME, state.function(NAME)) .replace(T_WRAPPER, state.function(WRAPPER_NAME)) + .trim() .pretty_print(f_init_wrappers); } } else { // Note: a global function is treated like a static function // with the parent being a nspace object instead of class object - Template t_register(getTemplate("jsv8_register_static_function")); + Template t_register = getTemplate("jsv8_register_static_function"); t_register.replace(T_PARENT, Getattr(current_namespace, NAME)) .replace(T_NAME, state.function(NAME)) .replace(T_WRAPPER, state.function(WRAPPER_NAME)) + .trim() .pretty_print(f_init_static_wrappers); } @@ -1966,14 +1968,16 @@ int V8Emitter::emitNamespaces() { String *parent_mangled = Swig_name_mangle(parent); // create namespace object and register it to the parent scope - Template t_create_ns(getTemplate("jsv8_create_namespace")); + Template t_create_ns = getTemplate("jsv8_create_namespace"); t_create_ns.replace(T_NAME_MANGLED, name_mangled) + .trim() .pretty_print(f_init_namespaces); - Template t_register_ns(getTemplate("jsv8_register_namespace")); + Template t_register_ns = getTemplate("jsv8_register_namespace"); t_register_ns.replace(T_NAME_MANGLED, name_mangled) .replace(T_NAME, name) - .replace(T_PARENT, parent_mangled); + .replace(T_PARENT, parent_mangled) + .trim(); // prepend in order to achieve reversed order of registration statements Insert(f_init_register_namespaces, 0, t_register_ns.str()); @@ -2001,6 +2005,7 @@ void V8Emitter::emitUndefined() { // emit clientData declaration Template clientDataDecl = getTemplate("jsv8_declare_class_template"); clientDataDecl.replace(T_NAME_MANGLED, mangled_name) + .trim() .pretty_print(f_class_templates); // emit an extra dtor for unknown types @@ -2008,6 +2013,7 @@ void V8Emitter::emitUndefined() { t_dtor.replace(T_NAME_MANGLED, mangled_name) .replace(T_WRAPPER, dtor) .replace(T_FREE, free) + .trim() .pretty_print(f_wrappers); // create a class template and initialize clientData @@ -2016,6 +2022,7 @@ void V8Emitter::emitUndefined() { .replace(T_NAME, mangled_name) .replace(T_TYPE_MANGLED, type_mangled) .replace(T_DTOR, dtor) + .trim() .pretty_print(f_init_class_templates); Delete(mangled_name); @@ -2137,8 +2144,6 @@ Template::Template(const String *code_) { } code = NewString(code_); templateName = NewString(""); - - trim(); } Template::Template(const String *code_, const String *templateName_) { @@ -2150,8 +2155,6 @@ Template::Template(const String *code_, const String *templateName_) { code = NewString(code_); templateName = NewString(templateName_); - - trim(); } @@ -2186,22 +2189,22 @@ String *Template::str() { return code; } -void Template::trim() { +Template& Template::trim() { const char* str = Char(code); - if (str == 0) return; + if (str == 0) return *this; int length = Len(code); - if (length == 0) return; + if (length == 0) return *this; int idx; for(idx=0; idx < length; ++idx) { - if (str[idx] == ' ' || str[idx] == '\t' || str[idx] == '\r' || str[idx] == '\n') + if (str[idx] != ' ' && str[idx] != '\t' && str[idx] != '\r' && str[idx] != '\n') break; } int start_pos = idx; for(idx=length-1; idx >= start_pos; --idx) { - if (str[idx] == ' ' || str[idx] == '\t' || str[idx] == '\r' || str[idx] == '\n') + if (str[idx] != ' ' && str[idx] != '\t' && str[idx] != '\r' && str[idx] != '\n') break; } int end_pos = idx; @@ -2214,6 +2217,8 @@ void Template::trim() { Delete(code); code = NewString(newstr); delete[] newstr; + + return *this; } /* ----------------------------------------------------------------------------- From 6d655a7f417a41562d42e3345a34b0d73e821644 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 20 Sep 2012 18:17:52 +0000 Subject: [PATCH 0158/1048] 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 0159/1048] 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 0160/1048] 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 0161/1048] 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 0162/1048] 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 0163/1048] 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 0164/1048] 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 0165/1048] 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 0166/1048] 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 0167/1048] 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 0168/1048] 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 0169/1048] 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 0170/1048] 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 0171/1048] 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 0172/1048] 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 0173/1048] 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 0174/1048] 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 0175/1048] 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 0176/1048] 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 0177/1048] 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 0178/1048] 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 0179/1048] 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 0180/1048] 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 0181/1048] 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 0182/1048] 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 0183/1048] 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 0184/1048] 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 0185/1048] 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 0186/1048] 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 0187/1048] 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 0188/1048] 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 0189/1048] 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 0190/1048] 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 0191/1048] 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 0192/1048] 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 0193/1048] 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 0194/1048] 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 0195/1048] 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 0196/1048] 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 0197/1048] 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 0198/1048] 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 0199/1048] 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 0200/1048] 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 0201/1048] 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 0202/1048] 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 0203/1048] 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 0204/1048] 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 0205/1048] 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 0206/1048] 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 0207/1048] 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 0208/1048] 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 0209/1048] 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 0210/1048] 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 0211/1048] 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 0212/1048] 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 57980975a0f86961b3a9545fd24f34575609c6c7 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 16 Nov 2012 22:10:02 +0100 Subject: [PATCH 0213/1048] Generate cleanup code. --- Source/Modules/javascript.cxx | 241 +++++++++++++++++++--------------- 1 file changed, 134 insertions(+), 107 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index ea1172c67..d43af979d 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -61,19 +61,19 @@ bool js_template_enable_debug = false; * named sub-hashes for class, variable, and function states. */ class JSEmitterState { - + public: JSEmitterState(); ~JSEmitterState(); - + DOH *global(); - + DOH *global(const char* key, DOH *initial = 0); - + DOH *clazz(bool reset = false); - + DOH *clazz(const char* key, DOH *initial = 0); DOH *function(bool reset = false); @@ -83,9 +83,9 @@ public: DOH *variable(bool reset = false); DOH *variable(const char* key, DOH *initial = 0); - + static int IsSet(DOH *val); - + private: DOH *getState(const char* key, bool reset = false); @@ -94,7 +94,7 @@ private: }; /** - * A convenience class that wraps a code snippet used as template + * A convenience class that wraps a code snippet used as template * for code generation. */ class Template { @@ -111,7 +111,7 @@ public: Template& replace(const String *pattern, const String *repl); Template& pretty_print(DOH *doh); - + void operator=(const Template& t); Template& trim(); @@ -169,7 +169,7 @@ public: /** * Switches the context for code generation. - * + * * Classes, global variables and global functions may need to * be registered in certain static tables. * This method should be used to switch output DOHs correspondingly. @@ -224,7 +224,7 @@ public: /** * Registers a given code snippet for a given key name. - * + * * This method is called by the fragmentDirective handler * of the JAVASCRIPT language module. **/ @@ -267,18 +267,20 @@ protected: virtual int emitSetter(Node *n, bool is_member, bool is_static); virtual void marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) = 0; - + virtual void emitInputTypemap(Node *n, Parm *p, Wrapper *wrapper, String *arg); virtual void marshalOutput(Node *n, Wrapper *wrapper, String *actioncode, const String *cresult=0, bool emitReturnVariable = true); + virtual void emitCleanupCode(Wrapper *wrapper, ParmList *params); + void registerProxyType(SwigType* type); /** * Helper function to retrieve the first parent class node. */ Node *getBaseClass(Node *n); - + Parm *skipIgnoredArgs(Parm *p); virtual int createNamespace(String *scope); @@ -286,14 +288,14 @@ protected: virtual Hash *createNamespaceEntry(const char *name, const char *parent); virtual int emitNamespaces() = 0; - + protected: Hash *templates; - + State state; - + // contains context specific data (DOHs) // to allow generation of namespace related code // which are switched on namespace change @@ -303,7 +305,7 @@ protected: Hash *undefined_types; String *defaultResultName; - + File *f_wrappers; }; @@ -322,7 +324,7 @@ class JAVASCRIPT:public Language { public: JAVASCRIPT(): emitter(NULL) {} - + ~JAVASCRIPT() { delete emitter; } @@ -337,7 +339,7 @@ public: virtual int constantWrapper(Node *n); virtual void main(int argc, char *argv[]); virtual int top(Node *n); - + /** * Registers all %fragments assigned to section "templates". **/ @@ -351,7 +353,7 @@ private: /* --------------------------------------------------------------------- * functionWrapper() * - * Low level code generator for functions + * Low level code generator for functions * --------------------------------------------------------------------- */ int JAVASCRIPT::functionWrapper(Node *n) { @@ -359,14 +361,14 @@ int JAVASCRIPT::functionWrapper(Node *n) { // note: the default implementation only prints a message // Language::functionWrapper(n); emitter->emitWrapperFunction(n); - + return SWIG_OK; } /* --------------------------------------------------------------------- * functionHandler() * - * Function handler for generating wrappers for functions + * Function handler for generating wrappers for functions * --------------------------------------------------------------------- */ int JAVASCRIPT::functionHandler(Node *n) { @@ -384,20 +386,20 @@ int JAVASCRIPT::functionHandler(Node *n) { /* --------------------------------------------------------------------- * globalfunctionHandler() * - * Function handler for generating wrappers for functions + * Function handler for generating wrappers for functions * --------------------------------------------------------------------- */ int JAVASCRIPT::globalfunctionHandler(Node *n) { emitter->switchNamespace(n); Language::globalfunctionHandler(n); - + return SWIG_OK; } /* --------------------------------------------------------------------- * staticmemberfunctionHandler() * - * Function handler for generating wrappers for static member functions + * Function handler for generating wrappers for static member functions * --------------------------------------------------------------------- */ int JAVASCRIPT::staticmemberfunctionHandler(Node *n) { @@ -406,19 +408,19 @@ int JAVASCRIPT::staticmemberfunctionHandler(Node *n) { * So, don't rely on that after here. Instead use the state variable which is * set by JSEmitter::enterFunction(). */ - Language::staticmemberfunctionHandler(n); + Language::staticmemberfunctionHandler(n); return SWIG_OK; } /* --------------------------------------------------------------------- * variableHandler() * - * Function handler for generating wrappers for variables + * Function handler for generating wrappers for variables * --------------------------------------------------------------------- */ int JAVASCRIPT::variableHandler(Node *n) { - emitter->enterVariable(n); + emitter->enterVariable(n); Language::variableHandler(n); emitter->exitVariable(n); @@ -428,7 +430,7 @@ int JAVASCRIPT::variableHandler(Node *n) { /* --------------------------------------------------------------------- * globalvariableHandler() * - * Function handler for generating wrappers for global variables + * Function handler for generating wrappers for global variables * --------------------------------------------------------------------- */ int JAVASCRIPT::globalvariableHandler(Node *n) { @@ -442,7 +444,7 @@ int JAVASCRIPT::globalvariableHandler(Node *n) { /* --------------------------------------------------------------------- * constantHandler() * - * Function handler for generating wrappers for constants + * Function handler for generating wrappers for constants * --------------------------------------------------------------------- */ int JAVASCRIPT::constantWrapper(Node *n) { @@ -460,7 +462,7 @@ int JAVASCRIPT::constantWrapper(Node *n) { /* --------------------------------------------------------------------- * classHandler() * - * Function handler for generating wrappers for class + * Function handler for generating wrappers for class * --------------------------------------------------------------------- */ int JAVASCRIPT::classHandler(Node *n) { @@ -491,8 +493,8 @@ int JAVASCRIPT::fragmentDirective(Node *n) { /* --------------------------------------------------------------------- * top() * - * Function handler for processing top node of the parse tree - * Wrapper code generation essentially starts from here + * Function handler for processing top node of the parse tree + * Wrapper code generation essentially starts from here * --------------------------------------------------------------------- */ int JAVASCRIPT::top(Node *n) { @@ -569,10 +571,10 @@ void JAVASCRIPT::main(int argc, char *argv[]) { // Add a symbol to the parser for conditional compilation Preprocessor_define("SWIGJAVASCRIPT 1", 0); - // Add typemap definitions + // Add typemap definitions SWIG_typemap_lang("javascript"); - // Set configuration file + // Set configuration file SWIG_config_file("javascript.swg"); allow_overloading(); @@ -600,7 +602,7 @@ extern "C" Language *swig_javascript(void) { JSEmitter::JSEmitter() : templates(NewHash()), - namespaces(NULL), + namespaces(NULL), current_namespace(NULL), undefined_types(NewHash()), defaultResultName(NewString("result")), @@ -618,7 +620,7 @@ JSEmitter::~JSEmitter() { /* ----------------------------------------------------------------------------- * JSEmitter::RegisterTemplate() : Registers a code template - * + * * Note: this is used only by JAVASCRIPT::fragmentDirective(). * ----------------------------------------------------------------------------- */ @@ -656,9 +658,9 @@ int JSEmitter::initialize(Node * n) { Hash *global_namespace = createNamespaceEntry(Char(Getattr(n, "name")), "global"); Setattr(namespaces, "::", global_namespace); current_namespace = global_namespace; - + f_wrappers = NewString(""); - + return SWIG_OK; } @@ -675,7 +677,7 @@ Parm *JSEmitter::skipIgnoredArgs(Parm *p) { /* ----------------------------------------------------------------------------- * JSEmitter::getBaseClass() : the node of the base class or NULL - * + * * Note: the first base class is provided. Multiple inheritance is not * supported. * ----------------------------------------------------------------------------- */ @@ -695,7 +697,7 @@ Node *JSEmitter::getBaseClass(Node *n) { /* ----------------------------------------------------------------------------- * JSEmitter::emitWrapperFunction() : dispatches emitter functions. - * + * * This allows to have small sized, dedicated emitting functions. * All state dependent branching is done here. * ----------------------------------------------------------------------------- */ @@ -762,7 +764,7 @@ int JSEmitter::enterClass(Node *n) { // HACK: assume that a class is abstract // this is resolved by emitCtor (which is only called for non abstract classes) SetFlag(state.clazz(), IS_ABSTRACT); - + return SWIG_OK; } @@ -773,7 +775,7 @@ int JSEmitter::enterFunction(Node *n) { if(Equal(Getattr(n, "storage"), "static")) { SetFlag(state.function(), IS_STATIC); } - + /* Initialize DOH for collecting function dispatchers */ bool is_overloaded = GetFlag(n, "sym:overloaded"); if (is_overloaded && state.global(FUNCTION_DISPATCHERS) == 0) { @@ -787,14 +789,14 @@ int JSEmitter::enterVariable(Node *n) { state.variable(true); state.variable(NAME, Swig_scopename_last(Getattr(n, "name"))); - + if(Equal(Getattr(n, "storage"), "static")) { SetFlag(state.variable(), IS_STATIC); } if (!Language::instance()->is_assignable(n) // FIXME: test "arrays_global" does not compile with that as it is not allowed to assign to char[] - // probably some error in char[] typemap + // probably some error in char[] typemap || Equal(Getattr(n, "type"), "a().char")) { SetFlag(state.variable(), IS_IMMUTABLE); } @@ -803,11 +805,11 @@ int JSEmitter::enterVariable(Node *n) { } int JSEmitter::emitCtor(Node *n) { - + Wrapper *wrapper = NewWrapper(); bool is_overloaded = GetFlag(n, "sym:overloaded"); - + Template t_ctor(getTemplate("js_ctor")); //String *mangled_name = SwigType_manglestr(Getattr(n, "name")); @@ -831,6 +833,9 @@ int JSEmitter::emitCtor(Node *n) { marshalInputArgs(n, params, wrapper, Ctor, true, false); Printv(wrapper->code, action, "\n", 0); + + emitCleanupCode(wrapper, params); + t_ctor.replace(T_WRAPPER, wrap_name) .replace(T_TYPE_MANGLED, state.clazz(TYPE_MANGLED)) .replace(T_LOCALS, wrapper->locals) @@ -842,7 +847,7 @@ int JSEmitter::emitCtor(Node *n) { t_ctor_case.replace(T_WRAPPER, wrap_name) .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)); Append(state.clazz(CTOR_DISPATCHERS), t_ctor_case.str()); - + DelWrapper(wrapper); // create a dispatching ctor @@ -874,7 +879,7 @@ int JSEmitter::emitDtor(Node *n) { String *free = NewString(""); // HACK: this is only for the v8 emitter. maybe set an attribute wrap:action of node - // TODO: generate dtors more similar to other wrappers + // TODO: generate dtors more similar to other wrappers if(SwigType_isarray(type)) { Printf(free, "delete [] (%s)", ctype); } else { @@ -891,14 +896,14 @@ int JSEmitter::emitDtor(Node *n) { Delete(p_classtype); Delete(ctype); Delete(free); - + return SWIG_OK; } int JSEmitter::emitGetter(Node *n, bool is_member, bool is_static) { Wrapper *wrapper = NewWrapper(); Template t_getter(getTemplate("js_getter")); - + // prepare wrapper name String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); Setattr(n, "wrap:name", wrap_name); @@ -914,6 +919,8 @@ int JSEmitter::emitGetter(Node *n, bool is_member, bool is_static) { marshalInputArgs(n, params, wrapper, Getter, is_member, is_static); marshalOutput(n, wrapper, action); + emitCleanupCode(wrapper, params); + t_getter.replace(T_WRAPPER, wrap_name) .replace(T_LOCALS, wrapper->locals) .replace(T_CODE, wrapper->code) @@ -930,7 +937,7 @@ int JSEmitter::emitSetter(Node *n, bool is_member, bool is_static) { if (State::IsSet(state.variable(IS_IMMUTABLE))) { return SWIG_OK; } - + Wrapper *wrapper = NewWrapper(); Template t_setter(getTemplate("js_setter")); @@ -950,6 +957,8 @@ int JSEmitter::emitSetter(Node *n, bool is_member, bool is_static) { marshalInputArgs(n, params, wrapper, Setter, is_member, is_static); Append(wrapper->code, action); + emitCleanupCode(wrapper, params); + t_setter.replace(T_WRAPPER, wrap_name) .replace(T_LOCALS, wrapper->locals) .replace(T_CODE, wrapper->code) @@ -967,7 +976,7 @@ int JSEmitter::emitSetter(Node *n, bool is_member, bool is_static) { int JSEmitter::emitConstant(Node *n) { Wrapper *wrapper = NewWrapper(); - + Template t_getter(getTemplate("js_getter")); // call the variable methods as a constants are @@ -1002,8 +1011,8 @@ int JSEmitter::emitConstant(Node *n) { } int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { - - Wrapper *wrapper = NewWrapper(); + + Wrapper *wrapper = NewWrapper(); Template t_function(getTemplate("js_function")); bool is_overloaded = GetFlag(n, "sym:overloaded"); @@ -1027,6 +1036,8 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { marshalInputArgs(n, params, wrapper, Function, is_member, is_static); marshalOutput(n, wrapper, action); + emitCleanupCode(wrapper, params); + t_function.replace(T_WRAPPER, wrap_name) .replace(T_LOCALS, wrapper->locals) .replace(T_CODE, wrapper->code) @@ -1040,7 +1051,7 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)); Append(state.global(FUNCTION_DISPATCHERS), t_dispatch_case.str()); } - + DelWrapper(wrapper); return SWIG_OK; @@ -1058,7 +1069,7 @@ int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { t_function.replace(T_LOCALS, wrapper->locals) .replace(T_CODE, wrapper->code); - + // call this here, to replace all variables t_function.replace(T_WRAPPER, wrap_name) .replace(T_NAME, state.function(NAME)) @@ -1074,7 +1085,7 @@ int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { void JSEmitter::registerProxyType(SwigType* type) { SwigType *ftype = SwigType_typedef_resolve_all(type); if(Language::instance()->classLookup(ftype)) return; - + // TODO: confused... more try and error... understand and fix eventually SwigType *p_ftype = SwigType_add_pointer(ftype); @@ -1140,8 +1151,24 @@ void JSEmitter::marshalOutput(Node *n, Wrapper *wrapper, String *actioncode, co } } +void JSEmitter::emitCleanupCode(Wrapper *wrapper, ParmList *params) { + Parm *p; + String *tm; + + for (p = params; p;) { + if ((tm = Getattr(p, "tmap:freearg"))) { + //addThrows(n, "tmap:freearg", p); + Replaceall(tm, "$input", Getattr(p, "emit:input")); + Printv(wrapper->code, tm, "\n", NIL); + p = Getattr(p, "tmap:freearg:next"); + } else { + p = nextSibling(p); + } + } +} + int JSEmitter::switchNamespace(Node *n) { - + if (!GetFlag(n, "feature:nspace")) { current_namespace = Getattr(namespaces, "::"); } else { @@ -1188,7 +1215,7 @@ Hash *JSEmitter::createNamespaceEntry(const char *_name, const char *parent) { Setattr(entry, NAME, Swig_scopename_last(name)); Setattr(entry, NAME_MANGLED, Swig_name_mangle(name)); Setattr(entry, PARENT, NewString(parent)); - + Delete(name); return entry; } @@ -1196,7 +1223,7 @@ Hash *JSEmitter::createNamespaceEntry(const char *_name, const char *parent) { /********************************************************************** * JavascriptCore: JSEmitter implementation for JavascriptCore engine **********************************************************************/ - + class JSCEmitter:public JSEmitter { public: @@ -1259,13 +1286,13 @@ private: #define STATIC_VARIABLES "static_variables" JSCEmitter::JSCEmitter() -: JSEmitter(), +: JSEmitter(), NULL_STR(NewString("NULL")), VETO_SET(NewString("JS_veto_set_variable")), GLOBAL_STR(NULL), f_wrap_cpp(NULL), - f_runtime(NULL), - f_header(NULL), + f_runtime(NULL), + f_header(NULL), f_init(NULL) { } @@ -1332,7 +1359,7 @@ void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Ma } int JSCEmitter::initialize(Node *n) { - + JSEmitter::initialize(n); /* Get the output file name */ @@ -1464,7 +1491,7 @@ int JSCEmitter::exitVariable(Node *n) { .replace(T_SETTER, state.variable(SETTER)); if (GetFlag(n, "ismember")) { - if (GetFlag(state.function(), IS_STATIC) + if (GetFlag(state.function(), IS_STATIC) || Equal(Getattr(n, "nodeType"), "enumitem")) { Append(state.clazz(STATIC_VARIABLES), t_variable.str()); } else { @@ -1589,7 +1616,7 @@ JSEmitter *swig_javascript_create_JSCEmitter() { **********************************************************************/ class V8Emitter: public JSEmitter { - + public: V8Emitter(); @@ -1616,10 +1643,10 @@ private: String *f_runtime; String *f_header; String *f_init; - + /* part for class templates */ String *f_class_templates; - + /* parts for initilizer */ String *f_init_namespaces; String *f_init_class_templates; @@ -1629,18 +1656,18 @@ private: String *f_init_static_wrappers; String *f_init_register_classes; String *f_init_register_namespaces; - + // the output cpp file File *f_wrap_cpp; - + String* GLOBAL; String* NULL_STR; String *VETO_SET; }; -V8Emitter::V8Emitter() -: JSEmitter(), +V8Emitter::V8Emitter() +: JSEmitter(), GLOBAL(NewString("global")), NULL_STR(NewString("0")), VETO_SET(NewString("JS_veto_set_variable")) @@ -1657,7 +1684,7 @@ V8Emitter::~V8Emitter() int V8Emitter::initialize(Node *n) { JSEmitter::initialize(n); - + // Get the output file name String *outfile = Getattr(n,"outfile"); f_wrap_cpp = NewFile(outfile, "w", SWIG_output_files()); @@ -1670,7 +1697,7 @@ int V8Emitter::initialize(Node *n) f_header = NewString(""); f_class_templates = NewString(""); f_init = NewString(""); - + f_init_namespaces = NewString(""); f_init_class_templates = NewString(""); f_init_wrappers = NewString(""); @@ -1739,19 +1766,19 @@ int V8Emitter::close() Delete(f_init_class_instances); Delete(f_init_static_wrappers); Delete(f_init_register_classes); - Delete(f_init_register_namespaces); - + Delete(f_init_register_namespaces); + // files Close(f_wrap_cpp); Delete(f_wrap_cpp); - + return SWIG_OK; } int V8Emitter::enterClass(Node *n) { JSEmitter::enterClass(n); - + // emit declaration of a v8 class template Template t_decl_class(getTemplate("jsv8_declare_class_template")); t_decl_class.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) @@ -1774,7 +1801,7 @@ int V8Emitter::exitClass(Node *n) String *clientData = NewString(""); Printf(clientData, "&%s_clientData", state.clazz(NAME_MANGLED)); SwigType_remember_clientdata(state.clazz(TYPE_MANGLED), clientData); - + // emit definition of v8 class template String *p_classtype = state.clazz(TYPE); String *p_classtype_str = SwigType_manglestr(p_classtype); @@ -1792,7 +1819,7 @@ int V8Emitter::exitClass(Node *n) .replace(T_CTOR, state.clazz(CTOR)) .trim() .pretty_print(f_init_class_instances); - + // emit inheritance setup Node* baseClass = getBaseClass(n); if(baseClass) { @@ -1804,7 +1831,7 @@ int V8Emitter::exitClass(Node *n) .pretty_print(f_init_inheritance); Delete(base_name_mangled); } - + // emit registeration of class template Template t_register = getTemplate("jsv8_register_class"); t_register.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) @@ -1812,14 +1839,14 @@ int V8Emitter::exitClass(Node *n) .replace(T_PARENT, Getattr(current_namespace, "name_mangled")) .trim() .pretty_print(f_init_register_classes); - + return SWIG_OK; } int V8Emitter::enterVariable(Node* n) { JSEmitter::enterVariable(n); - + state.variable(GETTER, NULL_STR); state.variable(SETTER, VETO_SET); @@ -1848,7 +1875,7 @@ int V8Emitter::exitVariable(Node* n) } } else { // Note: a global variable is treated like a static variable - // with the parent being a nspace object (instead of class object) + // with the parent being a nspace object (instead of class object) Template t_register = getTemplate("jsv8_register_static_variable"); t_register.replace(T_PARENT, Getattr(current_namespace, NAME)) .replace(T_NAME, state.variable(NAME)) @@ -1864,7 +1891,7 @@ int V8Emitter::exitVariable(Node* n) int V8Emitter::exitFunction(Node* n) { bool is_member = GetFlag(n, "ismember"); - + // create a dispatcher for overloaded functions bool is_overloaded = GetFlag(n, "sym:overloaded"); if (is_overloaded) { @@ -1876,7 +1903,7 @@ int V8Emitter::exitFunction(Node* n) return SWIG_OK; } } - + // register the function at the specific context if(is_member) { if(GetFlag(state.function(), IS_STATIC)) { @@ -1896,7 +1923,7 @@ int V8Emitter::exitFunction(Node* n) } } else { // Note: a global function is treated like a static function - // with the parent being a nspace object instead of class object + // with the parent being a nspace object instead of class object Template t_register = getTemplate("jsv8_register_static_function"); t_register.replace(T_PARENT, Getattr(current_namespace, NAME)) .replace(T_NAME, state.function(NAME)) @@ -1978,11 +2005,11 @@ int V8Emitter::emitNamespaces() { .replace(T_NAME, name) .replace(T_PARENT, parent_mangled) .trim(); - + // prepend in order to achieve reversed order of registration statements Insert(f_init_register_namespaces, 0, t_register_ns.str()); - } - + } + return SWIG_OK; } @@ -2015,7 +2042,7 @@ void V8Emitter::emitUndefined() { .replace(T_FREE, free) .trim() .pretty_print(f_wrappers); - + // create a class template and initialize clientData Template clientDataDef = getTemplate("jsv8_define_class_template"); clientDataDef.replace(T_NAME_MANGLED, mangled_name) @@ -2030,7 +2057,7 @@ void V8Emitter::emitUndefined() { Delete(free); Delete(ctype); - } + } } JSEmitter *swig_javascript_create_V8Emitter() { @@ -2042,8 +2069,8 @@ JSEmitter *swig_javascript_create_V8Emitter() { * Helper implementations **********************************************************************/ -JSEmitterState::JSEmitterState() - : _global(NewHash()) +JSEmitterState::JSEmitterState() + : _global(NewHash()) { // initialize sub-hashes Setattr(_global, "class", NewHash()); @@ -2051,12 +2078,12 @@ JSEmitterState::JSEmitterState() Setattr(_global, "variable", NewHash()); } -JSEmitterState::~JSEmitterState() -{ +JSEmitterState::~JSEmitterState() +{ Delete(_global); } - -DOH *JSEmitterState::getState(const char* key, bool _new) + +DOH *JSEmitterState::getState(const char* key, bool _new) { if (_new) { Hash *hash = NewHash(); @@ -2064,7 +2091,7 @@ DOH *JSEmitterState::getState(const char* key, bool _new) } return Getattr(_global, key); } - + DOH *JSEmitterState::global() { return _global; } @@ -2081,7 +2108,7 @@ DOH *JSEmitterState::clazz(bool _new) { return getState("class", _new); } - + DOH *JSEmitterState::clazz(const char* key, DOH *initial) { DOH *c = clazz(); @@ -2110,7 +2137,7 @@ DOH *JSEmitterState::variable(bool _new) return getState("variable", _new); } -DOH *JSEmitterState::variable(const char* key, DOH *initial) +DOH *JSEmitterState::variable(const char* key, DOH *initial) { DOH *v = variable(); if(initial != 0) { @@ -2118,9 +2145,9 @@ DOH *JSEmitterState::variable(const char* key, DOH *initial) } return Getattr(v, key); } - + /*static*/ -int JSEmitterState::IsSet(DOH *val) +int JSEmitterState::IsSet(DOH *val) { if (!val) { return 0; @@ -2213,7 +2240,7 @@ Template& Template::trim() { char* newstr = new char[new_length+1]; memcpy(newstr, str+start_pos, new_length); newstr[new_length] = 0; - + Delete(code); code = NewString(newstr); delete[] newstr; @@ -2223,9 +2250,9 @@ Template& Template::trim() { /* ----------------------------------------------------------------------------- * Template& Template::replace(const String* pattern, const String* repl) : - * + * * replaces all occurences of a given pattern with a given replacement. - * + * * - pattern: the pattern to be replaced * - repl: the replacement string * - returns a reference to the Template to allow chaining of methods. From 058a27bf32c6fc082c3753af3aaffb1ab4d85e83 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 17 Nov 2012 02:12:12 +0100 Subject: [PATCH 0214/1048] Simplify creation of a Javascript shell. --- Tools/javascript/javascript.cxx | 31 +++++------------------- Tools/javascript/js_shell.h | 12 ++++++---- Tools/javascript/jsc_shell.cxx | 38 ++++++++++++++--------------- Tools/javascript/v8_shell.cxx | 42 ++++++++++++++++----------------- 4 files changed, 53 insertions(+), 70 deletions(-) diff --git a/Tools/javascript/javascript.cxx b/Tools/javascript/javascript.cxx index 798158ff0..a1e6c9984 100644 --- a/Tools/javascript/javascript.cxx +++ b/Tools/javascript/javascript.cxx @@ -7,14 +7,6 @@ #include "js_shell.h" -#ifdef USE_JSC -extern JSShell* create_jsc_shell(); -#endif - -#ifdef USE_V8 -extern JSShell* create_v8_shell(); -#endif - void print_usage() { std::cout << "javascript [-i] [-jsc|-v8] [-l module] " << std::endl; } @@ -37,16 +29,12 @@ int main(int argc, char* argv[]) { std::string module_name(argv[idx]); module_names.push_back(module_name); } else if(strcmp(argv[idx], "-v8") == 0) { -#ifdef USE_V8 - shell = create_v8_shell(); -#else +#ifndef USE_V8 std::cerr << "V8 support is not enabled" << std::endl; exit(-1); #endif } else if(strcmp(argv[idx], "-jsc") == 0) { -#ifdef USE_JSC - shell = create_jsc_shell(); -#else +#ifndef USE_JSC std::cerr << "JSC support is not enabled" << std::endl; exit(-1); #endif @@ -56,16 +44,9 @@ int main(int argc, char* argv[]) { scriptPath = argv[idx]; } } - - if (shell == 0) { -#ifdef USE_JSC - shell = create_jsc_shell(); -#else - std::cerr << "JSC support is not enabled" << std::endl; - exit(-1); -#endif - } - + + shell = JSShell::Create(); + bool failed = false; for(std::vector::iterator it = module_names.begin(); it != module_names.end(); ++it) { @@ -94,6 +75,6 @@ int main(int argc, char* argv[]) { } delete shell; - + return 0; } diff --git a/Tools/javascript/js_shell.h b/Tools/javascript/js_shell.h index 96535a4c0..830873f0d 100644 --- a/Tools/javascript/js_shell.h +++ b/Tools/javascript/js_shell.h @@ -18,10 +18,12 @@ public: JSShell() {} - virtual ~JSShell(); - + virtual ~JSShell() = 0; + + static JSShell* Create(); + bool ImportModule(const std::string& name); - + virtual bool RunScript(const std::string& scriptPath); virtual bool RunShell(); @@ -31,7 +33,7 @@ protected: virtual bool RegisterModule(HANDLE library, const std::string& module_name) = 0; virtual bool InitializeEngine() = 0; - + virtual bool ExecuteScript(const std::string& source, const std::string& name) = 0; virtual bool DisposeEngine() = 0; @@ -39,7 +41,7 @@ protected: static std::string ReadFile(const std::string& fileName); protected: - + std::vector loaded_modules; }; diff --git a/Tools/javascript/jsc_shell.cxx b/Tools/javascript/jsc_shell.cxx index a21fb3f1a..c069b5c65 100644 --- a/Tools/javascript/jsc_shell.cxx +++ b/Tools/javascript/jsc_shell.cxx @@ -19,7 +19,7 @@ typedef int (*JSCIntializer)(JSGlobalContextRef context); public: JSCShell() {}; - + virtual ~JSCShell(); protected: @@ -27,14 +27,14 @@ protected: virtual bool RegisterModule(HANDLE library, const std::string& module_name); virtual bool InitializeEngine(); - + virtual bool ExecuteScript(const std::string& source, const std::string& name); virtual bool DisposeEngine(); private: - static JSValueRef Print(JSContextRef context,JSObjectRef object, JSObjectRef globalobj, size_t argc, const JSValueRef args[], JSValueRef* ex); + static JSValueRef Print(JSContextRef context,JSObjectRef object, JSObjectRef globalobj, size_t argc, const JSValueRef args[], JSValueRef* ex); static bool RegisterFunction(JSGlobalContextRef context, JSObjectRef object, const char* functionName, JSObjectCallAsFunctionCallback cbFunction); @@ -43,7 +43,7 @@ private: private: std::vector module_initializers; - + JSGlobalContextRef context; }; @@ -56,7 +56,7 @@ JSCShell::~JSCShell() { bool JSCShell::RegisterModule(HANDLE library, const std::string& module_name) { std::string symname = std::string(module_name).append("_initialize"); - + JSCIntializer init_function = reinterpret_cast((long) LOAD_SYMBOL(library, symname.c_str())); if(init_function == 0) return false; @@ -64,7 +64,7 @@ bool JSCShell::RegisterModule(HANDLE library, const std::string& module_name) { return true; } -bool JSCShell::InitializeEngine() { +bool JSCShell::InitializeEngine() { if(context != 0) { JSGlobalContextRelease(context); context = 0; @@ -81,7 +81,7 @@ bool JSCShell::InitializeEngine() { if(!init_function(context)) { return false; } - } + } return true; } @@ -104,9 +104,9 @@ bool JSCShell::DisposeEngine() { return true; } -JSValueRef JSCShell::Print(JSContextRef context, JSObjectRef object, - JSObjectRef globalobj, size_t argc, - const JSValueRef args[], JSValueRef* ex) { +JSValueRef JSCShell::Print(JSContextRef context, JSObjectRef object, + JSObjectRef globalobj, size_t argc, + const JSValueRef args[], JSValueRef* ex) { if (argc > 0) { JSStringRef string = JSValueToStringCopy(context, args[0], NULL); @@ -114,18 +114,18 @@ JSValueRef JSCShell::Print(JSContextRef context, JSObjectRef object, char *stringUTF8 = new char[numChars]; JSStringGetUTF8CString(string, stringUTF8, numChars); printf("%s\n", stringUTF8); - + delete[] stringUTF8; } - + return JSValueMakeUndefined(context); } -bool JSCShell::RegisterFunction(JSGlobalContextRef context, JSObjectRef object, +bool JSCShell::RegisterFunction(JSGlobalContextRef context, JSObjectRef object, const char* functionName, JSObjectCallAsFunctionCallback callback) { JSStringRef js_functionName = JSStringCreateWithUTF8CString(functionName); JSObjectSetProperty(context, object, js_functionName, - JSObjectMakeFunctionWithCallback(context, js_functionName, callback), + JSObjectMakeFunctionWithCallback(context, js_functionName, callback), kJSPropertyAttributeNone, NULL); JSStringRelease(js_functionName); return true; @@ -133,10 +133,10 @@ bool JSCShell::RegisterFunction(JSGlobalContextRef context, JSObjectRef object, void JSCShell::PrintError(JSContextRef ctx, JSValueRef err, const std::string& name) { char *buffer; - + JSStringRef string = JSValueToStringCopy(ctx, err, 0); size_t length = JSStringGetLength(string); - + buffer = new char[length+1]; JSStringGetUTF8CString(string, buffer, length+1); std::string errMsg(buffer); @@ -144,7 +144,7 @@ void JSCShell::PrintError(JSContextRef ctx, JSValueRef err, const std::string& n delete[] buffer; JSObjectRef errObj = JSValueToObject(ctx, err, 0); - + if(errObj == 0) { std::cerr << errMsg << std::endl; return; @@ -154,12 +154,12 @@ void JSCShell::PrintError(JSContextRef ctx, JSValueRef err, const std::string& n // though, it happened that this was always "" JSStringRef lineKey = JSStringCreateWithUTF8CString("line"); JSValueRef jsLine = JSObjectGetProperty(ctx, errObj, lineKey, 0); - int line = (int) JSValueToNumber(ctx, jsLine, 0); + int line = (int) JSValueToNumber(ctx, jsLine, 0); JSStringRelease(lineKey); std::cerr << name << ":" << line << ":" << errMsg << std::endl; } -JSShell* create_jsc_shell() { +JSShell* JSShell::Create() { return new JSCShell(); } diff --git a/Tools/javascript/v8_shell.cxx b/Tools/javascript/v8_shell.cxx index 27923dd86..71960caba 100755 --- a/Tools/javascript/v8_shell.cxx +++ b/Tools/javascript/v8_shell.cxx @@ -15,9 +15,9 @@ class V8Shell: public JSShell { public: V8Shell(); - + virtual ~V8Shell(); - + virtual bool RunScript(const std::string& scriptPath); virtual bool RunShell(); @@ -28,11 +28,11 @@ protected: virtual bool RegisterModule(HANDLE library, const std::string& module_name); virtual bool InitializeEngine(); - + virtual bool ExecuteScript(const std::string& source, const std::string& name); virtual bool DisposeEngine(); - + private: v8::Persistent CreateShellContext(); @@ -46,13 +46,13 @@ private: static v8::Handle Version(const v8::Arguments& args); static const char* ToCString(const v8::String::Utf8Value& value); - + void ExtendEngine(); - + protected: std::vector module_initializers; - + v8::Persistent context; }; @@ -75,7 +75,7 @@ V8Shell::~V8Shell() { bool V8Shell::RegisterModule(HANDLE library, const std::string& module_name) { std::string symname = std::string(module_name).append("_initialize"); - + V8ExtensionRegistrar init_function = reinterpret_cast((long) LOAD_SYMBOL(library, symname.c_str())); if(init_function == 0) return false; @@ -88,10 +88,10 @@ bool V8Shell::RunScript(const std::string& scriptPath) { if (!context.IsEmpty()) { context.Dispose(); } - + std::string source = ReadFile(scriptPath); - context = CreateShellContext(); + context = CreateShellContext(); if (context.IsEmpty()) { printf("Could not create context.\n"); return false; @@ -104,11 +104,11 @@ bool V8Shell::RunScript(const std::string& scriptPath) { if(!ExecuteScript(source, scriptPath)) { return false; } - + context->Exit(); context.Dispose(); v8::V8::Dispose(); - + return true; } @@ -117,18 +117,18 @@ bool V8Shell::RunShell() { if (!context.IsEmpty()) { context.Dispose(); } - - context = CreateShellContext(); + + context = CreateShellContext(); if (context.IsEmpty()) { printf("Could not create context.\n"); return false; } - + context->Enter(); v8::Context::Scope context_scope(context); ExtendEngine(); - + static const int kBufferSize = 1024; while (true) { char buffer[kBufferSize]; @@ -152,13 +152,13 @@ bool V8Shell::InitializeEngine() { } void V8Shell::ExtendEngine() { - + // register extensions for(std::vector::iterator it=module_initializers.begin(); it != module_initializers.end(); ++it) { (*it)(context); } - + } bool V8Shell::ExecuteScript(const std::string& source, const std::string& name) { @@ -195,7 +195,7 @@ bool V8Shell::DisposeEngine() { v8::Persistent V8Shell::CreateShellContext() { v8::HandleScope scope; - + // Create a template for the global object. v8::Handle global = v8::ObjectTemplate::New(); @@ -205,7 +205,7 @@ v8::Persistent V8Shell::CreateShellContext() { global->Set(v8::String::New("version"), v8::FunctionTemplate::New(V8Shell::Version)); v8::Persistent _context = v8::Context::New(NULL, global); - + return _context; } @@ -282,6 +282,6 @@ const char* V8Shell::ToCString(const v8::String::Utf8Value& value) { return *value ? *value : ""; } -JSShell* create_v8_shell() { +JSShell* JSShell::Create() { return new V8Shell(); } From 6754bf2b49862211eb67bc2a31ce79ae31de9034 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 17 Nov 2012 03:41:22 +0100 Subject: [PATCH 0215/1048] Generate cleanup code for %newobject. --- Source/Modules/javascript.cxx | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index d43af979d..90300a24f 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -272,7 +272,7 @@ protected: virtual void marshalOutput(Node *n, Wrapper *wrapper, String *actioncode, const String *cresult=0, bool emitReturnVariable = true); - virtual void emitCleanupCode(Wrapper *wrapper, ParmList *params); + virtual void emitCleanupCode(Node *n, Wrapper *wrapper, ParmList *params); void registerProxyType(SwigType* type); @@ -834,7 +834,7 @@ int JSEmitter::emitCtor(Node *n) { Printv(wrapper->code, action, "\n", 0); - emitCleanupCode(wrapper, params); + emitCleanupCode(n, wrapper, params); t_ctor.replace(T_WRAPPER, wrap_name) .replace(T_TYPE_MANGLED, state.clazz(TYPE_MANGLED)) @@ -919,7 +919,7 @@ int JSEmitter::emitGetter(Node *n, bool is_member, bool is_static) { marshalInputArgs(n, params, wrapper, Getter, is_member, is_static); marshalOutput(n, wrapper, action); - emitCleanupCode(wrapper, params); + emitCleanupCode(n, wrapper, params); t_getter.replace(T_WRAPPER, wrap_name) .replace(T_LOCALS, wrapper->locals) @@ -957,7 +957,7 @@ int JSEmitter::emitSetter(Node *n, bool is_member, bool is_static) { marshalInputArgs(n, params, wrapper, Setter, is_member, is_static); Append(wrapper->code, action); - emitCleanupCode(wrapper, params); + emitCleanupCode(n, wrapper, params); t_setter.replace(T_WRAPPER, wrap_name) .replace(T_LOCALS, wrapper->locals) @@ -1036,7 +1036,7 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { marshalInputArgs(n, params, wrapper, Function, is_member, is_static); marshalOutput(n, wrapper, action); - emitCleanupCode(wrapper, params); + emitCleanupCode(n, wrapper, params); t_function.replace(T_WRAPPER, wrap_name) .replace(T_LOCALS, wrapper->locals) @@ -1151,7 +1151,7 @@ void JSEmitter::marshalOutput(Node *n, Wrapper *wrapper, String *actioncode, co } } -void JSEmitter::emitCleanupCode(Wrapper *wrapper, ParmList *params) { +void JSEmitter::emitCleanupCode(Node *n, Wrapper *wrapper, ParmList *params) { Parm *p; String *tm; @@ -1165,6 +1165,15 @@ void JSEmitter::emitCleanupCode(Wrapper *wrapper, ParmList *params) { p = nextSibling(p); } } + + if (GetFlag(n, "feature:new")) { + tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0); + if (tm != NIL) { + //addThrows(throws_hash, "newfree", n); + Printv(wrapper->code, tm, "\n", NIL); + } + } + } int JSEmitter::switchNamespace(Node *n) { From 008adca72f5917d8a80cc252572f0b1e80ed4e69 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Thu, 22 Nov 2012 22:50:50 +0100 Subject: [PATCH 0216/1048] Provide more control about the target object/namespace where a v8 module is registered to. --- Lib/javascript/v8/javascriptcode.swg | 3 +-- Tools/javascript/v8_shell.cxx | 7 +++++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index eb95cb1bf..1b196cffd 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -386,12 +386,11 @@ fail: %{ extern "C" { -void $jsname_initialize(v8::Handle context) +void $jsname_initialize(v8::Handle context, v8::Handle global_obj) { SWIG_InitializeModule(0); v8::HandleScope scope; - v8::Local global_obj = context->Global(); // a class template for creating proxies of undefined types SWIGV8_SWIGTYPE_Proxy_class_templ = SWIGV8_CreateClassTemplate("SwigProxy"); diff --git a/Tools/javascript/v8_shell.cxx b/Tools/javascript/v8_shell.cxx index 71960caba..8b45ac0d6 100755 --- a/Tools/javascript/v8_shell.cxx +++ b/Tools/javascript/v8_shell.cxx @@ -9,7 +9,7 @@ #include "js_shell.h" -typedef int (*V8ExtensionRegistrar) (v8::Handle); +typedef int (*V8ExtensionRegistrar) (v8::Handle, v8::Handle); class V8Shell: public JSShell { @@ -153,10 +153,13 @@ bool V8Shell::InitializeEngine() { void V8Shell::ExtendEngine() { + v8::HandleScope scope; + v8::Local global = context->Global(); + // register extensions for(std::vector::iterator it=module_initializers.begin(); it != module_initializers.end(); ++it) { - (*it)(context); + (*it)(context, global); } } From caa6827dafc4cc5b0ea3b8c16922905c46bbbf29 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 23 Nov 2012 01:09:11 +0100 Subject: [PATCH 0217/1048] Javascript interpreter supports for JSC and V8 simultaneously. Before, one had to build two different versions. --- Tools/javascript/javascript.cxx | 14 +++++--------- Tools/javascript/js_shell.cxx | 31 +++++++++++++++++++++++++++++++ Tools/javascript/js_shell.h | 6 ++---- Tools/javascript/jsc_shell.cxx | 2 +- Tools/javascript/v8_shell.cxx | 2 +- 5 files changed, 40 insertions(+), 15 deletions(-) diff --git a/Tools/javascript/javascript.cxx b/Tools/javascript/javascript.cxx index a1e6c9984..82e94f434 100644 --- a/Tools/javascript/javascript.cxx +++ b/Tools/javascript/javascript.cxx @@ -29,15 +29,9 @@ int main(int argc, char* argv[]) { std::string module_name(argv[idx]); module_names.push_back(module_name); } else if(strcmp(argv[idx], "-v8") == 0) { -#ifndef USE_V8 - std::cerr << "V8 support is not enabled" << std::endl; - exit(-1); -#endif + shell = JSShell::Create(JSShell::V8); } else if(strcmp(argv[idx], "-jsc") == 0) { -#ifndef USE_JSC - std::cerr << "JSC support is not enabled" << std::endl; - exit(-1); -#endif + shell = JSShell::Create(JSShell::JSC); } else if(strcmp(argv[idx], "-i") == 0) { interactive = true; } else { @@ -45,7 +39,9 @@ int main(int argc, char* argv[]) { } } - shell = JSShell::Create(); + if (shell == 0) { + shell = JSShell::Create(); + } bool failed = false; for(std::vector::iterator it = module_names.begin(); diff --git a/Tools/javascript/js_shell.cxx b/Tools/javascript/js_shell.cxx index b2b8672a6..8762fbff5 100644 --- a/Tools/javascript/js_shell.cxx +++ b/Tools/javascript/js_shell.cxx @@ -15,6 +15,8 @@ #error "implement dll loading" #endif + + JSShell::~JSShell() { for(std::vector::iterator it = loaded_modules.begin(); @@ -93,3 +95,32 @@ std::string JSShell::ReadFile(const std::string& fileName) return script; } + +#ifdef ENABLE_JSC +extern JSShell* JSCShell_Create(); +#endif +#ifdef ENABLE_V8 +extern JSShell* V8Shell_Create(); +#endif + +typedef JSShell*(*ShellFactory)(); + +static ShellFactory js_shell_factories[2] = { +#ifdef ENABLE_JSC +JSCShell_Create, +#else +0, +#endif +#ifdef ENABLE_V8 +V8Shell_Create, +#else +0, +#endif +}; + +JSShell *JSShell::Create(Engine engine) { + if(js_shell_factories[engine] == 0) { + throw "Engine not supported."; + } + return js_shell_factories[engine](); +} diff --git a/Tools/javascript/js_shell.h b/Tools/javascript/js_shell.h index 830873f0d..54f55b69d 100644 --- a/Tools/javascript/js_shell.h +++ b/Tools/javascript/js_shell.h @@ -10,7 +10,7 @@ class JSShell { public: enum Engine { - JSC, + JSC = 0, V8 }; @@ -20,7 +20,7 @@ public: virtual ~JSShell() = 0; - static JSShell* Create(); + static JSShell* Create(Engine engine = JSC); bool ImportModule(const std::string& name); @@ -46,6 +46,4 @@ protected: }; -typedef JSShell* (*JSShellFactory)(); - #endif // JS_SHELL_H diff --git a/Tools/javascript/jsc_shell.cxx b/Tools/javascript/jsc_shell.cxx index c069b5c65..ee95e04a5 100644 --- a/Tools/javascript/jsc_shell.cxx +++ b/Tools/javascript/jsc_shell.cxx @@ -160,6 +160,6 @@ void JSCShell::PrintError(JSContextRef ctx, JSValueRef err, const std::string& n std::cerr << name << ":" << line << ":" << errMsg << std::endl; } -JSShell* JSShell::Create() { +JSShell* JSCShell_Create() { return new JSCShell(); } diff --git a/Tools/javascript/v8_shell.cxx b/Tools/javascript/v8_shell.cxx index 8b45ac0d6..0055bad98 100755 --- a/Tools/javascript/v8_shell.cxx +++ b/Tools/javascript/v8_shell.cxx @@ -285,6 +285,6 @@ const char* V8Shell::ToCString(const v8::String::Utf8Value& value) { return *value ? *value : ""; } -JSShell* JSShell::Create() { +JSShell* V8Shell_Create() { return new V8Shell(); } From bad64925eddf9f78b5bddd6fe559973c51b7f59f Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 23 Nov 2012 01:59:54 +0100 Subject: [PATCH 0218/1048] Configuration is now easier for building and running examples and tests using v8. --- Examples/Makefile.in | 50 +++++++++++++++++++++++++++----------------- configure.in | 22 ++++++++++++------- 2 files changed, 45 insertions(+), 27 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index bf9fe5cd8..803c7fa9a 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -520,19 +520,8 @@ java_clean: # You need to set this variable to the jscore[or other javascript engine] directories containing the # files "JavaScript.h" and others -ifeq (,$(V8)) - JS_INCLUDE = @JSCOREINC@ - JS_DLNK = @JSCOREDYNAMICLINKING@ -else - JS_INCLUDE = @JSV8INC@ - JS_DLNK = @JSV8DYNAMICLINKING@ -endif - -ifeq (,$(V8)) - SWIGJS = $(SWIG) -javascript -jsc -else - SWIGJS = $(SWIG) -javascript -v8 -endif +JS_INCLUDE = @JSCOREINC@ @JSV8INC@ +JS_DLNK = @JSCOREDYNAMICLINKING@ @JSV8DYNAMICLINKING@ # Extra JAVASCRIPT specific dynamic linking options JS_LIBPREFIX = @JSCORELIBRARYPREFIX@ @@ -541,17 +530,40 @@ JSLDSHARED = @JSCORELDSHARED@ JSCXXSHARED = @JSCORECXXSHARED@ JSCFLAGS = @JSCORECFLAGS@ JSCXXFLAGS = @JSCXXFLAGS@ +ROOT_DIR = @ROOT_DIR@ +JSCORE = @JSCORE@ +JSV8 = @JSV8@ +JSDEFAULT = @JSDEFAULT@ -JSEXE_SRC_DIR = $(TOP)/../Tools/javascript +JSEXE_SRC_DIR = $(ROOT_DIR)/Tools/javascript JSEXE = $(JSEXE_SRC_DIR)/javascript -ifeq (,$(V8)) - JSEXE_SRC = $(JSEXE_SRC_DIR)/javascript.cxx $(JSEXE_SRC_DIR)/js_shell.cxx $(JSEXE_SRC_DIR)/jsc_shell.cxx + +ifneq (,$(JSCORE)) + JSEXE_SRC_JSC = $(JSEXE_SRC_DIR)/jsc_shell.cxx + JSEXE_FLAGS_JSC = -DENABLE_JSC +endif + +ifneq (,$(JSV8)) + JSEXE_SRC_V8 = $(JSEXE_SRC_DIR)/v8_shell.cxx + JSEXE_FLAGS_V8 = -DENABLE_V8 +endif + +JSEXE_SRC = $(JSEXE_SRC_DIR)/javascript.cxx $(JSEXE_SRC_DIR)/js_shell.cxx $(JSEXE_SRC_JSC) $(JSEXE_SRC_V8) +JSEXE_FLAGS = $(JSEXE_FLAGS_JSC) $(JSEXE_FLAGS_V8) + +# this controls which engine the code will be generated for +# and correspondingly the argument for the js interpreter +ifneq (,$(JSC)) + SWIGJS = $(SWIG) -javascript -jsc JSEXE_OPTS = -jsc - JSEXE_FLAGS = -DUSE_JSC else - JSEXE_SRC = $(JSEXE_SRC_DIR)/javascript.cxx $(JSEXE_SRC_DIR)/js_shell.cxx $(JSEXE_SRC_DIR)/v8_shell.cxx +ifneq (,$(V8)) + SWIGJS = $(SWIG) -javascript -v8 JSEXE_OPTS = -v8 - JSEXE_FLAGS = -DUSE_V8 +else + SWIGJS = $(SWIG) -javascript -$(JSDEFAULT) + JSEXE_OPTS = -$(JSDEFAULT) +endif endif # ---------------------------------------------------------------- diff --git a/configure.in b/configure.in index 5a00636a2..e4841fc70 100644 --- a/configure.in +++ b/configure.in @@ -1081,12 +1081,13 @@ AC_SUBST(JAVACFLAGS) # Look for JAVASCRIPT [JavaScriptCore Headers and Library] #---------------------------------------------------------------- AC_ARG_WITH(javascript, AS_HELP_STRING([--without-javascript], [Disable JAVASCRIPT]), [with_javascript="$withval"], [with_javascript=yes]) +AC_ARG_VAR(JSDEFAULT, "The default engine to use ( v8 | jsc ).") # First, check for "--without-javascript" or "--with-javascript=no". if test x"${with_javascript}" = xno -o x"${with_alllang}" = xno ; then -AC_MSG_NOTICE([Disabling Javascript]) -JAVASCRIPT= -else + AC_MSG_NOTICE([Disabling Javascript]) + JAVASCRIPT= +fi ### JavascriptCore ### @@ -1120,8 +1121,8 @@ fi # check for JavaScriptCore, Webkit libraries -AC_ARG_WITH(jscorelib,[ --with-jscorelib =path Set location of JavaScriptCore (Webkit) library directory],[ - JSCORELIB="-L$withval"], [JSCORELIB=]) +AC_ARG_WITH(jscorelib,[ --with-jscorelib =path Set location of JavaScriptCore (Webkit) library directory], + [JSCORELIB="-L$withval"], [JSCORELIB=]) AC_MSG_CHECKING(for JavaScriptCore(Webkit) library) if test -z "$JSCORELIB"; then @@ -1149,10 +1150,10 @@ done if test -z "$JSCORELIB"; then AC_MSG_RESULT(not found) -fi - + JSCORE= else -AC_MSG_RESULT($JSCORELIB) + AC_MSG_RESULT($JSCORELIB) + JSCORE=1 fi # linking options @@ -1202,6 +1203,7 @@ case $host in esac fi +AC_SUBST(JSCORE) AC_SUBST(JSCOREINC) AC_SUBST(JSCOREDYNAMICLINKING) AC_SUBST(JSCORELIBRARYPREFIX) @@ -1237,6 +1239,9 @@ done if test "$JSV8INC" = "" ; then AC_MSG_RESULT(not found) + JSV8= +else + JSV8=1 fi @@ -1274,6 +1279,7 @@ esac AC_SUBST(JSV8INC) AC_SUBST(JSV8DYNAMICLINKING) +AC_SUBST(JSDEFAULT) #---------------------------------------------------------------- # Look for gcj From 9d2264456334c88a6b0b74940cc3e96add527325 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Thu, 29 Nov 2012 03:17:27 +0100 Subject: [PATCH 0219/1048] Rename a argument variable to avoid errors with overloaded functions. --- Lib/javascript/jsc/javascriptcode.swg | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index 34245ed14..87a11cecf 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -213,7 +213,7 @@ JSValueRef $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef th * ----------------------------------------------------------------------------- */ %fragment ("js_overloaded_function", "templates") %{ -int $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception, JSValueRef* result) +int $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception, JSValueRef* p_result) { $jslocals JSValueRef jsresult; @@ -221,7 +221,7 @@ int $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObjec if(argc != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); $jscode - *result = jsresult; + *p_result = jsresult; return SWIG_OK; goto fail; From f9d6afbdfef0d3ef3fb0d5a1675a0b1f4d2a5630 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Thu, 29 Nov 2012 03:19:00 +0100 Subject: [PATCH 0220/1048] Add a missing return statement in JS shell. --- Tools/javascript/js_shell.cxx | 1 + 1 file changed, 1 insertion(+) diff --git a/Tools/javascript/js_shell.cxx b/Tools/javascript/js_shell.cxx index 8762fbff5..322ca1cb9 100644 --- a/Tools/javascript/js_shell.cxx +++ b/Tools/javascript/js_shell.cxx @@ -74,6 +74,7 @@ bool JSShell::RunShell() { ExecuteScript(source, "(shell)"); } printf("\n"); + return true; } std::string JSShell::ReadFile(const std::string& fileName) From fb9c4955fb4c39f66ea74dcd714bb34f593b3b40 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Thu, 29 Nov 2012 03:20:49 +0100 Subject: [PATCH 0221/1048] Not a real change: removed some trailing spaces. --- Lib/javascript/jsc/javascriptcode.swg | 52 +++++++++++++-------------- Tools/javascript/js_shell.cxx | 12 +++---- 2 files changed, 32 insertions(+), 32 deletions(-) diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index 87a11cecf..000733ea7 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -14,7 +14,7 @@ JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size_t argc if(argc != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); $jscode - return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); + return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); goto fail; fail: return NULL; @@ -48,13 +48,13 @@ JSObjectRef $jswrapper(JSContextRef context, JSObjectRef ctorObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { JSObjectRef thisObject = NULL; - - // switch all cases by means of series of if-returns. + + // switch all cases by means of series of if-returns. $jsdispatchcases - // default: + // default: SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for contruction of $jsname"); - + fail: return thisObject; } @@ -74,7 +74,7 @@ JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size_t argc { $jslocals $jscode - return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); + return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); goto fail; fail: @@ -87,7 +87,7 @@ JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size_t argc * - $jsargcount: number of arguments of called ctor * - $jswrapper: wrapper of called ctor * - * Note: a try-catch-like mechanism is used to switch cases + * Note: a try-catch-like mechanism is used to switch cases * ----------------------------------------------------------------------------- */ %fragment ("js_ctor_dispatch_case", "templates") %{ @@ -125,13 +125,13 @@ JSValueRef $jswrapper(JSContextRef context, JSObjectRef thisObject, JSStringRef { $jslocals JSValueRef jsresult; - + $jscode return jsresult; goto fail; fail: - return NULL; + return NULL; } %} @@ -147,12 +147,12 @@ bool $jswrapper(JSContextRef context, JSObjectRef thisObject, JSStringRef proper { $jslocals $jscode - + return true; - + goto fail; fail: - return false; + return false; } %} @@ -170,13 +170,13 @@ JSValueRef $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef th JSValueRef jsresult; if(argc != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); - + $jscode return jsresult; - + goto fail; fail: - return NULL; + return NULL; } %} @@ -193,15 +193,15 @@ JSValueRef $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef th { $jslocals JSValueRef jsresult; - int res; + int res; $jscode - + SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function $jsname."); return jsresult; - + goto fail; fail: - return NULL; + return NULL; } %} @@ -219,14 +219,14 @@ int $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObjec JSValueRef jsresult; if(argc != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); - + $jscode *p_result = jsresult; return SWIG_OK; - + goto fail; fail: - return SWIG_TypeError; + return SWIG_TypeError; } %} @@ -260,12 +260,12 @@ bool $jsname_initialize(JSGlobalContextRef context) { SWIG_InitializeModule(0); JSObjectRef global_object = JSContextGetGlobalObject(context); - + /* Initialize the base swig type object */ _SwigObject_objectDefinition.staticFunctions = _SwigObject_functions; _SwigObject_objectDefinition.staticValues = _SwigObject_values; _SwigObject_classRef = JSClassCreate(&_SwigObject_objectDefinition); - + /* Create objects for namespaces */ $jscreatenamespaces @@ -358,7 +358,7 @@ JSStaticFunction $jsmangledname_functions[] = { * - $jsbaseclass: mangled name of base class * ----------------------------------------------------------------------------- */ %fragment ("jsc_class_definition", "templates") -%{ +%{ $jsmangledname_classDefinition.staticFunctions = $jsmangledname_staticFunctions; $jsmangledname_classDefinition.staticValues = $jsmangledname_staticValues; $jsmangledname_classDefinition.callAsConstructor = $jsctor; @@ -407,7 +407,7 @@ JSClassDefinition $jsnspace_classDefinition; * - $jsmangledname: mangled name of namespace * ----------------------------------------------------------------------------- */ %fragment ("jsc_nspace_definition", "templates") -%{ +%{ $jsmangledname_classDefinition.staticFunctions = $jsmangledname_functions; $jsmangledname_classDefinition.staticValues = $jsmangledname_values; JSObjectRef $jsmangledname_object = JSObjectMake(context, JSClassCreate(&$jsmangledname_classDefinition), NULL); diff --git a/Tools/javascript/js_shell.cxx b/Tools/javascript/js_shell.cxx index 322ca1cb9..f0290c785 100644 --- a/Tools/javascript/js_shell.cxx +++ b/Tools/javascript/js_shell.cxx @@ -33,19 +33,19 @@ bool JSShell::ImportModule(const std::string& name) { HANDLE handle = LOAD_LIBRARY(lib_name.c_str()); if(handle == 0) { - std::cout << "Could not load library " << lib_name << ":" + std::cout << "Could not load library " << lib_name << ":" << std::endl << LIBRARY_ERROR() << std::endl; return false; } - + if(!RegisterModule(handle, name)) { std::cout << "Could not find initializer function in " << lib_name << std::endl; CLOSE_LIBRARY(handle); return false; } - loaded_modules.push_back(handle); - + loaded_modules.push_back(handle); + return true; } @@ -56,14 +56,14 @@ bool JSShell::RunScript(const std::string& scriptPath) { if(!ExecuteScript(source, scriptPath)) { return false; } - + return DisposeEngine(); } bool JSShell::RunShell() { if(!InitializeEngine()) return false; - + static const int kBufferSize = 1024; while (true) { char buffer[kBufferSize]; From 7fffd801e410749c37a818b22c5682375c5f9a1b Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 1 Dec 2012 13:21:22 +0100 Subject: [PATCH 0222/1048] Fix std_string.i which generated compile errors in certain cases. --- Lib/javascript/jsc/std_string.i | 73 ++++++++++++++------------------- 1 file changed, 30 insertions(+), 43 deletions(-) diff --git a/Lib/javascript/jsc/std_string.i b/Lib/javascript/jsc/std_string.i index 9fbee75ef..5056b17bf 100755 --- a/Lib/javascript/jsc/std_string.i +++ b/Lib/javascript/jsc/std_string.i @@ -11,6 +11,30 @@ %{ #include + +std::string SWIGJSC_valueToString(JSContextRef context, JSValueRef value) { + JSStringRef jsstring = JSValueToStringCopy(context, value, /* JSValueRef *exception */ 0); + unsigned int length = JSStringGetLength(jsstring); + char *cstr = new char[length+1]; + JSStringGetUTF8CString(jsstring, cstr, length); + + // create a copy + std::string result(cstr); + + JSStringRelease(jsstring); + delete[] cstr; + + return result; +} + +JSValueRef SWIGJSC_stringToValue(JSContextRef context, const std::string& s) +{ + JSValueRef result; + JSStringRef jsstring = JSStringCreateWithUTF8CString(s.c_str()); + result = JSValueMakeString(context, jsstring); + JSStringRelease(jsstring); + return result; +} %} namespace std { @@ -21,51 +45,14 @@ class string; // string -%typemap(in) string -%{ if (!$input) { - // TODO: Throw exception? - return NULL; - } - JSStringRef $1_str = JSValueToStringCopy(context, $input, NULL); - size_t $1_strsize = JSStringGetMaximumUTF8CStringSize($1_str); - char* $1_cstr = (char *)malloc($1_strsize * sizeof(char)); - JSStringGetUTF8CString($1_str, $1_cstr, $1_strsize); - $1 = std::string($1_cstr); +%typemap(in) string, const string& +%{ + $1 = SWIGJSC_valueToString(context, $input); %} -%typemap(out) string %{ - JSStringRef jsstring = JSStringCreateWithUTF8CString($1.c_str()); - $result = JSValueMakeString(context, jsstring); - JSStringRelease(jsstring); +%typemap(out) string, const string& +%{ + $result = SWIGJSC_stringToValue(context, $1); %} -%typemap(freearg) string //TODO: Not working: A memory leak -%{ free($1_cstr); %} - -//%typemap(typecheck) string = char *; - -// const string & -%typemap(in) const string & -%{ if (!$input) { - // TODO: Throw exception? - return NULL; - } - JSStringRef $1_str = JSValueToStringCopy(context, $input, NULL); - size_t $1_strsize = JSStringGetMaximumUTF8CStringSize($1_str); - char* $1_cstr = (char *)malloc($1_strsize * sizeof(char)); - JSStringGetUTF8CString($1_str, $1_cstr, $1_strsize); - $1 = new std::string($1_cstr); -%} - -%typemap(out) const string & %{ - JSStringRef jsstring = JSStringCreateWithUTF8CString($1.c_str()); - $result = JSValueMakeString(context, jsstring); - JSStringRelease(jsstring); -%} - -%typemap(freearg) const string & //TODO: Not working: A memory leak -%{ free($1_cstr); %} - -//%typemap(typecheck) const string & = char *; - } From be06ceea2686f65a29a5d46d5d675d4366e5571c Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sun, 2 Dec 2012 23:51:47 +0100 Subject: [PATCH 0223/1048] Fixes in std_string for JSC generator. --- Lib/javascript/jsc/std_string.i | 41 ++++++++++++++++++++++----------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/Lib/javascript/jsc/std_string.i b/Lib/javascript/jsc/std_string.i index 5056b17bf..d1ac12ef9 100755 --- a/Lib/javascript/jsc/std_string.i +++ b/Lib/javascript/jsc/std_string.i @@ -15,8 +15,8 @@ std::string SWIGJSC_valueToString(JSContextRef context, JSValueRef value) { JSStringRef jsstring = JSValueToStringCopy(context, value, /* JSValueRef *exception */ 0); unsigned int length = JSStringGetLength(jsstring); - char *cstr = new char[length+1]; - JSStringGetUTF8CString(jsstring, cstr, length); + char *cstr = new char[length + 1]; + JSStringGetUTF8CString(jsstring, cstr, length + 1); // create a copy std::string result(cstr); @@ -38,21 +38,34 @@ JSValueRef SWIGJSC_stringToValue(JSContextRef context, const std::string& s) %} namespace std { + %naturalvar string; -%naturalvar string; + class string; -class string; -// string - -%typemap(in) string, const string& -%{ - $1 = SWIGJSC_valueToString(context, $input); -%} + %typemap(in) string + %{ + $1 = SWIGJSC_valueToString(context, $input); + %} -%typemap(out) string, const string& -%{ - $result = SWIGJSC_stringToValue(context, $1); -%} + %typemap(in) const string & + %{ + $1 = new std::string(SWIGJSC_valueToString(context, $input)); + %} + + %typemap(freearg) const string & + %{ + delete $1; + %} + + %typemap(out) string + %{ + $result = SWIGJSC_stringToValue(context, $1); + %} + + %typemap(out) const string & + %{ + $result = SWIGJSC_stringToValue(context, $1); + %} } From 2c4a90a37d7818f792417bfff73a88b9efcbdd01 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 4 Dec 2012 01:36:51 +0100 Subject: [PATCH 0224/1048] Generate defines for initializer function. --- Lib/javascript/jsc/javascriptcode.swg | 6 +++++- Source/Modules/javascript.cxx | 5 ++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index 000733ea7..0ad1e364d 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -244,6 +244,10 @@ int $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObjec } %} +%fragment ("js_initializer_define", "templates") %{ +#define SWIGJSC_INIT $jsname_initialize +%} + /* ----------------------------------------------------------------------------- * js_initializer: template for the module initializer function * - $jsname: module name @@ -256,7 +260,7 @@ int $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObjec extern "C" { #endif -bool $jsname_initialize(JSGlobalContextRef context) { +bool SWIGJSC_INIT (JSGlobalContextRef context) { SWIG_InitializeModule(0); JSObjectRef global_object = JSContextGetGlobalObject(context); diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 90300a24f..f0b8c472a 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1407,6 +1407,9 @@ int JSCEmitter::dump(Node *n) { // write the swig banner Swig_banner(f_wrap_cpp); + Template initializer_define(getTemplate("js_initializer_define")); + initializer_define.replace(T_NAME, module).pretty_print(f_header); + SwigType_emit_type_table(f_runtime, f_wrappers); Printv(f_wrap_cpp, f_runtime, "\n", 0); @@ -1414,7 +1417,7 @@ int JSCEmitter::dump(Node *n) { Printv(f_wrap_cpp, f_wrappers, "\n", 0); emitNamespaces(); - + // compose the initializer function using a template Template initializer(getTemplate("js_initializer")); initializer.replace(T_NAME, module) From 9d630ab930f83252e75d6e66e2912cbe75ca253f Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 8 Jan 2013 21:48:22 +0100 Subject: [PATCH 0225/1048] Fix std::string support for v8. --- Lib/javascript/jsc/std_string.i | 8 +- Lib/javascript/v8/javascriptstrings.swg | 5 +- Lib/javascript/v8/std_string.i | 106 +++++++++++++----------- 3 files changed, 60 insertions(+), 59 deletions(-) diff --git a/Lib/javascript/jsc/std_string.i b/Lib/javascript/jsc/std_string.i index d1ac12ef9..a23396fe6 100755 --- a/Lib/javascript/jsc/std_string.i +++ b/Lib/javascript/jsc/std_string.i @@ -1,12 +1,10 @@ /* ----------------------------------------------------------------------------- * std_string.i * - * Typemaps for std::string and const std::string& - * These are mapped to a JSCore String and are passed around by value. + * Typemaps for const std::string&. + * To use non-const std::string references use the following %apply: + * %apply const std::string & {std::string &}; * - * To use non-const std::string references use the following %apply. Note - * that they are passed by value. - * %apply const std::string & {std::string &}; * ----------------------------------------------------------------------------- */ %{ diff --git a/Lib/javascript/v8/javascriptstrings.swg b/Lib/javascript/v8/javascriptstrings.swg index e955bee3a..69b6836a8 100644 --- a/Lib/javascript/v8/javascriptstrings.swg +++ b/Lib/javascript/v8/javascriptstrings.swg @@ -2,7 +2,7 @@ /* ------------------------------------------------------------ * utility methods for char strings * ------------------------------------------------------------ */ -%fragment("SWIG_AsCharPtrAndSize","header",fragment="SWIG_pchar_descriptor") { +%fragment("SWIG_AsCharPtrAndSize", "header", fragment="SWIG_pchar_descriptor") { SWIGINTERN int SWIG_AsCharPtrAndSize(v8::Handle valRef, char** cptr, size_t* psize, int *alloc) { @@ -47,9 +47,6 @@ SWIG_FromCharPtrAndSize(const char* carray, size_t size) if (carray) { if (size > INT_MAX) { // TODO: handle extra long strings - //swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); - //return pchar_descriptor ? - // SWIG_InternalNewPointerObj(%const_cast(carray,char *), pchar_descriptor, 0) : SWIG_Py_Void(); return v8::Undefined(); } else { v8::Handle js_str = v8::String::New(carray, size); diff --git a/Lib/javascript/v8/std_string.i b/Lib/javascript/v8/std_string.i index 0d6143319..d9221627f 100755 --- a/Lib/javascript/v8/std_string.i +++ b/Lib/javascript/v8/std_string.i @@ -1,68 +1,74 @@ /* ----------------------------------------------------------------------------- * std_string.i * - * Typemaps for std::string and const std::string& - * These are mapped to a JSCore String and are passed around by value. + * Typemaps for std::string and const std::string&. + * + * To use non-const std::string references use the following %apply: + * %apply const std::string & {std::string &}; * - * To use non-const std::string references use the following %apply. Note - * that they are passed by value. - * %apply const std::string & {std::string &}; * ----------------------------------------------------------------------------- */ %{ #include %} +%fragment("SWIGV8_valueToString", "header", fragment="SWIG_AsCharPtrAndSize") { +std::string* SWIGV8_valueToStringPtr(v8::Handle val) { + int alloc; + size_t size; + char* chars; + int res = SWIG_AsCharPtrAndSize(val, &chars, &size, &alloc); + + if(res != SWIG_OK) { + v8::ThrowException(v8::Exception::TypeError(v8::String::New("Could not convert to string."))); + return 0; + } + + // copies the data (again) + std::string *str = new std::string(chars); + + if (alloc) delete[] chars; + + return str; +} +} + +%fragment("SWIGV8_stringToValue", "header", fragment="SWIG_FromCharPtrAndSize") { +v8::Handle SWIGV8_stringToValue(const std::string &str) { + return SWIG_FromCharPtrAndSize(str.c_str(), str.length()); +} +} + namespace std { + %naturalvar string; -%naturalvar string; + class string; -class string; + %typemap(in, fragment="SWIGV8_valueToString") string (std::string* tmp) + %{ + tmp = SWIGV8_valueToStringPtr($input); + $1 = *tmp; + delete tmp; + %} -// string + %typemap(in, fragment="SWIGV8_valueToString") const string & + %{ + $1 = SWIGV8_valueToStringPtr($input); + %} + + %typemap(freearg) const string & + %{ + delete $1; + %} -%typemap(in) string -%{ - if(!$input->IsString()) { - // TODO: Throw exception? - return NULL; - } + %typemap(out, fragment="SWIGV8_stringToValue") string + %{ + $result = SWIGV8_stringToValue($1); + %} - size_t $1_strsize = js_str->Utf8Length(); - char* 1_cstr = new char[1_strsize]; - js_str->WriteUtf8(1_cstr, 1_strsize); - $1 = std::string($1_cstr); -%} - -%typemap(out) string %{ - $result = v8::String::New($1.c_str(), $1.size()); -%} - -%typemap(freearg) string -%{%} - -// const string & -%typemap(in) const string & -%{ - - if(!$input->IsString()) { - // TODO: Throw exception? - return NULL; - } - - size_t $1_strsize = js_str->Utf8Length(); - char* 1_cstr = new char[1_strsize]; - js_str->WriteUtf8(1_cstr, 1_strsize); - $1 = newstd::string($1_cstr); -%} - -%typemap(out) const string & %{ - $result = v8::String::New($1.c_str(), $1.size()); -%} - -%typemap(freearg) const string & //TODO: Not working: A memory leak -%{ free($1_cstr); %} - -//%typemap(typecheck) const string & = char *; + %typemap(out, fragment="SWIGV8_stringToValue") const string & + %{ + $result = SWIGV8_stringToValue($1); + %} } From 31844ac72adfd82c310c239434db579ba7f6670a Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 8 Jan 2013 22:34:38 +0100 Subject: [PATCH 0226/1048] Simplify the signature of the v8 module intializer. --- Lib/javascript/v8/javascriptcode.swg | 2 +- Tools/javascript/v8_shell.cxx | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 1b196cffd..f86198622 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -386,7 +386,7 @@ fail: %{ extern "C" { -void $jsname_initialize(v8::Handle context, v8::Handle global_obj) +void $jsname_initialize(v8::Handle global_obj) { SWIG_InitializeModule(0); diff --git a/Tools/javascript/v8_shell.cxx b/Tools/javascript/v8_shell.cxx index 0055bad98..7e4b34a3d 100755 --- a/Tools/javascript/v8_shell.cxx +++ b/Tools/javascript/v8_shell.cxx @@ -9,7 +9,7 @@ #include "js_shell.h" -typedef int (*V8ExtensionRegistrar) (v8::Handle, v8::Handle); +typedef int (*V8ExtensionRegistrar) (v8::Handle); class V8Shell: public JSShell { @@ -159,7 +159,7 @@ void V8Shell::ExtendEngine() { // register extensions for(std::vector::iterator it=module_initializers.begin(); it != module_initializers.end(); ++it) { - (*it)(context, global); + (*it)(global); } } From 4fea3a403e5856565d51a5bf0b0a4cec4c03a583 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 8 Jan 2013 22:36:32 +0100 Subject: [PATCH 0227/1048] Generate an extra file part after the initializer for v8 modules. E.g., this is useful for creating node.js modules. --- Source/Modules/javascript.cxx | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index f0b8c472a..a307a399c 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1655,6 +1655,7 @@ private: String *f_runtime; String *f_header; String *f_init; + String *f_post_init; /* part for class templates */ String *f_class_templates; @@ -1709,6 +1710,7 @@ int V8Emitter::initialize(Node *n) f_header = NewString(""); f_class_templates = NewString(""); f_init = NewString(""); + f_post_init = NewString(""); f_init_namespaces = NewString(""); f_init_class_templates = NewString(""); @@ -1723,6 +1725,7 @@ int V8Emitter::initialize(Node *n) Swig_register_filebyname("runtime", f_runtime); Swig_register_filebyname("header", f_header); Swig_register_filebyname("init", f_init); + Swig_register_filebyname("post-init", f_post_init); return SWIG_OK; } @@ -1762,6 +1765,8 @@ int V8Emitter::dump(Node *n) Printv(f_wrap_cpp, f_init, 0); + Printv(f_wrap_cpp, f_post_init, 0); + return SWIG_OK; } @@ -1779,6 +1784,8 @@ int V8Emitter::close() Delete(f_init_static_wrappers); Delete(f_init_register_classes); Delete(f_init_register_namespaces); + Delete(f_init); + Delete(f_post_init); // files Close(f_wrap_cpp); From 213c107b7f4762bf58f7d6a7c7f8b463e2068206 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 8 Jan 2013 22:37:16 +0100 Subject: [PATCH 0228/1048] Add a swig macro to register node.js extensions. --- Lib/javascript/v8/node.i | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 Lib/javascript/v8/node.i diff --git a/Lib/javascript/v8/node.i b/Lib/javascript/v8/node.i new file mode 100644 index 000000000..3b60e92af --- /dev/null +++ b/Lib/javascript/v8/node.i @@ -0,0 +1,7 @@ +%define %node(moduleName) +%insert("post-init") %{ +extern "C" { + NODE_MODULE(moduleName, moduleName ## _initialize) +} +%} +%enddef \ No newline at end of file From caa92740d3241e6aa34ee38a6dbcf846d72c3275 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 9 Jan 2013 00:33:09 +0100 Subject: [PATCH 0229/1048] Add an option to deactivate creation of an extra module object in javascript. This is useful, if the extension host calls the initializer with custom local variables. E.g., this is the case with node.js. --- Source/Modules/javascript.cxx | 73 +++++++++++++++++++++++++---------- 1 file changed, 52 insertions(+), 21 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index a307a399c..8850ebd60 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -55,6 +55,8 @@ bool js_template_enable_debug = false; #define V8_REGISTER_CLASSES "$jsv8registerclasses" #define V8_REGISTER_NS "$jsv8registernspaces" +#define FLAG_NO_MODULE_OBJECT "NO_MODULE_OBJECT" + /** * A convenience class to manage state variables for emitters. * The implementation delegates to swig Hash DOHs and provides @@ -307,7 +309,6 @@ protected: String *defaultResultName; File *f_wrappers; - }; /********************************************************************** @@ -522,6 +523,8 @@ void JAVASCRIPT::main(int argc, char *argv[]) { int mode = -1; + bool createModuleObject = true; + for (int i = 1; i < argc; i++) { if (argv[i]) { if (strcmp(argv[i], "-v8") == 0) { @@ -539,6 +542,9 @@ void JAVASCRIPT::main(int argc, char *argv[]) { } else if (strcmp(argv[i], "-debug-codetemplates") == 0) { Swig_mark_arg(i); js_template_enable_debug = true; + } else if (strcmp(argv[i], "-no-moduleobject") == 0) { + Swig_mark_arg(i); + createModuleObject = false; } } } @@ -568,6 +574,10 @@ void JAVASCRIPT::main(int argc, char *argv[]) { } } + if(!createModuleObject) { + SetFlag(emitter->getState().global(), FLAG_NO_MODULE_OBJECT); + } + // Add a symbol to the parser for conditional compilation Preprocessor_define("SWIGJAVASCRIPT 1", 0); @@ -649,13 +659,19 @@ JSEmitterState &JSEmitter::getState() { return state; } -int JSEmitter::initialize(Node * n) { +int JSEmitter::initialize(Node *n) { if(namespaces != NULL) { Delete(namespaces); } namespaces = NewHash(); - Hash *global_namespace = createNamespaceEntry(Char(Getattr(n, "name")), "global"); + Hash *global_namespace; + if(State::IsSet(state.global(FLAG_NO_MODULE_OBJECT))) { + Printf(stdout, "AAAAAAAAAAAAAAAAAAAAAAAAAAA"); + global_namespace = createNamespaceEntry("global", 0); + } else { + global_namespace = createNamespaceEntry(Char(Getattr(n, "name")), "global"); + } Setattr(namespaces, "::", global_namespace); current_namespace = global_namespace; @@ -1417,7 +1433,7 @@ int JSCEmitter::dump(Node *n) { Printv(f_wrap_cpp, f_wrappers, "\n", 0); emitNamespaces(); - + // compose the initializer function using a template Template initializer(getTemplate("js_initializer")); initializer.replace(T_NAME, module) @@ -1676,6 +1692,7 @@ private: String* GLOBAL; String* NULL_STR; String *VETO_SET; + String *moduleName; }; @@ -1698,6 +1715,8 @@ int V8Emitter::initialize(Node *n) { JSEmitter::initialize(n); + moduleName = Getattr(n,"name"); + // Get the output file name String *outfile = Getattr(n,"outfile"); f_wrap_cpp = NewFile(outfile, "w", SWIG_output_files()); @@ -1730,11 +1749,8 @@ int V8Emitter::initialize(Node *n) return SWIG_OK; } -int V8Emitter::dump(Node *n) +int V8Emitter::dump(Node *) { - // Get the module name - String* module = Getattr(n,"name"); - // write the swig banner Swig_banner(f_wrap_cpp); @@ -1752,7 +1768,7 @@ int V8Emitter::dump(Node *n) // compose the initializer function using a template // filled with sub-parts Template initializer(getTemplate("js_initializer")); - initializer.replace(T_NAME, module) + initializer.replace(T_NAME, moduleName) .replace(V8_NAME_SPACES, f_init_namespaces) .replace(V8_CLASS_TEMPLATES, f_init_class_templates) .replace(V8_WRAPPERS, f_init_wrappers) @@ -2013,20 +2029,35 @@ int V8Emitter::emitNamespaces() { String *parent = Getattr(entry, PARENT); String *parent_mangled = Swig_name_mangle(parent); - // create namespace object and register it to the parent scope - Template t_create_ns = getTemplate("jsv8_create_namespace"); - t_create_ns.replace(T_NAME_MANGLED, name_mangled) - .trim() - .pretty_print(f_init_namespaces); + bool do_create = true; + bool do_register = true; - Template t_register_ns = getTemplate("jsv8_register_namespace"); - t_register_ns.replace(T_NAME_MANGLED, name_mangled) - .replace(T_NAME, name) - .replace(T_PARENT, parent_mangled) - .trim(); + if (Equal(parent, "")) { + do_register = false; + } - // prepend in order to achieve reversed order of registration statements - Insert(f_init_register_namespaces, 0, t_register_ns.str()); + if (Equal(name, "global")) { + do_create = false; + } + + if (do_create) { + // create namespace object and register it to the parent scope + Template t_create_ns = getTemplate("jsv8_create_namespace"); + t_create_ns.replace(T_NAME_MANGLED, name_mangled) + .trim() + .pretty_print(f_init_namespaces); + } + + if (do_register) { + Template t_register_ns = getTemplate("jsv8_register_namespace"); + t_register_ns.replace(T_NAME_MANGLED, name_mangled) + .replace(T_NAME, name) + .replace(T_PARENT, parent_mangled) + .trim(); + + // prepend in order to achieve reversed order of registration statements + Insert(f_init_register_namespaces, 0, t_register_ns.str()); + } } return SWIG_OK; From 04cdde05636f22d8504389a3a92a5c39885f04ad Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 18 Jan 2013 15:33:04 +0100 Subject: [PATCH 0230/1048] Add test to check javascript unicode strings. --- Examples/test-suite/javascript/Makefile.in | 5 ++- .../javascript/javascript_unicode_runme.js | 7 ++++ Examples/test-suite/javascript_unicode.i | 10 +++++ Lib/javascript/jsc/javascriptstrings.swg | 38 +++++++++---------- 4 files changed, 39 insertions(+), 21 deletions(-) create mode 100644 Examples/test-suite/javascript/javascript_unicode_runme.js create mode 100644 Examples/test-suite/javascript_unicode.i diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index d59f3d60e..e57081412 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -47,7 +47,8 @@ CPP_TEST_CASES = \ typemap_namespace \ typemap_ns_using \ using1 \ - using2 + using2 \ + javascript_unicode SKIP_CPP_CASES = @SKIP_CPP_CASES@ SKIP_C_CASES = @SKIP_C_CASES@ @@ -94,7 +95,7 @@ run_testcase = \ # Clean %.clean: - + clean: $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile javascript_clean diff --git a/Examples/test-suite/javascript/javascript_unicode_runme.js b/Examples/test-suite/javascript/javascript_unicode_runme.js new file mode 100644 index 000000000..4974ef40b --- /dev/null +++ b/Examples/test-suite/javascript/javascript_unicode_runme.js @@ -0,0 +1,7 @@ +var str = "olé"; + +var copy = javascript_unicode.copy_string(str); + +if (str !== copy) { + print("Error: copy is not equal: original="+str+", copy="+copy); +} diff --git a/Examples/test-suite/javascript_unicode.i b/Examples/test-suite/javascript_unicode.i new file mode 100644 index 000000000..516eee5dd --- /dev/null +++ b/Examples/test-suite/javascript_unicode.i @@ -0,0 +1,10 @@ +%module javascript_unicode + +%newobject copy_string; + +%inline %{ +#include +const char* copy_string(const char* str) { + return strdup(str); +} +%} diff --git a/Lib/javascript/jsc/javascriptstrings.swg b/Lib/javascript/jsc/javascriptstrings.swg index f83c7533d..26908d9da 100644 --- a/Lib/javascript/jsc/javascriptstrings.swg +++ b/Lib/javascript/jsc/javascriptstrings.swg @@ -1,5 +1,5 @@ /* ------------------------------------------------------------ - * utility methods for char strings + * utility methods for char strings * ------------------------------------------------------------ */ %fragment("SWIG_AsCharPtrAndSize","header",fragment="SWIG_pchar_descriptor") { SWIGINTERN int @@ -8,14 +8,14 @@ SWIG_JSC_AsCharPtrAndSize(JSContextRef context, JSValueRef valRef, char** cptr, if(JSValueIsString(context, valRef)) { JSStringRef js_str = JSValueToStringCopy(context, valRef, NULL); size_t len = JSStringGetMaximumUTF8CStringSize(js_str); - size_t abs_len = JSStringGetLength(js_str); char* cstr = (char*) malloc(len * sizeof(char)); - JSStringGetUTF8CString(js_str, cstr, len); - + /* JSStringGetUTF8CString returns the length including 0-terminator */ + len = JSStringGetUTF8CString(js_str, cstr, len); + if(alloc) *alloc = SWIG_NEWOBJ; - if(psize) *psize = abs_len + 1; + if(psize) *psize = len; if(cptr) *cptr = cstr; - + return SWIG_OK; } else { if(JSValueIsObject(context, valRef)) { @@ -47,7 +47,7 @@ SWIG_JSC_FromCharPtrAndSize(JSContextRef context, const char* carray, size_t siz if (size > INT_MAX) { // TODO: handle extra long strings //swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); - //return pchar_descriptor ? + //return pchar_descriptor ? // SWIG_InternalNewPointerObj(%const_cast(carray,char *), pchar_descriptor, 0) : SWIG_Py_Void(); return JSValueMakeUndefined(context); } else { @@ -58,7 +58,7 @@ SWIG_JSC_FromCharPtrAndSize(JSContextRef context, const char* carray, size_t siz for(i=0;i Date: Fri, 18 Jan 2013 15:34:11 +0100 Subject: [PATCH 0231/1048] Bugfix: in javascript interpreter load extensions on MacOSX correctly. --- Tools/javascript/js_shell.cxx | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Tools/javascript/js_shell.cxx b/Tools/javascript/js_shell.cxx index f0290c785..fa5500f8e 100644 --- a/Tools/javascript/js_shell.cxx +++ b/Tools/javascript/js_shell.cxx @@ -6,11 +6,16 @@ #include #ifdef __GNUC__ +#ifdef __APPLE__ +#define LIBRARY_EXT ".dylib" +#else +#define LIBRARY_EXT ".so" +#endif #include #define LOAD_LIBRARY(name) dlopen(name, RTLD_LAZY) #define CLOSE_LIBRARY(handle) dlclose(handle) #define LIBRARY_ERROR dlerror -#define LIBRARYFILE(name) std::string("lib").append(name).append(".so") +#define LIBRARYFILE(name) std::string("lib").append(name).append(LIBRARY_EXT) #else #error "implement dll loading" #endif From 04c0803f736ef8bd264d7a099a88b4258461547f Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 18 Jan 2013 15:35:45 +0100 Subject: [PATCH 0232/1048] Fixes in configuration to detect JavascriptCore on MacOSX correctly. --- configure.in | 99 ++++++++++++++++++++++++++++------------------------ 1 file changed, 54 insertions(+), 45 deletions(-) diff --git a/configure.in b/configure.in index e4841fc70..0e00c958a 100644 --- a/configure.in +++ b/configure.in @@ -1106,11 +1106,13 @@ if test -z "$JSCOREINCDIR"; then esac fi +JSCORE=0 for d in $JSCOREINCDIR ; do if test -r "$d/JavaScriptCore/JavaScript.h" || test -r "$d/JavaScript.h" ; then AC_MSG_RESULT($d) JSCOREINCDIR=$d JSCOREINC=-I\"$d\" + JSCORE=1 break fi done @@ -1119,51 +1121,55 @@ if test "$JSCOREINC" = "" ; then AC_MSG_RESULT(not found) fi +# under linux look for the javascript core library +case $host in + *-*-linux*) + # check for JavaScriptCore, Webkit libraries + AC_ARG_WITH(jscorelib,[ --with-jscorelib =path Set location of JavaScriptCore (Webkit) library directory], [JSCORELIB="-L$withval"], [JSCORELIB=]) + AC_MSG_CHECKING(for JavaScriptCore(Webkit) library) -# check for JavaScriptCore, Webkit libraries -AC_ARG_WITH(jscorelib,[ --with-jscorelib =path Set location of JavaScriptCore (Webkit) library directory], - [JSCORELIB="-L$withval"], [JSCORELIB=]) -AC_MSG_CHECKING(for JavaScriptCore(Webkit) library) + if test -z "$JSCORELIB"; then + JSCORELIBDIRS="/usr/lib/ /usr/local/lib/" + for i in $JSCORELIBDIRS ; do -if test -z "$JSCORELIB"; then -dirs="/usr/lib/ /usr/local/lib/" -for i in $dirs ; do + if test -r $i/libwebkit-1.0.la; then + AC_MSG_RESULT($i) + JSCORELIB="-L$i -lwebkit-1.0" + break + fi - if test -r $i/libwebkit-1.0.la; then - AC_MSG_RESULT($i) - JSCORELIB="-L$i -lwebkit-1.0" - break - fi + if test -r $i/libjavascriptcoregtk-1.0.so; then + AC_MSG_RESULT($i) + JSCORELIB="-L$i -ljavascriptcoregtk-1.0" + break + fi - if test -r $i/libjavascriptcoregtk-1.0.so; then - AC_MSG_RESULT($i) - JSCORELIB="-L$i -ljavascriptcoregtk-1.0" - break - fi + if test -r $i/libwebkitgtk-1.0.so; then + AC_MSG_RESULT($i) + JSCORELIB="-L$i -lwebkitgtk-1.0" + break + fi + done + fi - if test -r $i/libwebkitgtk-1.0.so; then - AC_MSG_RESULT($i) - JSCORELIB="-L$i -lwebkitgtk-1.0" - break - fi -done - -if test -z "$JSCORELIB"; then - AC_MSG_RESULT(not found) - JSCORE= -else - AC_MSG_RESULT($JSCORELIB) - JSCORE=1 -fi + if test -z "$JSCORELIB"; then + AC_MSG_RESULT(not found) + JSCORE=0 + else + AC_MSG_RESULT($JSCORELIB) + JSCORE=1 + fi + ;; +esac # linking options case $host in -*-*-darwin*) +*-*-darwin*) JSCOREDYNAMICLINKING="-framework JavaScriptCore" JSCORECFLAGS="" ;; -*-*-linux*) - JSCOREDYNAMICLINKING="$JSCORELIB" +*-*-linux*) + JSCOREDYNAMICLINKING="$JSCORELIB" JSCORECFLAGS="" ;; *) @@ -1179,18 +1185,18 @@ case $host in esac if test "$JS_NO_WARNINGS" == "1"; then -case $host in -*-*-darwin* | *-*-linux* | *-*-cygwin* | *-*-mingw*) - JSCXXFLAGS="`echo $CXXFLAGS | sed 's/-Wall//g'`" - ;; -*) - JSCXXFLAGS="$CXXFLAGS" -esac + case $host in + *-*-darwin* | *-*-linux* | *-*-cygwin* | *-*-mingw*) + JSCXXFLAGS="`echo $CXXFLAGS | sed 's/-Wall//g'`" + ;; + *) + JSCXXFLAGS="$CXXFLAGS" + esac fi # library output case $host in -*-*-darwin*) +*-*-darwin*) JSCORESO=".dylib" JSCORELDSHARED='$(CC) -dynamiclib' JSCORECXXSHARED='$(CXX) -dynamiclib' @@ -1201,7 +1207,6 @@ case $host in JSCORECXXSHARED='$(CXXSHARED)' ;; esac -fi AC_SUBST(JSCORE) AC_SUBST(JSCOREINC) @@ -1259,17 +1264,19 @@ done if test "$JSV8LIB" = "" ; then AC_MSG_RESULT(not found) + JSV8= else AC_MSG_RESULT($JSV8LIB) + JSV8=1 fi # linking options case $host in -*-*-darwin*) +*-*-darwin*) JSV8DYNAMICLINKING="" # TODO: add osx configuration ;; -*-*-linux*) +*-*-linux*) JSV8DYNAMICLINKING="$JSV8LIB" ;; *) @@ -1277,8 +1284,10 @@ case $host in ;; esac +AC_SUBST(JSV8) AC_SUBST(JSV8INC) AC_SUBST(JSV8DYNAMICLINKING) + AC_SUBST(JSDEFAULT) #---------------------------------------------------------------- From 8eb9aa9e73fca795fbd6a716ba830366a4919405 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 22 Jan 2013 15:53:39 +0100 Subject: [PATCH 0233/1048] Add gitignore file. --- .gitignore | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..72df6b572 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +Makefile +/Examples/Makefile +/Examples/*/Makefile +/Examples/test-suite/*/Makefile +/CCache +*.Po +swigp4.ml +Source/Include/stamp-h1 +Source/Include/swigconfig.h +config.log +config.status +preinst-swig +swig.spec From 22525249f26e36d6603c7ee7bce58cefd8ff611f Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 22 Jan 2013 15:54:08 +0100 Subject: [PATCH 0234/1048] Resolve compile warnings in v8_shell. --- Tools/javascript/v8_shell.cxx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Tools/javascript/v8_shell.cxx b/Tools/javascript/v8_shell.cxx index 7e4b34a3d..e2ab1541d 100755 --- a/Tools/javascript/v8_shell.cxx +++ b/Tools/javascript/v8_shell.cxx @@ -149,6 +149,7 @@ bool V8Shell::RunShell() { bool V8Shell::InitializeEngine() { + return true; } void V8Shell::ExtendEngine() { @@ -194,6 +195,7 @@ bool V8Shell::ExecuteScript(const std::string& source, const std::string& name) } bool V8Shell::DisposeEngine() { + return true; } v8::Persistent V8Shell::CreateShellContext() { From 8b10c47ed80a42c4f47b339820333132188659c0 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 22 Jan 2013 19:23:11 +0100 Subject: [PATCH 0235/1048] Fix regression: add an include for Node.js header. --- Lib/javascript/v8/node.i | 6 +++++- Source/Modules/javascript.cxx | 1 - 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/Lib/javascript/v8/node.i b/Lib/javascript/v8/node.i index 3b60e92af..3fed6e7db 100644 --- a/Lib/javascript/v8/node.i +++ b/Lib/javascript/v8/node.i @@ -1,7 +1,11 @@ +%insert("init") %{ +#include +%} + %define %node(moduleName) %insert("post-init") %{ extern "C" { NODE_MODULE(moduleName, moduleName ## _initialize) } %} -%enddef \ No newline at end of file +%enddef diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 8850ebd60..b35887ef0 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -667,7 +667,6 @@ int JSEmitter::initialize(Node *n) { namespaces = NewHash(); Hash *global_namespace; if(State::IsSet(state.global(FLAG_NO_MODULE_OBJECT))) { - Printf(stdout, "AAAAAAAAAAAAAAAAAAAAAAAAAAA"); global_namespace = createNamespaceEntry("global", 0); } else { global_namespace = createNamespaceEntry(Char(Getattr(n, "name")), "global"); From a4036deda841a9894e7228c4fb80cebe86ff8efc Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 22 Jan 2013 19:26:29 +0100 Subject: [PATCH 0236/1048] Add pre-processor defines to detect the javascript engine. --- Source/Modules/javascript.cxx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index b35887ef0..cf64b56c0 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -553,11 +553,13 @@ void JAVASCRIPT::main(int argc, char *argv[]) { case JSEmitter::V8: { emitter = swig_javascript_create_V8Emitter(); + Preprocessor_define("SWIG_JAVASCRIPT_V8 1", 0); break; } case JSEmitter::JavascriptCore: { emitter = swig_javascript_create_JSCEmitter(); + Preprocessor_define("SWIG_JAVASCRIPT_JSC 1", 0); break; } case JSEmitter::QtScript: From e3da21ee442913c5554203bf8699cab62a69ed15 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 22 Jan 2013 19:28:44 +0100 Subject: [PATCH 0237/1048] Add more ignores. --- .gitignore | 86 ++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 80 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index 72df6b572..2cd4b9b4e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,13 +1,87 @@ -Makefile -/Examples/Makefile -/Examples/*/Makefile -/Examples/test-suite/*/Makefile /CCache *.Po swigp4.ml -Source/Include/stamp-h1 -Source/Include/swigconfig.h config.log config.status preinst-swig swig.spec +3build +*.o +CCache/* +Lib/ocaml/swigp4.ml +Lib/swigwarn.swg +Source/Include/stamp-h1 +Source/Include/swigconfig.h +Source/Include/swigconfig.h.in +.deps +.dirstamp +*.cxx~ +*.h~ +Tools/config/* +config.log +config.status +configure +preinst-swig +swig +swig.spec +Source/CParse/parser.* +aclocal.m4 +autom4te.cache/* +*.so +example_wrap.cxx +Source/eswig +runme +.gitignore +swig-jsc.geany +/Makefile +Lib/guile/Makefile +Lib/mzscheme/Makefile +Examples/Makefile +Examples/test-suite/*/Makefile +Examples/perl5/*/Makefile +Examples/android/*/Makefile +Examples/lua/*/Makefile +Examples/guile/Makefile +Examples/guile/*/Makefile +Examples/xml/Makefile +Examples/tcl/*/Makefile +Examples/r/*/Makefile +Examples/octave/*/Makefile +Examples/ruby/*/Makefile +Examples/mzscheme/*/Makefile +Examples/python/*/Makefile +Examples/csharp/*/Makefile +Examples/d/*/Makefile +Examples/pike/*/Makefile +Examples/java/*/Makefile +Examples/php/*/Makefile +Examples/chicken/*/Makefile +Examples/go/*/Makefile +Examples/ocaml/*/Makefile +Examples/modula3/*/Makefile +CCache/Makefile +Source/Makefile +Doc/Manual/Makefile +Examples/test-suite/javascript/*.cxx +Examples/test-suite/javascript/*.c +Examples/test-suite/javascript/*.so +Source/Makefile.in +IndentBaks/ +Examples/javascript/vanilla/ +*.pyc +core +Examples/test-suite/*/*.cxx +Examples/test-suite/*/*.c +Examples/test-suite/*/*.h +Examples/test-suite/python/*.py +Examples/javascript/*/*_wrap.c +Tools/javascript/javascript +Tools/javascript/javascript_d +.settings +*.log +*_wrap.cxx +Examples/*/*/*.gdb +*.orig +*.kdev4 +*.geany +/build \ No newline at end of file From 65560a8664f19aaa03392bba33a4ac435867fa35 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 25 Jan 2013 14:07:06 +0100 Subject: [PATCH 0238/1048] Fix v8 string conversion in case of null arguments. --- Lib/javascript/v8/std_string.i | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/Lib/javascript/v8/std_string.i b/Lib/javascript/v8/std_string.i index d9221627f..e3248742b 100755 --- a/Lib/javascript/v8/std_string.i +++ b/Lib/javascript/v8/std_string.i @@ -14,19 +14,22 @@ %fragment("SWIGV8_valueToString", "header", fragment="SWIG_AsCharPtrAndSize") { std::string* SWIGV8_valueToStringPtr(v8::Handle val) { + + if (!val->IsString()) return 0; + int alloc; size_t size; char* chars; int res = SWIG_AsCharPtrAndSize(val, &chars, &size, &alloc); - + if(res != SWIG_OK) { v8::ThrowException(v8::Exception::TypeError(v8::String::New("Could not convert to string."))); return 0; } - + // copies the data (again) std::string *str = new std::string(chars); - + if (alloc) delete[] chars; return str; @@ -45,20 +48,22 @@ namespace std { class string; %typemap(in, fragment="SWIGV8_valueToString") string (std::string* tmp) - %{ + %{ tmp = SWIGV8_valueToStringPtr($input); $1 = *tmp; - delete tmp; + if (tmp == 0) { v8::ThrowException(v8::Exception::TypeError(v8::String::New("Null pointer."))); goto fail; } + if (tmp) delete tmp; %} - %typemap(in, fragment="SWIGV8_valueToString") const string & - %{ + %typemap(in, fragment="SWIGV8_valueToString") const string & + %{ $1 = SWIGV8_valueToStringPtr($input); + if ($1 == 0) { v8::ThrowException(v8::Exception::TypeError(v8::String::New("Null pointer."))); goto fail; } %} - - %typemap(freearg) const string & - %{ - delete $1; + + %typemap(freearg) const string & + %{ + if ($1) delete $1; %} %typemap(out, fragment="SWIGV8_stringToValue") string From 5da4f5794c45a09f3e8b641568d38ff650403752 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 25 Jan 2013 14:20:51 +0100 Subject: [PATCH 0239/1048] Add preprocessor define for building node.js extensions. --- Lib/javascript/v8/node.i | 1 + 1 file changed, 1 insertion(+) diff --git a/Lib/javascript/v8/node.i b/Lib/javascript/v8/node.i index 3fed6e7db..a0327a1e3 100644 --- a/Lib/javascript/v8/node.i +++ b/Lib/javascript/v8/node.i @@ -1,4 +1,5 @@ %insert("init") %{ +#define BUILDING_NODE_EXTENSION #include %} From 31feff8586c880bf91f7b6bde61b9dbdc6be57c9 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 25 Jan 2013 17:03:23 +0100 Subject: [PATCH 0240/1048] Add missing return statement in v8 code template. --- Lib/javascript/v8/javascriptcode.swg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index f86198622..3dbd12e09 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -57,7 +57,7 @@ v8::Handle $jswrapper(const v8::Arguments& args) { SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for contruction of $jsmangledname"); fail: - scope.Close(v8::Undefined()); + return scope.Close(v8::Undefined()); } %} From 827cef75a35ff9ff84c76c46abf483672c4dbcc4 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 25 Jan 2013 17:09:13 +0100 Subject: [PATCH 0241/1048] Add an ifndef-guard to resolve a warning when building nodejs extension. --- Lib/javascript/v8/node.i | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Lib/javascript/v8/node.i b/Lib/javascript/v8/node.i index a0327a1e3..4baa5e72f 100644 --- a/Lib/javascript/v8/node.i +++ b/Lib/javascript/v8/node.i @@ -1,5 +1,8 @@ %insert("init") %{ +#ifndef BUILDING_NODE_EXTENSION #define BUILDING_NODE_EXTENSION +#endif + #include %} @@ -7,6 +10,6 @@ %insert("post-init") %{ extern "C" { NODE_MODULE(moduleName, moduleName ## _initialize) -} +} %} %enddef From d3aa8e06fb3d3eb49c05975108acf2c84b716774 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 30 Jan 2013 18:50:03 +0100 Subject: [PATCH 0242/1048] Bugfix: treat persistent V8 references correctly. V8 is somewhat inconvenient regarding invoke of destructors for C++ proxies. --- Lib/javascript/v8/javascriptcode.swg | 3 +++ Lib/javascript/v8/javascriptruntime.swg | 17 ++++++++++++----- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 3dbd12e09..256b71315 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -118,6 +118,9 @@ void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) { $jsfree proxy->swigCObject; } delete proxy; + + object.Clear(); + object.Dispose(); } %} diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index b6ef55d90..f61bb27b3 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -72,12 +72,17 @@ public: }; ~SWIGV8_Proxy() { + handle.ClearWeak(); + handle->SetInternalField(0, v8::Undefined()); + handle.Dispose(); + handle.Clear(); v8::V8::AdjustAmountOfExternalAllocatedMemory(-SWIGV8_AVG_OBJ_SIZE); } bool swigCMemOwn; void *swigCObject; swig_type_info *info; + v8::Persistent handle; }; class SWIGV8_ClientData { @@ -131,14 +136,16 @@ void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; cdata->info = info; obj->SetPointerInInternalField(0, cdata); - - v8::Persistent weakptr = v8::Persistent::New(obj); - // clientdata must be set for owned data as we need to register the dtor + + cdata->handle = v8::Persistent::New(obj); + + // clientdata must be set for owned data as we need to register the dtor if(cdata->swigCMemOwn) { - weakptr.MakeWeak(cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); + cdata->handle.MakeWeak(cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); } else { - weakptr.MakeWeak(cdata, SWIGV8_Proxy_DefaultDtor); + cdata->handle.MakeWeak(cdata, SWIGV8_Proxy_DefaultDtor); } + cdata->handle.MarkIndependent(); } int SWIG_V8_ConvertPtr(v8::Handle valRef, void** ptr, swig_type_info *info, int flags) { From b511e33121c5167a9a206ddc2f3417f56d39afa9 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 3 May 2013 18:23:36 +0200 Subject: [PATCH 0243/1048] Remove std::iostream relicts from generated v8 wrapper code. --- Lib/javascript/v8/javascriptcode.swg | 1 - Lib/javascript/v8/javascriptruntime.swg | 1 - 2 files changed, 2 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 256b71315..0856c12ae 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -114,7 +114,6 @@ fail: void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) { SWIGV8_Proxy* proxy = (SWIGV8_Proxy*) parameter; if(proxy->swigCMemOwn && proxy->swigCObject) { - std::cout << "Deleting wrapped instance: " << proxy->info->name << std::endl; $jsfree proxy->swigCObject; } delete proxy; diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index f61bb27b3..8136be184 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -8,7 +8,6 @@ #include #include #include -#include %} %insert(runtime) "swigrun.swg"; /* SWIG API */ From 26a4f849485d03fe57ba47435f11953b019ae515 Mon Sep 17 00:00:00 2001 From: Vladimir Menshakov Date: Thu, 11 Jul 2013 15:06:08 +0400 Subject: [PATCH 0244/1048] added missing javascript/v8 dir --- Makefile.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile.in b/Makefile.in index 0a485cd33..9a19d73fa 100644 --- a/Makefile.in +++ b/Makefile.in @@ -431,7 +431,7 @@ install-main: @$(INSTALL_PROGRAM) $(TARGET) $(DESTDIR)$(BIN_DIR)/`echo $(TARGET_NOEXE) | sed '$(transform)'`@EXEEXT@ lib-languages = gcj typemaps tcl perl5 python guile java mzscheme ruby php ocaml octave \ - pike chicken csharp modula3 allegrocl clisp lua cffi uffi r go d javascript javascript/jsc + pike chicken csharp modula3 allegrocl clisp lua cffi uffi r go d javascript javascript/jsc javascript/v8 lib-modules = std From 9111773400ba10b6b98fea7996d3dcbf53b97ecf Mon Sep 17 00:00:00 2001 From: Vladimir Menshakov Date: Thu, 11 Jul 2013 16:41:40 +0400 Subject: [PATCH 0245/1048] generate v8-3.19.x compatible code --- Lib/javascript/v8/javascriptcode.swg | 9 ++++----- Lib/javascript/v8/javascripthelpers.swg | 4 ++-- Lib/javascript/v8/javascriptruntime.swg | 22 ++++++++++------------ 3 files changed, 16 insertions(+), 19 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 0856c12ae..6ca0fff42 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -111,15 +111,14 @@ fail: * ----------------------------------------------------------------------------- */ %fragment ("js_dtor", "templates") %{ -void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) { - SWIGV8_Proxy* proxy = (SWIGV8_Proxy*) parameter; +void $jswrapper(v8::Isolate *iso, v8::Persistent< v8::Object > * object, SWIGV8_Proxy *proxy) { if(proxy->swigCMemOwn && proxy->swigCObject) { $jsfree proxy->swigCObject; } delete proxy; - object.Clear(); - object.Dispose(); + object->Dispose(); + object->Clear(); } %} @@ -395,7 +394,7 @@ void $jsname_initialize(v8::Handle global_obj) v8::HandleScope scope; // a class template for creating proxies of undefined types - SWIGV8_SWIGTYPE_Proxy_class_templ = SWIGV8_CreateClassTemplate("SwigProxy"); + SWIGV8_SWIGTYPE_Proxy_class_templ.Reset(v8::Isolate::GetCurrent(), SWIGV8_CreateClassTemplate("SwigProxy")); /* create objects for namespaces */ $jsv8nspaces diff --git a/Lib/javascript/v8/javascripthelpers.swg b/Lib/javascript/v8/javascripthelpers.swg index 4fcf0e447..b3868efff 100644 --- a/Lib/javascript/v8/javascripthelpers.swg +++ b/Lib/javascript/v8/javascripthelpers.swg @@ -3,14 +3,14 @@ /** * Creates a class template for a class with specified initialization function. */ -v8::Persistent SWIGV8_CreateClassTemplate(const char* symbol) { +v8::Handle SWIGV8_CreateClassTemplate(const char* symbol) { v8::Local class_templ = v8::FunctionTemplate::New(); class_templ->SetClassName(v8::String::NewSymbol(symbol)); v8::Handle inst_templ = class_templ->InstanceTemplate(); inst_templ->SetInternalFieldCount(1); - return v8::Persistent::New(class_templ); + return class_templ; } /** diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index 8136be184..13d8cf590 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -72,7 +72,7 @@ public: ~SWIGV8_Proxy() { handle.ClearWeak(); - handle->SetInternalField(0, v8::Undefined()); + //handle->SetInternalField(0, v8::Undefined()); handle.Dispose(); handle.Clear(); v8::V8::AdjustAmountOfExternalAllocatedMemory(-SWIGV8_AVG_OBJ_SIZE); @@ -87,7 +87,7 @@ public: class SWIGV8_ClientData { public: v8::Handle class_templ; - void (*dtor) (v8::Persistent< v8::Value > object, void *parameter); + void (*dtor) (v8::Isolate *iso, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *parameter); }; v8::Persistent SWIGV8_SWIGTYPE_Proxy_class_templ; @@ -97,7 +97,7 @@ int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_t if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; v8::Handle cdataRef = objRef->GetInternalField(0); - SWIGV8_Proxy *cdata = (SWIGV8_Proxy *) v8::External::Unwrap(cdataRef); + SWIGV8_Proxy *cdata = (SWIGV8_Proxy *) (!cdataRef.IsEmpty() && cdataRef->IsExternal()? cdataRef.As()->Value(): NULL); if(cdata == NULL) { return SWIG_ERROR; } @@ -122,11 +122,8 @@ int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_t return SWIG_OK; } -void SWIGV8_Proxy_DefaultDtor(v8::Persistent< v8::Value > object, void *parameter) { - SWIGV8_Proxy* proxy = (SWIGV8_Proxy*) parameter; - if(proxy) { - delete proxy; - } +void SWIGV8_Proxy_DefaultDtor(v8::Isolate* isolate, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy) { + delete proxy; } void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info *info, int flags) { @@ -134,9 +131,9 @@ void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info cdata->swigCObject = ptr; cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; cdata->info = info; - obj->SetPointerInInternalField(0, cdata); + obj->SetAlignedPointerInInternalField(0, cdata); - cdata->handle = v8::Persistent::New(obj); + cdata->handle.Reset(v8::Isolate::GetCurrent(), obj); // clientdata must be set for owned data as we need to register the dtor if(cdata->swigCMemOwn) { @@ -159,12 +156,13 @@ int SWIG_V8_ConvertPtr(v8::Handle valRef, void** ptr, swig_type_info v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, int flags) { v8::HandleScope scope; + v8::Isolate *iso = v8::Isolate::GetCurrent(); v8::Handle class_templ; if(info->clientdata != 0) { - class_templ = ((SWIGV8_ClientData*) info->clientdata)->class_templ; + class_templ = v8::Handle::New(iso, ((SWIGV8_ClientData*) info->clientdata)->class_templ); } else { - class_templ = SWIGV8_SWIGTYPE_Proxy_class_templ; + class_templ = v8::Handle::New(iso, SWIGV8_SWIGTYPE_Proxy_class_templ); } v8::Handle result = class_templ->InstanceTemplate()->NewInstance(); SWIGV8_SetPrivateData(result, ptr, info, flags); From fe25e2dfc8fd4fa29702685684337444f5948cb1 Mon Sep 17 00:00:00 2001 From: Vladimir Menshakov Date: Thu, 18 Jul 2013 18:42:03 +0400 Subject: [PATCH 0246/1048] replaced GetInternalField with GetAlignedPointer (it does not work with SetAlignedPointer, btw) --- Lib/javascript/v8/javascriptruntime.swg | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index 13d8cf590..d23efcb55 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -96,8 +96,7 @@ int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_t v8::HandleScope scope; if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; - v8::Handle cdataRef = objRef->GetInternalField(0); - SWIGV8_Proxy *cdata = (SWIGV8_Proxy *) (!cdataRef.IsEmpty() && cdataRef->IsExternal()? cdataRef.As()->Value(): NULL); + SWIGV8_Proxy *cdata = static_cast(objRef->GetAlignedPointerFromInternalField(0)); if(cdata == NULL) { return SWIG_ERROR; } From 9b6a4870dd96656f0e9ec731e9b2dea856ae4939 Mon Sep 17 00:00:00 2001 From: Vladimir Menshakov Date: Thu, 18 Jul 2013 18:53:15 +0400 Subject: [PATCH 0247/1048] added missing scope.Close() --- Lib/javascript/v8/javascripthelpers.swg | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Lib/javascript/v8/javascripthelpers.swg b/Lib/javascript/v8/javascripthelpers.swg index b3868efff..d28243d88 100644 --- a/Lib/javascript/v8/javascripthelpers.swg +++ b/Lib/javascript/v8/javascripthelpers.swg @@ -4,13 +4,14 @@ * Creates a class template for a class with specified initialization function. */ v8::Handle SWIGV8_CreateClassTemplate(const char* symbol) { + v8::HandleScope scope; v8::Local class_templ = v8::FunctionTemplate::New(); class_templ->SetClassName(v8::String::NewSymbol(symbol)); v8::Handle inst_templ = class_templ->InstanceTemplate(); inst_templ->SetInternalFieldCount(1); - return class_templ; + return scope.Close(class_templ); } /** From 45bfc97ef437eb919bec2579dd39e3bbb0fd1c12 Mon Sep 17 00:00:00 2001 From: Vladimir Menshakov Date: Thu, 18 Jul 2013 19:15:38 +0400 Subject: [PATCH 0248/1048] converted function templates to the persistent ones (fixed crash on large wrappers) --- Lib/javascript/v8/javascriptcode.swg | 2 +- Lib/javascript/v8/javascriptruntime.swg | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 6ca0fff42..a6cd18c62 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -261,7 +261,7 @@ fail: %fragment("jsv8_define_class_template", "templates") %{ v8::Handle $jsmangledname_class = SWIGV8_CreateClassTemplate("$jsmangledname"); - $jsmangledname_clientData.class_templ = $jsmangledname_class; + $jsmangledname_clientData.class_templ.Reset(v8::Isolate::GetCurrent(), $jsmangledname_class); $jsmangledname_clientData.dtor = $jsdtor; SWIGTYPE$jsmangledtype->clientdata = &$jsmangledname_clientData; %} diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index d23efcb55..12c274ed2 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -86,7 +86,7 @@ public: class SWIGV8_ClientData { public: - v8::Handle class_templ; + v8::Persistent class_templ; void (*dtor) (v8::Isolate *iso, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *parameter); }; From a190288e663e207375a42bfb7476ab1ca336f2af Mon Sep 17 00:00:00 2001 From: Vladimir Menshakov Date: Thu, 18 Jul 2013 21:03:56 +0400 Subject: [PATCH 0249/1048] fixed overloaded functions multiplication --- Source/Modules/javascript.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index cf64b56c0..cd562737f 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1093,7 +1093,7 @@ int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { .pretty_print(f_wrappers); // Delete the state variable - state.global(FUNCTION_DISPATCHERS, 0); + state.global(FUNCTION_DISPATCHERS, NewString("")); DelWrapper(wrapper); return SWIG_OK; From 868803ce2ad158326cb70d2e5667baf4014df31a Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sat, 31 Aug 2013 03:44:44 +0200 Subject: [PATCH 0250/1048] Merge replayed as done by c778d16abed35829b103d607a53c8f88e3b2d595 --- CMakeLists.txt | 4 -- Lib/javascript/v8/javascriptcode.swg | 44 +++++++++++++-- Lib/javascript/v8/javascriptinit.swg | 42 +++++++++++--- Lib/javascript/v8/javascriptruntime.swg | 59 +++++++++++++++---- Lib/javascript/v8/node.i | 15 ++--- Lib/javascript/v8/std_pair.i | 1 - Lib/javascript/v8/std_string.i | 2 +- Makefile.in | 3 +- Source/Modules/javascript.cxx | 75 ++++++++++++++++--------- 9 files changed, 179 insertions(+), 66 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e7d96cc8e..1bf7a2c76 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -135,10 +135,6 @@ add_library(modules "${SWIG_SOURCE_DIR}/Modules/allegrocl.cxx" "${SWIG_SOURCE_DIR}/Modules/guile.cxx" "${SWIG_SOURCE_DIR}/Modules/java.cxx" "${SWIG_SOURCE_DIR}/Modules/javascript.cxx" - "${SWIG_SOURCE_DIR}/Modules/javascript_emitter.h" - "${SWIG_SOURCE_DIR}/Modules/javascript_emitter.cxx" - "${SWIG_SOURCE_DIR}/Modules/javascript_v8.h" - "${SWIG_SOURCE_DIR}/Modules/javascript_v8.cxx" "${SWIG_SOURCE_DIR}/Modules/lang.cxx" "${SWIG_SOURCE_DIR}/Modules/lua.cxx" "${SWIG_SOURCE_DIR}/Modules/modula3.cxx" diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index a6cd18c62..d79a0c34b 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -111,14 +111,28 @@ fail: * ----------------------------------------------------------------------------- */ %fragment ("js_dtor", "templates") %{ -void $jswrapper(v8::Isolate *iso, v8::Persistent< v8::Object > * object, SWIGV8_Proxy *proxy) { + +#ifdef BUILDING_NODE_EXTENSION +void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) +#else +void $jswrapper(v8::Isolate *isolate, v8::Persistent< v8::Object > * object, SWIGV8_Proxy *proxy) +#endif +{ if(proxy->swigCMemOwn && proxy->swigCObject) { +#ifdef SWIGRUNTIME_DEBUG + printf("Deleting wrapped instance: %s\n", proxy->info->name); +#endif $jsfree proxy->swigCObject; } delete proxy; - object->Dispose(); object->Clear(); + +#ifdef BUILDING_NODE_EXTENSION + object->Dispose(); +#else + object->Dispose(isolate); +#endif } %} @@ -266,6 +280,7 @@ fail: SWIGTYPE$jsmangledtype->clientdata = &$jsmangledname_clientData; %} + /* ----------------------------------------------------------------------------- * jsv8_inherit: template for an class inherit statement. * - $jsmangledname: mangled class name @@ -273,7 +288,17 @@ fail: * ----------------------------------------------------------------------------- */ %fragment("jsv8_inherit", "templates") %{ - $jsmangledname_class->Inherit($jsbaseclass_class); + if (SWIGTYPE_p$jsbaseclass->clientdata && !(static_cast(SWIGTYPE_p$jsbaseclass->clientdata)->class_templ.IsEmpty())) + { + $jsmangledname_class->Inherit(static_cast(SWIGTYPE_p$jsbaseclass->clientdata)->class_templ); +#ifdef SWIGRUNTIME_DEBUG + printf("Inheritance successful $jsmangledname $jsbaseclass\n"); +#endif + } else { +#ifdef SWIGRUNTIME_DEBUG + printf("Unable to inherit baseclass, it didn't exist $jsmangledname $jsbaseclass\n"); +#endif + } %} /* ----------------------------------------------------------------------------- @@ -387,9 +412,13 @@ fail: %{ extern "C" { +#ifdef BUILDING_NODE_EXTENSION +void $jsname_initialize(v8::Handle global_obj, v8::Handle /*module*/) +#else void $jsname_initialize(v8::Handle global_obj) +#endif { - SWIG_InitializeModule(0); + SWIG_InitializeModule(static_cast(&global_obj)); v8::HandleScope scope; @@ -419,8 +448,13 @@ void $jsname_initialize(v8::Handle global_obj) /* create and register namespace objects */ $jsv8registernspaces - } +#ifdef BUILDING_NODE_EXTENSION +NODE_MODULE($jsname, $jsname_initialize); +#endif + + + } // extern "C" %} diff --git a/Lib/javascript/v8/javascriptinit.swg b/Lib/javascript/v8/javascriptinit.swg index 1bca4c244..684728023 100644 --- a/Lib/javascript/v8/javascriptinit.swg +++ b/Lib/javascript/v8/javascriptinit.swg @@ -1,14 +1,42 @@ %insert(init) %{ -SWIGRUNTIME void -SWIG_V8_SetModule(swig_module_info *swig_module) {} -SWIGRUNTIME swig_module_info * -SWIG_V8_GetModule(void) { - return 0; + +SWIGRUNTIME void +SWIG_V8_SetModule(void *, swig_module_info *swig_module) { + v8::Local global_obj = v8::Context::GetCurrent()->Global(); + v8::Local mod = v8::External::New(swig_module); + assert(!mod.IsEmpty()); + global_obj->SetHiddenValue(v8::String::New("swig_module_info_data"), mod); } -#define SWIG_GetModule(clientdata) SWIG_V8_GetModule() -#define SWIG_SetModule(clientdata, pointer) SWIG_V8_SetModule(pointer) +SWIGRUNTIME swig_module_info * +SWIG_V8_GetModule(void *) { + v8::Local global_obj = v8::Context::GetCurrent()->Global(); + v8::Local moduleinfo = global_obj->GetHiddenValue(v8::String::New("swig_module_info_data")); + + if (moduleinfo.IsEmpty()) + { + // It's not yet loaded + return 0; + } + + v8::Local moduleinfo_extern = v8::Local::Cast(moduleinfo); + + if (moduleinfo_extern.IsEmpty()) + { + // Something's not right + return 0; + } + + void *ptr = moduleinfo_extern->Value(); + assert(ptr); + swig_module_info *retptr = static_cast(ptr); + assert(retptr); + return retptr; +} + +#define SWIG_GetModule(clientdata) SWIG_V8_GetModule(clientdata) +#define SWIG_SetModule(clientdata, pointer) SWIG_V8_SetModule(clientdata, pointer) %} diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index 12c274ed2..f2443ce1f 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -5,7 +5,9 @@ * ----------------------------------------------------------------------------- */ %insert(runtime) %{ + #include + #include #include %} @@ -60,7 +62,7 @@ public: %insert(runtime) %{ -// Note: to trigger the c8 gc more often one can tell v8 about the memory consumption +// Note: to trigger the v8 gc more often one can tell v8 about the memory consumption // TODO: we could add a v8 specific parameter to control this value #define SWIGV8_AVG_OBJ_SIZE 1000 @@ -71,9 +73,19 @@ public: }; ~SWIGV8_Proxy() { +#ifdef BUILDING_NODE_EXTENSION handle.ClearWeak(); +#else + handle.ClearWeak(v8::Isolate::GetCurrent()); +#endif + //handle->SetInternalField(0, v8::Undefined()); + +#ifdef BUILDING_NODE_EXTENSION handle.Dispose(); +#else + handle.Dispose(v8::Isolate::GetCurrent()); +#endif handle.Clear(); v8::V8::AdjustAmountOfExternalAllocatedMemory(-SWIGV8_AVG_OBJ_SIZE); } @@ -87,7 +99,12 @@ public: class SWIGV8_ClientData { public: v8::Persistent class_templ; - void (*dtor) (v8::Isolate *iso, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *parameter); + +#ifdef BUILDING_NODE_EXTENSION + void (*dtor) (v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy); +#else + void (*dtor) (v8::Isolate *isolate, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy); +#endif }; v8::Persistent SWIGV8_SWIGTYPE_Proxy_class_templ; @@ -101,15 +118,11 @@ int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_t return SWIG_ERROR; } if(cdata->info != info) { - bool type_valid = false; - swig_cast_info *t = info->cast; - while(t != NULL) { - if(t->type == cdata->info) { - type_valid = true; - break; - } - t = t->next; + swig_cast_info *tc = SWIG_TypeCheckStruct(cdata->info, info); + if (!tc && cdata->info->name) { + tc = SWIG_TypeCheck(cdata->info->name, info); } + bool type_valid = tc != 0; if(!type_valid) { return SWIG_TypeError; } @@ -121,8 +134,13 @@ int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_t return SWIG_OK; } -void SWIGV8_Proxy_DefaultDtor(v8::Isolate* isolate, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy) { - delete proxy; +#ifdef BUILDING_NODE_EXTENSION +void SWIGV8_Proxy_DefaultDtor(v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy) +#else +void SWIGV8_Proxy_DefaultDtor(v8::Isolate *, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy) +#endif +{ + delete proxy; } void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info *info, int flags) { @@ -132,8 +150,13 @@ void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info cdata->info = info; obj->SetAlignedPointerInInternalField(0, cdata); +#ifdef BUILDING_NODE_EXTENSION + #warning port me +#else cdata->handle.Reset(v8::Isolate::GetCurrent(), obj); +#endif +#ifdef BUILDING_NODE_EXTENSION // clientdata must be set for owned data as we need to register the dtor if(cdata->swigCMemOwn) { cdata->handle.MakeWeak(cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); @@ -141,6 +164,14 @@ void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info cdata->handle.MakeWeak(cdata, SWIGV8_Proxy_DefaultDtor); } cdata->handle.MarkIndependent(); +#else + if(cdata->swigCMemOwn) { + cdata->handle.MakeWeak(v8::Isolate::GetCurrent(), cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); + } else { + cdata->handle.MakeWeak(v8::Isolate::GetCurrent(), cdata, SWIGV8_Proxy_DefaultDtor); + } + cdata->handle.MarkIndependent(v8::Isolate::GetCurrent()); +#endif } int SWIG_V8_ConvertPtr(v8::Handle valRef, void** ptr, swig_type_info *info, int flags) { @@ -175,4 +206,8 @@ v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, in #define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_V8_ConvertInstancePtr(obj, pptr, type, flags) #define SWIG_NewInstanceObj(thisvalue, type, flags) SWIG_V8_NewPointerObj(thisvalue, type, flags) +#define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_V8_ConvertPtr(obj, pptr, type, 0) +#define SWIG_NewFunctionPtrObj(ptr, type) SWIG_V8_NewPointerObj(ptr, type, 0) + %} + diff --git a/Lib/javascript/v8/node.i b/Lib/javascript/v8/node.i index 4baa5e72f..8bf9ef061 100644 --- a/Lib/javascript/v8/node.i +++ b/Lib/javascript/v8/node.i @@ -1,15 +1,12 @@ -%insert("init") %{ +%insert("begin") %{ #ifndef BUILDING_NODE_EXTENSION #define BUILDING_NODE_EXTENSION #endif - -#include %} -%define %node(moduleName) -%insert("post-init") %{ -extern "C" { - NODE_MODULE(moduleName, moduleName ## _initialize) -} +%insert("runtime") %{ +// we are including relative to the src folder because of issues +// with other files which might be named "node.h" +#include %} -%enddef + diff --git a/Lib/javascript/v8/std_pair.i b/Lib/javascript/v8/std_pair.i index fe45ee676..8d6057223 100755 --- a/Lib/javascript/v8/std_pair.i +++ b/Lib/javascript/v8/std_pair.i @@ -5,7 +5,6 @@ * ----------------------------------------------------------------------------- */ %include -%include // ------------------------------------------------------------------------ // std::pair diff --git a/Lib/javascript/v8/std_string.i b/Lib/javascript/v8/std_string.i index e3248742b..5ad1ead27 100755 --- a/Lib/javascript/v8/std_string.i +++ b/Lib/javascript/v8/std_string.i @@ -73,7 +73,7 @@ namespace std { %typemap(out, fragment="SWIGV8_stringToValue") const string & %{ - $result = SWIGV8_stringToValue($1); + $result = SWIGV8_stringToValue(*$1); %} } diff --git a/Makefile.in b/Makefile.in index 9a19d73fa..c1fc82f74 100644 --- a/Makefile.in +++ b/Makefile.in @@ -431,7 +431,8 @@ install-main: @$(INSTALL_PROGRAM) $(TARGET) $(DESTDIR)$(BIN_DIR)/`echo $(TARGET_NOEXE) | sed '$(transform)'`@EXEEXT@ lib-languages = gcj typemaps tcl perl5 python guile java mzscheme ruby php ocaml octave \ - pike chicken csharp modula3 allegrocl clisp lua cffi uffi r go d javascript javascript/jsc javascript/v8 + pike chicken csharp modula3 allegrocl clisp lua cffi uffi r go d javascript javascript/jsc \ + javascript/v8 lib-modules = std diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index cd562737f..4c36e838a 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -22,7 +22,6 @@ bool js_template_enable_debug = false; #define CTOR_DISPATCHERS "ctor_dispatchers" #define DTOR "dtor" #define ARGCOUNT "wrap:argc" -#define FUNCTION_DISPATCHERS "function_dispatchers" // variables used in code templates // ATTENTION: be aware of prefix collisions when defining those variables @@ -793,12 +792,6 @@ int JSEmitter::enterFunction(Node *n) { SetFlag(state.function(), IS_STATIC); } - /* Initialize DOH for collecting function dispatchers */ - bool is_overloaded = GetFlag(n, "sym:overloaded"); - if (is_overloaded && state.global(FUNCTION_DISPATCHERS) == 0) { - state.global(FUNCTION_DISPATCHERS, NewString("")); - } - return SWIG_OK; } @@ -1061,13 +1054,6 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)) .pretty_print(f_wrappers); - // handle function overloading - if (is_overloaded) { - Template t_dispatch_case = getTemplate("js_function_dispatch_case"); - t_dispatch_case.replace(T_WRAPPER, wrap_name) - .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)); - Append(state.global(FUNCTION_DISPATCHERS), t_dispatch_case.str()); - } DelWrapper(wrapper); @@ -1075,14 +1061,47 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { } int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { + Wrapper *wrapper = NewWrapper(); + + // Generate call list, go to first node + Node *sibl = n; + + while (Getattr(sibl, "sym:previousSibling")) + sibl = Getattr(sibl, "sym:previousSibling"); // go all the way up + + do { + String *siblname = Getattr(sibl, "wrap:name"); + + if (siblname) + { + // handle function overloading + Template t_dispatch_case = getTemplate("js_function_dispatch_case"); + t_dispatch_case.replace(T_WRAPPER, siblname) + .replace(T_ARGCOUNT, Getattr(sibl, ARGCOUNT)); + + Append(wrapper->code, t_dispatch_case.str()); + } + + } while ((sibl = Getattr(sibl, "sym:nextSibling"))); + + + Template t_function(getTemplate("js_function_dispatcher")); - Wrapper *wrapper = NewWrapper(); - String *wrap_name = Swig_name_wrapper(Getattr(n, "name")); - Setattr(n, "wrap:name", wrap_name); +// String *wrap_name = Swig_name_wrapper(Getattr(n, "name")); - Append(wrapper->code, state.global(FUNCTION_DISPATCHERS)); + + String *fun_name = Getattr(n, "sym:name"); + + Node *methodclass = Swig_methodclass(n); + String *class_name = Getattr(methodclass, "sym:name"); + + String *new_string = NewStringf("%s_%s", class_name, fun_name); + String *wrap_name = Swig_name_wrapper(new_string); + + Setattr(n, "wrap:name", wrap_name); + state.function(WRAPPER_NAME, wrap_name); t_function.replace(T_LOCALS, wrapper->locals) .replace(T_CODE, wrapper->code); @@ -1093,7 +1112,6 @@ int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { .pretty_print(f_wrappers); // Delete the state variable - state.global(FUNCTION_DISPATCHERS, NewString("")); DelWrapper(wrapper); return SWIG_OK; @@ -1480,7 +1498,7 @@ int JSCEmitter::exitFunction(Node *n) { // handle overloaded functions if (is_overloaded) { if (!Getattr(n, "sym:nextSibling")) { - state.function(WRAPPER_NAME, Swig_name_wrapper(Getattr(n, "name"))); + //state.function(WRAPPER_NAME, Swig_name_wrapper(Getattr(n, "name"))); // create dispatcher emitFunctionDispatcher(n, is_member); } else { @@ -1742,6 +1760,7 @@ int V8Emitter::initialize(Node *n) f_init_register_namespaces = NewString(""); // note: this is necessary for built-in generation of swig runtime code + Swig_register_filebyname("begin", f_wrap_cpp); Swig_register_filebyname("runtime", f_runtime); Swig_register_filebyname("header", f_header); Swig_register_filebyname("init", f_init); @@ -1757,7 +1776,8 @@ int V8Emitter::dump(Node *) SwigType_emit_type_table(f_runtime, f_wrappers); - emitUndefined(); + // Let's not and say we did + // emitUndefined(); Printv(f_wrap_cpp, f_runtime, "\n", 0); Printv(f_wrap_cpp, f_header, "\n", 0); @@ -1859,12 +1879,15 @@ int V8Emitter::exitClass(Node *n) // emit inheritance setup Node* baseClass = getBaseClass(n); if(baseClass) { + String *base_name = Getattr(baseClass, "name"); + Template t_inherit = getTemplate("jsv8_inherit"); - String *base_name_mangled = SwigType_manglestr(Getattr(baseClass, "name")); + + String *base_name_mangled = SwigType_manglestr(base_name); t_inherit.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) - .replace(T_BASECLASS, base_name_mangled) - .trim() - .pretty_print(f_init_inheritance); + .replace(T_BASECLASS, base_name_mangled) + .trim() + .pretty_print(f_init_inheritance); Delete(base_name_mangled); } @@ -1932,7 +1955,7 @@ int V8Emitter::exitFunction(Node* n) bool is_overloaded = GetFlag(n, "sym:overloaded"); if (is_overloaded) { if (!Getattr(n, "sym:nextSibling")) { - state.function(WRAPPER_NAME, Swig_name_wrapper(Getattr(n, "name"))); + //state.function(WRAPPER_NAME, Swig_name_wrapper(Getattr(n, "name"))); emitFunctionDispatcher(n, is_member); } else { //don't register wrappers of overloaded functions in function tables From 9e74bdb97e049511be20322aa85884c1249d3606 Mon Sep 17 00:00:00 2001 From: Vladimir Menshakov Date: Tue, 6 Aug 2013 15:50:43 +0400 Subject: [PATCH 0251/1048] added virtual dtor to V8ErrorHandler --- Lib/javascript/v8/javascriptruntime.swg | 1 + 1 file changed, 1 insertion(+) diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index c2aca8c32..329354d8a 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -40,6 +40,7 @@ void SWIG_V8_Raise(const char* msg) { */ class V8ErrorHandler { public: + virtual ~V8ErrorHandler() {} virtual void error(int code, const char* msg) { SWIG_V8_Raise(msg); } From 3af7d543cb52623f962a48f91a129181af29901a Mon Sep 17 00:00:00 2001 From: Vladimir Menshakov Date: Wed, 7 Aug 2013 16:11:59 +0400 Subject: [PATCH 0252/1048] fixed crash while instantiating generic-wrapped objects from external code, please review --- Lib/javascript/v8/javascriptruntime.swg | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index 329354d8a..17c33ca09 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -171,14 +171,14 @@ void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info #ifdef BUILDING_NODE_EXTENSION // clientdata must be set for owned data as we need to register the dtor - if(cdata->swigCMemOwn) { + if(cdata->swigCMemOwn && (SWIGV8_ClientData*)info->clientdata) { cdata->handle.MakeWeak(cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); } else { cdata->handle.MakeWeak(cdata, SWIGV8_Proxy_DefaultDtor); } cdata->handle.MarkIndependent(); #else - if(cdata->swigCMemOwn) { + if(cdata->swigCMemOwn && (SWIGV8_ClientData*)info->clientdata) { cdata->handle.MakeWeak(v8::Isolate::GetCurrent(), cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); } else { cdata->handle.MakeWeak(v8::Isolate::GetCurrent(), cdata, SWIGV8_Proxy_DefaultDtor); From cf9b7e89ac52badd89acc2ba2bb5072055837ce0 Mon Sep 17 00:00:00 2001 From: Jason Turner Date: Sat, 27 Jul 2013 09:50:03 -0600 Subject: [PATCH 0253/1048] Get memory updates working with Node.js again. --- Lib/javascript/v8/javascriptcode.swg | 20 ++++++++++++-- Lib/javascript/v8/javascriptruntime.swg | 35 ++++++++++++++++++++----- 2 files changed, 47 insertions(+), 8 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index d79a0c34b..daeeee6be 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -118,6 +118,11 @@ void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) void $jswrapper(v8::Isolate *isolate, v8::Persistent< v8::Object > * object, SWIGV8_Proxy *proxy) #endif { + +#ifdef BUILDING_NODE_EXTENSION + SWIGV8_Proxy *proxy = static_cast(parameter); +#endif + if(proxy->swigCMemOwn && proxy->swigCObject) { #ifdef SWIGRUNTIME_DEBUG printf("Deleting wrapped instance: %s\n", proxy->info->name); @@ -126,11 +131,12 @@ void $jswrapper(v8::Isolate *isolate, v8::Persistent< v8::Object > * object, SWI } delete proxy; - object->Clear(); #ifdef BUILDING_NODE_EXTENSION - object->Dispose(); + object.Clear(); + object.Dispose(); #else + object->Clear(); object->Dispose(isolate); #endif } @@ -275,7 +281,11 @@ fail: %fragment("jsv8_define_class_template", "templates") %{ v8::Handle $jsmangledname_class = SWIGV8_CreateClassTemplate("$jsmangledname"); +#ifdef BUILDING_NODE_EXTENSION + $jsmangledname_clientData.class_templ = v8::Persistent::New($jsmangledname_class); +#else $jsmangledname_clientData.class_templ.Reset(v8::Isolate::GetCurrent(), $jsmangledname_class); +#endif $jsmangledname_clientData.dtor = $jsdtor; SWIGTYPE$jsmangledtype->clientdata = &$jsmangledname_clientData; %} @@ -423,7 +433,13 @@ void $jsname_initialize(v8::Handle global_obj) v8::HandleScope scope; // a class template for creating proxies of undefined types + +#ifdef BUILDING_NODE_EXTENSION + SWIGV8_SWIGTYPE_Proxy_class_templ = v8::Persistent::New(SWIGV8_CreateClassTemplate("SwigProxy")); +#else SWIGV8_SWIGTYPE_Proxy_class_templ.Reset(v8::Isolate::GetCurrent(), SWIGV8_CreateClassTemplate("SwigProxy")); +#endif + /* create objects for namespaces */ $jsv8nspaces diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index f2443ce1f..c2aca8c32 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -101,7 +101,7 @@ public: v8::Persistent class_templ; #ifdef BUILDING_NODE_EXTENSION - void (*dtor) (v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy); + void (*dtor) (v8::Persistent< v8::Value> object, void *parameter); #else void (*dtor) (v8::Isolate *isolate, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy); #endif @@ -113,7 +113,14 @@ int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_t v8::HandleScope scope; if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; + +#ifdef BUILDING_NODE_EXTENSION + v8::Handle cdataRef = objRef->GetInternalField(0); + SWIGV8_Proxy *cdata = static_cast(v8::External::Unwrap(cdataRef)); +#else SWIGV8_Proxy *cdata = static_cast(objRef->GetAlignedPointerFromInternalField(0)); +#endif + if(cdata == NULL) { return SWIG_ERROR; } @@ -135,12 +142,16 @@ int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_t } #ifdef BUILDING_NODE_EXTENSION -void SWIGV8_Proxy_DefaultDtor(v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy) +void SWIGV8_Proxy_DefaultDtor(v8::Persistent< v8::Value > object, void *parameter) #else void SWIGV8_Proxy_DefaultDtor(v8::Isolate *, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy) #endif { - delete proxy; +#ifdef BUILDING_NODE_EXTENSION + SWIGV8_Proxy *proxy = static_cast(parameter); +#endif + + delete proxy; } void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info *info, int flags) { @@ -148,11 +159,12 @@ void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info cdata->swigCObject = ptr; cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; cdata->info = info; - obj->SetAlignedPointerInInternalField(0, cdata); #ifdef BUILDING_NODE_EXTENSION - #warning port me + obj->SetPointerInInternalField(0, cdata); + cdata->handle = v8::Persistent::New(obj); #else + obj->SetAlignedPointerInInternalField(0, cdata); cdata->handle.Reset(v8::Isolate::GetCurrent(), obj); #endif @@ -186,14 +198,25 @@ int SWIG_V8_ConvertPtr(v8::Handle valRef, void** ptr, swig_type_info v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, int flags) { v8::HandleScope scope; + v8::Handle class_templ; + + +#ifdef BUILDING_NODE_EXTENSION + if(info->clientdata != 0) { + class_templ = ((SWIGV8_ClientData*) info->clientdata)->class_templ; + } else { + class_templ = SWIGV8_SWIGTYPE_Proxy_class_templ; + } +#else v8::Isolate *iso = v8::Isolate::GetCurrent(); - v8::Handle class_templ; if(info->clientdata != 0) { class_templ = v8::Handle::New(iso, ((SWIGV8_ClientData*) info->clientdata)->class_templ); } else { class_templ = v8::Handle::New(iso, SWIGV8_SWIGTYPE_Proxy_class_templ); } +#endif + v8::Handle result = class_templ->InstanceTemplate()->NewInstance(); SWIGV8_SetPrivateData(result, ptr, info, flags); From d5df0bb72101d057b6d59cf7d683263e65288884 Mon Sep 17 00:00:00 2001 From: Eric Wing Date: Wed, 7 Aug 2013 15:11:49 -0700 Subject: [PATCH 0254/1048] Added #if defined guard for V8_3_14 to allow users from the original SWIG v8 implementation to continue using the new changes. It works similarly to the BUILDING_NODE_EXTENSION in all but two places. This define must be explicitly set by users because there is no way to auto detect. (Perhaps a command line switch can be added to generate this on request?) --- Lib/javascript/v8/javascriptcode.swg | 16 ++++++++-------- Lib/javascript/v8/javascriptruntime.swg | 18 +++++++++--------- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 195141214..42be1a2dc 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -112,14 +112,14 @@ fail: %fragment ("js_dtor", "templates") %{ -#ifdef BUILDING_NODE_EXTENSION +#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) #else void $jswrapper(v8::Isolate *isolate, v8::Persistent< v8::Object > * object, SWIGV8_Proxy *proxy) #endif { -#ifdef BUILDING_NODE_EXTENSION +#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) SWIGV8_Proxy *proxy = static_cast(parameter); #endif @@ -132,7 +132,7 @@ void $jswrapper(v8::Isolate *isolate, v8::Persistent< v8::Object > * object, SWI delete proxy; -#ifdef BUILDING_NODE_EXTENSION +#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) object.Clear(); object.Dispose(); #else @@ -281,7 +281,7 @@ fail: %fragment("jsv8_define_class_template", "templates") %{ v8::Handle $jsmangledname_class = SWIGV8_CreateClassTemplate("$jsmangledname"); -#ifdef BUILDING_NODE_EXTENSION +#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) $jsmangledname_clientData.class_templ = v8::Persistent::New($jsmangledname_class); #else $jsmangledname_clientData.class_templ.Reset(v8::Isolate::GetCurrent(), $jsmangledname_class); @@ -300,7 +300,7 @@ fail: %{ if (SWIGTYPE_p$jsbaseclass->clientdata && !(static_cast(SWIGTYPE_p$jsbaseclass->clientdata)->class_templ.IsEmpty())) { -#ifdef BUILDING_NODE_EXTENSION +#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) $jsmangledname_class->Inherit(static_cast(SWIGTYPE_p$jsbaseclass->clientdata)->class_templ); #else $jsmangledname_class->Inherit( @@ -431,7 +431,7 @@ fail: %{ extern "C" { -#ifdef BUILDING_NODE_EXTENSION +#if defined(BUILDING_NODE_EXTENSION) void $jsname_initialize(v8::Handle global_obj, v8::Handle /*module*/) #else void $jsname_initialize(v8::Handle global_obj) @@ -443,7 +443,7 @@ void $jsname_initialize(v8::Handle global_obj) // a class template for creating proxies of undefined types -#ifdef BUILDING_NODE_EXTENSION +#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) SWIGV8_SWIGTYPE_Proxy_class_templ = v8::Persistent::New(SWIGV8_CreateClassTemplate("SwigProxy")); #else SWIGV8_SWIGTYPE_Proxy_class_templ.Reset(v8::Isolate::GetCurrent(), SWIGV8_CreateClassTemplate("SwigProxy")); @@ -475,7 +475,7 @@ void $jsname_initialize(v8::Handle global_obj) $jsv8registernspaces } -#ifdef BUILDING_NODE_EXTENSION +#if defined(BUILDING_NODE_EXTENSION) NODE_MODULE($jsname, $jsname_initialize); #endif diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index 17c33ca09..fddfcf70c 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -74,7 +74,7 @@ public: }; ~SWIGV8_Proxy() { -#ifdef BUILDING_NODE_EXTENSION +#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) handle.ClearWeak(); #else handle.ClearWeak(v8::Isolate::GetCurrent()); @@ -82,7 +82,7 @@ public: //handle->SetInternalField(0, v8::Undefined()); -#ifdef BUILDING_NODE_EXTENSION +#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) handle.Dispose(); #else handle.Dispose(v8::Isolate::GetCurrent()); @@ -101,7 +101,7 @@ class SWIGV8_ClientData { public: v8::Persistent class_templ; -#ifdef BUILDING_NODE_EXTENSION +#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) void (*dtor) (v8::Persistent< v8::Value> object, void *parameter); #else void (*dtor) (v8::Isolate *isolate, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy); @@ -115,7 +115,7 @@ int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_t if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; -#ifdef BUILDING_NODE_EXTENSION +#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) v8::Handle cdataRef = objRef->GetInternalField(0); SWIGV8_Proxy *cdata = static_cast(v8::External::Unwrap(cdataRef)); #else @@ -142,13 +142,13 @@ int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_t return SWIG_OK; } -#ifdef BUILDING_NODE_EXTENSION +#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) void SWIGV8_Proxy_DefaultDtor(v8::Persistent< v8::Value > object, void *parameter) #else void SWIGV8_Proxy_DefaultDtor(v8::Isolate *, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy) #endif { -#ifdef BUILDING_NODE_EXTENSION +#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) SWIGV8_Proxy *proxy = static_cast(parameter); #endif @@ -161,7 +161,7 @@ void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; cdata->info = info; -#ifdef BUILDING_NODE_EXTENSION +#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) obj->SetPointerInInternalField(0, cdata); cdata->handle = v8::Persistent::New(obj); #else @@ -169,7 +169,7 @@ void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info cdata->handle.Reset(v8::Isolate::GetCurrent(), obj); #endif -#ifdef BUILDING_NODE_EXTENSION +#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) // clientdata must be set for owned data as we need to register the dtor if(cdata->swigCMemOwn && (SWIGV8_ClientData*)info->clientdata) { cdata->handle.MakeWeak(cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); @@ -202,7 +202,7 @@ v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, in v8::Handle class_templ; -#ifdef BUILDING_NODE_EXTENSION +#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) if(info->clientdata != 0) { class_templ = ((SWIGV8_ClientData*) info->clientdata)->class_templ; } else { From 046ca7686b5605fc7e729d5a4afbe28f2d2c6807 Mon Sep 17 00:00:00 2001 From: Jason Turner Date: Sat, 27 Jul 2013 12:35:36 -0600 Subject: [PATCH 0255/1048] Adjust for v8::Persistent API which was deprecated @ 3.19.16 https://groups.google.com/forum/#!topic/v8-users/oBE_DTpRC08 --- Lib/javascript/v8/javascriptcode.swg | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index daeeee6be..195141214 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -300,7 +300,16 @@ fail: %{ if (SWIGTYPE_p$jsbaseclass->clientdata && !(static_cast(SWIGTYPE_p$jsbaseclass->clientdata)->class_templ.IsEmpty())) { +#ifdef BUILDING_NODE_EXTENSION $jsmangledname_class->Inherit(static_cast(SWIGTYPE_p$jsbaseclass->clientdata)->class_templ); +#else + $jsmangledname_class->Inherit( + v8::Handle::New( + v8::Isolate::GetCurrent(), + static_cast(SWIGTYPE_p$jsbaseclass->clientdata)->class_templ) + ); +#endif + #ifdef SWIGRUNTIME_DEBUG printf("Inheritance successful $jsmangledname $jsbaseclass\n"); #endif From ed729f7d3adaf675bbf7f1f800cdcbe17287d987 Mon Sep 17 00:00:00 2001 From: Eric Wing Date: Thu, 11 Jul 2013 19:09:17 -0700 Subject: [PATCH 0256/1048] This brings over the memory leak fixes for pointers to structs with a %extend destructor from my Neha fork. The generator was not generating and connecting the needed code for the requested destructor to the v8 dtor finalizer. I did not realize this branch has some JavaScriptCore stuff in it too. Unfortunately, it seems to have its own unique problems (like creating C++ files when it should be generating C files). My changes are targeted for v8, and I don't think my JSCore changes fully reach in this JSCore implementation so more work would need to be done to get this branch working. I think my Neha fork is in better shape at the moment. Also, I did port over the 'NULL out the dtor function pointer' in the %nodefaultdtor fix to v8. Usage case: struct MyData { %extend { ~MyData() { FreeData($self); } } }; %newobject CreateData; struct MyData* CreateData(void); %delobject FreeData; void FreeData(struct MyData* the_data); where the use case is something like: var my_data = example.CreateData(); my_data = null; --- Lib/javascript/jsc/javascriptcode.swg | 19 +++++ Lib/javascript/v8/javascriptcode.swg | 21 +++++- Source/Modules/javascript.cxx | 101 +++++++++++++++++++++++++- 3 files changed, 137 insertions(+), 4 deletions(-) diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index 0ad1e364d..40ce9c9b0 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -113,6 +113,25 @@ void $jswrapper(JSObjectRef thisObject) } %} +/* ----------------------------------------------------------------------------- + * js_dtor: template for a destructor wrapper + * - $jsmangledname: mangled class name + * - $jstype: class type + * - ${destructor_action}: The custom destructor action to invoke. + * ----------------------------------------------------------------------------- */ +%fragment ("js_dtoroverride", "templates") +%{ +void $jswrapper(JSObjectRef thisObject) +{ + SWIG_PRV_DATA* t = (SWIG_PRV_DATA*) JSObjectGetPrivate(thisObject); + if(t && t->swigCMemOwn) { + $jstype* arg1 = ($jstype*)t->swigCObject; + ${destructor_action} + } + if(t) free(t); +} +%} + /* ----------------------------------------------------------------------------- * js_getter: template for getter function wrappers * - $jswrapper: wrapper function name diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index f86198622..62267ae52 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -114,13 +114,32 @@ fail: void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) { SWIGV8_Proxy* proxy = (SWIGV8_Proxy*) parameter; if(proxy->swigCMemOwn && proxy->swigCObject) { - std::cout << "Deleting wrapped instance: " << proxy->info->name << std::endl; +// std::cout << "Deleting wrapped instance: " << proxy->info->name << std::endl; $jsfree proxy->swigCObject; } delete proxy; } %} +/* ----------------------------------------------------------------------------- + * js_dtoroverride: template for a destructor wrapper + * - $jsmangledname: mangled class name + * - $jstype: class type + * - ${destructor_action}: The custom destructor action to invoke. + * ----------------------------------------------------------------------------- */ +%fragment ("js_dtoroverride", "templates") +%{ +void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) { + SWIGV8_Proxy* proxy = (SWIGV8_Proxy*) parameter; + if(proxy->swigCMemOwn && proxy->swigCObject) { +// std::cout << "Deleting wrapped instance: " << proxy->info->name << std::endl; + $jstype arg1 = ($jstype)t->swigCObject; + ${destructor_action} + } + delete proxy; +} +%} + /* ----------------------------------------------------------------------------- * js_getter: template for getter function wrappers * - $jswrapper: wrapper function name diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 8850ebd60..a8f1b0b0a 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -886,7 +886,6 @@ int JSEmitter::emitCtor(Node *n) { int JSEmitter::emitDtor(Node *n) { - Template t_dtor = getTemplate("js_dtor"); String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); SwigType *type = state.clazz(TYPE); @@ -894,20 +893,116 @@ int JSEmitter::emitDtor(Node *n) { String *ctype = SwigType_lstr(p_classtype, ""); String *free = NewString(""); + // (Taken from JSCore implementation.) + /* The if (Extend) block was taken from the Ruby implementation. + * The problem is that in the case of an %extend to create a destructor for a struct to coordinate automatic memory cleanup with the Javascript collector, + * the swig function was not being generated. More specifically: + struct MyData { + %extend { + ~MyData() { + FreeData($self); + } + } + }; + %newobject CreateData; + struct MyData* CreateData(void); + %delobject FreeData; + void FreeData(struct MyData* the_data); + + where the use case is something like: + var my_data = example.CreateData(); + my_data = null; + + This function was not being generated: + SWIGINTERN void delete_MyData(struct MyData *self){ + FreeData(self); + } + + I don't understand fully why it wasn't being generated. It just seems to happen in the Lua generator. + There is a comment about staticmemberfunctionHandler having an inconsistency and I tracked down dome of the SWIGINTERN void delete_* + code to that function in the Language base class. + The Ruby implementation seems to have an explicit check for if(Extend) and explicitly generates the code, so that's what I'm doing here. + The Ruby implementation does other stuff which I omit. + */ + if (Extend) { + String *wrap = Getattr(n, "wrap:code"); + if (wrap) { + Printv(f_wrappers, wrap, NIL); + } + } + + // HACK: this is only for the v8 emitter. maybe set an attribute wrap:action of node // TODO: generate dtors more similar to other wrappers + // EW: I think this is wrong. delete should only be used when new was used to create. If malloc was used, free needs to be used. if(SwigType_isarray(type)) { Printf(free, "delete [] (%s)", ctype); } else { Printf(free, "delete (%s)", ctype); } - state.clazz(DTOR, wrap_name); - t_dtor.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) + String* destructor_action = Getattr(n, "wrap:action"); + // Adapted from the JSCore implementation. + /* The next challenge is to generate the correct finalize function for JavaScriptCore to call. + Originally, it would use this fragment from javascriptcode.swg + %fragment ("JS_destructordefn", "templates") + %{ + void _wrap_${classname_mangled}_finalize(JSObjectRef thisObject) + { + SWIG_PRV_DATA* t = (SWIG_PRV_DATA*)JSObjectGetPrivate(thisObject); + if(t && t->swigCMemOwn) free ((${type}*)t->swigCObject); + if(t) free(t); + } + %} + + But for the above example case of %extend to define a destructor on a struct, we need to override the system to not call + free ((${type}*)t->swigCObject); + and substitute it with what the user has provided. + To solve this, I created a variation fragment called JS_destructoroverridedefn: + SWIG_PRV_DATA* t = (SWIG_PRV_DATA*)JSObjectGetPrivate(thisObject); + if(t && t->swigCMemOwn) { + ${type}* arg1 = (${type}*)t->swigCObject; + ${destructor_action} + } + if(t) free(t); + + Based on what I saw in the Lua and Ruby modules, I use Getattr(n, "wrap:action") + to decide if the user has a preferred destructor action. + Based on that, I decide which fragment to use. + And in the case of the custom action, I substitute that action in. + I noticed that destructor_action has the form + delete_MyData(arg1); + The explicit arg1 is a little funny, so I structured the fragment to create a temporary variable called arg1 to make the generation easier. + This might suggest this solution misunderstands a more complex case. + + Also, there is a problem where destructor_action is always true for me, even when not requesting %extend as above. + So this code doesn't actually quite work as I expect. The end result is that the code still works because + destructor_action calls free like the original template. The one caveat is the string in destructor_action casts to char* which is wierd. + I think there is a deeper underlying SWIG issue because I don't think it should be char*. However, it doesn't really matter for free. + + Maybe the fix for the destructor_action always true problem is that this is supposed to be embedded in the if(Extend) block above. + But I don't fully understand the conditions of any of these things, and since it works for the moment, I don't want to break more stuff. + */ + if(destructor_action) { + Template t_dtor = getTemplate("js_dtoroverride"); + state.clazz(DTOR, wrap_name); + t_dtor.replace("${classname_mangled}", state.clazz(NAME_MANGLED)) + .replace(T_WRAPPER, wrap_name) + .replace(T_FREE, free) + .replace(T_TYPE, ctype); + + t_dtor.replace("${destructor_action}", destructor_action); + Wrapper_pretty_print(t_dtor.str(), f_wrappers); + } + else { + Template t_dtor = getTemplate("js_dtor"); + state.clazz(DTOR, wrap_name); + t_dtor.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) .replace(T_WRAPPER, wrap_name) .replace(T_FREE, free) .replace(T_TYPE, ctype) .pretty_print(f_wrappers); + } Delete(p_classtype); Delete(ctype); From f8feeacb68593063914c58c60e408d8515295b7f Mon Sep 17 00:00:00 2001 From: Eric Wing Date: Thu, 11 Jul 2013 19:11:56 -0700 Subject: [PATCH 0257/1048] v8: Removed the extern "C" around the initialize function because it makes no sense since it requires a C++ templates object as a parameter. --- Lib/javascript/v8/javascriptcode.swg | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 62267ae52..003658613 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -403,7 +403,8 @@ fail: * ----------------------------------------------------------------------------- */ %fragment("js_initializer", "templates") %{ -extern "C" { +// The extern "C" makes little sense here because the paramater is using C++ objects and templates. +// extern "C" { void $jsname_initialize(v8::Handle global_obj) { @@ -440,5 +441,5 @@ void $jsname_initialize(v8::Handle global_obj) } -} // extern "C" +// } // extern "C" %} From 65a0be8876959dd9a79bc3d7290af15ab646202d Mon Sep 17 00:00:00 2001 From: Eric Wing Date: Thu, 11 Jul 2013 20:04:01 -0700 Subject: [PATCH 0258/1048] v8: variable name bug fix in my template modifications for pointers to structs. --- Lib/javascript/v8/javascriptcode.swg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 003658613..ef3d1f896 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -133,7 +133,7 @@ void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) { SWIGV8_Proxy* proxy = (SWIGV8_Proxy*) parameter; if(proxy->swigCMemOwn && proxy->swigCObject) { // std::cout << "Deleting wrapped instance: " << proxy->info->name << std::endl; - $jstype arg1 = ($jstype)t->swigCObject; + $jstype arg1 = ($jstype)proxy->swigCObject; ${destructor_action} } delete proxy; From 4503c5390304202275a849eaa8473985adf86f02 Mon Sep 17 00:00:00 2001 From: Eric Wing Date: Wed, 7 Aug 2013 15:12:36 -0700 Subject: [PATCH 0259/1048] Since this code uses assert, #include is needed. --- Lib/javascript/v8/javascriptinit.swg | 1 + 1 file changed, 1 insertion(+) diff --git a/Lib/javascript/v8/javascriptinit.swg b/Lib/javascript/v8/javascriptinit.swg index 684728023..13ec1aff8 100644 --- a/Lib/javascript/v8/javascriptinit.swg +++ b/Lib/javascript/v8/javascriptinit.swg @@ -1,5 +1,6 @@ %insert(init) %{ +#include SWIGRUNTIME void SWIG_V8_SetModule(void *, swig_module_info *swig_module) { From 0732592ed99759afab2f05e6be1723659e955464 Mon Sep 17 00:00:00 2001 From: Kota Iguchi Date: Wed, 7 Aug 2013 18:10:53 -0700 Subject: [PATCH 0260/1048] Patch to support argout typemap for your swig-v8 branch. --- Source/Modules/javascript.cxx | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 8c82890a6..6eb2c572d 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1285,6 +1285,16 @@ void JSEmitter::emitCleanupCode(Node *n, Wrapper *wrapper, ParmList *params) { Parm *p; String *tm; + for (p = params; p;) { + if ((tm = Getattr(p, "tmap:argout"))) { + Replaceall(tm, "$input", Getattr(p, "emit:input")); + Printv(wrapper->code, tm, "\n", NIL); + p = Getattr(p, "tmap:argout:next"); + } else { + p = nextSibling(p); + } + } + for (p = params; p;) { if ((tm = Getattr(p, "tmap:freearg"))) { //addThrows(n, "tmap:freearg", p); From cb5f4dc47eeac71a0c5f39618027382567cb53d4 Mon Sep 17 00:00:00 2001 From: Vladimir Menshakov Date: Thu, 15 Aug 2013 14:33:00 +0400 Subject: [PATCH 0261/1048] ported to newer, more efficient v8 api --- Lib/javascript/v8/javascriptcode.swg | 67 ++++++++++++------------- Lib/javascript/v8/javascripthelpers.swg | 10 ++-- 2 files changed, 38 insertions(+), 39 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 39c1f3a79..ebe841b22 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -7,19 +7,18 @@ * - $jsmangledtype: mangled type of class * ----------------------------------------------------------------------------- */ %fragment("js_ctor", "templates") %{ -v8::Handle $jswrapper(const v8::Arguments& args) { +void $jswrapper(const v8::FunctionCallbackInfo& args) { v8::HandleScope scope; v8::Handle self = args.Holder(); $jslocals if(args.Length() != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); $jscode - - SWIGV8_SetPrivateData(self, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); - return scope.Close(self); - goto fail; + SWIGV8_SetPrivateData(self, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); + args.GetReturnValue().Set(self); + fail: - return scope.Close(v8::Undefined()); + return; } %} @@ -30,10 +29,9 @@ fail: * ----------------------------------------------------------------------------- */ %fragment ("js_veto_ctor", "templates") %{ -v8::Handle $jswrapper(const v8::Arguments& args) { +void $jswrapper(const v8::FunctionCallbackInfo& args) { v8::HandleScope scope; SWIG_exception(SWIG_ERROR, "Class $jsname can not be instantiated"); - return scope.Close(v8::Undefined()); } %} @@ -45,7 +43,7 @@ v8::Handle $jswrapper(const v8::Arguments& args) { * ----------------------------------------------------------------------------- */ %fragment ("js_ctor_dispatcher", "templates") %{ -v8::Handle $jswrapper(const v8::Arguments& args) { +void $jswrapper(const v8::FunctionCallbackInfo& args) { v8::HandleScope scope; OverloadErrorHandler errorHandler; v8::Handle self; @@ -57,7 +55,7 @@ v8::Handle $jswrapper(const v8::Arguments& args) { SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for contruction of $jsmangledname"); fail: - return scope.Close(v8::Undefined()); + return; } %} @@ -70,7 +68,7 @@ fail: * - $jsmangledtype: mangled type of class * ----------------------------------------------------------------------------- */ %fragment("js_overloaded_ctor", "templates") %{ -v8::Handle $jswrapper(const v8::Arguments& args, V8ErrorHandler& SWIGV8_ErrorHandler) { +void $jswrapper(const v8::FunctionCallbackInfo& args, V8ErrorHandler& SWIGV8_ErrorHandler) { v8::HandleScope scope; v8::Handle self = args.Holder(); $jslocals @@ -78,11 +76,11 @@ v8::Handle $jswrapper(const v8::Arguments& args, V8ErrorHandler& SWIG $jscode SWIGV8_SetPrivateData(self, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); - return scope.Close(self); + args.GetReturnValue().Set(self); goto fail; fail: - return scope.Close(v8::Undefined()); + return; } %} @@ -97,10 +95,9 @@ fail: %{ if(args.Length() == $jsargcount) { errorHandler.err.Clear(); - self = $jswrapper(args, errorHandler); - if(errorHandler.err.IsEmpty()) { - return scope.Close(self); - } + $jswrapper(args, errorHandler); + if(errorHandler.err.IsEmpty()) + return; } %} @@ -171,15 +168,16 @@ void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) { * ----------------------------------------------------------------------------- */ %fragment("js_getter", "templates") %{ -v8::Handle $jswrapper(v8::Local property, const v8::AccessorInfo& info) { +void $jswrapper(v8::Local property, const v8::PropertyCallbackInfo& info) { v8::HandleScope scope; v8::Handle jsresult; $jslocals $jscode - return scope.Close(jsresult); + info.GetReturnValue().Set(jsresult); + return; goto fail; fail: - return scope.Close(v8::Undefined()); + return; } %} @@ -191,7 +189,7 @@ fail: * ----------------------------------------------------------------------------- */ %fragment("js_setter", "templates") %{ -void $jswrapper(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { +void $jswrapper(v8::Local property, v8::Local value, const v8::PropertyCallbackInfo& info) { v8::HandleScope scope; $jslocals $jscode @@ -209,17 +207,18 @@ fail: * ----------------------------------------------------------------------------- */ %fragment("js_function", "templates") %{ -v8::Handle $jswrapper(const v8::Arguments &args) { +void $jswrapper(const v8::FunctionCallbackInfo& args) { v8::HandleScope scope; v8::Handle jsresult; $jslocals if(args.Length() != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); - + $jscode - return scope.Close(jsresult); + args.GetReturnValue().Set(jsresult); + return; goto fail; fail: - return scope.Close(v8::Undefined()); + return; } %} @@ -232,7 +231,7 @@ fail: * ----------------------------------------------------------------------------- */ %fragment("js_function_dispatcher", "templates") %{ -v8::Handle $jswrapper(const v8::Arguments &args) { +void $jswrapper(const v8::FunctionCallbackInfo& args) { v8::HandleScope scope; v8::Handle jsresult; OverloadErrorHandler errorHandler; @@ -242,7 +241,7 @@ v8::Handle $jswrapper(const v8::Arguments &args) { goto fail; fail: - return scope.Close(v8::Undefined()); + return; } %} @@ -254,16 +253,17 @@ fail: * ----------------------------------------------------------------------------- */ %fragment ("js_overloaded_function", "templates") %{ -v8::Handle $jswrapper(const v8::Arguments &args, V8ErrorHandler& SWIGV8_ErrorHandler) +void $jswrapper(const v8::FunctionCallbackInfo& args, V8ErrorHandler& SWIGV8_ErrorHandler) { v8::HandleScope scope; v8::Handle jsresult; $jslocals $jscode - return scope.Close(jsresult); + args.GetReturnValue().Set(jsresult); + return; goto fail; fail: - return scope.Close(jsresult); + return; } %} @@ -277,10 +277,9 @@ fail: %{ if(args.Length() == $jsargcount) { errorHandler.err.Clear(); - jsresult = $jswrapper(args, errorHandler); - if(errorHandler.err.IsEmpty()) { - return scope.Close(jsresult); - } + $jswrapper(args, errorHandler); + if(errorHandler.err.IsEmpty()) + return; } %} diff --git a/Lib/javascript/v8/javascripthelpers.swg b/Lib/javascript/v8/javascripthelpers.swg index d28243d88..847e9b73c 100644 --- a/Lib/javascript/v8/javascripthelpers.swg +++ b/Lib/javascript/v8/javascripthelpers.swg @@ -17,7 +17,7 @@ v8::Handle SWIGV8_CreateClassTemplate(const char* symbol) /** * Registers a class method with given name for a given class template. */ -void SWIGV8_AddMemberFunction(v8::Handle class_templ, const char* symbol, v8::InvocationCallback _func) { +void SWIGV8_AddMemberFunction(v8::Handle class_templ, const char* symbol, v8::FunctionCallback _func) { v8::Handle proto_templ = class_templ->PrototypeTemplate(); proto_templ->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)); } @@ -25,7 +25,7 @@ void SWIGV8_AddMemberFunction(v8::Handle class_templ, cons /** * Registers a class property with given name for a given class template. */ -void SWIGV8_AddMemberVariable(v8::Handle class_templ, const char* symbol, v8::AccessorGetter getter, v8::AccessorSetter setter) { +void SWIGV8_AddMemberVariable(v8::Handle class_templ, const char* symbol, v8::AccessorGetterCallback getter, v8::AccessorSetterCallback setter) { v8::Handle proto_templ = class_templ->InstanceTemplate(); proto_templ->SetAccessor(v8::String::NewSymbol(symbol), getter, setter); } @@ -33,18 +33,18 @@ void SWIGV8_AddMemberVariable(v8::Handle class_templ, cons /** * Registers a class method with given name for a given object. */ -void SWIGV8_AddStaticFunction(v8::Handle obj, const char* symbol, v8::InvocationCallback _func) { +void SWIGV8_AddStaticFunction(v8::Handle obj, const char* symbol, const v8::FunctionCallback& _func) { obj->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)->GetFunction()); } /** * Registers a class method with given name for a given object. */ -void SWIGV8_AddStaticVariable(v8::Handle obj, const char* symbol, v8::AccessorGetter getter, v8::AccessorSetter setter) { +void SWIGV8_AddStaticVariable(v8::Handle obj, const char* symbol, v8::AccessorGetterCallback getter, v8::AccessorSetterCallback setter) { obj->SetAccessor(v8::String::NewSymbol(symbol), getter, setter); } -void JS_veto_set_variable(v8::Local property, v8::Local value, const v8::AccessorInfo& info) +void JS_veto_set_variable(v8::Local property, v8::Local value, const v8::PropertyCallbackInfo& info) { char buffer[256]; char msg[512]; From 5aba4c7ea657f086519acb950e19c416d808b74a Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 3 Sep 2013 05:35:03 +0200 Subject: [PATCH 0262/1048] Starting from scratch with Examples configuration. --- Examples/Makefile.in | 89 +++++++------------------------------------- 1 file changed, 14 insertions(+), 75 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 803c7fa9a..94a00e642 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -517,102 +517,41 @@ java_clean: ##### JAVASCRIPT ###### ################################################################## -# You need to set this variable to the jscore[or other javascript engine] directories containing the -# files "JavaScript.h" and others - -JS_INCLUDE = @JSCOREINC@ @JSV8INC@ -JS_DLNK = @JSCOREDYNAMICLINKING@ @JSV8DYNAMICLINKING@ - -# Extra JAVASCRIPT specific dynamic linking options -JS_LIBPREFIX = @JSCORELIBRARYPREFIX@ -JSSO =@JSCORESO@ -JSLDSHARED = @JSCORELDSHARED@ -JSCXXSHARED = @JSCORECXXSHARED@ -JSCFLAGS = @JSCORECFLAGS@ -JSCXXFLAGS = @JSCXXFLAGS@ -ROOT_DIR = @ROOT_DIR@ -JSCORE = @JSCORE@ -JSV8 = @JSV8@ -JSDEFAULT = @JSDEFAULT@ - -JSEXE_SRC_DIR = $(ROOT_DIR)/Tools/javascript -JSEXE = $(JSEXE_SRC_DIR)/javascript - -ifneq (,$(JSCORE)) - JSEXE_SRC_JSC = $(JSEXE_SRC_DIR)/jsc_shell.cxx - JSEXE_FLAGS_JSC = -DENABLE_JSC -endif - -ifneq (,$(JSV8)) - JSEXE_SRC_V8 = $(JSEXE_SRC_DIR)/v8_shell.cxx - JSEXE_FLAGS_V8 = -DENABLE_V8 -endif - -JSEXE_SRC = $(JSEXE_SRC_DIR)/javascript.cxx $(JSEXE_SRC_DIR)/js_shell.cxx $(JSEXE_SRC_JSC) $(JSEXE_SRC_V8) -JSEXE_FLAGS = $(JSEXE_FLAGS_JSC) $(JSEXE_FLAGS_V8) - -# this controls which engine the code will be generated for -# and correspondingly the argument for the js interpreter -ifneq (,$(JSC)) - SWIGJS = $(SWIG) -javascript -jsc - JSEXE_OPTS = -jsc -else -ifneq (,$(V8)) - SWIGJS = $(SWIG) -javascript -v8 - JSEXE_OPTS = -v8 -else - SWIGJS = $(SWIG) -javascript -$(JSDEFAULT) - JSEXE_OPTS = -$(JSDEFAULT) -endif -endif - # ---------------------------------------------------------------- -# Build a javascript dynamically loadable module (C) +# Definitions # ---------------------------------------------------------------- -# Note: for v8 there is no C support, so forwarding to javascript_cpp -ifeq (,$(V8)) -javascript: $(SRCS) - $(SWIGJS) $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(JSCFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(JS_INCLUDE) - $(JSLDSHARED) $(CCSHARED) $(OBJS) $(IOBJS) $(JS_DLNK) $(LIBS) -o $(JS_LIBPREFIX)$(TARGET)$(JSSO) -else -javascript: $(SRCS) javascript_cpp -endif +JSEXE = node +SWIGJS = $(SWIG) -javascript -node +JS_BUILD = node-gyp rebuild # ---------------------------------------------------------------- -# Build a javascript dynamically loadable module (C++) +# Run the javascript executable # ---------------------------------------------------------------- -javascript_cpp: $(SRCS) +javascript_wrapper_cpp: $(SRCS) $(SWIGJS) -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(JSCXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(JS_INCLUDE) - $(JSCXXSHARED) $(CCSHARED) $(OBJS) $(IOBJS) $(JS_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(JS_LIBPREFIX)$(TARGET)$(JSSO) -# ---------------------------------------------------------------- -# Compile a javascript executable -# ---------------------------------------------------------------- -javascript_exe: $(SRCS) - $(CXX) $(CXXFLAGS) $(JSEXE_FLAGS) $(JS_INCLUDE) $(LIBS) $(JSEXE_SRC) $(JS_DLNK) -ldl -o $(JSEXE) +javascript_build: + $(JS_BUILD) -# ---------------------------------------------------------------- -# Run the Compile a javascript executable -# ---------------------------------------------------------------- +#javascript_run: $(SRCS) +# env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(JSEXE) $(JSEXE_OPTS) -l $(TARGET) $(JS_SCRIPT) javascript_run: $(SRCS) - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(JSEXE) $(JSEXE_OPTS) -l $(TARGET) $(JS_SCRIPT) + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(JSEXE) $(JSEXE_OPTS) $(JS_SCRIPT) # ----------------------------------------------------------------- # Cleaning the javascript examples # ----------------------------------------------------------------- javascript_clean: + rm -rf build rm -f *_wrap* runme rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *@JSCORESO@ - ################################################################## ##### MODULA3 ###### ################################################################## @@ -1247,14 +1186,14 @@ R_CFLAGS=-fPIC r: $(SRCS) $(SWIG) -r $(SWIGOPT) $(INTERFACEPATH) ifneq ($(SRCS),) - $(CXX) -g -c $(CFLAGS) $(R_CFLAGS) $(SRCS) $(INCLUDES) + $(CXX) -g -c $(CFLAGS) $(R_CFLAGS) $(SRCS) $(INCLUDES) endif +( PKG_CPPFLAGS="$(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(ISRCS) $(OBJS) > /dev/null ) r_cpp: $(CXXSRCS) $(SWIG) -c++ -r $(SWIGOPT) -o $(RCXXSRCS) $(INTERFACEPATH) ifneq ($(CXXSRCS),) - $(CXX) -g -c $(CFLAGS) $(R_CFLAGS) $(CXXSRCS) $(INCLUDES) + $(CXX) -g -c $(CFLAGS) $(R_CFLAGS) $(CXXSRCS) $(INCLUDES) endif +( PKG_CPPFLAGS="$(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(RCXXSRCS) $(OBJS) > /dev/null ) From 5228c0eeab0e96930d18e1b0b0d732636adc882f Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 3 Sep 2013 05:36:41 +0200 Subject: [PATCH 0263/1048] Add a dedicated mode for creating node modules. --- Source/Modules/javascript.cxx | 31 +++++++++++++------------------ 1 file changed, 13 insertions(+), 18 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 6eb2c572d..884e09ebe 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -145,8 +145,7 @@ public: enum JSEmitterType { JavascriptCore, - V8, - QtScript + V8 }; JSEmitter(); @@ -530,14 +529,16 @@ void JAVASCRIPT::main(int argc, char *argv[]) { Swig_mark_arg(i); mode = JSEmitter::V8; SWIG_library_directory("javascript/v8"); + } else if (strcmp(argv[i], "-node") == 0) { + Swig_mark_arg(i); + mode = JSEmitter::V8; + SWIG_library_directory("javascript/v8"); + createModuleObject = false; + Preprocessor_define("BUILDING_NODE_EXTENSION 1", 0); } else if (strcmp(argv[i], "-jsc") == 0) { Swig_mark_arg(i); mode = JSEmitter::JavascriptCore; SWIG_library_directory("javascript/jsc"); - } else if (strcmp(argv[i], "-qt") == 0) { - Swig_mark_arg(i); - mode = JSEmitter::QtScript; - SWIG_library_directory("javascript/qt"); } else if (strcmp(argv[i], "-debug-codetemplates") == 0) { Swig_mark_arg(i); js_template_enable_debug = true; @@ -561,12 +562,6 @@ void JAVASCRIPT::main(int argc, char *argv[]) { Preprocessor_define("SWIG_JAVASCRIPT_JSC 1", 0); break; } - case JSEmitter::QtScript: - { - Printf(stderr, "QtScript support is not yet implemented."); - SWIG_exit(-1); - break; - } default: { Printf(stderr, "Unknown emitter type."); @@ -898,15 +893,15 @@ int JSEmitter::emitDtor(Node *n) { } } }; - %newobject CreateData; + %newobject CreateData; struct MyData* CreateData(void); %delobject FreeData; void FreeData(struct MyData* the_data); - + where the use case is something like: var my_data = example.CreateData(); my_data = null; - + This function was not being generated: SWIGINTERN void delete_MyData(struct MyData *self){ FreeData(self); @@ -964,13 +959,13 @@ int JSEmitter::emitDtor(Node *n) { to decide if the user has a preferred destructor action. Based on that, I decide which fragment to use. And in the case of the custom action, I substitute that action in. - I noticed that destructor_action has the form + I noticed that destructor_action has the form delete_MyData(arg1); The explicit arg1 is a little funny, so I structured the fragment to create a temporary variable called arg1 to make the generation easier. This might suggest this solution misunderstands a more complex case. Also, there is a problem where destructor_action is always true for me, even when not requesting %extend as above. - So this code doesn't actually quite work as I expect. The end result is that the code still works because + So this code doesn't actually quite work as I expect. The end result is that the code still works because destructor_action calls free like the original template. The one caveat is the string in destructor_action casts to char* which is wierd. I think there is a deeper underlying SWIG issue because I don't think it should be char*. However, it doesn't really matter for free. @@ -1186,7 +1181,7 @@ int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { // String *wrap_name = Swig_name_wrapper(Getattr(n, "name")); - + String *fun_name = Getattr(n, "sym:name"); Node *methodclass = Swig_methodclass(n); From a48438c562b3f1601e5bbc9cedcf9f124af97975 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 3 Sep 2013 05:39:37 +0200 Subject: [PATCH 0264/1048] Better v8 version handling. You should start to specify a version on command line, e.g., swig -javascript -v8 -DSWIG_V8_VERSION=0x032007 --- Lib/javascript/v8/javascriptcode.swg | 180 ++++++++++++++---------- Lib/javascript/v8/javascripthelpers.swg | 44 ++++-- Lib/javascript/v8/javascriptruntime.swg | 44 ++++-- 3 files changed, 168 insertions(+), 100 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index ebe841b22..377e93752 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -6,19 +6,37 @@ * - $jsargcount: number of arguments * - $jsmangledtype: mangled type of class * ----------------------------------------------------------------------------- */ + +%insert(runtime) %{ +#if (SWIG_V8_VERSION < 0x031900) +typedef v8::Handle SwigV8ReturnValue; +typedef v8::Arguments SwigV8Arguments; +typedef v8::AccessorInfo SwigV8PropertyCallbackInfo; +#define SWIGV8_RETURN(val) return scope.Close(val) +#define SWIGV8_RETURN_INFO(val, info) return scope.Close(val) +#else +typedef void SwigV8ReturnValue; +typedef v8::FunctionCallbackInfo SwigV8Arguments; +typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfo; +#define SWIGV8_RETURN(val) return args.GetReturnValue().Set(val) +#define SWIGV8_RETURN_INFO(val, info) return args.GetReturnValue().Set(val) +#endif +%} + %fragment("js_ctor", "templates") %{ -void $jswrapper(const v8::FunctionCallbackInfo& args) { +SwigV8ReturnValue $jswrapper(const SwigV8Arguments& args) { v8::HandleScope scope; v8::Handle self = args.Holder(); $jslocals - if(args.Length() != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); + if(args.Length() != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); $jscode SWIGV8_SetPrivateData(self, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); - args.GetReturnValue().Set(self); + SWIGV8_RETURN(self); + goto fail; fail: - return; + SWIGV8_RETURN(v8::Undefined()); } %} @@ -29,9 +47,10 @@ fail: * ----------------------------------------------------------------------------- */ %fragment ("js_veto_ctor", "templates") %{ -void $jswrapper(const v8::FunctionCallbackInfo& args) { +SwigV8ReturnValue $jswrapper(const SwigV8Arguments& args) { v8::HandleScope scope; SWIG_exception(SWIG_ERROR, "Class $jsname can not be instantiated"); + SWIGV8_RETURN(v8::Undefined()); } %} @@ -43,18 +62,19 @@ void $jswrapper(const v8::FunctionCallbackInfo& args) { * ----------------------------------------------------------------------------- */ %fragment ("js_ctor_dispatcher", "templates") %{ -void $jswrapper(const v8::FunctionCallbackInfo& args) { +SwigV8ReturnValue $jswrapper(const SwigV8Arguments& args) { v8::HandleScope scope; OverloadErrorHandler errorHandler; v8::Handle self; - + // switch all cases by means of series of if-returns. $jsdispatchcases // default: SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for contruction of $jsmangledname"); - + fail: + SWIGV8_RETURN(v8::Undefined()); return; } %} @@ -68,19 +88,19 @@ fail: * - $jsmangledtype: mangled type of class * ----------------------------------------------------------------------------- */ %fragment("js_overloaded_ctor", "templates") %{ -void $jswrapper(const v8::FunctionCallbackInfo& args, V8ErrorHandler& SWIGV8_ErrorHandler) { +SwigV8ReturnValue $jswrapper(const SwigV8Arguments& args, V8ErrorHandler& SWIGV8_ErrorHandler) { v8::HandleScope scope; v8::Handle self = args.Holder(); $jslocals - if(args.Length() != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); + if(args.Length() != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); $jscode - + SWIGV8_SetPrivateData(self, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); - args.GetReturnValue().Set(self); + SWIGV8_RETURN(self); goto fail; fail: - return; + SWIGV8_RETURN(v8::Undefined()); } %} @@ -89,15 +109,23 @@ fail: * - $jsargcount: number of arguments of called ctor * - $jswrapper: wrapper of called ctor * - * Note: a try-catch-like mechanism is used to switch cases + * Note: a try-catch-like mechanism is used to switch cases * ----------------------------------------------------------------------------- */ %fragment ("js_ctor_dispatch_case", "templates") %{ if(args.Length() == $jsargcount) { errorHandler.err.Clear(); +#if SWIG_V8_VERSION < 0x031900 + self = $jswrapper(args, errorHandler); + if(errorHandler.err.IsEmpty()) { + return scope.Close(self); + } +#else $jswrapper(args, errorHandler); - if(errorHandler.err.IsEmpty()) + if(errorHandler.err.IsEmpty()) { return; + } +#endif } %} @@ -109,15 +137,13 @@ fail: %fragment ("js_dtor", "templates") %{ -#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) -void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) -#else -void $jswrapper(v8::Isolate *isolate, v8::Persistent< v8::Object > * object, SWIGV8_Proxy *proxy) -#endif +#if (SWIG_V8_VERSION < 0x031900) +void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) +{ + SWIGV8_Proxy *proxy = static_cast(parameter); +#else +void $jswrapper(v8::Isolate *isolate, v8::Persistent< v8::Object > * object, SWIGV8_Proxy *proxy) { - -#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) - SWIGV8_Proxy *proxy = static_cast(parameter); #endif if(proxy->swigCMemOwn && proxy->swigCObject) { @@ -129,11 +155,10 @@ void $jswrapper(v8::Isolate *isolate, v8::Persistent< v8::Object > * object, SWI delete proxy; -#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) object.Clear(); +#if (SWIG_V8_VERSION < 0x031900) object.Dispose(); #else - object->Clear(); object->Dispose(isolate); #endif } @@ -143,7 +168,7 @@ void $jswrapper(v8::Isolate *isolate, v8::Persistent< v8::Object > * object, SWI * js_dtoroverride: template for a destructor wrapper * - $jsmangledname: mangled class name * - $jstype: class type - * - ${destructor_action}: The custom destructor action to invoke. + * - ${destructor_action}: The custom destructor action to invoke. * ----------------------------------------------------------------------------- */ %fragment ("js_dtoroverride", "templates") %{ @@ -166,18 +191,18 @@ void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) { * - $jslocals: locals part of wrapper * - $jscode: code part of wrapper * ----------------------------------------------------------------------------- */ -%fragment("js_getter", "templates") +%fragment("js_getter", "templates") %{ -void $jswrapper(v8::Local property, const v8::PropertyCallbackInfo& info) { +SwigV8ReturnValue $jswrapper(v8::Local property, const SwigV8PropertyCallbackInfo& info) { v8::HandleScope scope; v8::Handle jsresult; $jslocals $jscode - info.GetReturnValue().Set(jsresult); - return; + SWIGV8_RETURN_INFO(jsresult, info); + goto fail; fail: - return; + SWIGV8_RETURN_INFO(v8::Undefined(), info); } %} @@ -189,7 +214,8 @@ fail: * ----------------------------------------------------------------------------- */ %fragment("js_setter", "templates") %{ -void $jswrapper(v8::Local property, v8::Local value, const v8::PropertyCallbackInfo& info) { +void $jswrapper(v8::Local property, v8::Local value, + const SwigV8PropertyCallbackInfo& info) { v8::HandleScope scope; $jslocals $jscode @@ -205,20 +231,20 @@ fail: * - $jslocals: locals part of wrapper * - $jscode: code part of wrapper * ----------------------------------------------------------------------------- */ -%fragment("js_function", "templates") +%fragment("js_function", "templates") %{ -void $jswrapper(const v8::FunctionCallbackInfo& args) { +SwigV8ReturnValue $jswrapper(const SwigV8Arguments& args) { v8::HandleScope scope; v8::Handle jsresult; $jslocals - if(args.Length() != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); + if(args.Length() != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); $jscode - args.GetReturnValue().Set(jsresult); - return; + SWIGV8_RETURN(jsresult); + goto fail; fail: - return; + SWIGV8_RETURN(v8::Undefined()); } %} @@ -231,7 +257,7 @@ fail: * ----------------------------------------------------------------------------- */ %fragment("js_function_dispatcher", "templates") %{ -void $jswrapper(const v8::FunctionCallbackInfo& args) { +SwigV8ReturnValue $jswrapper(const SwigV8Arguments& args) { v8::HandleScope scope; v8::Handle jsresult; OverloadErrorHandler errorHandler; @@ -241,7 +267,7 @@ void $jswrapper(const v8::FunctionCallbackInfo& args) { goto fail; fail: - return; + SWIGV8_RETURN(v8::Undefined()); } %} @@ -253,17 +279,17 @@ fail: * ----------------------------------------------------------------------------- */ %fragment ("js_overloaded_function", "templates") %{ -void $jswrapper(const v8::FunctionCallbackInfo& args, V8ErrorHandler& SWIGV8_ErrorHandler) +SwigV8ReturnValue $jswrapper(const SwigV8Arguments& args, V8ErrorHandler& SWIGV8_ErrorHandler) { - v8::HandleScope scope; + v8::HandleScope scope; v8::Handle jsresult; $jslocals $jscode - args.GetReturnValue().Set(jsresult); - return; + SWIGV8_RETURN(jsresult); + goto fail; fail: - return; + SWIGV8_RETURN(v8::Undefined()); } %} @@ -275,11 +301,20 @@ fail: * ----------------------------------------------------------------------------- */ %fragment ("js_function_dispatch_case", "templates") %{ + if(args.Length() == $jsargcount) { - errorHandler.err.Clear(); - $jswrapper(args, errorHandler); - if(errorHandler.err.IsEmpty()) + errorHandler.err.Clear(); +#if (SWIG_V8_VERSION < 0x031900) + jsresult = $jswrapper(args, errorHandler); + if(errorHandler.err.IsEmpty()) { + return scope.Close(jsresult); + } +#else + $jswrapper(args, errorHandler); + if(errorHandler.err.IsEmpty()) { return; + } +#endif } %} @@ -287,7 +322,7 @@ fail: * jsv8_declare_class_template: template for a class template declaration. * - $jsmangledname: mangled class name * ----------------------------------------------------------------------------- */ -%fragment("jsv8_declare_class_template", "templates") +%fragment("jsv8_declare_class_template", "templates") %{ SWIGV8_ClientData $jsmangledname_clientData; %} @@ -298,15 +333,15 @@ fail: * - $jsmangledtype: mangled class type * - $jsdtor: the dtor wrapper * ----------------------------------------------------------------------------- */ -%fragment("jsv8_define_class_template", "templates") +%fragment("jsv8_define_class_template", "templates") %{ v8::Handle $jsmangledname_class = SWIGV8_CreateClassTemplate("$jsmangledname"); -#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) +#if (SWIG_V8_VERSION < 0x031900) $jsmangledname_clientData.class_templ = v8::Persistent::New($jsmangledname_class); #else $jsmangledname_clientData.class_templ.Reset(v8::Isolate::GetCurrent(), $jsmangledname_class); #endif - $jsmangledname_clientData.dtor = $jsdtor; + $jsmangledname_clientData.dtor = $jsdtor; SWIGTYPE$jsmangledtype->clientdata = &$jsmangledname_clientData; %} @@ -316,11 +351,11 @@ fail: * - $jsmangledname: mangled class name * - $jsbaseclass: mangled name of the base class * ----------------------------------------------------------------------------- */ -%fragment("jsv8_inherit", "templates") +%fragment("jsv8_inherit", "templates") %{ if (SWIGTYPE_p$jsbaseclass->clientdata && !(static_cast(SWIGTYPE_p$jsbaseclass->clientdata)->class_templ.IsEmpty())) { -#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) +#if (SWIG_V8_VERSION < 0x031900) $jsmangledname_class->Inherit(static_cast(SWIGTYPE_p$jsbaseclass->clientdata)->class_templ); #else $jsmangledname_class->Inherit( @@ -345,7 +380,7 @@ fail: * - $jsname: class name * - $jsmangledname: mangled class name * ----------------------------------------------------------------------------- */ -%fragment("jsv8_create_class_instance", "templates") +%fragment("jsv8_create_class_instance", "templates") %{ v8::Handle $jsmangledname_class_0 = SWIGV8_CreateClassTemplate("$jsname"); $jsmangledname_class_0->SetCallHandler($jsctor); @@ -360,7 +395,7 @@ fail: * - $jsmangledname: mangled class name * - $jsparent: mangled name of parent namespace * ----------------------------------------------------------------------------- */ -%fragment("jsv8_register_class", "templates") +%fragment("jsv8_register_class", "templates") %{ $jsparent_obj->Set(v8::String::NewSymbol("$jsname"), $jsmangledname_obj); %} @@ -369,7 +404,7 @@ fail: * jsv8_create_namespace: template for a statement that creates a namespace object. * - $jsmangledname: mangled namespace name * ----------------------------------------------------------------------------- */ -%fragment("jsv8_create_namespace", "templates") +%fragment("jsv8_create_namespace", "templates") %{ v8::Handle $jsmangledname_obj = v8::Object::New(); %} @@ -380,7 +415,7 @@ fail: * - $jsmangledname: mangled name of namespace * - $jsparent: mangled name of parent namespace * ----------------------------------------------------------------------------- */ -%fragment("jsv8_register_namespace", "templates") +%fragment("jsv8_register_namespace", "templates") %{ $jsparent_obj->Set(v8::String::NewSymbol("$jsname"), $jsmangledname_obj); %} @@ -391,7 +426,7 @@ fail: * - $jsname: name of the function * - $jswrapper: wrapper of the member function * ----------------------------------------------------------------------------- */ -%fragment("jsv8_register_member_function", "templates") +%fragment("jsv8_register_member_function", "templates") %{ SWIGV8_AddMemberFunction($jsmangledname_class, "$jsname", $jswrapper); %} @@ -416,7 +451,7 @@ fail: * * Note: this template is also used for global functions. * ----------------------------------------------------------------------------- */ -%fragment("jsv8_register_static_function", "templates") +%fragment("jsv8_register_static_function", "templates") %{ SWIGV8_AddStaticFunction($jsparent_obj, "$jsname", $jswrapper); %} @@ -430,7 +465,7 @@ fail: * * Note: this template is also used for global variables. * ----------------------------------------------------------------------------- */ -%fragment("jsv8_register_static_variable", "templates") +%fragment("jsv8_register_static_variable", "templates") %{ SWIGV8_AddStaticVariable($jsparent_obj, "$jsname", $jsgetter, $jssetter); %} @@ -447,10 +482,8 @@ fail: * - $jsv8registerclasses: part with code that registers class objects in namespaces * - $jsv8registernspaces: part with code that registers namespaces in parent namespaces * ----------------------------------------------------------------------------- */ -%fragment("js_initializer", "templates") +%fragment("js_initializer", "templates") %{ -// The extern "C" makes little sense here because the paramater is using C++ objects and templates. -// extern "C" { #if defined(BUILDING_NODE_EXTENSION) void $jsname_initialize(v8::Handle global_obj, v8::Handle /*module*/) @@ -464,34 +497,34 @@ void $jsname_initialize(v8::Handle global_obj) // a class template for creating proxies of undefined types -#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) +#if (SWIG_V8_VERSION < 0x031900) SWIGV8_SWIGTYPE_Proxy_class_templ = v8::Persistent::New(SWIGV8_CreateClassTemplate("SwigProxy")); #else SWIGV8_SWIGTYPE_Proxy_class_templ.Reset(v8::Isolate::GetCurrent(), SWIGV8_CreateClassTemplate("SwigProxy")); #endif - + /* create objects for namespaces */ $jsv8nspaces - + /* create class templates */ $jsv8classtemplates - + /* register wrapper functions */ $jsv8wrappers - + /* setup inheritances */ $jsv8inheritance - + /* class instances */ $jsv8classinstances - + /* add static class functions and variables */ $jsv8staticwrappers /* register classes */ $jsv8registerclasses - + /* create and register namespace objects */ $jsv8registernspaces } @@ -500,7 +533,4 @@ void $jsname_initialize(v8::Handle global_obj) NODE_MODULE($jsname, $jsname_initialize); #endif - - -// } // extern "C" %} diff --git a/Lib/javascript/v8/javascripthelpers.swg b/Lib/javascript/v8/javascripthelpers.swg index 847e9b73c..61bc45da5 100644 --- a/Lib/javascript/v8/javascripthelpers.swg +++ b/Lib/javascript/v8/javascripthelpers.swg @@ -1,7 +1,20 @@ %insert(runtime) %{ +// Note: since 3.19 there are new CallBack types, since 03.21.9 the old ones have been removed +#if SWIG_V8_VERSION < 0x031900 +typedef v8::InvocationCallback SwigV8FunctionCallback; +typedef v8::AccessorGetter SwigV8AccessorGetterCallback; +typedef v8::AccessorSetter SwigV8AccessorSetterCallback; +typedef v8::AccessorInfo SwigV8PropertyCallbackInfoVoid; +#else +typedef v8::FunctionCallback SwigV8FunctionCallback; +typedef v8::AccessorGetterCallback SwigV8AccessorGetterCallback; +typedef v8::AccessorSetterCallback SwigV8AccessorSetterCallback; +typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfoVoid; +#endif + /** - * Creates a class template for a class with specified initialization function. + * Creates a class template for a class with specified initialization function. */ v8::Handle SWIGV8_CreateClassTemplate(const char* symbol) { v8::HandleScope scope; @@ -15,44 +28,49 @@ v8::Handle SWIGV8_CreateClassTemplate(const char* symbol) } /** - * Registers a class method with given name for a given class template. + * Registers a class method with given name for a given class template. */ -void SWIGV8_AddMemberFunction(v8::Handle class_templ, const char* symbol, v8::FunctionCallback _func) { +void SWIGV8_AddMemberFunction(v8::Handle class_templ, const char* symbol, + SwigV8FunctionCallback _func) { v8::Handle proto_templ = class_templ->PrototypeTemplate(); - proto_templ->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)); + proto_templ->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)); } /** - * Registers a class property with given name for a given class template. + * Registers a class property with given name for a given class template. */ -void SWIGV8_AddMemberVariable(v8::Handle class_templ, const char* symbol, v8::AccessorGetterCallback getter, v8::AccessorSetterCallback setter) { +void SWIGV8_AddMemberVariable(v8::Handle class_templ, const char* symbol, + SwigV8AccessorGetterCallback getter, SwigV8AccessorSetterCallback setter) { v8::Handle proto_templ = class_templ->InstanceTemplate(); proto_templ->SetAccessor(v8::String::NewSymbol(symbol), getter, setter); } /** - * Registers a class method with given name for a given object. + * Registers a class method with given name for a given object. */ -void SWIGV8_AddStaticFunction(v8::Handle obj, const char* symbol, const v8::FunctionCallback& _func) { +void SWIGV8_AddStaticFunction(v8::Handle obj, const char* symbol, + const SwigV8FunctionCallback& _func) { obj->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)->GetFunction()); } /** - * Registers a class method with given name for a given object. + * Registers a class method with given name for a given object. */ -void SWIGV8_AddStaticVariable(v8::Handle obj, const char* symbol, v8::AccessorGetterCallback getter, v8::AccessorSetterCallback setter) { +void SWIGV8_AddStaticVariable(v8::Handle obj, const char* symbol, + SwigV8AccessorGetterCallback getter, SwigV8AccessorSetterCallback setter) { obj->SetAccessor(v8::String::NewSymbol(symbol), getter, setter); } -void JS_veto_set_variable(v8::Local property, v8::Local value, const v8::PropertyCallbackInfo& info) +void JS_veto_set_variable(v8::Local property, v8::Local value, + const SwigV8PropertyCallbackInfoVoid& info) { char buffer[256]; char msg[512]; int res; - + property->WriteUtf8(buffer, 256); res = sprintf(msg, "Tried to write read-only variable: %s.", buffer); - + if(res<0) { SWIG_exception(SWIG_ERROR, "Tried to write read-only variable."); } else { diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index fddfcf70c..841b03e21 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -4,8 +4,28 @@ * Javascript support code * ----------------------------------------------------------------------------- */ -%insert(runtime) %{ +%define %swig_v8_define_version(version) +%begin %{ +#ifndef SWIG_V8_VERSION +#define SWIG_V8_VERSION version +#endif +%} +%enddef +#ifdef SWIG_V8_VERSION +%swig_v8_define_version(SWIG_V8_VERSION) +#else +// HACK: defining a default version +%swig_v8_define_version(SWIG_V8_VERSION) +#endif + +#ifdef BUILDING_NODE_EXTENSION +%insert("runtime") %{ +#include +%} +#endif + +%insert(runtime) %{ #include #include @@ -13,7 +33,7 @@ %} %insert(runtime) "swigrun.swg"; /* SWIG API */ -%insert(runtime) "swigerrors.swg"; /* SWIG errors */ +%insert(runtime) "swigerrors.swg"; /* SWIG errors */ %insert(runtime) %{ #define SWIG_Error(code, msg) SWIGV8_ErrorHandler.error(code, msg) @@ -25,16 +45,16 @@ void SWIG_V8_Raise(const char* msg) { v8::ThrowException(v8::Exception::Error(v8::String::New(msg))); } -/* +/* Note: There are two contexts for handling errors. A static V8ErrorHandler is used in not overloaded methods. For overloaded methods the throwing type checking mechanism is used during dispatching. As V8 exceptions can not be resetted properly the trick is to use a dynamic ErrorHandler with same local name as the global one. - + - See defintion of SWIG_Error above. - - See code templates 'JS_function_dispatcher', 'JS_functionwrapper_overload', + - See code templates 'JS_function_dispatcher', 'JS_functionwrapper_overload', and 'JS_function_dispatch_case' in javascriptcode.swg */ @@ -72,8 +92,8 @@ public: SWIGV8_Proxy(): swigCMemOwn(false), swigCObject(0), info(0) { v8::V8::AdjustAmountOfExternalAllocatedMemory(SWIGV8_AVG_OBJ_SIZE); }; - - ~SWIGV8_Proxy() { + + ~SWIGV8_Proxy() { #if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) handle.ClearWeak(); #else @@ -90,7 +110,7 @@ public: handle.Clear(); v8::V8::AdjustAmountOfExternalAllocatedMemory(-SWIGV8_AVG_OBJ_SIZE); } - + bool swigCMemOwn; void *swigCObject; swig_type_info *info; @@ -112,7 +132,7 @@ v8::Persistent SWIGV8_SWIGTYPE_Proxy_class_templ; int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_type_info *info, int flags) { v8::HandleScope scope; - + if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; #if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) @@ -157,7 +177,7 @@ void SWIGV8_Proxy_DefaultDtor(v8::Isolate *, v8::Persistent< v8::Object > *objec void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info *info, int flags) { SWIGV8_Proxy* cdata = new SWIGV8_Proxy(); - cdata->swigCObject = ptr; + cdata->swigCObject = ptr; cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; cdata->info = info; @@ -210,7 +230,7 @@ v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, in } #else v8::Isolate *iso = v8::Isolate::GetCurrent(); - + if(info->clientdata != 0) { class_templ = v8::Handle::New(iso, ((SWIGV8_ClientData*) info->clientdata)->class_templ); } else { @@ -220,7 +240,7 @@ v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, in v8::Handle result = class_templ->InstanceTemplate()->NewInstance(); SWIGV8_SetPrivateData(result, ptr, info, flags); - + return scope.Close(result); } From 11e2179dd318d49665fe665022a2a5ea30c59392 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 3 Sep 2013 05:40:22 +0200 Subject: [PATCH 0265/1048] First example that addresses node.js as primary execution environment. --- Examples/javascript/class/Makefile | 14 +++++----- Examples/javascript/class/binding.gyp | 8 ++++++ Examples/javascript/class/runme.js | 39 ++++++++++++++------------- 3 files changed, 35 insertions(+), 26 deletions(-) create mode 100644 Examples/javascript/class/binding.gyp diff --git a/Examples/javascript/class/Makefile b/Examples/javascript/class/Makefile index 507289ed1..99a9e9e86 100755 --- a/Examples/javascript/class/Makefile +++ b/Examples/javascript/class/Makefile @@ -5,17 +5,17 @@ JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -all:: +wrapper:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean -javascript_exe:: - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - TOP='$(TOP)' javascript_exe - -check:: all +check:: build $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/class/binding.gyp b/Examples/javascript/class/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/class/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/class/runme.js b/Examples/javascript/class/runme.js index 50261d868..0ecaf3f82 100755 --- a/Examples/javascript/class/runme.js +++ b/Examples/javascript/class/runme.js @@ -1,15 +1,16 @@ // file: runme.js +var example = require("./build/Release/example"); // ----- Object creation ----- -print("Creating some objects:"); +console.log("Creating some objects:"); c = new example.Circle(10); -print("Created circle " + c); +console.log("Created circle " + c); s = new example.Square(10); -print("Created square " + s); +console.log("Created square " + s); // ----- Access a static member ----- -print("\nA total of " + example.Shape.nshapes + " shapes were created"); // access static member as properties of the class object +console.log("\nA total of " + example.Shape.nshapes + " shapes were created"); // access static member as properties of the class object // ----- Member data access ----- // Set the location of the object. @@ -21,26 +22,26 @@ c.y = 30; s.x = -10; s.y = 5; -print("\nHere is their new position:"); -print("Circle = (" + c.x + "," + c.y + ")"); -print("Square = (" + s.x + "," + s.y + ")"); +console.log("\nHere is their new position:"); +console.log("Circle = (" + c.x + "," + c.y + ")"); +console.log("Square = (" + s.x + "," + s.y + ")"); // ----- Call some methods ----- -print("\nHere are some properties of the shapes:"); -print("Circle:"); -print("area = " + c.area() + ""); -print("perimeter = " + c.perimeter() + ""); -print("\n"); -print("Square:"); -print("area = " + s.area() + ""); -print("perimeter = " + s.perimeter() + ""); +console.log("\nHere are some properties of the shapes:"); +console.log("Circle:"); +console.log("area = " + c.area() + ""); +console.log("perimeter = " + c.perimeter() + ""); +console.log("\n"); +console.log("Square:"); +console.log("area = " + s.area() + ""); +console.log("perimeter = " + s.perimeter() + ""); // ----- Delete everything ----- -print("\nGuess I'll clean up now"); +console.log("\nGuess I'll clean up now"); // Note: this invokes the virtual destructor delete c; -delete s; +delete s; -print (example.Shape.nshapes + " shapes remain"); +console.log(example.Shape.nshapes + " shapes remain"); -print("Goodbye"); +console.log("Goodbye"); From dbf2b1fe945714641322c2f758bde63140db37fa Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 3 Sep 2013 05:46:19 +0200 Subject: [PATCH 0266/1048] Ignore javascript Example build files. --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 2cd4b9b4e..147e44cb2 100644 --- a/.gitignore +++ b/.gitignore @@ -84,4 +84,5 @@ Examples/*/*/*.gdb *.orig *.kdev4 *.geany -/build \ No newline at end of file +Examples/javascript/*/build +build From 5da54ca435741f74a7212d7034b11b9fa17046d7 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 3 Sep 2013 06:26:54 +0200 Subject: [PATCH 0267/1048] Convert javascript examples to nodejs. --- Examples/javascript/class/runme.js | 1 - Examples/javascript/constant/Makefile | 16 ++--- Examples/javascript/constant/binding.gyp | 8 +++ Examples/javascript/constant/runme.js | 24 +++---- Examples/javascript/enum/Makefile | 16 ++--- Examples/javascript/enum/binding.gyp | 8 +++ .../enum/{example.cpp => example.cxx} | 0 Examples/javascript/enum/runme.js | 26 ++++---- Examples/javascript/exception/Makefile | 16 ++--- Examples/javascript/exception/binding.gyp | 8 +++ .../exception/{example.cpp => example.cxx} | 0 Examples/javascript/exception/runme.js | 25 ++++---- Examples/javascript/functor/Makefile | 16 ++--- Examples/javascript/functor/binding.gyp | 8 +++ .../functor/{example.cpp => example.cxx} | 0 Examples/javascript/functor/runme.js | 7 +-- Examples/javascript/namespace/Makefile | 16 ++--- Examples/javascript/namespace/binding.gyp | 8 +++ .../namespace/{example.cpp => example.cxx} | 0 Examples/javascript/namespace/runme.js | 17 +++-- Examples/javascript/operator/Makefile | 16 ++--- Examples/javascript/operator/binding.gyp | 8 +++ Examples/javascript/operator/example.cpp | 0 Examples/javascript/operator/runme.js | 16 ++--- Examples/javascript/overload/Makefile | 16 ++--- Examples/javascript/overload/binding.gyp | 8 +++ Examples/javascript/overload/example.cpp | 0 Examples/javascript/overload/runme.js | 2 + Examples/javascript/pointer/Makefile | 16 ++--- Examples/javascript/pointer/binding.gyp | 8 +++ .../pointer/{example.cpp => example.cxx} | 0 Examples/javascript/pointer/runme.js | 19 +++--- Examples/javascript/reference/Makefile | 16 ++--- Examples/javascript/reference/binding.gyp | 8 +++ .../reference/{example.cpp => example.cxx} | 0 Examples/javascript/reference/runme.js | 24 +++---- Examples/javascript/simple/Makefile | 18 +++--- Examples/javascript/simple/binding.gyp | 8 +++ .../simple/{example.c => example.cxx} | 0 Examples/javascript/simple/runme.js | 8 +-- Examples/javascript/template/Makefile | 16 ++--- Examples/javascript/template/binding.gyp | 8 +++ Examples/javascript/template/example.cpp | 0 Examples/javascript/template/runme.js | 12 ++-- Examples/javascript/variables/Makefile | 18 +++--- Examples/javascript/variables/binding.gyp | 8 +++ .../variables/{example.c => example.cxx} | 0 Examples/javascript/variables/runme.js | 62 +++++++++---------- 48 files changed, 312 insertions(+), 223 deletions(-) create mode 100644 Examples/javascript/constant/binding.gyp create mode 100644 Examples/javascript/enum/binding.gyp rename Examples/javascript/enum/{example.cpp => example.cxx} (100%) create mode 100644 Examples/javascript/exception/binding.gyp rename Examples/javascript/exception/{example.cpp => example.cxx} (100%) create mode 100644 Examples/javascript/functor/binding.gyp rename Examples/javascript/functor/{example.cpp => example.cxx} (100%) create mode 100644 Examples/javascript/namespace/binding.gyp rename Examples/javascript/namespace/{example.cpp => example.cxx} (100%) create mode 100644 Examples/javascript/operator/binding.gyp delete mode 100644 Examples/javascript/operator/example.cpp create mode 100644 Examples/javascript/overload/binding.gyp delete mode 100644 Examples/javascript/overload/example.cpp create mode 100644 Examples/javascript/pointer/binding.gyp rename Examples/javascript/pointer/{example.cpp => example.cxx} (100%) create mode 100644 Examples/javascript/reference/binding.gyp rename Examples/javascript/reference/{example.cpp => example.cxx} (100%) create mode 100644 Examples/javascript/simple/binding.gyp rename Examples/javascript/simple/{example.c => example.cxx} (100%) create mode 100644 Examples/javascript/template/binding.gyp delete mode 100644 Examples/javascript/template/example.cpp create mode 100644 Examples/javascript/variables/binding.gyp rename Examples/javascript/variables/{example.c => example.cxx} (100%) diff --git a/Examples/javascript/class/runme.js b/Examples/javascript/class/runme.js index 0ecaf3f82..5bb62ecd4 100755 --- a/Examples/javascript/class/runme.js +++ b/Examples/javascript/class/runme.js @@ -1,4 +1,3 @@ -// file: runme.js var example = require("./build/Release/example"); // ----- Object creation ----- diff --git a/Examples/javascript/constant/Makefile b/Examples/javascript/constant/Makefile index dbf2f6660..99a9e9e86 100755 --- a/Examples/javascript/constant/Makefile +++ b/Examples/javascript/constant/Makefile @@ -1,21 +1,21 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -CXXSRCS = +CXXSRCS = example.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -all:: +wrapper:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean -javascript_exe:: - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - TOP='$(TOP)' javascript_exe - -check:: all +check:: build $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/constant/binding.gyp b/Examples/javascript/constant/binding.gyp new file mode 100644 index 000000000..69af46b22 --- /dev/null +++ b/Examples/javascript/constant/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/constant/runme.js b/Examples/javascript/constant/runme.js index cd4783a27..b11c08c98 100755 --- a/Examples/javascript/constant/runme.js +++ b/Examples/javascript/constant/runme.js @@ -1,14 +1,14 @@ -// file: runme.js +var example = require("./build/Release/example"); -print("ICONST = " + example.ICONST + " (should be 42)\n"); -print("FCONST = " + example.FCONST + " (should be 2.1828)\n"); -print("CCONST = " + example.CCONST + " (should be 'x')\n"); -print("CCONST2 = " + example.CCONST2 + " (this should be on a new line)\n"); -print("SCONST = " + example.SCONST + " (should be 'Hello World')\n"); -print("SCONST2 = " + example.SCONST2 + " (should be '\"Hello World\"')\n"); -print("EXPR = " + example.EXPR + " (should be 48.5484)\n"); -print("iconst = " + example.iconst + " (should be 37)\n"); -print("fconst = " + example.fconst + " (should be 3.14)\n"); +console.log("ICONST = " + example.ICONST + " (should be 42)\n"); +console.log("FCONST = " + example.FCONST + " (should be 2.1828)\n"); +console.log("CCONST = " + example.CCONST + " (should be 'x')\n"); +console.log("CCONST2 = " + example.CCONST2 + " (this should be on a new line)\n"); +console.log("SCONST = " + example.SCONST + " (should be 'Hello World')\n"); +console.log("SCONST2 = " + example.SCONST2 + " (should be '\"Hello World\"')\n"); +console.log("EXPR = " + example.EXPR + " (should be 48.5484)\n"); +console.log("iconst = " + example.iconst + " (should be 37)\n"); +console.log("fconst = " + example.fconst + " (should be 3.14)\n"); -print("EXTERN = " + example.EXTERN + " (should be undefined)\n"); -print("FOO = " + example.FOO + " (should be undefined)\n"); +console.log("EXTERN = " + example.EXTERN + " (should be undefined)\n"); +console.log("FOO = " + example.FOO + " (should be undefined)\n"); diff --git a/Examples/javascript/enum/Makefile b/Examples/javascript/enum/Makefile index 180e99cae..99a9e9e86 100755 --- a/Examples/javascript/enum/Makefile +++ b/Examples/javascript/enum/Makefile @@ -1,21 +1,21 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cpp +CXXSRCS = example.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -all:: +wrapper:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean -javascript_exe:: - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - TOP='$(TOP)' javascript_exe - -check:: all +check:: build $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/enum/binding.gyp b/Examples/javascript/enum/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/enum/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/enum/example.cpp b/Examples/javascript/enum/example.cxx similarity index 100% rename from Examples/javascript/enum/example.cpp rename to Examples/javascript/enum/example.cxx diff --git a/Examples/javascript/enum/runme.js b/Examples/javascript/enum/runme.js index 3f6283639..9d3accd1d 100755 --- a/Examples/javascript/enum/runme.js +++ b/Examples/javascript/enum/runme.js @@ -1,26 +1,26 @@ -// file: runme.py +var example = require("./build/Release/example"); // ----- Object creation ----- // Print out the value of some enums -print("*** color ***"); -print(" RED =" + example.RED); -print(" BLUE =" + example.BLUE); -print(" GREEN =" + example.GREEN); +console.log("*** color ***"); +console.log(" RED =" + example.RED); +console.log(" BLUE =" + example.BLUE); +console.log(" GREEN =" + example.GREEN); -print("\n*** Foo::speed ***"); -print(" Foo_IMPULSE =" + example.Foo.IMPULSE); -print(" Foo_WARP =" + example.Foo.WARP); -print(" Foo_LUDICROUS =" + example.Foo.LUDICROUS); +console.log("\n*** Foo::speed ***"); +console.log(" Foo_IMPULSE =" + example.Foo.IMPULSE); +console.log(" Foo_WARP =" + example.Foo.WARP); +console.log(" Foo_LUDICROUS =" + example.Foo.LUDICROUS); -print("\nTesting use of enums with functions\n"); +console.log("\nTesting use of enums with functions\n"); example.enum_test(example.RED, example.Foo.IMPULSE); example.enum_test(example.BLUE, example.Foo.WARP); example.enum_test(example.GREEN, example.Foo.LUDICROUS); example.enum_test(1234,5678); -print("\nTesting use of enum with class method"); +console.log("\nTesting use of enum with class method"); f = new example.Foo(); f.enum_test(example.Foo.IMPULSE); @@ -28,7 +28,7 @@ f.enum_test(example.Foo.WARP); f.enum_test(example.Foo.LUDICROUS); // enum value BLUE of enum color is accessed as property of cconst -print("example.BLUE= " + example.BLUE); +console.log("example.BLUE= " + example.BLUE); // enum value LUDICROUS of enum Foo::speed is accessed as as property of cconst -print("example.speed.LUDICROUS= " + example.Foo.LUDICROUS); +console.log("example.speed.LUDICROUS= " + example.Foo.LUDICROUS); diff --git a/Examples/javascript/exception/Makefile b/Examples/javascript/exception/Makefile index 180e99cae..99a9e9e86 100755 --- a/Examples/javascript/exception/Makefile +++ b/Examples/javascript/exception/Makefile @@ -1,21 +1,21 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cpp +CXXSRCS = example.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -all:: +wrapper:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean -javascript_exe:: - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - TOP='$(TOP)' javascript_exe - -check:: all +check:: build $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/exception/binding.gyp b/Examples/javascript/exception/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/exception/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/exception/example.cpp b/Examples/javascript/exception/example.cxx similarity index 100% rename from Examples/javascript/exception/example.cpp rename to Examples/javascript/exception/example.cxx diff --git a/Examples/javascript/exception/runme.js b/Examples/javascript/exception/runme.js index 936b37883..f7041f028 100644 --- a/Examples/javascript/exception/runme.js +++ b/Examples/javascript/exception/runme.js @@ -1,7 +1,6 @@ -//file: runme.js -// Throw a lot of exceptions +var example = require("./build/Release/example"); -print("Trying to catch some exceptions."); +console.log("Trying to catch some exceptions."); t = new example.Test(); try{ t.unknown(); @@ -9,9 +8,9 @@ try{ } catch(error) { if(error == -1) { - print("t.unknown() didn't throw"); + console.log("t.unknown() didn't throw"); } else { - print("successfully catched throw in Test::unknown()."); + console.log("successfully catched throw in Test::unknown()."); } } @@ -21,9 +20,9 @@ try{ } catch(error){ if(error == -1) { - print("t.simple() did not throw"); + console.log("t.simple() did not throw"); } else { - print("successfully catched throw in Test::simple()."); + console.log("successfully catched throw in Test::simple()."); } } @@ -32,9 +31,9 @@ try{ throw -1; } catch(error){ if(error == -1) { - print("t.message() did not throw"); + console.log("t.message() did not throw"); } else { - print("successfully catched throw in Test::message()."); + console.log("successfully catched throw in Test::message()."); } } @@ -44,9 +43,9 @@ try{ } catch(error){ if(error == -1) { - print("t.hosed() did not throw"); + console.log("t.hosed() did not throw"); } else { - print("successfully catched throw in Test::hosed()."); + console.log("successfully catched throw in Test::hosed()."); } } @@ -57,9 +56,9 @@ for (var i=1; i<4; i++) { } catch(error){ if(error == -1) { - print("t.multi(" + i + ") did not throw"); + console.log("t.multi(" + i + ") did not throw"); } else { - print("successfully catched throw in Test::multi()."); + console.log("successfully catched throw in Test::multi()."); } } } diff --git a/Examples/javascript/functor/Makefile b/Examples/javascript/functor/Makefile index 180e99cae..99a9e9e86 100755 --- a/Examples/javascript/functor/Makefile +++ b/Examples/javascript/functor/Makefile @@ -1,21 +1,21 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cpp +CXXSRCS = example.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -all:: +wrapper:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean -javascript_exe:: - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - TOP='$(TOP)' javascript_exe - -check:: all +check:: build $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/functor/binding.gyp b/Examples/javascript/functor/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/functor/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/functor/example.cpp b/Examples/javascript/functor/example.cxx similarity index 100% rename from Examples/javascript/functor/example.cpp rename to Examples/javascript/functor/example.cxx diff --git a/Examples/javascript/functor/runme.js b/Examples/javascript/functor/runme.js index 48d332c83..f7be78286 100644 --- a/Examples/javascript/functor/runme.js +++ b/Examples/javascript/functor/runme.js @@ -1,5 +1,4 @@ -// Operator overloading example - +var example = require("./build/Release/example"); a = new example.intSum(0); b = new example.doubleSum(100.0); @@ -11,6 +10,6 @@ for (i=1;i<=100;i++) a.call(i); // Note: function call b.call(Math.sqrt(i)); // Note: function call -print(a.result()); -print(b.result()); +console.log(a.result()); +console.log(b.result()); diff --git a/Examples/javascript/namespace/Makefile b/Examples/javascript/namespace/Makefile index 180e99cae..99a9e9e86 100755 --- a/Examples/javascript/namespace/Makefile +++ b/Examples/javascript/namespace/Makefile @@ -1,21 +1,21 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cpp +CXXSRCS = example.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -all:: +wrapper:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean -javascript_exe:: - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - TOP='$(TOP)' javascript_exe - -check:: all +check:: build $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/namespace/binding.gyp b/Examples/javascript/namespace/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/namespace/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/namespace/example.cpp b/Examples/javascript/namespace/example.cxx similarity index 100% rename from Examples/javascript/namespace/example.cpp rename to Examples/javascript/namespace/example.cxx diff --git a/Examples/javascript/namespace/runme.js b/Examples/javascript/namespace/runme.js index dc49b078e..9a9d6744d 100644 --- a/Examples/javascript/namespace/runme.js +++ b/Examples/javascript/namespace/runme.js @@ -1,11 +1,10 @@ - print("Global variable Foo=" + example.nspace.Foo); - example.nspace.Foo = 5; - print("Variable Foo changed to " + example.nspace.Foo); - print("GCD of number 6,18 is " + example.nspace.gcd(6,18)); +var example = require("./build/Release/example"); -print("Creating some objects:"); +console.log("Global variable Foo=" + example.nspace.Foo); +example.nspace.Foo = 5; +console.log("Variable Foo changed to " + example.nspace.Foo); +console.log("GCD of number 6,18 is " + example.nspace.gcd(6,18)); + +console.log("Creating some objects:"); c = new example.nspace.Circle(10); -print("area = " + c.area()); - - - +console.log("area = " + c.area()); diff --git a/Examples/javascript/operator/Makefile b/Examples/javascript/operator/Makefile index 180e99cae..99a9e9e86 100755 --- a/Examples/javascript/operator/Makefile +++ b/Examples/javascript/operator/Makefile @@ -1,21 +1,21 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cpp +CXXSRCS = example.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -all:: +wrapper:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean -javascript_exe:: - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - TOP='$(TOP)' javascript_exe - -check:: all +check:: build $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/operator/binding.gyp b/Examples/javascript/operator/binding.gyp new file mode 100644 index 000000000..69af46b22 --- /dev/null +++ b/Examples/javascript/operator/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/operator/example.cpp b/Examples/javascript/operator/example.cpp deleted file mode 100644 index e69de29bb..000000000 diff --git a/Examples/javascript/operator/runme.js b/Examples/javascript/operator/runme.js index 92b8e3b74..9dba4b7f9 100644 --- a/Examples/javascript/operator/runme.js +++ b/Examples/javascript/operator/runme.js @@ -1,23 +1,23 @@ -// Operator overloading example +var example = require("./build/Release/example"); a = new example.Complex(2,3); b = new example.Complex(-5,10); -print ("a =" + a); -print ("b =" + b); +console.log ("a =" + a); +console.log ("b =" + b); c = a.plus(b); -print("c =" + c); -print("a*b =" + a.times(b)); -print("a-c =" + a.minus(c)); +console.log("c =" + c); +console.log("a*b =" + a.times(b)); +console.log("a-c =" + a.minus(c)); e = example.Complex.copy(a.minus(c)); -print("e =" + e); +console.log("e =" + e); // Big expression f = a.plus(b).times(c.plus(b.times(e))).plus(a.uminus()); -print("f =" + f); +console.log("f =" + f); diff --git a/Examples/javascript/overload/Makefile b/Examples/javascript/overload/Makefile index 180e99cae..99a9e9e86 100755 --- a/Examples/javascript/overload/Makefile +++ b/Examples/javascript/overload/Makefile @@ -1,21 +1,21 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cpp +CXXSRCS = example.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -all:: +wrapper:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean -javascript_exe:: - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - TOP='$(TOP)' javascript_exe - -check:: all +check:: build $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/overload/binding.gyp b/Examples/javascript/overload/binding.gyp new file mode 100644 index 000000000..69af46b22 --- /dev/null +++ b/Examples/javascript/overload/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/overload/example.cpp b/Examples/javascript/overload/example.cpp deleted file mode 100644 index e69de29bb..000000000 diff --git a/Examples/javascript/overload/runme.js b/Examples/javascript/overload/runme.js index 6b822f107..5ff5d01be 100644 --- a/Examples/javascript/overload/runme.js +++ b/Examples/javascript/overload/runme.js @@ -1,3 +1,5 @@ +var example = require("./build/Release/example"); + example.f(); example.f(1); example.f(1, 2); diff --git a/Examples/javascript/pointer/Makefile b/Examples/javascript/pointer/Makefile index 180e99cae..99a9e9e86 100755 --- a/Examples/javascript/pointer/Makefile +++ b/Examples/javascript/pointer/Makefile @@ -1,21 +1,21 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cpp +CXXSRCS = example.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -all:: +wrapper:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean -javascript_exe:: - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - TOP='$(TOP)' javascript_exe - -check:: all +check:: build $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/pointer/binding.gyp b/Examples/javascript/pointer/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/pointer/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/pointer/example.cpp b/Examples/javascript/pointer/example.cxx similarity index 100% rename from Examples/javascript/pointer/example.cpp rename to Examples/javascript/pointer/example.cxx diff --git a/Examples/javascript/pointer/runme.js b/Examples/javascript/pointer/runme.js index 48f92f11f..00778dfbc 100755 --- a/Examples/javascript/pointer/runme.js +++ b/Examples/javascript/pointer/runme.js @@ -1,7 +1,7 @@ -// file: runme.js +var example = require("./build/Release/example"); // First create some objects using the pointer library. -print("Testing the pointer library\n"); +console.log("Testing the pointer library\n"); a = example.new_intp(); b = example.new_intp(); c = example.new_intp(); @@ -9,9 +9,9 @@ c = example.new_intp(); example.intp_assign(a,37); example.intp_assign(b,42); -print(" a = " + example.intp_value(a) + "\n"); -print(" b = " + example.intp_value(b) + "\n"); -print(" c = " + example.intp_value(c) + "\n"); +console.log(" a = " + example.intp_value(a) + "\n"); +console.log(" b = " + example.intp_value(b) + "\n"); +console.log(" c = " + example.intp_value(c) + "\n"); //// Call the add() function with some pointers example.add(a, b, c); @@ -19,7 +19,7 @@ example.add(a, b, c); // //// Now get the result r = example.intp_value(c); -print(" 37 + 42 = " + r + "\n"); +console.log(" 37 + 42 = " + r + "\n"); // Clean up the pointers example.delete_intp(a); @@ -30,9 +30,6 @@ example.delete_intp(c); //// This should be much easier. Now how it is no longer //// necessary to manufacture pointers. //"OUTPUT" Mapping is not supported - -//print("Trying the typemap library"); +//console.log("Trying the typemap library"); //r = example.subtract(37,42); -//print("37 - 42 =" + r); - - +//console.log("37 - 42 =" + r); diff --git a/Examples/javascript/reference/Makefile b/Examples/javascript/reference/Makefile index 180e99cae..99a9e9e86 100755 --- a/Examples/javascript/reference/Makefile +++ b/Examples/javascript/reference/Makefile @@ -1,21 +1,21 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cpp +CXXSRCS = example.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -all:: +wrapper:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean -javascript_exe:: - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - TOP='$(TOP)' javascript_exe - -check:: all +check:: build $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/reference/binding.gyp b/Examples/javascript/reference/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/reference/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/reference/example.cpp b/Examples/javascript/reference/example.cxx similarity index 100% rename from Examples/javascript/reference/example.cpp rename to Examples/javascript/reference/example.cxx diff --git a/Examples/javascript/reference/runme.js b/Examples/javascript/reference/runme.js index 5cf00061e..ee5737076 100755 --- a/Examples/javascript/reference/runme.js +++ b/Examples/javascript/reference/runme.js @@ -1,23 +1,23 @@ // This file illustrates the manipulation of C++ references in Javascript. -// TODO: deleteion of vector objects created here +var example = require("./build/Release/example"); // ----- Object creation ----- -print("Creating some objects:\n"); +console.log("Creating some objects:\n"); a = new example.Vector(3,4,5); b = new example.Vector(10,11,12); -print(" created" + a.print()); -print(" created" + b.print()); +console.log(" created" + a.print()); +console.log(" created" + b.print()); // ----- Call an overloaded operator ----- // This calls the wrapper we placed around operator+(const Vector &a, const Vector &) // It returns a new allocated object. -print("Adding a+b\n"); +console.log("Adding a+b\n"); c = example.addv(a, b); -print("a+b = " + c.print()); +console.log("a+b = " + c.print()); // TODO: Note: Unless we free the result, a memory leak will occur @@ -26,9 +26,9 @@ print("a+b = " + c.print()); // ----- Create a vector array ----- // Note: Using the high-level interface here -print("Creating an array of vectors\n"); +console.log("Creating an array of vectors\n"); va = new example.VectorArray(10); -print("va = " + va + "\n"); +console.log("va = " + va + "\n"); // ----- Set some values in the array ----- @@ -46,20 +46,20 @@ va.set(2,example.addv(a,b)); // Get some values from the array -print("Getting some array values\n"); +console.log("Getting some array values\n"); for (i = 0; i < 5; i++) { temp = va.get(i); - print(i,temp.print()); + console.log(i,temp.print()); } // Watch under resource meter to check on this -print("Making sure we don't leak memory.\n"); +console.log("Making sure we don't leak memory.\n"); for (i = 0; i < 1000000; i++) { c = va.get(i % 10); } //---------TODO--------- //----- Clean up ----- -//print("Cleaning up\n"); +//console.log("Cleaning up\n"); //example.delete_VectorArray(va); //example.delete_Vector(a); diff --git a/Examples/javascript/simple/Makefile b/Examples/javascript/simple/Makefile index fb4669329..99a9e9e86 100755 --- a/Examples/javascript/simple/Makefile +++ b/Examples/javascript/simple/Makefile @@ -1,21 +1,21 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -SRCS = example.c +CXXSRCS = example.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript +wrapper:: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean -javascript_exe:: - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - TOP='$(TOP)' javascript_exe - -check:: all +check:: build $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/simple/binding.gyp b/Examples/javascript/simple/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/simple/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/simple/example.c b/Examples/javascript/simple/example.cxx similarity index 100% rename from Examples/javascript/simple/example.c rename to Examples/javascript/simple/example.cxx diff --git a/Examples/javascript/simple/runme.js b/Examples/javascript/simple/runme.js index 96c11a5a2..d970dcb7c 100755 --- a/Examples/javascript/simple/runme.js +++ b/Examples/javascript/simple/runme.js @@ -1,22 +1,22 @@ -/* file: runme.js */ +var example = require("./build/Release/example"); /* Call our gcd() function */ x = 42; y = 105; g = example.gcd(x,y); -print("GCD of x and y is=" + g); +console.log("GCD of x and y is=" + g); /* Manipulate the Foo global variable */ /* Output its current value */ -print("Global variable Foo=" + example.Foo); +console.log("Global variable Foo=" + example.Foo); /* Change its value */ example.Foo = 3.1415926; /* See if the change took effect */ -print("Variable Foo changed to=" + example.Foo); +console.log("Variable Foo changed to=" + example.Foo); diff --git a/Examples/javascript/template/Makefile b/Examples/javascript/template/Makefile index 180e99cae..99a9e9e86 100755 --- a/Examples/javascript/template/Makefile +++ b/Examples/javascript/template/Makefile @@ -1,21 +1,21 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cpp +CXXSRCS = example.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -all:: +wrapper:: $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_cpp + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean -javascript_exe:: - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - TOP='$(TOP)' javascript_exe - -check:: all +check:: build $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/template/binding.gyp b/Examples/javascript/template/binding.gyp new file mode 100644 index 000000000..69af46b22 --- /dev/null +++ b/Examples/javascript/template/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/template/example.cpp b/Examples/javascript/template/example.cpp deleted file mode 100644 index e69de29bb..000000000 diff --git a/Examples/javascript/template/runme.js b/Examples/javascript/template/runme.js index b2a5264ab..551475c72 100644 --- a/Examples/javascript/template/runme.js +++ b/Examples/javascript/template/runme.js @@ -1,8 +1,8 @@ -// file: runme.js +var example = require("./build/Release/example"); //Call some templated functions -print(example.maxint(3,7)); -print(example.maxdouble(3.14,2.18)); +console.log(example.maxint(3,7)); +console.log(example.maxdouble(3.14,2.18)); // Create some class @@ -19,14 +19,12 @@ sum = 0; for(i=0;i<=100;i++) sum = sum + iv.getitem(i); -print(sum); +console.log(sum); sum = 0.0; for(i=0;i<=1000;i++) sum = sum + dv.getitem(i); -print(sum); +console.log(sum); delete iv; delete dv; - - diff --git a/Examples/javascript/variables/Makefile b/Examples/javascript/variables/Makefile index fb4669329..99a9e9e86 100755 --- a/Examples/javascript/variables/Makefile +++ b/Examples/javascript/variables/Makefile @@ -1,21 +1,21 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig -SRCS = example.c +CXXSRCS = example.cxx JS_SCRIPT = runme.js TARGET = example INTERFACE = example.i -all:: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript +wrapper:: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build clean:: $(MAKE) -f $(TOP)/Makefile javascript_clean -javascript_exe:: - $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ - TOP='$(TOP)' javascript_exe - -check:: all +check:: build $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/variables/binding.gyp b/Examples/javascript/variables/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/variables/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/variables/example.c b/Examples/javascript/variables/example.cxx similarity index 100% rename from Examples/javascript/variables/example.c rename to Examples/javascript/variables/example.cxx diff --git a/Examples/javascript/variables/runme.js b/Examples/javascript/variables/runme.js index 7c4e151de..22d208480 100755 --- a/Examples/javascript/variables/runme.js +++ b/Examples/javascript/variables/runme.js @@ -1,4 +1,4 @@ -// file: runme.js +var example = require("./build/Release/example"); // Try to set the values of some global variables example.ivar = 42; @@ -17,52 +17,52 @@ example.iptrvar= example.new_int(37); example.ptptr = example.new_Point(37,42); example.name = "Bill"; -// Now print out the values of the variables -print("Variables (values printed from Python)" + "\n"); -print("ivar = " + example.ivar + "\n"); -print("svar = " + example.svar + "\n"); -print("lvar = " + example.lvar + "\n"); -print("uivar = " + example.uivar + "\n"); -print("usvar = " + example.usvar + "\n"); -print("ulvar = " + example.ulvar + "\n"); -print("scvar = " + example.scvar + "\n"); -print("ucvar = " + example.ucvar + "\n"); -print("fvar = " + example.fvar + "\n"); -print("dvar = " + example.dvar + "\n"); -print("cvar = " + example.cvar + "\n"); -print("strvar = " + example.strvar+ "\n"); -print("cstrvar = " + example.cstrvar+ "\n"); -print("iptrvar = " + example.iptrvar+ "\n"); -print("name = " + example.name + "\n"); -print("ptptr = " + example.ptptr + ": " + example.Point_print(example.ptptr) + "\n"); -print("pt = " + example.pt + ": " + example.Point_print(example.pt) + "\n"); +// Now console.log out the values of the variables +console.log("Variables (values console.loged from Python)" + "\n"); +console.log("ivar = " + example.ivar + "\n"); +console.log("svar = " + example.svar + "\n"); +console.log("lvar = " + example.lvar + "\n"); +console.log("uivar = " + example.uivar + "\n"); +console.log("usvar = " + example.usvar + "\n"); +console.log("ulvar = " + example.ulvar + "\n"); +console.log("scvar = " + example.scvar + "\n"); +console.log("ucvar = " + example.ucvar + "\n"); +console.log("fvar = " + example.fvar + "\n"); +console.log("dvar = " + example.dvar + "\n"); +console.log("cvar = " + example.cvar + "\n"); +console.log("strvar = " + example.strvar+ "\n"); +console.log("cstrvar = " + example.cstrvar+ "\n"); +console.log("iptrvar = " + example.iptrvar+ "\n"); +console.log("name = " + example.name + "\n"); +console.log("ptptr = " + example.ptptr + ": " + example.Point_print(example.ptptr) + "\n"); +console.log("pt = " + example.pt + ": " + example.Point_print(example.pt) + "\n"); -print("\nVariables (values printed from C)"); +console.log("\nVariables (values console.loged from C)"); example.print_vars(); -print("\nNow I'm going to try and modify some read only variables"); +console.log("\nNow I'm going to try and modify some read only variables"); -print("Tring to set 'path'"); +console.log("Tring to set 'path'"); try{ example.path = "Whoa!"; - print("Hey, what's going on?!?! This shouldn't work"); + console.log("Hey, what's going on?!?! This shouldn't work"); } catch(e){ - print("Good."); + console.log("Good."); } -print("Trying to set 'status'"); +console.log("Trying to set 'status'"); try{ example.status = 0; - print("Hey, what's going on?!?! This shouldn't work"); + console.log("Hey, what's going on?!?! This shouldn't work"); } catch(e){ - print("Good."); + console.log("Good."); } -print("\nI'm going to try and update a structure variable.\n"); +console.log("\nI'm going to try and update a structure variable.\n"); example.pt = example.ptptr; -print("The new value is: "); +console.log("The new value is: "); example.pt_print(); -print("You should see the value: " + example.Point_print(example.ptptr)); +console.log("You should see the value: " + example.Point_print(example.ptptr)); From 14a137adca1a101595e103893d7143aa43525791 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 3 Sep 2013 06:27:14 +0200 Subject: [PATCH 0268/1048] Fix regression. --- Lib/javascript/v8/javascriptcode.swg | 1 - 1 file changed, 1 deletion(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 377e93752..068632380 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -75,7 +75,6 @@ SwigV8ReturnValue $jswrapper(const SwigV8Arguments& args) { fail: SWIGV8_RETURN(v8::Undefined()); - return; } %} From 78a3cc9e3e4bdf6d55cb52ab8812c4127e6ad475 Mon Sep 17 00:00:00 2001 From: Kota Iguchi Date: Fri, 16 Aug 2013 10:15:37 +0900 Subject: [PATCH 0269/1048] Added the finalize callback (JSObjectFinalizeCallback) --- Lib/javascript/jsc/javascriptcode.swg | 5 +++-- Source/Modules/javascript.cxx | 1 + 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index 40ce9c9b0..0325a7a35 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -108,7 +108,7 @@ JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size_t argc void $jswrapper(JSObjectRef thisObject) { SWIG_PRV_DATA* t = (SWIG_PRV_DATA*) JSObjectGetPrivate(thisObject); - if(t && t->swigCMemOwn) free (($jstype*)t->swigCObject); + if(t && t->swigCMemOwn) free (($jstype)t->swigCObject); if(t) free(t); } %} @@ -125,7 +125,7 @@ void $jswrapper(JSObjectRef thisObject) { SWIG_PRV_DATA* t = (SWIG_PRV_DATA*) JSObjectGetPrivate(thisObject); if(t && t->swigCMemOwn) { - $jstype* arg1 = ($jstype*)t->swigCObject; + $jstype arg1 = ($jstype)t->swigCObject; ${destructor_action} } if(t) free(t); @@ -385,6 +385,7 @@ JSStaticFunction $jsmangledname_functions[] = { $jsmangledname_classDefinition.staticFunctions = $jsmangledname_staticFunctions; $jsmangledname_classDefinition.staticValues = $jsmangledname_staticValues; $jsmangledname_classDefinition.callAsConstructor = $jsctor; + $jsmangledname_classDefinition.finalize = $jsdtor; $jsmangledname_objectDefinition.staticValues = $jsmangledname_values; $jsmangledname_objectDefinition.staticFunctions = $jsmangledname_functions; $jsmangledname_objectDefinition.parentClass = $jsbaseclass_classRef; diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 884e09ebe..cec65338a 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1700,6 +1700,7 @@ int JSCEmitter::exitClass(Node *n) { .replace(T_TYPE_MANGLED, state.clazz(TYPE_MANGLED)) .replace(T_BASECLASS, base_name_mangled) .replace(T_CTOR, state.clazz(CTOR)) + .replace(T_DTOR, state.clazz(DTOR)) .pretty_print(state.global(INITIALIZER)); Delete(base_name_mangled); From a29975c69a0bf0628d740232cab722387588eed2 Mon Sep 17 00:00:00 2001 From: Kota Iguchi Date: Fri, 16 Aug 2013 16:08:47 +0900 Subject: [PATCH 0270/1048] Typemap for natural support for arrays --- Lib/javascript/jsc/arrays_javascript.i | 123 ++++++++++++++++++++++++ Lib/javascript/v8/arrays_javascript.i | 125 +++++++++++++++++++++++++ 2 files changed, 248 insertions(+) create mode 100644 Lib/javascript/jsc/arrays_javascript.i create mode 100644 Lib/javascript/v8/arrays_javascript.i diff --git a/Lib/javascript/jsc/arrays_javascript.i b/Lib/javascript/jsc/arrays_javascript.i new file mode 100644 index 000000000..b9199d86b --- /dev/null +++ b/Lib/javascript/jsc/arrays_javascript.i @@ -0,0 +1,123 @@ +/* ----------------------------------------------------------------------------- + * arrays_javascript.i + * + * These typemaps give more natural support for arrays. The typemaps are not efficient + * as there is a lot of copying of the array values whenever the array is passed to C/C++ + * from JavaScript and vice versa. The JavaScript array is expected to be the same size as the C array. + * An exception is thrown if they are not. + * + * Example usage: + * Wrapping: + * + * %include + * %inline %{ + * extern int FiddleSticks[3]; + * %} + * + * Use from JavaScript like this: + * + * var fs = [10, 11, 12]; + * example.FiddleSticks = fs; + * fs = example.FiddleSticks; + * ----------------------------------------------------------------------------- */ + +%fragment("SWIG_JSCGetIntProperty", "header", fragment=SWIG_AsVal_frag(int)) {} +%fragment("SWIG_JSCGetNumberProperty", "header", fragment=SWIG_AsVal_frag(double)) {} + +%typemap(in, fragment="SWIG_JSCGetIntProperty") int[], int[ANY] + (int length = 0, JSObjectRef array, JSValueRef jsvalue, int i = 0, int res = 0, $*1_ltype temp) { + if (JSValueIsObject(context, $input)) + { + // Convert into Array + array = JSValueToObject(context, $input, NULL); + + length = $1_dim0; + + $1 = ($*1_ltype *)malloc(sizeof($*1_ltype) * length); + + // Get each element from array + for (i = 0; i < length; i++) + { + jsvalue = JSObjectGetPropertyAtIndex(context, array, i, NULL); + + // Get primitive value from JSObject + res = SWIG_AsVal(int)(jsvalue, &temp); + if (!SWIG_IsOK(res)) + { + SWIG_exception_fail(SWIG_ERROR, "Failed to convert $input to double"); + } + arg$argnum[i] = temp; + } + + } + else + { + SWIG_exception_fail(SWIG_ERROR, "$input is not JSObjectRef"); + } +} + +%typemap(freearg) int[], int[ANY] { + free($1); +} + +%typemap(out, fragment=SWIG_From_frag(int)) int[], int[ANY] (int length = 0, int i = 0) +{ + length = $1_dim0; + JSValueRef values[length]; + + for (i = 0; i < length; i++) + { + values[i] = SWIG_From(int)($1[i]); + } + + $result = JSObjectMakeArray(context, length, values, NULL); +} + +%typemap(in, fragment="SWIG_JSCGetNumberProperty") double[], double[ANY] + (int length = 0, JSObjectRef array, JSValueRef jsvalue, int i = 0, int res = 0, $*1_ltype temp) { + if (JSValueIsObject(context, $input)) + { + // Convert into Array + array = JSValueToObject(context, $input, NULL); + + length = $1_dim0; + + $1 = ($*1_ltype *)malloc(sizeof($*1_ltype) * length); + + // Get each element from array + for (i = 0; i < length; i++) + { + jsvalue = JSObjectGetPropertyAtIndex(context, array, i, NULL); + + // Get primitive value from JSObject + res = SWIG_AsVal(double)(jsvalue, &temp); + if (!SWIG_IsOK(res)) + { + SWIG_exception_fail(SWIG_ERROR, "Failed to convert $input to double"); + } + arg$argnum[i] = temp; + } + + } + else + { + SWIG_exception_fail(SWIG_ERROR, "$input is not JSObjectRef"); + } +} + +%typemap(freearg) double[], double[ANY] { + free($1); +} + +%typemap(out, fragment=SWIG_From_frag(double)) double[], double[ANY] (int length = 0, int i = 0) +{ + length = $1_dim0; + JSValueRef values[length]; + + for (i = 0; i < length; i++) + { + values[i] = SWIG_From(double)($1[i]); + } + + $result = JSObjectMakeArray(context, length, values, NULL); +} diff --git a/Lib/javascript/v8/arrays_javascript.i b/Lib/javascript/v8/arrays_javascript.i new file mode 100644 index 000000000..22b50be8f --- /dev/null +++ b/Lib/javascript/v8/arrays_javascript.i @@ -0,0 +1,125 @@ +/* ----------------------------------------------------------------------------- + * arrays_javascript.i + * + * These typemaps give more natural support for arrays. The typemaps are not efficient + * as there is a lot of copying of the array values whenever the array is passed to C/C++ + * from JavaScript and vice versa. The JavaScript array is expected to be the same size as the C array. + * An exception is thrown if they are not. + * + * Example usage: + * Wrapping: + * + * %include + * %inline %{ + * extern int FiddleSticks[3]; + * %} + * + * Use from JavaScript like this: + * + * var fs = [10, 11, 12]; + * example.FiddleSticks = fs; + * fs = example.FiddleSticks; + * ----------------------------------------------------------------------------- */ + +%fragment("SWIG_JSCGetIntProperty", "header", fragment=SWIG_AsVal_frag(int)) {} +%fragment("SWIG_JSCGetNumberProperty", "header", fragment=SWIG_AsVal_frag(double)) {} + +%typemap(in, fragment="SWIG_JSCGetIntProperty") int[], int[ANY] + (int length = 0, v8::Local array, v8::Local jsvalue, int i = 0, int res = 0, $*1_ltype temp) { + if ($input->IsArray()) + { + // Convert into Array + array = v8::Local::Cast($input); + + length = $1_dim0; + + $1 = ($*1_ltype *)malloc(sizeof($*1_ltype) * length); + + // Get each element from array + for (i = 0; i < length; i++) + { + jsvalue = array->Get(i); + + // Get primitive value from JSObject + res = SWIG_AsVal(int)(jsvalue, &temp); + if (!SWIG_IsOK(res)) + { + SWIG_exception_fail(SWIG_ERROR, "Failed to convert $input to double"); + } + arg$argnum[i] = temp; + } + + } + else + { + SWIG_exception_fail(SWIG_ERROR, "$input is not JSObjectRef"); + } +} + +%typemap(freearg) int[], int[ANY] { + free($1); +} + +%typemap(out, fragment=SWIG_From_frag(int)) int[], int[ANY] (int length = 0, int i = 0) +{ + length = $1_dim0; + v8::Local array = v8::Array::New(length); + + for (i = 0; i < length; i++) + { + array->Set(i, SWIG_From(int)($1[i])); + } + + + $result = array; +} + +%typemap(in, fragment="SWIG_JSCGetNumberProperty") double[], double[ANY] + (int length = 0, v8::Local array, v8::Local jsvalue, int i = 0, int res = 0, $*1_ltype temp) { + if ($input->IsArray()) + { + // Convert into Array + array = v8::Local::Cast($input); + + length = $1_dim0; + + $1 = ($*1_ltype *)malloc(sizeof($*1_ltype) * length); + + // Get each element from array + for (i = 0; i < length; i++) + { + jsvalue = array->Get(i); + + // Get primitive value from JSObject + res = SWIG_AsVal(double)(jsvalue, &temp); + if (!SWIG_IsOK(res)) + { + SWIG_exception_fail(SWIG_ERROR, "Failed to convert $input to double"); + } + arg$argnum[i] = temp; + } + + } + else + { + SWIG_exception_fail(SWIG_ERROR, "$input is not JSObjectRef"); + } +} + +%typemap(freearg) double[], double[ANY] { + free($1); +} + +%typemap(out, fragment=SWIG_From_frag(double)) double[], double[ANY] (int length = 0, int i = 0) +{ + length = $1_dim0; + v8::Local array = v8::Array::New(length); + + for (i = 0; i < length; i++) + { + array->Set(i, SWIG_From(double)($1[i])); + } + + + $result = array; +} From f70c0e16f292e1fab77fb9ae63f56e86c3ae90c4 Mon Sep 17 00:00:00 2001 From: Kota Iguchi Date: Wed, 28 Aug 2013 15:08:50 +0900 Subject: [PATCH 0271/1048] Add "equals" to compare between pointers Add "getCPtr" to retrieve pointer value --- Lib/javascript/jsc/javascriptruntime.swg | 23 +++++++- Lib/javascript/v8/javascripthelpers.swg | 6 ++ Lib/javascript/v8/javascriptruntime.swg | 73 ++++++++++++++++++++++++ 3 files changed, 101 insertions(+), 1 deletion(-) diff --git a/Lib/javascript/jsc/javascriptruntime.swg b/Lib/javascript/jsc/javascriptruntime.swg index 1eddf93f1..88379415a 100644 --- a/Lib/javascript/jsc/javascriptruntime.swg +++ b/Lib/javascript/jsc/javascriptruntime.swg @@ -78,6 +78,23 @@ JSValueRef _wrap_SwigObject_getCPtr(JSContextRef context, JSObjectRef function, return jsresult; } +JSValueRef _wrap_SwigObject_equals(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + JSValueRef jsresult; + bool result; + + JSObjectRef obj = JSValueToObject(context, thisObject, NULL); + SWIG_PRV_DATA *cdata = (SWIG_PRV_DATA*) JSObjectGetPrivate(obj); + + JSObjectRef obj2 = JSValueToObject(context, argv[0], NULL); + SWIG_PRV_DATA *cdata2 = (SWIG_PRV_DATA*) JSObjectGetPrivate(obj2); + + result = (cdata->swigCObject == cdata2->swigCObject); + jsresult = JSValueMakeBoolean(context, result); + + return jsresult; +} + JSStaticValue _SwigObject_values[] = { { 0, 0, 0, 0 @@ -87,7 +104,11 @@ JSStaticValue _SwigObject_values[] = { JSStaticFunction _SwigObject_functions[] = { { "disown",_wrap_SwigObject_disown, kJSPropertyAttributeNone - },{ + }, + { + "equals",_wrap_SwigObject_equals, kJSPropertyAttributeNone + }, + { "getCPtr",_wrap_SwigObject_getCPtr, kJSPropertyAttributeNone }, { diff --git a/Lib/javascript/v8/javascripthelpers.swg b/Lib/javascript/v8/javascripthelpers.swg index 61bc45da5..52f3f106f 100644 --- a/Lib/javascript/v8/javascripthelpers.swg +++ b/Lib/javascript/v8/javascripthelpers.swg @@ -24,6 +24,12 @@ v8::Handle SWIGV8_CreateClassTemplate(const char* symbol) v8::Handle inst_templ = class_templ->InstanceTemplate(); inst_templ->SetInternalFieldCount(1); + v8::Handle equals_templ = class_templ->PrototypeTemplate(); + equals_templ->Set(v8::String::NewSymbol("equals"), v8::FunctionTemplate::New(_wrap_equals)); + + v8::Handle cptr_templ = class_templ->PrototypeTemplate(); + cptr_templ->Set(v8::String::NewSymbol("getCPtr"), v8::FunctionTemplate::New(_wrap_getCPtr)); + return scope.Close(class_templ); } diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index 841b03e21..bfc93a8fb 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -175,6 +175,28 @@ void SWIGV8_Proxy_DefaultDtor(v8::Isolate *, v8::Persistent< v8::Object > *objec delete proxy; } +int SWIG_V8_GetInstancePtr(v8::Handle valRef, void** ptr) { + if(!valRef->IsObject()) { + return SWIG_TypeError; + } + v8::Handle objRef = valRef->ToObject(); + + if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; + +#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) + v8::Handle cdataRef = objRef->GetInternalField(0); + SWIGV8_Proxy *cdata = static_cast(v8::External::Unwrap(cdataRef)); +#else + SWIGV8_Proxy *cdata = static_cast(objRef->GetAlignedPointerFromInternalField(0)); +#endif + + if(cdata == NULL) { + return SWIG_ERROR; + } + + *ptr = cdata->swigCObject; +} + void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info *info, int flags) { SWIGV8_Proxy* cdata = new SWIGV8_Proxy(); cdata->swigCObject = ptr; @@ -253,5 +275,56 @@ v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, in #define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_V8_ConvertPtr(obj, pptr, type, 0) #define SWIG_NewFunctionPtrObj(ptr, type) SWIG_V8_NewPointerObj(ptr, type, 0) +#define SWIG_GetInstancePtr(obj, ptr) SWIG_V8_GetInstancePtr(obj, ptr) + +v8::Handle _wrap_equals(const v8::Arguments &args) { + v8::HandleScope scope; + v8::Handle jsresult; + void *arg1 = (void *) 0 ; + void *arg2 = (void *) 0 ; + bool result; + int res1; + int res2; + + if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_equals."); + + res1 = SWIG_GetInstancePtr(args.Holder(), &arg1); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ERROR, "Could not get pointer from 'this' object for _wrap_equals."); + } + res2 = SWIG_GetInstancePtr(args[0], &arg2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "equals" "', argument " "1"" of type '" "void *""'"); + } + + result = (bool)(arg1 == arg2); + jsresult = v8::Boolean::New(result); + + return scope.Close(jsresult); + goto fail; +fail: + return scope.Close(v8::Undefined()); +} + +v8::Handle _wrap_getCPtr(const v8::Arguments &args) { + v8::HandleScope scope; + v8::Handle jsresult; + void *arg1 = (void *) 0 ; + long result; + int res1; + + res1 = SWIG_GetInstancePtr(args.Holder(), &arg1); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "getCPtr" "', argument " "1"" of type '" "void *""'"); + } + + result = (long)arg1; + jsresult = v8::Number::New(result); + + return scope.Close(jsresult); + goto fail; +fail: + return scope.Close(v8::Undefined()); +} %} From d3074ba4c1cc46bfebd3b09671f92965cab533ed Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 3 Sep 2013 14:02:52 +0200 Subject: [PATCH 0272/1048] Fix error in SWIG_V8_GetInstancePtr. --- Lib/javascript/v8/javascriptruntime.swg | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index bfc93a8fb..1c97506da 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -195,6 +195,8 @@ int SWIG_V8_GetInstancePtr(v8::Handle valRef, void** ptr) { } *ptr = cdata->swigCObject; + + return SWIG_OK; } void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info *info, int flags) { From cef82c720f4875b9ddf53667e5396d3b80c7eefd Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 3 Sep 2013 14:41:35 +0200 Subject: [PATCH 0273/1048] Replace old style v8 version switches. --- Lib/javascript/v8/javascriptruntime.swg | 28 ++++++++++--------------- 1 file changed, 11 insertions(+), 17 deletions(-) diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index 1c97506da..139a5a3ee 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -94,19 +94,14 @@ public: }; ~SWIGV8_Proxy() { -#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) +#if (SWIG_V8_VERSION < 0x031900) handle.ClearWeak(); -#else - handle.ClearWeak(v8::Isolate::GetCurrent()); -#endif - - //handle->SetInternalField(0, v8::Undefined()); - -#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) handle.Dispose(); #else + handle.ClearWeak(v8::Isolate::GetCurrent()); handle.Dispose(v8::Isolate::GetCurrent()); #endif + handle.Clear(); v8::V8::AdjustAmountOfExternalAllocatedMemory(-SWIGV8_AVG_OBJ_SIZE); } @@ -121,7 +116,7 @@ class SWIGV8_ClientData { public: v8::Persistent class_templ; -#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) +#if (SWIG_V8_VERSION < 0x031900) void (*dtor) (v8::Persistent< v8::Value> object, void *parameter); #else void (*dtor) (v8::Isolate *isolate, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy); @@ -135,7 +130,7 @@ int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_t if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; -#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) +#if (SWIG_V8_VERSION < 0x031900) v8::Handle cdataRef = objRef->GetInternalField(0); SWIGV8_Proxy *cdata = static_cast(v8::External::Unwrap(cdataRef)); #else @@ -162,13 +157,13 @@ int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_t return SWIG_OK; } -#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) +#if (SWIG_V8_VERSION < 0x031900) void SWIGV8_Proxy_DefaultDtor(v8::Persistent< v8::Value > object, void *parameter) #else void SWIGV8_Proxy_DefaultDtor(v8::Isolate *, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy) #endif { -#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) +#if (SWIG_V8_VERSION < 0x031900) SWIGV8_Proxy *proxy = static_cast(parameter); #endif @@ -183,7 +178,7 @@ int SWIG_V8_GetInstancePtr(v8::Handle valRef, void** ptr) { if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; -#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) +#if (SWIG_V8_VERSION < 0x031900) v8::Handle cdataRef = objRef->GetInternalField(0); SWIGV8_Proxy *cdata = static_cast(v8::External::Unwrap(cdataRef)); #else @@ -205,7 +200,7 @@ void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; cdata->info = info; -#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) +#if (SWIG_V8_VERSION < 0x031900) obj->SetPointerInInternalField(0, cdata); cdata->handle = v8::Persistent::New(obj); #else @@ -213,7 +208,7 @@ void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info cdata->handle.Reset(v8::Isolate::GetCurrent(), obj); #endif -#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) +#if (SWIG_V8_VERSION < 0x031900) // clientdata must be set for owned data as we need to register the dtor if(cdata->swigCMemOwn && (SWIGV8_ClientData*)info->clientdata) { cdata->handle.MakeWeak(cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); @@ -246,7 +241,7 @@ v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, in v8::Handle class_templ; -#if defined(BUILDING_NODE_EXTENSION) || defined(V8_3_14) +#if (SWIG_V8_VERSION < 0x031900) if(info->clientdata != 0) { class_templ = ((SWIGV8_ClientData*) info->clientdata)->class_templ; } else { @@ -329,4 +324,3 @@ fail: return scope.Close(v8::Undefined()); } %} - From 8bbd92883101584583e3139e442bc418100b4a45 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 3 Sep 2013 16:57:40 +0200 Subject: [PATCH 0274/1048] Make javascript test-suite work with nodejs. --- .gitignore | 1 + Examples/test-suite/javascript/Makefile.in | 60 ++++++++++--------- .../javascript/abstract_access_runme.js | 3 +- .../javascript/abstract_typedef2_runme.js | 2 + .../javascript/abstract_typedef_runme.js | 2 + .../javascript/abstract_virtual_runme.js | 2 + .../javascript/array_member_runme.js | 2 + .../javascript/arrays_global_runme.js | 2 + .../javascript/char_binary_runme.js | 2 + .../javascript/class_ignore_runme.js | 1 + .../javascript/class_scope_weird_runme.js | 1 + .../javascript/complextest_runme.js | 1 + .../test-suite/javascript/constover_runme.js | 4 +- .../javascript/constructor_copy_runme.js | 1 + .../test-suite/javascript/cpp_enum_runme.js | 2 + .../javascript/cpp_namespace_runme.js | 4 +- .../test-suite/javascript/cpp_static_runme.js | 2 + .../javascript/director_alternating_runme.js | 1 + .../javascript/enum_template_runme.js | 4 +- .../javascript/javascript_unicode_runme.js | 2 + .../namespace_virtual_method_runme.js | 1 + .../javascript/overload_copy_runme.js | 1 + .../javascript/preproc_include_runme.js | 1 + .../test-suite/javascript/preproc_runme.js | 1 + .../javascript/ret_by_value_runme.js | 1 + Examples/test-suite/javascript/setup_test.sh | 6 ++ .../javascript/struct_value_runme.js | 5 +- .../javascript/template_static_runme.js | 1 + .../javascript/typedef_class_runme.js | 8 ++- .../javascript/typedef_inherit_runme.js | 1 + .../javascript/typedef_scope_runme.js | 5 +- .../javascript/typemap_arrays_runme.js | 1 + .../javascript/typemap_delete_runme.js | 1 + .../javascript/typemap_namespace_runme.js | 1 + .../javascript/typemap_ns_using_runme.js | 1 + .../test-suite/javascript/using1_runme.js | 2 +- .../test-suite/javascript/using2_runme.js | 1 + 37 files changed, 98 insertions(+), 39 deletions(-) create mode 100644 Examples/test-suite/javascript/setup_test.sh diff --git a/.gitignore b/.gitignore index 147e44cb2..665699d05 100644 --- a/.gitignore +++ b/.gitignore @@ -75,6 +75,7 @@ Examples/test-suite/*/*.c Examples/test-suite/*/*.h Examples/test-suite/python/*.py Examples/javascript/*/*_wrap.c +Examples/test-suite/javascript/*/* Tools/javascript/javascript Tools/javascript/javascript_d .settings diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index e57081412..edc621c7e 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -10,25 +10,23 @@ top_builddir = @top_builddir@ JS_INCLUDE = @JSCOREINC@ JS_DLNK = @JSCOREDYNAMICLINKING@ JSCXXFLAGS = @JSCXXFLAGS@ -JAVASCRIPT_EXE = $(top_srcdir)/Tools/javascript/javascript +JAVASCRIPT_EXE = node +SWIG = $(top_builddir)/preinst_swig C_TEST_CASES = \ - preproc \ - preproc_include + preproc + CPP_TEST_CASES = \ abstract_access \ abstract_typedef \ abstract_typedef2 \ abstract_virtual \ - array_member \ arrays_global \ char_binary \ class_ignore \ class_scope_weird \ - complextest \ constover \ - constructor_copy \ cpp_enum \ cpp_namespace \ cpp_static \ @@ -50,6 +48,12 @@ CPP_TEST_CASES = \ using2 \ javascript_unicode +BROKEN_TEST_CASES = \ + array_member \ + complextest \ + constructor_copy \ + preproc_include + SKIP_CPP_CASES = @SKIP_CPP_CASES@ SKIP_C_CASES = @SKIP_C_CASES@ SKIP_CPP_STD_CASES = @SKIP_CPP_STD_CASES@ @@ -57,45 +61,47 @@ SKIP_MULTI_CPP_CASES = @SKIP_MULTI_CPP_CASES@ include $(srcdir)/../common.mk -ifeq (,$(V8)) -JSENGINEFLAG = -jsc -else -JSENGINEFLAG = -v8 -endif - # Overridden variables here # Custom tests - tests with additional commandline options -javascript_exe: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TOP='$(top_builddir)/$(EXAMPLES)' javascript_exe - # Rules for the different types of tests -%.cpptest: javascript_exe - $(setup) - +$(swig_and_compile_cpp) +%.cpptest: + $(prepare_test) + $(generate_cpp_wrapper) + $(build_module) $(run_testcase) -%.ctest: javascript_exe - $(setup) - +$(swig_and_compile_c) +%.ctest: + $(prepare_test) + $(generate_cpp_wrapper) + $(build_module) $(run_testcase) -%.multicpptest: javascript_exe - $(setup) - +$(swig_and_compile_multi_cpp) +%.multicpptest: + $(prepare_test) + $(generate_cpp_wrapper) + $(build_module) $(run_testcase) +prepare_test = \ + sh ./setup_test.sh $* + +generate_cpp_wrapper = \ + $(SWIG) -c++ -javascript -node -o $*/$*_wrap.cxx ../$*.i + +build_module = \ + cd $* && node-gyp configure build && cd .. + # Runs the testcase. A testcase is only run if # a file is found which has _runme.js appended after the testcase name. run_testcase = \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(JAVASCRIPT_EXE) $(JSENGINEFLAG) -l $* $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + if [ -f $(srcdir)/$*$(SCRIPTSUFFIX) ]; then \ + node $(srcdir)/$*$(SCRIPTSUFFIX); \ fi # Clean %.clean: - clean: $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile javascript_clean diff --git a/Examples/test-suite/javascript/abstract_access_runme.js b/Examples/test-suite/javascript/abstract_access_runme.js index 356d07ea7..8f87d2105 100644 --- a/Examples/test-suite/javascript/abstract_access_runme.js +++ b/Examples/test-suite/javascript/abstract_access_runme.js @@ -1,5 +1,6 @@ +var abstract_access = require("./abstract_access"); + var d = new abstract_access.D() if (d.do_x() != 1) { throw "Error"; } - diff --git a/Examples/test-suite/javascript/abstract_typedef2_runme.js b/Examples/test-suite/javascript/abstract_typedef2_runme.js index 8adc2e05b..c177e49c3 100644 --- a/Examples/test-suite/javascript/abstract_typedef2_runme.js +++ b/Examples/test-suite/javascript/abstract_typedef2_runme.js @@ -1,3 +1,5 @@ +var abstract_typedef2 = require("./abstract_typedef2"); + var a = new abstract_typedef2.A_UF(); if (a == undefined) diff --git a/Examples/test-suite/javascript/abstract_typedef_runme.js b/Examples/test-suite/javascript/abstract_typedef_runme.js index 106baea65..abcfc581d 100644 --- a/Examples/test-suite/javascript/abstract_typedef_runme.js +++ b/Examples/test-suite/javascript/abstract_typedef_runme.js @@ -1,3 +1,5 @@ +var abstract_typedef = require("./abstract_typedef"); + var e = new abstract_typedef.Engine(); var a = new abstract_typedef.A() diff --git a/Examples/test-suite/javascript/abstract_virtual_runme.js b/Examples/test-suite/javascript/abstract_virtual_runme.js index c15abb5f6..9e2814e41 100644 --- a/Examples/test-suite/javascript/abstract_virtual_runme.js +++ b/Examples/test-suite/javascript/abstract_virtual_runme.js @@ -1,3 +1,5 @@ +var abstract_virtual = require("./abstract_virtual"); + d = new abstract_virtual.D() if (d == undefined) diff --git a/Examples/test-suite/javascript/array_member_runme.js b/Examples/test-suite/javascript/array_member_runme.js index dee4c2ca9..8c4ef1da5 100644 --- a/Examples/test-suite/javascript/array_member_runme.js +++ b/Examples/test-suite/javascript/array_member_runme.js @@ -1,3 +1,5 @@ +var array_member = require("./array_member"); + var f = new array_member.Foo(); f.data = array_member.global_data; diff --git a/Examples/test-suite/javascript/arrays_global_runme.js b/Examples/test-suite/javascript/arrays_global_runme.js index 9668826f3..fdb365f83 100644 --- a/Examples/test-suite/javascript/arrays_global_runme.js +++ b/Examples/test-suite/javascript/arrays_global_runme.js @@ -1,3 +1,5 @@ +var arrays_global = require("./arrays_global"); + arrays_global.array_i = arrays_global.array_const_i; arrays_global.BeginString_FIX44a; diff --git a/Examples/test-suite/javascript/char_binary_runme.js b/Examples/test-suite/javascript/char_binary_runme.js index 7cd09bd5c..42abe6060 100644 --- a/Examples/test-suite/javascript/char_binary_runme.js +++ b/Examples/test-suite/javascript/char_binary_runme.js @@ -1,3 +1,5 @@ +var char_binary = require("./char_binary"); + var t = new char_binary.Test(); if (t.strlen('hile') != 4) { print(t.strlen('hile')); diff --git a/Examples/test-suite/javascript/class_ignore_runme.js b/Examples/test-suite/javascript/class_ignore_runme.js index 00bb2591e..f0a32a1c4 100644 --- a/Examples/test-suite/javascript/class_ignore_runme.js +++ b/Examples/test-suite/javascript/class_ignore_runme.js @@ -1,3 +1,4 @@ +var class_ignore = require("./class_ignore"); a = new class_ignore.Bar(); diff --git a/Examples/test-suite/javascript/class_scope_weird_runme.js b/Examples/test-suite/javascript/class_scope_weird_runme.js index c442cc7f6..ac745d023 100644 --- a/Examples/test-suite/javascript/class_scope_weird_runme.js +++ b/Examples/test-suite/javascript/class_scope_weird_runme.js @@ -1,3 +1,4 @@ +var class_scope_weird = require("./class_scope_weird"); f = new class_scope_weird.Foo(); g = new class_scope_weird.Foo(3); diff --git a/Examples/test-suite/javascript/complextest_runme.js b/Examples/test-suite/javascript/complextest_runme.js index 9d3cf4264..1fcc97648 100644 --- a/Examples/test-suite/javascript/complextest_runme.js +++ b/Examples/test-suite/javascript/complextest_runme.js @@ -1,3 +1,4 @@ +var complextest = require("./complextest"); a = [-1,2]; diff --git a/Examples/test-suite/javascript/constover_runme.js b/Examples/test-suite/javascript/constover_runme.js index f131ef444..764d8b328 100644 --- a/Examples/test-suite/javascript/constover_runme.js +++ b/Examples/test-suite/javascript/constover_runme.js @@ -1,3 +1,5 @@ +var constover = require("./constover"); + p = constover.test("test"); if (p != "test") { throw "test failed!"; @@ -7,7 +9,7 @@ p = constover.test_pconst("test"); if (p != "test_pconst") { throw "test_pconst failed!"; } - + f = new constover.Foo(); p = f.test("test"); diff --git a/Examples/test-suite/javascript/constructor_copy_runme.js b/Examples/test-suite/javascript/constructor_copy_runme.js index 627b0936b..39dce52ce 100644 --- a/Examples/test-suite/javascript/constructor_copy_runme.js +++ b/Examples/test-suite/javascript/constructor_copy_runme.js @@ -1,3 +1,4 @@ +var constructor_copy = require("./constructor_copy"); f1 = new constructor_copy.Foo1(3); f11 = new constructor_copy.Foo1(f1); diff --git a/Examples/test-suite/javascript/cpp_enum_runme.js b/Examples/test-suite/javascript/cpp_enum_runme.js index f5a9e3595..35f7c60ac 100644 --- a/Examples/test-suite/javascript/cpp_enum_runme.js +++ b/Examples/test-suite/javascript/cpp_enum_runme.js @@ -1,3 +1,5 @@ +var cpp_enum = require("./cpp_enum"); + var f = new cpp_enum.Foo() if(f.hola != cpp_enum.Hello){ diff --git a/Examples/test-suite/javascript/cpp_namespace_runme.js b/Examples/test-suite/javascript/cpp_namespace_runme.js index 5795536bd..3bdfef3e9 100644 --- a/Examples/test-suite/javascript/cpp_namespace_runme.js +++ b/Examples/test-suite/javascript/cpp_namespace_runme.js @@ -1,3 +1,5 @@ +var cpp_namespace = require("./cpp_namespace"); + var n = cpp_namespace.fact(4); if (n != 24){ throw ("Bad return value error!"); @@ -16,7 +18,7 @@ if (cpp_namespace.do_method(t) != "Test::method"){ if (cpp_namespace.do_method2(t) != "Test::method"){ throw ("Bad return value error!"); -} +} cpp_namespace.weird("hello", 4); delete t; diff --git a/Examples/test-suite/javascript/cpp_static_runme.js b/Examples/test-suite/javascript/cpp_static_runme.js index 0ff28b4ee..2579aeafe 100644 --- a/Examples/test-suite/javascript/cpp_static_runme.js +++ b/Examples/test-suite/javascript/cpp_static_runme.js @@ -1,3 +1,5 @@ +var cpp_static = require("./cpp_static"); + cpp_static.StaticFunctionTest.static_func(); cpp_static.StaticFunctionTest.static_func_2(1); cpp_static.StaticFunctionTest.static_func_3(1,2); diff --git a/Examples/test-suite/javascript/director_alternating_runme.js b/Examples/test-suite/javascript/director_alternating_runme.js index 3c2c883a1..a0411eace 100644 --- a/Examples/test-suite/javascript/director_alternating_runme.js +++ b/Examples/test-suite/javascript/director_alternating_runme.js @@ -1,3 +1,4 @@ +var director_alternating = require("./director_alternating"); id = director_alternating.getBar().id(); if (id != director_alternating.idFromGetBar()) diff --git a/Examples/test-suite/javascript/enum_template_runme.js b/Examples/test-suite/javascript/enum_template_runme.js index 54195c78b..20f8c3482 100644 --- a/Examples/test-suite/javascript/enum_template_runme.js +++ b/Examples/test-suite/javascript/enum_template_runme.js @@ -1,6 +1,8 @@ +var enum_template = require("./enum_template"); + if (enum_template.MakeETest() != 1) throw "RuntimeError"; if (enum_template.TakeETest(0) != null) throw "RuntimeError"; - + diff --git a/Examples/test-suite/javascript/javascript_unicode_runme.js b/Examples/test-suite/javascript/javascript_unicode_runme.js index 4974ef40b..f5f747aa7 100644 --- a/Examples/test-suite/javascript/javascript_unicode_runme.js +++ b/Examples/test-suite/javascript/javascript_unicode_runme.js @@ -1,3 +1,5 @@ +var javascript_unicode = require("./javascript_unicode"); + var str = "olé"; var copy = javascript_unicode.copy_string(str); diff --git a/Examples/test-suite/javascript/namespace_virtual_method_runme.js b/Examples/test-suite/javascript/namespace_virtual_method_runme.js index bb187b993..24d3bd487 100644 --- a/Examples/test-suite/javascript/namespace_virtual_method_runme.js +++ b/Examples/test-suite/javascript/namespace_virtual_method_runme.js @@ -1,2 +1,3 @@ +var namespace_virtual_method = require("./namespace_virtual_method"); x = new namespace_virtual_method.Spam(); diff --git a/Examples/test-suite/javascript/overload_copy_runme.js b/Examples/test-suite/javascript/overload_copy_runme.js index 88fab3720..1039ffda1 100644 --- a/Examples/test-suite/javascript/overload_copy_runme.js +++ b/Examples/test-suite/javascript/overload_copy_runme.js @@ -1,3 +1,4 @@ +var overload_copy = require("./overload_copy"); f = new overload_copy.Foo(); g = new overload_copy.Foo(f); diff --git a/Examples/test-suite/javascript/preproc_include_runme.js b/Examples/test-suite/javascript/preproc_include_runme.js index d52ef97c1..4b827fbcc 100644 --- a/Examples/test-suite/javascript/preproc_include_runme.js +++ b/Examples/test-suite/javascript/preproc_include_runme.js @@ -1,3 +1,4 @@ +var preproc_include = require("./preproc_include"); if (preproc_include.multiply10(10) != 100) throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/preproc_runme.js b/Examples/test-suite/javascript/preproc_runme.js index b708385da..669f9d1f0 100644 --- a/Examples/test-suite/javascript/preproc_runme.js +++ b/Examples/test-suite/javascript/preproc_runme.js @@ -1,3 +1,4 @@ +var preproc = require("./preproc"); if (preproc.endif != 1) throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/ret_by_value_runme.js b/Examples/test-suite/javascript/ret_by_value_runme.js index 720cd398f..d9a77a20b 100644 --- a/Examples/test-suite/javascript/ret_by_value_runme.js +++ b/Examples/test-suite/javascript/ret_by_value_runme.js @@ -1,3 +1,4 @@ +var ret_by_value = require("./ret_by_value"); a = ret_by_value.get_test(); if (a.myInt != 100) diff --git a/Examples/test-suite/javascript/setup_test.sh b/Examples/test-suite/javascript/setup_test.sh new file mode 100644 index 000000000..03ce3bc90 --- /dev/null +++ b/Examples/test-suite/javascript/setup_test.sh @@ -0,0 +1,6 @@ +#!/bin/sh +if [ ! -d $1 ]; then + mkdir $1; +fi +echo "module.exports = require('./build/Release/$1')" > $1/index.js +echo "{\"targets\":[{\"target_name\": \"$1\",\"sources\":[\"$1_wrap.cxx\"]}]}" > $1/binding.gyp diff --git a/Examples/test-suite/javascript/struct_value_runme.js b/Examples/test-suite/javascript/struct_value_runme.js index 314551688..d6b26f726 100644 --- a/Examples/test-suite/javascript/struct_value_runme.js +++ b/Examples/test-suite/javascript/struct_value_runme.js @@ -1,10 +1,11 @@ +var struct_value = require("./struct_value"); b = new struct_value.Bar(); b.a.x = 3; -if (b.a.x != 3) +if (b.a.x != 3) throw "RuntimeError"; b.b.x = 3; -if (b.b.x != 3) +if (b.b.x != 3) throw "RuntimeError" diff --git a/Examples/test-suite/javascript/template_static_runme.js b/Examples/test-suite/javascript/template_static_runme.js index 338e2c55c..477d97249 100644 --- a/Examples/test-suite/javascript/template_static_runme.js +++ b/Examples/test-suite/javascript/template_static_runme.js @@ -1,2 +1,3 @@ +var template_static = require("./template_static"); template_static.Foo.bar_double(1); diff --git a/Examples/test-suite/javascript/typedef_class_runme.js b/Examples/test-suite/javascript/typedef_class_runme.js index accefb499..3e4dc9093 100644 --- a/Examples/test-suite/javascript/typedef_class_runme.js +++ b/Examples/test-suite/javascript/typedef_class_runme.js @@ -1,5 +1,7 @@ +var typedef_class = require("./typedef_class"); + a = new typedef_class.RealA(); -a.a = 3; - +a.a = 3; + b = new typedef_class.B(); -b.testA(a); +b.testA(a); diff --git a/Examples/test-suite/javascript/typedef_inherit_runme.js b/Examples/test-suite/javascript/typedef_inherit_runme.js index f16c1787e..4abcc2536 100644 --- a/Examples/test-suite/javascript/typedef_inherit_runme.js +++ b/Examples/test-suite/javascript/typedef_inherit_runme.js @@ -1,3 +1,4 @@ +var typedef_inherit = require("./typedef_inherit"); a = new typedef_inherit.Foo(); b = new typedef_inherit.Bar(); diff --git a/Examples/test-suite/javascript/typedef_scope_runme.js b/Examples/test-suite/javascript/typedef_scope_runme.js index 8a08ffb9b..0ac56884c 100644 --- a/Examples/test-suite/javascript/typedef_scope_runme.js +++ b/Examples/test-suite/javascript/typedef_scope_runme.js @@ -1,3 +1,4 @@ +var typedef_scope = require("./typedef_scope"); b = new typedef_scope.Bar(); x = b.test1(42,"hello"); @@ -7,5 +8,5 @@ if (x != 42) x = b.test2(42,"hello"); if (x != "hello") print("Failed!!"); - - + + diff --git a/Examples/test-suite/javascript/typemap_arrays_runme.js b/Examples/test-suite/javascript/typemap_arrays_runme.js index 2126ed15f..cd6827ac9 100644 --- a/Examples/test-suite/javascript/typemap_arrays_runme.js +++ b/Examples/test-suite/javascript/typemap_arrays_runme.js @@ -1,3 +1,4 @@ +var typemap_arrays = require("./typemap_arrays"); if (typemap_arrays.sumA(null) != 60) throw "RuntimeError, Sum is wrong"; diff --git a/Examples/test-suite/javascript/typemap_delete_runme.js b/Examples/test-suite/javascript/typemap_delete_runme.js index d58684df4..4b3174956 100644 --- a/Examples/test-suite/javascript/typemap_delete_runme.js +++ b/Examples/test-suite/javascript/typemap_delete_runme.js @@ -1,3 +1,4 @@ +var typemap_delete = require("./typemap_delete"); r = new typemap_delete.Rect(123); if (r.val != 123) diff --git a/Examples/test-suite/javascript/typemap_namespace_runme.js b/Examples/test-suite/javascript/typemap_namespace_runme.js index d679f3b0b..614e0ffeb 100644 --- a/Examples/test-suite/javascript/typemap_namespace_runme.js +++ b/Examples/test-suite/javascript/typemap_namespace_runme.js @@ -1,3 +1,4 @@ +var typemap_namespace = require("./typemap_namespace"); if (typemap_namespace.test1("hello") != "hello") throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/typemap_ns_using_runme.js b/Examples/test-suite/javascript/typemap_ns_using_runme.js index d05f7f0c1..9115c16ae 100644 --- a/Examples/test-suite/javascript/typemap_ns_using_runme.js +++ b/Examples/test-suite/javascript/typemap_ns_using_runme.js @@ -1,3 +1,4 @@ +var typemap_ns_using = require("./typemap_ns_using"); if (typemap_ns_using.spam(37) != 37) throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/using1_runme.js b/Examples/test-suite/javascript/using1_runme.js index cb54a62fa..a2e37fcb6 100644 --- a/Examples/test-suite/javascript/using1_runme.js +++ b/Examples/test-suite/javascript/using1_runme.js @@ -1,4 +1,4 @@ - +var using1 = require("./using1"); if (using1.spam(37) != 37) throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/using2_runme.js b/Examples/test-suite/javascript/using2_runme.js index 948f58ead..aa5e9b15f 100644 --- a/Examples/test-suite/javascript/using2_runme.js +++ b/Examples/test-suite/javascript/using2_runme.js @@ -1,3 +1,4 @@ +var using2 = require("./using2"); if (using2.spam(37) != 37) throw "RuntimeError"; From fa27ff29769031cef7dbb3b1951ec6adde09b0cf Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 3 Sep 2013 17:03:08 +0200 Subject: [PATCH 0275/1048] Add a travis configuration (experimental). --- .travis.yml | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 000000000..7d848aa07 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,5 @@ +node_js: + -0.10.0 + +before_script: "./autogen.sh && ./configure.sh && make" +script: "make check-javascript-test-suite" From 0aabfeb231d74ac997b28e816987fb033d6b2fd9 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 3 Sep 2013 17:07:49 +0200 Subject: [PATCH 0276/1048] Slight modification to travis config. --- .travis.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 7d848aa07..04ce3c8b9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,7 @@ node_js: -0.10.0 - +language: c +compiler: + - gcc before_script: "./autogen.sh && ./configure.sh && make" script: "make check-javascript-test-suite" From 83e6aa85b6e7f8097eb02179bb8f3faaeb06037b Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 3 Sep 2013 17:13:38 +0200 Subject: [PATCH 0277/1048] Not a real change. --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 04ce3c8b9..d2df5ffa3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,5 +3,6 @@ node_js: language: c compiler: - gcc + before_script: "./autogen.sh && ./configure.sh && make" script: "make check-javascript-test-suite" From 262aca8ead684a53c4f2029db5f32a3505e348b3 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 3 Sep 2013 17:16:40 +0200 Subject: [PATCH 0278/1048] Fix in travis config. --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index d2df5ffa3..37f81955e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,5 +4,5 @@ language: c compiler: - gcc -before_script: "./autogen.sh && ./configure.sh && make" +before_script: "./autogen.sh && ./configure && make" script: "make check-javascript-test-suite" From da48f3307f4ac358ca2d325f8c04b9a5afb90323 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 3 Sep 2013 18:24:19 +0200 Subject: [PATCH 0279/1048] Remove javascript autoconf detection (Temporarily). I want to cut it down to a minimum having only nodejs. We will activate the others (native JSC and V8) later. --- configure.in | 213 --------------------------------------------------- 1 file changed, 213 deletions(-) diff --git a/configure.in b/configure.in index 0e00c958a..6ff3d5258 100644 --- a/configure.in +++ b/configure.in @@ -1089,207 +1089,6 @@ if test x"${with_javascript}" = xno -o x"${with_alllang}" = xno ; then JAVASCRIPT= fi -### JavascriptCore ### - -# check for include files -AC_MSG_CHECKING(for include file JavaScriptCore/JavaScript.h) -AC_ARG_WITH(javascriptincl, [ --with-javascript=path Set location of Javascript include directory], [JSCOREINCDIR="$withval"], [JSCOREINCDIR=]) - -if test -z "$JSCOREINCDIR"; then - JSCOREINCDIR="/usr/include/ /usr/local/include/" - - # Add in default directory for JavaScriptCore headers for Linux and MacOSX - case $host in - *-*-linux*) JSCOREINCDIR="/usr/include/webkit-1.0/ /usr/include/webkitgtk-1.0/ /usr/local/include/webkit-1.0/JavaScriptCore/ $JSCOREINCDIR";; - *-*-darwin*) JSCOREINCDIR="/System/Library/Frameworks/JavaScriptCore.framework/Headers/ $JSCOREINCDIR";; - *);; - esac -fi - -JSCORE=0 -for d in $JSCOREINCDIR ; do - if test -r "$d/JavaScriptCore/JavaScript.h" || test -r "$d/JavaScript.h" ; then - AC_MSG_RESULT($d) - JSCOREINCDIR=$d - JSCOREINC=-I\"$d\" - JSCORE=1 - break - fi -done - -if test "$JSCOREINC" = "" ; then - AC_MSG_RESULT(not found) -fi - -# under linux look for the javascript core library -case $host in - *-*-linux*) - # check for JavaScriptCore, Webkit libraries - AC_ARG_WITH(jscorelib,[ --with-jscorelib =path Set location of JavaScriptCore (Webkit) library directory], [JSCORELIB="-L$withval"], [JSCORELIB=]) - AC_MSG_CHECKING(for JavaScriptCore(Webkit) library) - - if test -z "$JSCORELIB"; then - JSCORELIBDIRS="/usr/lib/ /usr/local/lib/" - for i in $JSCORELIBDIRS ; do - - if test -r $i/libwebkit-1.0.la; then - AC_MSG_RESULT($i) - JSCORELIB="-L$i -lwebkit-1.0" - break - fi - - if test -r $i/libjavascriptcoregtk-1.0.so; then - AC_MSG_RESULT($i) - JSCORELIB="-L$i -ljavascriptcoregtk-1.0" - break - fi - - if test -r $i/libwebkitgtk-1.0.so; then - AC_MSG_RESULT($i) - JSCORELIB="-L$i -lwebkitgtk-1.0" - break - fi - done - fi - - if test -z "$JSCORELIB"; then - AC_MSG_RESULT(not found) - JSCORE=0 - else - AC_MSG_RESULT($JSCORELIB) - JSCORE=1 - fi - ;; -esac - -# linking options -case $host in -*-*-darwin*) - JSCOREDYNAMICLINKING="-framework JavaScriptCore" - JSCORECFLAGS="" - ;; -*-*-linux*) - JSCOREDYNAMICLINKING="$JSCORELIB" - JSCORECFLAGS="" - ;; -*) - JSCOREDYNAMICLINKING="" - JSCORECFLAGS="" - ;; -esac - -# JSCORELIBRARYPREFIX -case $host in -*-*-cygwin* | *-*-mingw*) JSCORELIBRARYPREFIX="";; -*) JSCORELIBRARYPREFIX="lib";; -esac - -if test "$JS_NO_WARNINGS" == "1"; then - case $host in - *-*-darwin* | *-*-linux* | *-*-cygwin* | *-*-mingw*) - JSCXXFLAGS="`echo $CXXFLAGS | sed 's/-Wall//g'`" - ;; - *) - JSCXXFLAGS="$CXXFLAGS" - esac -fi - -# library output -case $host in -*-*-darwin*) - JSCORESO=".dylib" - JSCORELDSHARED='$(CC) -dynamiclib' - JSCORECXXSHARED='$(CXX) -dynamiclib' - ;; -*) - JSCORESO=$SO - JSCORELDSHARED='$(LDSHARED)' - JSCORECXXSHARED='$(CXXSHARED)' - ;; -esac - -AC_SUBST(JSCORE) -AC_SUBST(JSCOREINC) -AC_SUBST(JSCOREDYNAMICLINKING) -AC_SUBST(JSCORELIBRARYPREFIX) -AC_SUBST(JSCORECFLAGS) -AC_SUBST(JSCORESO) -AC_SUBST(JSCORELDSHARED) -AC_SUBST(JSCORECXXSHARED) -AC_SUBST(JSCXXFLAGS) - -### V8 ### - -# check for include files -AC_MSG_CHECKING(for include file v8.h) -AC_ARG_WITH(v8inc, [ --with-v8inc=path Set location of Javascript include directory], [JSV8INCDIR="$withval"]) - -if test -z "$JSV8INCDIR"; then - # Add in default directory for JavaScriptCore headers for Linux and MacOSX - case $host in - *-*-linux*) JSV8INCDIR="/usr/include /usr/local/include/ $JSV8INCDIR";; - *-*-darwin*) JSV8INCDIR="$JSV8INCDIR";; #TODO: add configuration for osx - *);; - esac -fi - -for d in $JSV8INCDIR ; do - if test -r "$d/v8.h" ; then - AC_MSG_RESULT($d) - JSV8INCDIR=$d - JSV8INC=-I\"$d\" - break - fi -done - -if test "$JSV8INC" = "" ; then - AC_MSG_RESULT(not found) - JSV8= -else - JSV8=1 -fi - - -# check for V8 library -AC_MSG_CHECKING(for v8 library) -AC_ARG_WITH(v8lib,[ --with-v8lib=path Set location of V8 library directory],[JSV8LIBDIR="$withval"], [JSV8LIB=]) - -v8libdirs="$JSV8LIBDIR /usr/lib/ /usr/local/lib/" -for i in $v8libdirs ; do - if test -r $i/libv8.so; then - JSV8LIB="-L$i -lv8" - break - fi -done - -if test "$JSV8LIB" = "" ; then - AC_MSG_RESULT(not found) - JSV8= -else - AC_MSG_RESULT($JSV8LIB) - JSV8=1 -fi - - -# linking options -case $host in -*-*-darwin*) - JSV8DYNAMICLINKING="" # TODO: add osx configuration - ;; -*-*-linux*) - JSV8DYNAMICLINKING="$JSV8LIB" - ;; -*) - JSV8DYNAMICLINKING="" - ;; -esac - -AC_SUBST(JSV8) -AC_SUBST(JSV8INC) -AC_SUBST(JSV8DYNAMICLINKING) - -AC_SUBST(JSDEFAULT) - #---------------------------------------------------------------- # Look for gcj #---------------------------------------------------------------- @@ -2451,18 +2250,6 @@ fi AC_SUBST(SKIP_JAVA) SKIP_JAVASCRIPT= -if test -z "$JSCOREINC" && test -z "$JSV8INC"; then - # Add in default directory for JavaScriptCore headers for Linux and MacOSX - case $host in - *-*-linux*) if test -z "$JSCORELIB" && test -z "$JSV8LIB"; then - SKIP_JAVASCRIPT="1" - fi - ;; - *-*-darwin*)SKIP_JAVASCRIPT="1" - ;; - *);; - esac -fi AC_SUBST(SKIP_JAVASCRIPT) SKIP_GUILE= From 0e78fc0ad7a962f2d3687c1fb32294e174e68dd5 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 3 Sep 2013 18:50:46 +0200 Subject: [PATCH 0280/1048] Fixing travis configuration. --- .travis.yml | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 37f81955e..f57e81319 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,8 +1,12 @@ -node_js: - -0.10.0 language: c compiler: - gcc - -before_script: "./autogen.sh && ./configure && make" +node_js: + -0.10.12 +before_script: + - "sudo add-apt-repository -y ppa:chris-lea/node.js" + - "sudo apt-get update" + - "sudo apt-get install -y nodejs" + - "sudo npm install -g node-gyp" + - "./autogen.sh && ./configure && make" script: "make check-javascript-test-suite" From 8778146b4b45d5033bb65701ab881b1edcc51b9b Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 4 Sep 2013 12:10:08 +0200 Subject: [PATCH 0281/1048] Relax type check in SWIG_AsVal_int. The array_member test-case revealed that integers come in as `Numbers`. --- Examples/test-suite/javascript/Makefile.in | 2 +- Lib/javascript/v8/javascriptprimitives.swg | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index edc621c7e..42e3d6b45 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -23,6 +23,7 @@ CPP_TEST_CASES = \ abstract_typedef2 \ abstract_virtual \ arrays_global \ + array_member \ char_binary \ class_ignore \ class_scope_weird \ @@ -49,7 +50,6 @@ CPP_TEST_CASES = \ javascript_unicode BROKEN_TEST_CASES = \ - array_member \ complextest \ constructor_copy \ preproc_include diff --git a/Lib/javascript/v8/javascriptprimitives.swg b/Lib/javascript/v8/javascriptprimitives.swg index bd0295478..f34bbb75a 100644 --- a/Lib/javascript/v8/javascriptprimitives.swg +++ b/Lib/javascript/v8/javascriptprimitives.swg @@ -33,7 +33,7 @@ v8::Handle SWIG_From_dec(int)(int value) SWIGINTERN int SWIG_AsVal_dec(int)(v8::Handle valRef, int* val) { - if (!valRef->IsInt32()) { + if (!valRef->IsNumber()) { return SWIG_TypeError; } if(val) *val = valRef->IntegerValue(); From 54dd7e96c0f9623649947f8f6237a8f1be1ac770 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 4 Sep 2013 12:47:24 +0200 Subject: [PATCH 0282/1048] Fix cleanup configuration for javascript test-suite. --- Examples/test-suite/javascript/Makefile.in | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index 42e3d6b45..058a06f99 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -91,7 +91,11 @@ generate_cpp_wrapper = \ $(SWIG) -c++ -javascript -node -o $*/$*_wrap.cxx ../$*.i build_module = \ - cd $* && node-gyp configure build && cd .. + if [ ! -f $(srcdir)/$*/build/Makefile ]; then \ + cd $* && node-gyp configure build && cd ..; \ + else \ + cd $* && node-gyp build && cd ..; \ + fi # Runs the testcase. A testcase is only run if # a file is found which has _runme.js appended after the testcase name. @@ -102,6 +106,6 @@ run_testcase = \ # Clean %.clean: + rm -rf $* clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile javascript_clean From fec11a8def1e1bea9626fab8f17d05c253178bec Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 4 Sep 2013 13:07:07 +0200 Subject: [PATCH 0283/1048] Allow exceptions in generated example/test node extensions. --- Examples/test-suite/javascript/Makefile.in | 4 ++-- Examples/test-suite/javascript/setup_test.sh | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index 058a06f99..f0810a167 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -27,7 +27,9 @@ CPP_TEST_CASES = \ char_binary \ class_ignore \ class_scope_weird \ + complextest \ constover \ + constructor_copy \ cpp_enum \ cpp_namespace \ cpp_static \ @@ -50,8 +52,6 @@ CPP_TEST_CASES = \ javascript_unicode BROKEN_TEST_CASES = \ - complextest \ - constructor_copy \ preproc_include SKIP_CPP_CASES = @SKIP_CPP_CASES@ diff --git a/Examples/test-suite/javascript/setup_test.sh b/Examples/test-suite/javascript/setup_test.sh index 03ce3bc90..3f45d814a 100644 --- a/Examples/test-suite/javascript/setup_test.sh +++ b/Examples/test-suite/javascript/setup_test.sh @@ -2,5 +2,5 @@ if [ ! -d $1 ]; then mkdir $1; fi -echo "module.exports = require('./build/Release/$1')" > $1/index.js -echo "{\"targets\":[{\"target_name\": \"$1\",\"sources\":[\"$1_wrap.cxx\"]}]}" > $1/binding.gyp +sed s/\$testcase/$1/ node_template/binding.gyp.in > $1/binding.gyp +sed s/\$testcase/$1/ node_template/index.js.in > $1/index.js From b7db2a84c907b96e3371b8c8301b32421a10fef5 Mon Sep 17 00:00:00 2001 From: Vladimir Menshakov Date: Wed, 4 Sep 2013 19:33:48 +0400 Subject: [PATCH 0284/1048] fixed return values and added missing newer v8 dtor wrapper. --- Lib/javascript/v8/javascriptcode.swg | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 068632380..89d011e3d 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -18,8 +18,8 @@ typedef v8::AccessorInfo SwigV8PropertyCallbackInfo; typedef void SwigV8ReturnValue; typedef v8::FunctionCallbackInfo SwigV8Arguments; typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfo; -#define SWIGV8_RETURN(val) return args.GetReturnValue().Set(val) -#define SWIGV8_RETURN_INFO(val, info) return args.GetReturnValue().Set(val) +#define SWIGV8_RETURN(val) args.GetReturnValue().Set(val); return +#define SWIGV8_RETURN_INFO(val, info) info.GetReturnValue().Set(val); return #endif %} @@ -171,16 +171,25 @@ void $jswrapper(v8::Isolate *isolate, v8::Persistent< v8::Object > * object, SWI * ----------------------------------------------------------------------------- */ %fragment ("js_dtoroverride", "templates") %{ -void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) { - SWIGV8_Proxy* proxy = (SWIGV8_Proxy*) parameter; +#if (SWIG_V8_VERSION < 0x031900) +void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) +{ + SWIGV8_Proxy *proxy = static_cast(parameter); +#else +void $jswrapper(v8::Isolate *isolate, v8::Persistent< v8::Object > * object, SWIGV8_Proxy *proxy) +{ +#endif if(proxy->swigCMemOwn && proxy->swigCObject) { $jstype arg1 = ($jstype)proxy->swigCObject; ${destructor_action} } delete proxy; - object.Clear(); +#if (SWIG_V8_VERSION < 0x031900) object.Dispose(); +#else + object->Dispose(isolate); +#endif } %} @@ -214,7 +223,7 @@ fail: %fragment("js_setter", "templates") %{ void $jswrapper(v8::Local property, v8::Local value, - const SwigV8PropertyCallbackInfo& info) { + const SwigV8PropertyCallbackInfoVoid& info) { v8::HandleScope scope; $jslocals $jscode From 4068f31c6b66f08c24f760f46da5b4a4d7b6f11b Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 4 Sep 2013 17:54:35 +0200 Subject: [PATCH 0285/1048] Use a diffent name for the V8_VERSION provided via command line. --- Lib/javascript/v8/javascriptruntime.swg | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index 139a5a3ee..5acd04de9 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -12,11 +12,11 @@ %} %enddef -#ifdef SWIG_V8_VERSION -%swig_v8_define_version(SWIG_V8_VERSION) +#ifdef V8_VERSION +%swig_v8_define_version(V8_VERSION) #else // HACK: defining a default version -%swig_v8_define_version(SWIG_V8_VERSION) +%swig_v8_define_version(0x031110) #endif #ifdef BUILDING_NODE_EXTENSION From 315287b6563f4730468e4b882e569fa72893ba71 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 4 Sep 2013 17:55:44 +0200 Subject: [PATCH 0286/1048] Put the SWIG_V8_VERSION macro into "runtime" block. --- Lib/javascript/v8/javascriptruntime.swg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index 5acd04de9..f998b729b 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -5,7 +5,7 @@ * ----------------------------------------------------------------------------- */ %define %swig_v8_define_version(version) -%begin %{ +%insert("runtime") %{ #ifndef SWIG_V8_VERSION #define SWIG_V8_VERSION version #endif From 8b0ee5491a9f19a57fef83433d755cc0a9e40c40 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 4 Sep 2013 18:04:40 +0200 Subject: [PATCH 0287/1048] Added missing template configuration files for nodejs based tests. --- .../javascript/node_template/binding.gyp.in | 25 +++++++++++++++++++ .../javascript/node_template/index.js.in | 1 + 2 files changed, 26 insertions(+) create mode 100644 Examples/test-suite/javascript/node_template/binding.gyp.in create mode 100644 Examples/test-suite/javascript/node_template/index.js.in diff --git a/Examples/test-suite/javascript/node_template/binding.gyp.in b/Examples/test-suite/javascript/node_template/binding.gyp.in new file mode 100644 index 000000000..2895d3080 --- /dev/null +++ b/Examples/test-suite/javascript/node_template/binding.gyp.in @@ -0,0 +1,25 @@ +{ + "targets": [ + { + "target_name": "$testcase", + "sources":[ "$testcase_wrap.cxx" ], + "include_dirs": ["../.."], + 'conditions': [ + ['OS=="mac"', + { + 'xcode_settings': { + 'GCC_ENABLE_CPP_RTTI': 'YES', + 'GCC_ENABLE_CPP_EXCEPTIONS' : 'YES' + } + } + ], + ['OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="solaris"', + { + 'cflags!': [ '-fno-exceptions' ], + 'cflags_cc!': [ '-fno-exceptions', '-fno-rtti' ] + } + ] + ], + } + ], +} diff --git a/Examples/test-suite/javascript/node_template/index.js.in b/Examples/test-suite/javascript/node_template/index.js.in new file mode 100644 index 000000000..72330499d --- /dev/null +++ b/Examples/test-suite/javascript/node_template/index.js.in @@ -0,0 +1 @@ +module.exports = require('./build/Release/$testcase'); From 2a39abebb684e7e5a2bf878b9d74c54de415bae1 Mon Sep 17 00:00:00 2001 From: Vladimir Menshakov Date: Wed, 4 Sep 2013 20:10:42 +0400 Subject: [PATCH 0288/1048] moved common swig v8 definitions in javascriptruntime.swg, fixed obsoleted api calls --- Lib/javascript/v8/javascriptcode.swg | 16 ------------- Lib/javascript/v8/javascriptruntime.swg | 32 +++++++++++++++++++++---- 2 files changed, 28 insertions(+), 20 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 89d011e3d..4277e8b0c 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -7,22 +7,6 @@ * - $jsmangledtype: mangled type of class * ----------------------------------------------------------------------------- */ -%insert(runtime) %{ -#if (SWIG_V8_VERSION < 0x031900) -typedef v8::Handle SwigV8ReturnValue; -typedef v8::Arguments SwigV8Arguments; -typedef v8::AccessorInfo SwigV8PropertyCallbackInfo; -#define SWIGV8_RETURN(val) return scope.Close(val) -#define SWIGV8_RETURN_INFO(val, info) return scope.Close(val) -#else -typedef void SwigV8ReturnValue; -typedef v8::FunctionCallbackInfo SwigV8Arguments; -typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfo; -#define SWIGV8_RETURN(val) args.GetReturnValue().Set(val); return -#define SWIGV8_RETURN_INFO(val, info) info.GetReturnValue().Set(val); return -#endif -%} - %fragment("js_ctor", "templates") %{ SwigV8ReturnValue $jswrapper(const SwigV8Arguments& args) { v8::HandleScope scope; diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index 139a5a3ee..5febe07bf 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -35,6 +35,22 @@ %insert(runtime) "swigrun.swg"; /* SWIG API */ %insert(runtime) "swigerrors.swg"; /* SWIG errors */ +%insert(runtime) %{ +#if (SWIG_V8_VERSION < 0x031900) +typedef v8::Handle SwigV8ReturnValue; +typedef v8::Arguments SwigV8Arguments; +typedef v8::AccessorInfo SwigV8PropertyCallbackInfo; +#define SWIGV8_RETURN(val) return scope.Close(val) +#define SWIGV8_RETURN_INFO(val, info) return scope.Close(val) +#else +typedef void SwigV8ReturnValue; +typedef v8::FunctionCallbackInfo SwigV8Arguments; +typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfo; +#define SWIGV8_RETURN(val) args.GetReturnValue().Set(val); return +#define SWIGV8_RETURN_INFO(val, info) info.GetReturnValue().Set(val); return +#endif +%} + %insert(runtime) %{ #define SWIG_Error(code, msg) SWIGV8_ErrorHandler.error(code, msg) #define SWIG_exception(code, msg) SWIGV8_ErrorHandler.error(code, msg) @@ -274,7 +290,11 @@ v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, in #define SWIG_GetInstancePtr(obj, ptr) SWIG_V8_GetInstancePtr(obj, ptr) +#if (SWIG_V8_VERSION < 0x031900) v8::Handle _wrap_equals(const v8::Arguments &args) { +#else +void _wrap_equals(const v8::FunctionCallbackInfo& args) { +#endif v8::HandleScope scope; v8::Handle jsresult; void *arg1 = (void *) 0 ; @@ -297,13 +317,17 @@ v8::Handle _wrap_equals(const v8::Arguments &args) { result = (bool)(arg1 == arg2); jsresult = v8::Boolean::New(result); - return scope.Close(jsresult); + SWIGV8_RETURN(jsresult); goto fail; fail: - return scope.Close(v8::Undefined()); + SWIGV8_RETURN(v8::Undefined()); } +#if (SWIG_V8_VERSION < 0x031900) v8::Handle _wrap_getCPtr(const v8::Arguments &args) { +#else +void _wrap_getCPtr(const v8::FunctionCallbackInfo& args) { +#endif v8::HandleScope scope; v8::Handle jsresult; void *arg1 = (void *) 0 ; @@ -318,9 +342,9 @@ v8::Handle _wrap_getCPtr(const v8::Arguments &args) { result = (long)arg1; jsresult = v8::Number::New(result); - return scope.Close(jsresult); + SWIGV8_RETURN(jsresult); goto fail; fail: - return scope.Close(v8::Undefined()); + SWIGV8_RETURN(v8::Undefined()); } %} From b49da78b0a6ef1d6e9f624c60710f79e709fca2e Mon Sep 17 00:00:00 2001 From: Vladimir Menshakov Date: Thu, 5 Sep 2013 19:50:15 +0400 Subject: [PATCH 0289/1048] fixed deprecation warnings for v8-3.21 --- Lib/javascript/v8/javascriptcode.swg | 8 ++++++-- Lib/javascript/v8/javascriptruntime.swg | 10 ++++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 4277e8b0c..ac322ab42 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -141,8 +141,10 @@ void $jswrapper(v8::Isolate *isolate, v8::Persistent< v8::Object > * object, SWI object.Clear(); #if (SWIG_V8_VERSION < 0x031900) object.Dispose(); -#else +#elif (SWIG_V8_VERSION < 0x032100) object->Dispose(isolate); +#else + object->Dispose(); #endif } %} @@ -171,8 +173,10 @@ void $jswrapper(v8::Isolate *isolate, v8::Persistent< v8::Object > * object, SWI #if (SWIG_V8_VERSION < 0x031900) object.Dispose(); -#else +#elif (SWIG_V8_VERSION < 0x032100) object->Dispose(isolate); +#else + object->Dispose(); #endif } %} diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index ab52aa815..31ce84a04 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -110,7 +110,7 @@ public: }; ~SWIGV8_Proxy() { -#if (SWIG_V8_VERSION < 0x031900) +#if (SWIG_V8_VERSION < 0x031900 || SWIG_V8_VERSION >= 0x032100) handle.ClearWeak(); handle.Dispose(); #else @@ -238,7 +238,13 @@ void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info } else { cdata->handle.MakeWeak(v8::Isolate::GetCurrent(), cdata, SWIGV8_Proxy_DefaultDtor); } - cdata->handle.MarkIndependent(v8::Isolate::GetCurrent()); + +# if (SWIG_V8_VERSION < 0x032100) + cdata->handle.MarkIndependent(v8::Isolate::GetCurrent()); +# else + cdata->handle.MarkIndependent(); +# endif + #endif } From 4794fa1884215982384535d25bfcc8e37b496629 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 6 Sep 2013 00:38:07 +0300 Subject: [PATCH 0290/1048] Refactored custom javascript engines to support primitive 'require' statements. --- Tools/javascript/javascript.cxx | 24 +----- Tools/javascript/js_shell.cxx | 47 +++++++---- Tools/javascript/js_shell.h | 7 +- Tools/javascript/jsc_shell.cxx | 134 +++++++++++++++++++++++--------- Tools/javascript/v8_shell.cxx | 122 ++++++++++++++++------------- 5 files changed, 203 insertions(+), 131 deletions(-) diff --git a/Tools/javascript/javascript.cxx b/Tools/javascript/javascript.cxx index 82e94f434..ec4ac4e3f 100644 --- a/Tools/javascript/javascript.cxx +++ b/Tools/javascript/javascript.cxx @@ -14,21 +14,12 @@ void print_usage() { int main(int argc, char* argv[]) { std::string scriptPath = ""; - std::vector module_names; bool interactive = false; JSShell* shell = 0; for (int idx = 1; idx < argc; ++idx) { - if(strcmp(argv[idx], "-l") == 0) { - idx++; - if(idx > argc) { - print_usage(); - exit(-1); - } - std::string module_name(argv[idx]); - module_names.push_back(module_name); - } else if(strcmp(argv[idx], "-v8") == 0) { + if(strcmp(argv[idx], "-v8") == 0) { shell = JSShell::Create(JSShell::V8); } else if(strcmp(argv[idx], "-jsc") == 0) { shell = JSShell::Create(JSShell::JSC); @@ -44,19 +35,6 @@ int main(int argc, char* argv[]) { } bool failed = false; - for(std::vector::iterator it = module_names.begin(); - it != module_names.end(); ++it) { - std::string module_name = *it; - - bool success = shell->ImportModule(module_name); - failed |= !success; - } - - if (failed) { - delete shell; - printf("FAIL: Some modules could not be loaded.\n"); - return -1; - } if(interactive) { failed = !(shell->RunShell()); diff --git a/Tools/javascript/js_shell.cxx b/Tools/javascript/js_shell.cxx index fa5500f8e..ca5ca7ecd 100644 --- a/Tools/javascript/js_shell.cxx +++ b/Tools/javascript/js_shell.cxx @@ -21,7 +21,6 @@ #endif - JSShell::~JSShell() { for(std::vector::iterator it = loaded_modules.begin(); @@ -32,32 +31,46 @@ JSShell::~JSShell() { } -bool JSShell::ImportModule(const std::string& name) { +// TODO: this could be done more intelligent... +// - can we achieve source file relative loading? +// - better path resolution +std::string JSShell::LoadModule(const std::string& name, HANDLE* library) { - std::string lib_name = LIBRARYFILE(name); + // works only for posix like OSs + size_t pathIdx = name.find_last_of("/"); - HANDLE handle = LOAD_LIBRARY(lib_name.c_str()); - if(handle == 0) { - std::cout << "Could not load library " << lib_name << ":" - << std::endl << LIBRARY_ERROR() << std::endl; - return false; - } + std::string lib_name; + std::string module_name; + if (pathIdx == std::string::npos) { + module_name = name; + lib_name = std::string(name).append(LIBRARY_EXT); + } else { + std::string path = name.substr(0, pathIdx+1); + module_name = name.substr(pathIdx+1); + lib_name = path.append(module_name).append(LIBRARY_EXT); + } - if(!RegisterModule(handle, name)) { - std::cout << "Could not find initializer function in " << lib_name << std::endl; - CLOSE_LIBRARY(handle); - return false; - } + HANDLE handle = LOAD_LIBRARY(lib_name.c_str()); + if(handle == 0) { + std::cout << "Could not load library " << lib_name << ":" + << std::endl << LIBRARY_ERROR() << std::endl; + return 0; + } - loaded_modules.push_back(handle); + loaded_modules.push_back(handle); - return true; + *library = handle; + + return module_name; } bool JSShell::RunScript(const std::string& scriptPath) { std::string source = ReadFile(scriptPath); if(!InitializeEngine()) return false; + // Node.js compatibility: make `print` available as `console.log()` + ExecuteScript("var console = {}; console.log = print;", ""); + if(!ExecuteScript(source, scriptPath)) { return false; } @@ -126,7 +139,7 @@ V8Shell_Create, JSShell *JSShell::Create(Engine engine) { if(js_shell_factories[engine] == 0) { - throw "Engine not supported."; + throw "Engine not available."; } return js_shell_factories[engine](); } diff --git a/Tools/javascript/js_shell.h b/Tools/javascript/js_shell.h index 54f55b69d..84a8534d6 100644 --- a/Tools/javascript/js_shell.h +++ b/Tools/javascript/js_shell.h @@ -5,6 +5,7 @@ #include typedef void* HANDLE; +typedef void* MODULE; class JSShell { @@ -22,7 +23,7 @@ public: static JSShell* Create(Engine engine = JSC); - bool ImportModule(const std::string& name); + std::string LoadModule(const std::string& name, HANDLE* library); virtual bool RunScript(const std::string& scriptPath); @@ -30,11 +31,9 @@ public: protected: - virtual bool RegisterModule(HANDLE library, const std::string& module_name) = 0; - virtual bool InitializeEngine() = 0; - virtual bool ExecuteScript(const std::string& source, const std::string& name) = 0; + virtual bool ExecuteScript(const std::string& source, const std::string& scriptPath) = 0; virtual bool DisposeEngine() = 0; diff --git a/Tools/javascript/jsc_shell.cxx b/Tools/javascript/jsc_shell.cxx index ee95e04a5..e4e8cdd96 100644 --- a/Tools/javascript/jsc_shell.cxx +++ b/Tools/javascript/jsc_shell.cxx @@ -14,7 +14,7 @@ class JSCShell: public JSShell { -typedef int (*JSCIntializer)(JSGlobalContextRef context); +typedef int (*JSCIntializer)(JSGlobalContextRef context, JSObjectRef *module); public: @@ -24,26 +24,26 @@ public: protected: - virtual bool RegisterModule(HANDLE library, const std::string& module_name); - virtual bool InitializeEngine(); - virtual bool ExecuteScript(const std::string& source, const std::string& name); + virtual bool ExecuteScript(const std::string& source, const std::string& scriptPath); virtual bool DisposeEngine(); private: - static JSValueRef Print(JSContextRef context,JSObjectRef object, JSObjectRef globalobj, size_t argc, const JSValueRef args[], JSValueRef* ex); + JSObjectRef Import(const std::string &moduleName); + + static JSValueRef Print(JSContextRef context, JSObjectRef object, JSObjectRef globalobj, size_t argc, const JSValueRef args[], JSValueRef* ex); + + static JSValueRef Require(JSContextRef context, JSObjectRef object, JSObjectRef globalobj, size_t argc, const JSValueRef args[], JSValueRef* ex); static bool RegisterFunction(JSGlobalContextRef context, JSObjectRef object, const char* functionName, JSObjectCallAsFunctionCallback cbFunction); - static void PrintError(JSContextRef, JSValueRef, const std::string&); + static void PrintError(JSContextRef, JSValueRef); private: - std::vector module_initializers; - JSGlobalContextRef context; }; @@ -54,16 +54,6 @@ JSCShell::~JSCShell() { } } -bool JSCShell::RegisterModule(HANDLE library, const std::string& module_name) { - std::string symname = std::string(module_name).append("_initialize"); - - JSCIntializer init_function = reinterpret_cast((long) LOAD_SYMBOL(library, symname.c_str())); - if(init_function == 0) return false; - - module_initializers.push_back(init_function); - return true; -} - bool JSCShell::InitializeEngine() { if(context != 0) { JSGlobalContextRelease(context); @@ -73,26 +63,33 @@ bool JSCShell::InitializeEngine() { context = JSGlobalContextCreate(NULL); if(context == 0) return false; JSObjectRef globalObject = JSContextGetGlobalObject(context); + + + // store this for later use + JSClassDefinition __shell_classdef__; + JSClassRef __shell_class__ = JSClassCreate(&__shell_classdef__); + JSObjectRef __shell__ = JSObjectMake(context, __shell_class__, 0); + bool success = JSObjectSetPrivate(__shell__, (void*) (long) this); + JSStringRef shellKey = JSStringCreateWithUTF8CString("__shell__"); + JSObjectSetProperty(context, globalObject, shellKey, __shell__, kJSPropertyAttributeReadOnly, NULL); + JSStringRelease(shellKey); + JSCShell::RegisterFunction(context, globalObject, "print", JSCShell::Print); - // Call module initializers - for(std::vector::iterator it = module_initializers.begin(); - it != module_initializers.end(); ++it) { - JSCIntializer init_function = *it; - if(!init_function(context)) { - return false; - } - } + JSCShell::RegisterFunction(context, globalObject, "require", JSCShell::Require); + return true; } -bool JSCShell::ExecuteScript(const std::string& source, const std::string& name) { +bool JSCShell::ExecuteScript(const std::string& source, const std::string& scriptPath) { JSStringRef jsScript; + JSStringRef sourceURL; JSValueRef ex; jsScript = JSStringCreateWithUTF8CString(source.c_str()); - JSValueRef jsResult = JSEvaluateScript(context, jsScript, 0, 0, 0, &ex); + sourceURL = JSStringCreateWithUTF8CString(scriptPath.c_str()); + JSValueRef jsResult = JSEvaluateScript(context, jsScript, 0, sourceURL, 0, &ex); JSStringRelease(jsScript); if (jsResult == NULL && ex != NULL) { - JSCShell::PrintError(context, ex, name); + JSCShell::PrintError(context, ex); return false; } return true; @@ -121,6 +118,65 @@ JSValueRef JSCShell::Print(JSContextRef context, JSObjectRef object, return JSValueMakeUndefined(context); } +// Attention: this feature should not create too high expectations. +// It is only capable of loading things relative to the execution directory +// and not relative to the parent script. +JSValueRef JSCShell::Require(JSContextRef context, JSObjectRef object, + JSObjectRef globalObj, size_t argc, + const JSValueRef args[], JSValueRef* ex) { + JSObjectRef module; + + JSStringRef shellKey = JSStringCreateWithUTF8CString("__shell__"); + JSValueRef shellAsVal = JSObjectGetProperty(context, globalObj, shellKey, NULL); + JSStringRelease(shellKey); + JSObjectRef shell = JSValueToObject(context, shellAsVal, 0); + JSCShell *_this = (JSCShell*) (long) JSObjectGetPrivate(shell); + + if (argc > 0) + { + JSStringRef string = JSValueToStringCopy(context, args[0], NULL); + size_t numChars = JSStringGetMaximumUTF8CStringSize(string); + char *stringUTF8 = new char[numChars]; + JSStringGetUTF8CString(string, stringUTF8, numChars); + + std::string modulePath(stringUTF8); + module = _this->Import(modulePath); + + delete[] stringUTF8; + } + + if (module) { + return module; + } else { + printf("Ooops.\n"); + return JSValueMakeUndefined(context); + } +} + +JSObjectRef JSCShell::Import(const std::string& module_path) { + + HANDLE library; + std::string module_name = LoadModule(module_path, &library); + + if (library == 0) { + printf("Could not load module."); + return 0; + } + + std::string symname = std::string(module_name).append("_initialize"); + + JSCIntializer init_function = reinterpret_cast((long) LOAD_SYMBOL(library, symname.c_str())); + if(init_function == 0) { + printf("Could not find module's initializer function."); + return 0; + } + + JSObjectRef module; + init_function(context, &module); + + return module; +} + bool JSCShell::RegisterFunction(JSGlobalContextRef context, JSObjectRef object, const char* functionName, JSObjectCallAsFunctionCallback callback) { JSStringRef js_functionName = JSStringCreateWithUTF8CString(functionName); @@ -131,12 +187,12 @@ bool JSCShell::RegisterFunction(JSGlobalContextRef context, JSObjectRef object, return true; } -void JSCShell::PrintError(JSContextRef ctx, JSValueRef err, const std::string& name) { +void JSCShell::PrintError(JSContextRef ctx, JSValueRef err) { char *buffer; + size_t length; JSStringRef string = JSValueToStringCopy(ctx, err, 0); - size_t length = JSStringGetLength(string); - + length = JSStringGetLength(string); buffer = new char[length+1]; JSStringGetUTF8CString(string, buffer, length+1); std::string errMsg(buffer); @@ -150,14 +206,22 @@ void JSCShell::PrintError(JSContextRef ctx, JSValueRef err, const std::string& n return; } - // Note: usually you would also retrieve the property "sourceURL" - // though, it happened that this was always "" + JSStringRef sourceURLKey = JSStringCreateWithUTF8CString("sourceURL"); + JSStringRef sourceURLStr = JSValueToStringCopy(ctx, JSObjectGetProperty(ctx, errObj, sourceURLKey, 0), 0); + length = JSStringGetLength(sourceURLStr); + buffer = new char[length+1]; + JSStringGetUTF8CString(sourceURLStr, buffer, length+1); + std::string sourceURL(buffer); + delete[] buffer; + JSStringRelease(sourceURLStr); + JSStringRelease(sourceURLKey); + JSStringRef lineKey = JSStringCreateWithUTF8CString("line"); JSValueRef jsLine = JSObjectGetProperty(ctx, errObj, lineKey, 0); int line = (int) JSValueToNumber(ctx, jsLine, 0); JSStringRelease(lineKey); - std::cerr << name << ":" << line << ":" << errMsg << std::endl; + std::cerr << sourceURL << ":" << line << ":" << errMsg << std::endl; } JSShell* JSCShell_Create() { diff --git a/Tools/javascript/v8_shell.cxx b/Tools/javascript/v8_shell.cxx index e2ab1541d..8a571e0f1 100755 --- a/Tools/javascript/v8_shell.cxx +++ b/Tools/javascript/v8_shell.cxx @@ -9,7 +9,7 @@ #include "js_shell.h" -typedef int (*V8ExtensionRegistrar) (v8::Handle); +typedef int (*V8ExtensionInitializer) (v8::Handle module); class V8Shell: public JSShell { @@ -25,36 +25,33 @@ public: protected: - virtual bool RegisterModule(HANDLE library, const std::string& module_name); - virtual bool InitializeEngine(); - virtual bool ExecuteScript(const std::string& source, const std::string& name); + virtual bool ExecuteScript(const std::string& source, const std::string& scriptPath); virtual bool DisposeEngine(); private: + v8::Handle Import(const std::string& moduleName); + v8::Persistent CreateShellContext(); void ReportException(v8::TryCatch* handler); static v8::Handle Print(const v8::Arguments& args); + static v8::Handle Require(const v8::Arguments& args); + static v8::Handle Quit(const v8::Arguments& args); static v8::Handle Version(const v8::Arguments& args); static const char* ToCString(const v8::String::Utf8Value& value); - void ExtendEngine(); - protected: - std::vector module_initializers; - v8::Persistent context; - }; #ifdef __GNUC__ @@ -73,16 +70,6 @@ V8Shell::~V8Shell() { v8::V8::Dispose(); } -bool V8Shell::RegisterModule(HANDLE library, const std::string& module_name) { - std::string symname = std::string(module_name).append("_initialize"); - - V8ExtensionRegistrar init_function = reinterpret_cast((long) LOAD_SYMBOL(library, symname.c_str())); - if(init_function == 0) return false; - - module_initializers.push_back(init_function); - return true; -} - bool V8Shell::RunScript(const std::string& scriptPath) { if (!context.IsEmpty()) { @@ -97,9 +84,16 @@ bool V8Shell::RunScript(const std::string& scriptPath) { return false; } context->Enter(); + //v8::Context::Scope context_scope(context); + v8::HandleScope scope; - v8::Context::Scope context_scope(context); - ExtendEngine(); + // Store a pointer to this shell for later use + v8::Handle global = context->Global(); + v8::Local __shell__ = v8::External::New((void*) (long) this); + global->SetHiddenValue(v8::String::New("__shell__"), __shell__); + + // Node.js compatibility: make `print` available as `console.log()` + ExecuteScript("var console = {}; console.log = print;", ""); if(!ExecuteScript(source, scriptPath)) { return false; @@ -127,7 +121,8 @@ bool V8Shell::RunShell() { context->Enter(); v8::Context::Scope context_scope(context); - ExtendEngine(); + + ExecuteScript("var console = {}; console.log = print;", ""); static const int kBufferSize = 1024; while (true) { @@ -152,45 +147,26 @@ bool V8Shell::InitializeEngine() { return true; } -void V8Shell::ExtendEngine() { - - v8::HandleScope scope; - v8::Local global = context->Global(); - - // register extensions - for(std::vector::iterator it=module_initializers.begin(); - it != module_initializers.end(); ++it) { - (*it)(global); - } - -} - bool V8Shell::ExecuteScript(const std::string& source, const std::string& name) { v8::HandleScope handle_scope; v8::TryCatch try_catch; v8::Handle script = v8::Script::Compile(v8::String::New(source.c_str()), v8::String::New(name.c_str())); + + // Stop if script is empty if (script.IsEmpty()) { // Print errors that happened during compilation. ReportException(&try_catch); return false; + } + + v8::Handle result = script->Run(); + + // Print errors that happened during execution. + if (try_catch.HasCaught()) { + ReportException(&try_catch); + return false; } else { - v8::Handle result = script->Run(); - if (result.IsEmpty()) { - assert(try_catch.HasCaught()); - // Print errors that happened during execution. - ReportException(&try_catch); - return false; - } else { - assert(!try_catch.HasCaught()); - if (!result->IsUndefined()) { - // If all went well and the result wasn't undefined then print - // the returned value. - //v8::String::Utf8Value str(result); - //const char* cstr = V8Shell::ToCString(str); - //printf("%s\n", cstr); - } - return true; - } + return true; } } @@ -207,6 +183,7 @@ v8::Persistent V8Shell::CreateShellContext() { // Bind global functions global->Set(v8::String::New("print"), v8::FunctionTemplate::New(V8Shell::Print)); global->Set(v8::String::New("quit"), v8::FunctionTemplate::New(V8Shell::Quit)); + global->Set(v8::String::New("require"), v8::FunctionTemplate::New(V8Shell::Require)); global->Set(v8::String::New("version"), v8::FunctionTemplate::New(V8Shell::Version)); v8::Persistent _context = v8::Context::New(NULL, global); @@ -214,6 +191,26 @@ v8::Persistent V8Shell::CreateShellContext() { return _context; } +v8::Handle V8Shell::Import(const std::string& module_path) +{ + v8::HandleScope scope; + + HANDLE library; + std::string module_name = LoadModule(module_path, &library); + + std::string symname = std::string(module_name).append("_initialize"); + + V8ExtensionInitializer init_function = reinterpret_cast((long) LOAD_SYMBOL(library, symname.c_str())); + + if(init_function == 0) { + printf("Could not find initializer function."); + return v8::Undefined(); + } + + v8::Local module = v8::Object::New(); + init_function(module); + return scope.Close(module); +} v8::Handle V8Shell::Print(const v8::Arguments& args) { bool first = true; @@ -233,6 +230,27 @@ v8::Handle V8Shell::Print(const v8::Arguments& args) { return v8::Undefined(); } +v8::Handle V8Shell::Require(const v8::Arguments& args) { + v8::HandleScope scope; + + if (args.Length() != 1) { + printf("Illegal arguments for `require`"); + }; + + v8::String::Utf8Value str(args[0]); + const char* cstr = V8Shell::ToCString(str); + std::string moduleName(cstr); + + v8::Local global = v8::Context::GetCurrent()->Global(); + v8::Local hidden = global->GetHiddenValue(v8::String::New("__shell__")); + v8::Local __shell__ = v8::Local::Cast(hidden); + V8Shell* _this = (V8Shell*) (long) __shell__->Value(); + + v8::Handle module = _this->Import(moduleName); + + return scope.Close(module); +} + v8::Handle V8Shell::Quit(const v8::Arguments& args) { int exit_code = args[0]->Int32Value(); fflush(stdout); From 29ccb270afa761d57d6a6728ca49d92fe9d35bc0 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 6 Sep 2013 00:40:29 +0300 Subject: [PATCH 0291/1048] Renamed object provided to JS initializers. JSC initializer create a new module object. V8 initializer fill a provided 'exports' object. --- Lib/javascript/jsc/javascriptcode.swg | 6 ++-- Lib/javascript/v8/javascriptcode.swg | 13 +++++--- Source/Modules/javascript.cxx | 45 ++++++++++++++------------- 3 files changed, 35 insertions(+), 29 deletions(-) diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index 0325a7a35..a55f24d33 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -279,11 +279,9 @@ int $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObjec extern "C" { #endif -bool SWIGJSC_INIT (JSGlobalContextRef context) { +bool SWIGJSC_INIT (JSGlobalContextRef context, JSObjectRef *exports) { SWIG_InitializeModule(0); - JSObjectRef global_object = JSContextGetGlobalObject(context); - /* Initialize the base swig type object */ _SwigObject_objectDefinition.staticFunctions = _SwigObject_functions; _SwigObject_objectDefinition.staticValues = _SwigObject_values; @@ -298,6 +296,8 @@ bool SWIGJSC_INIT (JSGlobalContextRef context) { /* Register namespaces */ $jsregisternamespaces + *exports = exports_object; + return true; } diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 4277e8b0c..dcaf2a707 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -477,15 +477,19 @@ fail: %fragment("js_initializer", "templates") %{ -#if defined(BUILDING_NODE_EXTENSION) -void $jsname_initialize(v8::Handle global_obj, v8::Handle /*module*/) +// Note: 'extern "C"'' disables name mangling which makes it easier to load the symbol manually +// TODO: is it ok to do that? +extern "C" +#if (NODE_MODULE_VERSION < 0x000C) +void $jsname_initialize(v8::Handle exports) #else -void $jsname_initialize(v8::Handle global_obj) +void $jsname_initialize(v8::Handle exports, v8::Handle /*module*/) #endif { - SWIG_InitializeModule(static_cast(&global_obj)); + SWIG_InitializeModule(static_cast(&exports)); v8::HandleScope scope; + v8::Handle exports_obj = exports; // a class template for creating proxies of undefined types @@ -495,7 +499,6 @@ void $jsname_initialize(v8::Handle global_obj) SWIGV8_SWIGTYPE_Proxy_class_templ.Reset(v8::Isolate::GetCurrent(), SWIGV8_CreateClassTemplate("SwigProxy")); #endif - /* create objects for namespaces */ $jsv8nspaces diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index cec65338a..360fb1aec 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -521,7 +521,10 @@ void JAVASCRIPT::main(int argc, char *argv[]) { int mode = -1; - bool createModuleObject = true; + // Note: creating a module object is not supported anymore. + // instead the initializer is called with an externally created object + // This makes it obsolete to handle node extensions differently + bool createModuleObject = false; for (int i = 1; i < argc; i++) { if (argv[i]) { @@ -533,7 +536,6 @@ void JAVASCRIPT::main(int argc, char *argv[]) { Swig_mark_arg(i); mode = JSEmitter::V8; SWIG_library_directory("javascript/v8"); - createModuleObject = false; Preprocessor_define("BUILDING_NODE_EXTENSION 1", 0); } else if (strcmp(argv[i], "-jsc") == 0) { Swig_mark_arg(i); @@ -544,7 +546,6 @@ void JAVASCRIPT::main(int argc, char *argv[]) { js_template_enable_debug = true; } else if (strcmp(argv[i], "-no-moduleobject") == 0) { Swig_mark_arg(i); - createModuleObject = false; } } } @@ -655,18 +656,18 @@ JSEmitterState &JSEmitter::getState() { return state; } -int JSEmitter::initialize(Node *n) { +int JSEmitter::initialize(Node * /*n*/) { if(namespaces != NULL) { Delete(namespaces); } namespaces = NewHash(); Hash *global_namespace; - if(State::IsSet(state.global(FLAG_NO_MODULE_OBJECT))) { - global_namespace = createNamespaceEntry("global", 0); - } else { - global_namespace = createNamespaceEntry(Char(Getattr(n, "name")), "global"); - } +// if(State::IsSet(state.global(FLAG_NO_MODULE_OBJECT))) { + global_namespace = createNamespaceEntry("exports", 0); +// } else { +// global_namespace = createNamespaceEntry(Char(Getattr(n, "name")), "global"); +// } Setattr(namespaces, "::", global_namespace); current_namespace = global_namespace; @@ -1407,8 +1408,6 @@ private: String *NULL_STR; String *VETO_SET; - const char *GLOBAL_STR; - // output file and major code parts File *f_wrap_cpp; @@ -1433,7 +1432,6 @@ JSCEmitter::JSCEmitter() : JSEmitter(), NULL_STR(NewString("NULL")), VETO_SET(NewString("JS_veto_set_variable")), - GLOBAL_STR(NULL), f_wrap_cpp(NULL), f_runtime(NULL), f_header(NULL), @@ -1735,6 +1733,8 @@ int JSCEmitter::emitNamespaces() { String *functions = Getattr(entry, "functions"); String *variables = Getattr(entry, "values"); + // skip the global namespace which is given by the application + Template namespace_definition(getTemplate("jsc_nspace_declaration")); namespace_definition.replace("$jsglobalvariables", variables) .replace("$jsglobalfunctions", functions) @@ -1745,11 +1745,15 @@ int JSCEmitter::emitNamespaces() { t_createNamespace.replace(T_NAME_MANGLED, name_mangled); Append(state.global(CREATE_NAMESPACES), t_createNamespace.str()); - Template t_registerNamespace(getTemplate("jsc_nspace_registration")); - t_registerNamespace.replace(T_NAME_MANGLED, name_mangled) - .replace(T_NAME, name) - .replace(T_PARENT, parent_mangled); - Append(state.global(REGISTER_NAMESPACES), t_registerNamespace.str()); + // Don't register 'exports' as namespace. It is return to the application. + if (!Equal("exports", name)) { + Template t_registerNamespace(getTemplate("jsc_nspace_registration")); + t_registerNamespace.replace(T_NAME_MANGLED, name_mangled) + .replace(T_NAME, name) + .replace(T_PARENT, parent_mangled); + Append(state.global(REGISTER_NAMESPACES), t_registerNamespace.str()); + } + } return SWIG_OK; @@ -1809,7 +1813,6 @@ private: // the output cpp file File *f_wrap_cpp; - String* GLOBAL; String* NULL_STR; String *VETO_SET; String *moduleName; @@ -1818,7 +1821,6 @@ private: V8Emitter::V8Emitter() : JSEmitter(), - GLOBAL(NewString("global")), NULL_STR(NewString("0")), VETO_SET(NewString("JS_veto_set_variable")) { @@ -1826,7 +1828,6 @@ V8Emitter::V8Emitter() V8Emitter::~V8Emitter() { - Delete(GLOBAL); Delete(NULL_STR); Delete(VETO_SET); } @@ -2161,7 +2162,9 @@ int V8Emitter::emitNamespaces() { do_register = false; } - if (Equal(name, "global")) { + // Note: 'exports' is by convention the name of the object where + // globals are stored into + if (Equal(name, "exports")) { do_create = false; } From 962207e0f33a322af3f9303f1e15ce9e28eb7281 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 6 Sep 2013 00:41:18 +0300 Subject: [PATCH 0292/1048] Rewritten Javascript autoconfiguration. --- configure.in | 201 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 198 insertions(+), 3 deletions(-) diff --git a/configure.in b/configure.in index 6ff3d5258..75727de51 100644 --- a/configure.in +++ b/configure.in @@ -1078,17 +1078,212 @@ AC_SUBST(JAVACXXSHARED) AC_SUBST(JAVACFLAGS) #---------------------------------------------------------------- -# Look for JAVASCRIPT [JavaScriptCore Headers and Library] +# Look for JAVASCRIPT #---------------------------------------------------------------- AC_ARG_WITH(javascript, AS_HELP_STRING([--without-javascript], [Disable JAVASCRIPT]), [with_javascript="$withval"], [with_javascript=yes]) -AC_ARG_VAR(JSDEFAULT, "The default engine to use ( v8 | jsc ).") # First, check for "--without-javascript" or "--with-javascript=no". -if test x"${with_javascript}" = xno -o x"${with_alllang}" = xno ; then +if test x"${with_javascript}" = xno -o x"${with_alllang}" = xno ; then AC_MSG_NOTICE([Disabling Javascript]) JAVASCRIPT= +else + #---------------------------------------------------------------- + # General Javascript settings shared by JSC and V8 + #---------------------------------------------------------------- + + case $host in + *-*-cygwin* | *-*-mingw*) + JSLIBRARYPREFIX="" + ;; + *) + JSLIBRARYPREFIX="lib" + ;; + esac + + case $host in + *-*-darwin*) + JSSO=".dylib" + JSLDSHARED='$(CC) -dynamiclib' + JSCXXSHARED='$(CXX) -dynamiclib' + ;; + *) + JSSO=$SO + JSLDSHARED='$(LDSHARED)' + JSCXXSHARED='$(CXXSHARED)' + ;; + esac + + #---------------------------------------------------------------- + # Look for JavascriptCore (Webkit) settings (JSCOREINCDIR, JSCOREDYNAMICLINKING) + #---------------------------------------------------------------- + + # check for include files + AC_MSG_CHECKING(for include file JavaScriptCore/JavaScript.h) + AC_ARG_WITH(jscoreinc, [ --with-jscinc=path Set location of Javascript include directory], [JSCOREINCDIR="$withval"], [JSCOREINCDIR=]) + + if test -z "$JSCOREINCDIR"; then + JSCOREINCDIR="/usr/include/ /usr/local/include/" + + # Add in default directory for JavaScriptCore headers for Linux and MacOSX + case $host in + *-*-linux*) + JSCOREINCDIR="/usr/include/webkit-1.0/ /usr/include/webkitgtk-1.0/ /usr/local/include/webkit-1.0/JavaScriptCore/ $JSCOREINCDIR" + ;; + *-*-darwin*) + JSCOREINCDIR="/System/Library/Frameworks/JavaScriptCore.framework/Headers/ $JSCOREINCDIR" + ;; + *) + ;; + esac + fi + + for d in $JSCOREINCDIR ; do + if test -r "$d/JavaScriptCore/JavaScript.h" || test -r "$d/JavaScript.h" ; then + AC_MSG_RESULT($d) + JSCOREINCDIR=$d + JSCOREINC=-I\"$d\" + break + fi + done + + if test "$JSCOREINC" = "" ; then + AC_MSG_RESULT(not found) + fi + + # check for JavaScriptCore/Webkit libraries + AC_ARG_WITH(jscorelib,[ --with-jsclib =path Set location of the JavaScriptCore/Webkit library directory],[JSCORELIB="-L$withval"], [JSCORELIB=]) + AC_MSG_CHECKING(for JavaScriptCore/Webkit library) + + # look for the library when not provided + if test -z "$JSCORELIB"; then + case $host in + *-*-linux*) + dirs="/usr/lib/ /usr/local/lib/" + for i in $dirs ; do + if test -r $i/libwebkit-1.0.la; then + AC_MSG_RESULT($i) + JSCORELIB="-L$i -lwebkit-1.0" + break + fi + + if test -r $i/libjavascriptcoregtk-1.0.so; then + AC_MSG_RESULT($i) + JSCORELIB="-L$i -ljavascriptcoregtk-1.0" + break + fi + + if test -r $i/libwebkitgtk-1.0.so; then + AC_MSG_RESULT($i) + JSCORELIB="-L$i -lwebkitgtk-1.0" + break + fi + done + + if test -z "$JSCORELIB"; then + AC_MSG_RESULT(not found) + JSCENABLED=0 + else + JSCOREDYNAMICLINKING="$JSCORELIB" + JSCENABLED=1 + fi + ;; + *-*-darwin*) + JSCOREDYNAMICLINKING="-framework JavaScriptCore" + ;; + *) + ;; + esac + fi + + #---------------------------------------------------------------- + # Look for V8 settings (JSV8INCDIR, JSV8DYNAMICLINKING) + #---------------------------------------------------------------- + + # check for include files + AC_MSG_CHECKING(for include file v8.h) + AC_ARG_WITH(jsv8inc, [ --with-v8inc=path Set location of Javascript include directory], [JSV8INCDIR="$withval"]) + + # if not include dir is specified we try to find + if test -z "$JSV8INCDIR"; then + # Add in default directory for JavaScriptCore headers for Linux and MacOSX + case $host in + *-*-linux*) + JSV8INCDIR="/usr/include /usr/local/include/ $JSV8INCDIR" + ;; + *-*-darwin*) + JSV8INCDIR="$JSV8INCDIR" + ;; + *) + ;; + esac + fi + + for d in $JSV8INCDIR ; do + if test -r "$d/v8.h" ; then + JSV8INCDIR=$d + JSV8INC=-I\"$d\" + break + fi + done + + if test "$JSV8INC" = "" ; then + AC_MSG_RESULT(not found) + else + AC_MSG_RESULT($JSV8INCDIR) + fi + + # check for V8 library + AC_MSG_CHECKING(for v8 library) + AC_ARG_WITH(jsv8lib,[ --with-v8lib=path Set location of V8 library directory],[JSV8LIBDIR="$withval"], [JSV8LIB=]) + + v8libdirs="$JSV8LIBDIR /usr/lib/ /usr/local/lib/" + for d in $v8libdirs ; do + if test -r $d/libv8.so; then + JSV8LIBDIR=$d + JSV8LIB="-L$d -lv8" + break + fi + done + + if test "$JSV8LIB" = "" ; then + AC_MSG_RESULT(not found) + JSV8ENABLED=0 + else + AC_MSG_RESULT($JSV8LIBDIR) + JSV8ENABLED=1 + fi + + + # linking options + case $host in + *-*-darwin*) + JSV8DYNAMICLINKING="" # TODO: add osx configuration + ;; + *-*-linux*) + JSV8DYNAMICLINKING="$JSV8LIB" + ;; + *) + JSV8DYNAMICLINKING="" + ;; + esac + fi +AC_SUBST(JSCFLAGS) +AC_SUBST(JSCXXFLAGS) +AC_SUBST(JSLIBRARYPREFIX) +AC_SUBST(JSSO) +AC_SUBST(JSLDSHARED) +AC_SUBST(JSCXXSHARED) + +AC_SUBST(JSCOREINC) +AC_SUBST(JSCOREDYNAMICLINKING) +AC_SUBST(JSV8INC) +AC_SUBST(JSV8DYNAMICLINKING) + +AC_SUBST(JSCENABLED) +AC_SUBST(JSV8ENABLED) + #---------------------------------------------------------------- # Look for gcj #---------------------------------------------------------------- From 26b5acbbe850c3494f4b79c62f678a92f219f61a Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 6 Sep 2013 00:42:56 +0300 Subject: [PATCH 0293/1048] Test-suite Makefile now supports testing for all three Javascript variants. - node.js - custom JavascriptCore interpreter - custom V8 interpreter --- Examples/Makefile.in | 68 +++++++-- Examples/test-suite/javascript/Makefile.in | 157 +++++++++------------ 2 files changed, 123 insertions(+), 102 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 94a00e642..806ed09d4 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -517,29 +517,67 @@ java_clean: ##### JAVASCRIPT ###### ################################################################## +ROOT_DIR = @ROOT_DIR@ +JSCFLAGS = @JSCFLAGS@ +JSCXXFLAGS = @JSCXXFLAGS@ +JSINCLUDES = @JSCOREINC@ @JSV8INC@ +JSDYNAMICLINKING = @JSCOREDYNAMICLINKING@ @JSV8DYNAMICLINKING@ +JSLIBRARYPREFIX = @JSLIBRARYPREFIX@ +JSSO =@JSSO@ +JSLDSHARED = @JSLDSHARED@ +JSCXXSHARED = @JSCXXSHARED@ + # ---------------------------------------------------------------- -# Definitions +# Compile a custom javascript interpreter +# ---------------------------------------------------------------- +# +# Note: +# There is no common CLI Javascript interpreter. +# V8 comes with one 'd8' which however does not provide a means +# to load extensions. Therefore, by default we use nodejs as +# environment. +# For testing native v8 and jsc extensions we provide our own +# interpreter (see 'Tools/javascript'). # ---------------------------------------------------------------- -JSEXE = node -SWIGJS = $(SWIG) -javascript -node -JS_BUILD = node-gyp rebuild +JS_INTERPRETER_SRC_DIR = $(ROOT_DIR)/Tools/javascript + +# These settings are provided by 'configure' (see '/configure.in') +ifeq (1, @JSV8ENABLED@) + JS_INTERPRETER_SRC_V8 = $(JS_INTERPRETER_SRC_DIR)/v8_shell.cxx + JS_INTERPRETER_CXXFLAGS_V8 = -DENABLE_V8 +endif + +ifeq (1, @JSCENABLED@) + JS_INTERPRETER_SRC_JSC = $(JS_INTERPRETER_SRC_DIR)/jsc_shell.cxx + JS_INTERPRETER_CXXFLAGS_JSC = -DENABLE_JSC +endif + +JS_INTERPRETER_CXXFLAGS = $(JS_INTERPRETER_CXXFLAGS_JSC) $(JS_INTERPRETER_CXXFLAGS_V8) +JS_INTERPRETER_SRC = \ + $(JS_INTERPRETER_SRC_DIR)/javascript.cxx $(JS_INTERPRETER_SRC_DIR)/js_shell.cxx $(JS_INTERPRETER_SRC_JSC) $(JS_INTERPRETER_SRC_V8) + +# TODO: improve: +# - exe suffix +# - '-ldl' should come from configure +javascript_exe: $(SRCS) + $(CXX) $(CXXFLAGS) $(JS_INTERPRETER_CXXFLAGS) $(JSINCLUDES) $(JS_INTERPRETER_SRC) -ldl $(LIBS) $(JSDYNAMICLINKING) -o $(JS_INTERPRETER_SRC_DIR)/javascript + +SWIGJS = $(SWIG) -javascript # ---------------------------------------------------------------- # Run the javascript executable # ---------------------------------------------------------------- -javascript_wrapper_cpp: $(SRCS) +javascript: $(SRCS) + $(SWIGJS) $(SWIGOPT) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CFLAGS) $(JSCFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) $(JSINCLUDES) + $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + +javascript_cpp: $(SRCS) $(SWIGJS) -c++ $(SWIGOPT) $(INTERFACEPATH) - -javascript_build: - $(JS_BUILD) - -#javascript_run: $(SRCS) -# env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(JSEXE) $(JSEXE_OPTS) -l $(TARGET) $(JS_SCRIPT) - -javascript_run: $(SRCS) - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(JSEXE) $(JSEXE_OPTS) $(JS_SCRIPT) + $(CXX) -c $(CCSHARED) $(CFLAGS) $(JSCFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(JSINCLUDES) + $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- # Cleaning the javascript examples @@ -549,7 +587,7 @@ javascript_clean: rm -rf build rm -f *_wrap* runme rm -f core @EXTRA_CLEAN@ - rm -f *.@OBJEXT@ *@JSCORESO@ + rm -f *.@OBJEXT@ *@JSSO@ ################################################################## diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index f0810a167..c78553c6c 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -7,105 +7,88 @@ SCRIPTSUFFIX = _runme.js srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -JS_INCLUDE = @JSCOREINC@ -JS_DLNK = @JSCOREDYNAMICLINKING@ -JSCXXFLAGS = @JSCXXFLAGS@ -JAVASCRIPT_EXE = node -SWIG = $(top_builddir)/preinst_swig +SWIG = $(top_builddir)/preinst_swig -C_TEST_CASES = \ - preproc - - -CPP_TEST_CASES = \ - abstract_access \ - abstract_typedef \ - abstract_typedef2 \ - abstract_virtual \ - arrays_global \ - array_member \ - char_binary \ - class_ignore \ - class_scope_weird \ - complextest \ - constover \ - constructor_copy \ - cpp_enum \ - cpp_namespace \ - cpp_static \ - director_alternating \ - enum_template \ - namespace_virtual_method \ - overload_copy \ - ret_by_value \ - struct_value \ - template_static \ - typedef_class \ - typedef_inherit \ - typedef_scope \ - typemap_arrays \ - typemap_delete \ - typemap_namespace \ - typemap_ns_using \ - using1 \ - using2 \ - javascript_unicode - -BROKEN_TEST_CASES = \ - preproc_include - -SKIP_CPP_CASES = @SKIP_CPP_CASES@ -SKIP_C_CASES = @SKIP_C_CASES@ -SKIP_CPP_STD_CASES = @SKIP_CPP_STD_CASES@ -SKIP_MULTI_CPP_CASES = @SKIP_MULTI_CPP_CASES@ +ifneq (, $(ENGINE)) + JSENGINE = $(ENGINE) +else + JSENGINE = "node" +endif include $(srcdir)/../common.mk -# Overridden variables here +SWIGOPT += -$(JSENGINE) -# Custom tests - tests with additional commandline options +ifeq ("node",$(JSENGINE)) -# Rules for the different types of tests -%.cpptest: - $(prepare_test) - $(generate_cpp_wrapper) - $(build_module) - $(run_testcase) + setup = \ + if [ ! -f $(srcdir)/$*/binding.gyp ]; then \ + echo "Setting up nodejs addon..."; \ + sh ./setup_test.sh $*; \ + $(SWIG) -c++ -javascript -node -o $*/$*_wrap.cxx ../$*.i; \ + fi -%.ctest: - $(prepare_test) - $(generate_cpp_wrapper) - $(build_module) - $(run_testcase) + nodejs_swig_and_compile = \ + if [ ! -f $(srcdir)/$*/build/Makefile ]; then \ + echo "Configuring node add-on..."; \ + node-gyp --directory $* configure; \ + fi; \ + echo "Building node add-on..."; \ + node-gyp --directory $* build; \ -%.multicpptest: - $(prepare_test) - $(generate_cpp_wrapper) - $(build_module) - $(run_testcase) + run_testcase = \ + if [ -f $(srcdir)/$*$(SCRIPTSUFFIX) ]; then \ + node $(srcdir)/$*$(SCRIPTSUFFIX); \ + fi -prepare_test = \ - sh ./setup_test.sh $* + # Rules for the different types of tests + %.cpptest: + $(setup) + $(nodejs_swig_and_compile) + $(run_testcase) -generate_cpp_wrapper = \ - $(SWIG) -c++ -javascript -node -o $*/$*_wrap.cxx ../$*.i + %.ctest: + $(setup) + $(nodejs_swig_and_compile) + $(run_testcase) -build_module = \ - if [ ! -f $(srcdir)/$*/build/Makefile ]; then \ - cd $* && node-gyp configure build && cd ..; \ - else \ - cd $* && node-gyp build && cd ..; \ - fi + %.multicpptest: + $(setup) + $(nodejs_swig_and_compile) + $(run_testcase) -# Runs the testcase. A testcase is only run if -# a file is found which has _runme.js appended after the testcase name. -run_testcase = \ - if [ -f $(srcdir)/$*$(SCRIPTSUFFIX) ]; then \ - node $(srcdir)/$*$(SCRIPTSUFFIX); \ - fi + # Clean + %.clean: + rm -rf $* + +else + + run_testcase = \ + if [ -f $(srcdir)/$*$(SCRIPTSUFFIX) ]; then \ + $(top_srcdir)/Tools/javascript/javascript -$(JSENGINE) $(srcdir)/$*$(SCRIPTSUFFIX); \ + fi + + # Rules for the different types of tests + %.cpptest: + $(setup) + +$(swig_and_compile_cpp) + $(run_testcase) + + %.ctest: + $(setup) + +$(swig_and_compile_c) + $(run_testcase) + + %.multicpptest: + $(setup) + +$(swig_and_compile_multi_cpp) + $(run_testcase) + + # Clean + %.clean: + rm $*_wrap.cxx + +endif -# Clean -%.clean: - rm -rf $* clean: From 492d3010ff33c1b6af9bca9472ad08e0330ffb42 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 6 Sep 2013 01:40:23 +0300 Subject: [PATCH 0294/1048] Javascript V8 test-cases always create cpp wrappers. --- Examples/test-suite/javascript/Makefile.in | 69 ++++++++++++---------- 1 file changed, 37 insertions(+), 32 deletions(-) diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index c78553c6c..dcc643649 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -10,38 +10,38 @@ top_builddir = @top_builddir@ SWIG = $(top_builddir)/preinst_swig ifneq (, $(ENGINE)) - JSENGINE = $(ENGINE) + JSENGINE = $(ENGINE) else - JSENGINE = "node" + JSENGINE = "node" endif include $(srcdir)/../common.mk SWIGOPT += -$(JSENGINE) + ifeq ("node",$(JSENGINE)) - setup = \ - if [ ! -f $(srcdir)/$*/binding.gyp ]; then \ - echo "Setting up nodejs addon..."; \ - sh ./setup_test.sh $*; \ - $(SWIG) -c++ -javascript -node -o $*/$*_wrap.cxx ../$*.i; \ - fi + setup = \ + if [ ! -f $(srcdir)/$*/binding.gyp ]; then \ + echo "Setting up nodejs addon..."; \ + sh ./setup_test.sh $*; \ + $(SWIG) -c++ -javascript -node -o $*/$*_wrap.cxx ../$*.i; \ + fi - nodejs_swig_and_compile = \ - if [ ! -f $(srcdir)/$*/build/Makefile ]; then \ - echo "Configuring node add-on..."; \ - node-gyp --directory $* configure; \ - fi; \ - echo "Building node add-on..."; \ - node-gyp --directory $* build; \ + nodejs_swig_and_compile = \ + if [ ! -f $(srcdir)/$*/build/Makefile ]; then \ + echo "Configuring node add-on..."; \ + node-gyp --directory $* configure; \ + fi; \ + echo "Building node add-on..."; \ + node-gyp --directory $* build; \ - run_testcase = \ - if [ -f $(srcdir)/$*$(SCRIPTSUFFIX) ]; then \ - node $(srcdir)/$*$(SCRIPTSUFFIX); \ - fi + run_testcase = \ + if [ -f $(srcdir)/$*$(SCRIPTSUFFIX) ]; then \ + node $(srcdir)/$*$(SCRIPTSUFFIX); \ + fi - # Rules for the different types of tests %.cpptest: $(setup) $(nodejs_swig_and_compile) @@ -57,38 +57,43 @@ ifeq ("node",$(JSENGINE)) $(nodejs_swig_and_compile) $(run_testcase) - # Clean %.clean: rm -rf $* else - run_testcase = \ - if [ -f $(srcdir)/$*$(SCRIPTSUFFIX) ]; then \ - $(top_srcdir)/Tools/javascript/javascript -$(JSENGINE) $(srcdir)/$*$(SCRIPTSUFFIX); \ - fi + run_testcase = \ + if [ -f $(srcdir)/$*$(SCRIPTSUFFIX) ]; then \ + $(top_srcdir)/Tools/javascript/javascript -$(JSENGINE) $(srcdir)/$*$(SCRIPTSUFFIX); \ + fi - # Rules for the different types of tests %.cpptest: $(setup) +$(swig_and_compile_cpp) $(run_testcase) - %.ctest: - $(setup) - +$(swig_and_compile_c) - $(run_testcase) - %.multicpptest: $(setup) +$(swig_and_compile_multi_cpp) $(run_testcase) - # Clean %.clean: rm $*_wrap.cxx endif +ifeq (v8,$(ENGINE)) + %.ctest: + $(setup) + +$(swig_and_compile_cpp) + $(run_testcase) +endif + +ifeq (jsc,$(ENGINE)) + %.ctest: + $(setup) + +$(swig_and_compile_c) + $(run_testcase) +endif clean: From 0facc7ecf9f48a98a6f66c557917657d3adb2d36 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 6 Sep 2013 15:59:43 +0300 Subject: [PATCH 0295/1048] Allow to run the test suite with our list of smoke tests. The javascript generator can not deal with the whole test-suite. Moreover, during development I want to have immediate feedback using a set of smoke tests. --- Examples/test-suite/javascript/Makefile.in | 99 +++++++++++++++++----- 1 file changed, 80 insertions(+), 19 deletions(-) diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index dcc643649..0f532b119 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -15,27 +15,85 @@ else JSENGINE = "node" endif +# Note: the javascript generator is not ready yet for the real game. +# To be able keep the behavior continously tested that is expected to work already +# we have a 'light' version of the test-suite +# This will be removed and replaced by a list of 'BROKEN_TEST_CASES' when +# the number gets smaller (currently we have about 65 broken tests for JSC, and 85 for V8) + +ifneq (,$(SMOKE)) + +C_TEST_CASES = \ + preproc + +CPP_TEST_CASES = \ + abstract_access \ + abstract_typedef \ + abstract_typedef2 \ + abstract_virtual \ + arrays_global \ + array_member \ + char_binary \ + class_ignore \ + class_scope_weird \ + complextest \ + constover \ + constructor_copy \ + cpp_enum \ + cpp_namespace \ + cpp_static \ + director_alternating \ + enum_template \ + namespace_virtual_method \ + overload_copy \ + ret_by_value \ + struct_value \ + template_static \ + typedef_class \ + typedef_inherit \ + typedef_scope \ + typemap_arrays \ + typemap_delete \ + typemap_namespace \ + typemap_ns_using \ + using1 \ + using2 \ + javascript_unicode + +BROKEN_TEST_CASES = \ + preproc_include + +SKIP_CPP_CASES = @SKIP_CPP_CASES@ +SKIP_C_CASES = @SKIP_C_CASES@ +SKIP_CPP_STD_CASES = @SKIP_CPP_STD_CASES@ +SKIP_MULTI_CPP_CASES = @SKIP_MULTI_CPP_CASES@ + +endif + include $(srcdir)/../common.mk SWIGOPT += -$(JSENGINE) +_setup = \ + if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + echo "$(ACTION)ing testcase $* (with run test) under javascript ($(JSENGINE))" ; \ + else \ + echo "$(ACTION)ing testcase $* under javascript ($(JSENGINE))" ; \ + fi; ifeq ("node",$(JSENGINE)) - setup = \ + __setup = \ if [ ! -f $(srcdir)/$*/binding.gyp ]; then \ - echo "Setting up nodejs addon..."; \ sh ./setup_test.sh $*; \ $(SWIG) -c++ -javascript -node -o $*/$*_wrap.cxx ../$*.i; \ fi nodejs_swig_and_compile = \ if [ ! -f $(srcdir)/$*/build/Makefile ]; then \ - echo "Configuring node add-on..."; \ - node-gyp --directory $* configure; \ + node-gyp --loglevel=silent --directory $* configure; \ fi; \ - echo "Building node add-on..."; \ - node-gyp --directory $* build; \ + node-gyp --loglevel=silent --directory $* build; \ run_testcase = \ if [ -f $(srcdir)/$*$(SCRIPTSUFFIX) ]; then \ @@ -43,23 +101,23 @@ ifeq ("node",$(JSENGINE)) fi %.cpptest: - $(setup) + $(_setup) + $(__setup) $(nodejs_swig_and_compile) $(run_testcase) %.ctest: - $(setup) + $(_setup) + $(__setup) $(nodejs_swig_and_compile) $(run_testcase) %.multicpptest: - $(setup) + $(_setup) + $(__setup) $(nodejs_swig_and_compile) $(run_testcase) - %.clean: - rm -rf $* - else run_testcase = \ @@ -68,32 +126,35 @@ else fi %.cpptest: - $(setup) + $(_setup) +$(swig_and_compile_cpp) $(run_testcase) %.multicpptest: - $(setup) + $(_setup) +$(swig_and_compile_multi_cpp) $(run_testcase) - %.clean: - rm $*_wrap.cxx - endif ifeq (v8,$(ENGINE)) %.ctest: - $(setup) + $(_setup) +$(swig_and_compile_cpp) $(run_testcase) endif ifeq (jsc,$(ENGINE)) %.ctest: - $(setup) + $(_setup) +$(swig_and_compile_c) $(run_testcase) endif +%.clean: + rm -rf $* + clean: + rm -f *_wrap.cxx + rm -f *_wrap.c + rm -f *.so From 6b35c2d419eac4f71780a939254e8a459c075849 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 6 Sep 2013 16:26:02 +0300 Subject: [PATCH 0296/1048] Let Travis test all three targets. - nodejs: 0.10.12 - libwebgitgtk 1.0 - libv8 3.7.12 We should soon switch to a new v8 version or add an extra runner. --- .travis.yml | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index f57e81319..a38965992 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,5 +8,11 @@ before_script: - "sudo apt-get update" - "sudo apt-get install -y nodejs" - "sudo npm install -g node-gyp" + - "sudo apt-get install libv8-3.7.12.22 libv8-dev" + - "sudo apt-get install libwebkitgtk-dev" - "./autogen.sh && ./configure && make" -script: "make check-javascript-test-suite" + - "cd Examples && make javascript_exe && cd .." +script: + - "make SMOKE=1 check-javascript-test-suite" + - "make SMOKE=1 ENGINE=jsc check-javascript-test-suite" + - "make SMOKE=1 ENGINE=v8 check-javascript-test-suite" From 1729fac3605d6649919ee508bcf8b03f904886f4 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 9 Sep 2013 12:46:07 +0300 Subject: [PATCH 0297/1048] Bug-fix for static variables as proposed by Kota Iguchi. Fixes #20. --- Source/Modules/javascript.cxx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 360fb1aec..54135d852 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1636,7 +1636,7 @@ int JSCEmitter::exitVariable(Node *n) { .replace(T_SETTER, state.variable(SETTER)); if (GetFlag(n, "ismember")) { - if (GetFlag(state.function(), IS_STATIC) + if (GetFlag(state.variable(), IS_STATIC) || Equal(Getattr(n, "nodeType"), "enumitem")) { Append(state.clazz(STATIC_VARIABLES), t_variable.str()); } else { From e01e337d752dbbfc58a06b87fe1169d3f6ada76f Mon Sep 17 00:00:00 2001 From: Eric Wing Date: Thu, 5 Sep 2013 14:50:15 -0700 Subject: [PATCH 0298/1048] Added unit test using C99 INFINITY. This test actually tests a float conversion bug where converting to float imposed overflow checking which should not be there and causes this program to error out. This was seen originally in Javascript, but it turns out Python has the same bug. Lua does not have this bug. Other generators have not been tested. This test also tests the rename feature. The Javascript generator was not renaming the variable correctly. --- Examples/test-suite/infinity.i | 49 +++++++++++++++++++ .../test-suite/javascript/infinity_runme.js | 4 ++ 2 files changed, 53 insertions(+) create mode 100644 Examples/test-suite/infinity.i create mode 100644 Examples/test-suite/javascript/infinity_runme.js diff --git a/Examples/test-suite/infinity.i b/Examples/test-suite/infinity.i new file mode 100644 index 000000000..a01f05fc5 --- /dev/null +++ b/Examples/test-suite/infinity.i @@ -0,0 +1,49 @@ +%module infinity + +#include + +/* C99 defines INFINITY + Because INFINITY may be defined by compiler built-ins, we can't use #define. + Instead, expose the variable MYINFINITY and then use %rename to make it INFINITY in the scripting language. +*/ +%rename(INFINITY) MYINFINITY; + + +%inline %{ +#include + +/* C99 math.h defines INFINITY. If not available, this is the fallback. */ +#ifndef INFINITY + #ifdef _MSC_VER + union MSVC_EVIL_FLOAT_HACK + { + unsigned __int8 Bytes[4]; + float Value; + }; + static union MSVC_EVIL_FLOAT_HACK INFINITY_HACK = {{0x00, 0x00, 0x80, 0x7F}}; + #define INFINITY (INFINITY_HACK.Value) + #endif + + #ifdef __GNUC__ + #define INFINITY (__builtin_inf()) + #elif defined(__clang__) + #if __has_builtin(__builtin_inf) + #define INFINITY (__builtin_inf()) + #endif + #endif + + #ifndef INFINITY + #define INFINITY (1e1000) + #endif +#endif + +/* This will allow us to bind the real INFINITY value through SWIG via MYINFINITY. Use %rename to fix the name. */ +const double MYINFINITY = INFINITY; + +/* Use of float is intentional because the original bug was in the float conversion due to overflow checking. */ +float use_infinity(float inf_val) +{ + return inf_val; +} +%} + diff --git a/Examples/test-suite/javascript/infinity_runme.js b/Examples/test-suite/javascript/infinity_runme.js new file mode 100644 index 000000000..f15134848 --- /dev/null +++ b/Examples/test-suite/javascript/infinity_runme.js @@ -0,0 +1,4 @@ + +var my_infinity = infinity.INFINTY; +var ret_val = infinity.use_infinity(my_infinity); + From 1438d0cfb45f0f1b740eb8d1d366f694ba99d0b6 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 9 Sep 2013 13:17:38 +0300 Subject: [PATCH 0299/1048] Add `infinity` test-case to list of smoke tests. --- Examples/test-suite/javascript/Makefile.in | 1 + Examples/test-suite/javascript/infinity_runme.js | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index 0f532b119..0b6d2f7c6 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -44,6 +44,7 @@ CPP_TEST_CASES = \ cpp_static \ director_alternating \ enum_template \ + infinity \ namespace_virtual_method \ overload_copy \ ret_by_value \ diff --git a/Examples/test-suite/javascript/infinity_runme.js b/Examples/test-suite/javascript/infinity_runme.js index f15134848..1dcf366c6 100644 --- a/Examples/test-suite/javascript/infinity_runme.js +++ b/Examples/test-suite/javascript/infinity_runme.js @@ -1,4 +1,4 @@ +var infinity = require("./infinity"); var my_infinity = infinity.INFINTY; var ret_val = infinity.use_infinity(my_infinity); - From 64da1173ddf8bd1fe04800e2afbe0f9c5d2dc818 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 9 Sep 2013 13:23:47 +0300 Subject: [PATCH 0300/1048] Activate Javascript testcases `rename1-4`. --- Examples/test-suite/javascript/Makefile.in | 4 ++ .../test-suite/javascript/rename1_runme.js | 68 +++++++++++++++++++ .../test-suite/javascript/rename2_runme.js | 68 +++++++++++++++++++ .../test-suite/javascript/rename3_runme.js | 68 +++++++++++++++++++ .../test-suite/javascript/rename4_runme.js | 68 +++++++++++++++++++ 5 files changed, 276 insertions(+) create mode 100644 Examples/test-suite/javascript/rename1_runme.js create mode 100644 Examples/test-suite/javascript/rename2_runme.js create mode 100644 Examples/test-suite/javascript/rename3_runme.js create mode 100644 Examples/test-suite/javascript/rename4_runme.js diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index 0b6d2f7c6..7c6b9ad4e 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -47,6 +47,10 @@ CPP_TEST_CASES = \ infinity \ namespace_virtual_method \ overload_copy \ + rename1 \ + rename2 \ + rename3 \ + rename4 \ ret_by_value \ struct_value \ template_static \ diff --git a/Examples/test-suite/javascript/rename1_runme.js b/Examples/test-suite/javascript/rename1_runme.js new file mode 100644 index 000000000..8374e6a89 --- /dev/null +++ b/Examples/test-suite/javascript/rename1_runme.js @@ -0,0 +1,68 @@ +var rename = require("./rename1"); + +function part1() { + var xyz = new rename.XYZInt(); + notxyz = new rename.NotXYZInt(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother2(); + xyz.opT2(); + xyz.tMethod2(0); + xyz.tMethodNotXYZ2(notxyz); + xyz.opNotXYZ2(); + xyz.opXYZ2(); +} + +function part2() { + var xyz = new rename.XYZDouble(); + var notxyz = new rename.NotXYZDouble(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother1(); + xyz.opT1(); + xyz.tMethod1(0); + xyz.tMethodNotXYZ1(notxyz); + xyz.opNotXYZ1(); + xyz.opXYZ1(); +} + +function part3(){ + var xyz = new rename.XYZKlass(); + var notxyz = new rename.NotXYZKlass(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother3(); + xyz.opT3(); + xyz.tMethod3(new rename.Klass()); + xyz.tMethodNotXYZ3(notxyz); + xyz.opNotXYZ3(); + xyz.opXYZ3(); +} + +function part4() { + var xyz = new rename.XYZEnu(); + var notxyz = new rename.NotXYZEnu(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother4(); + xyz.opT4(); + xyz.tMethod4(rename.En1); + xyz.tMethodNotXYZ4(notxyz); + xyz.opNotXYZ4(); + xyz.opXYZ4(); +} + +function part5() { + var abc = new rename.ABC(); + abc.methodABC(abc); + var k = new rename.Klass(); + abc.methodKlass(k); + var a = abc.opABC(); + k = abc.opKlass(); +} + +part1(); +part2(); +part3(); +part4(); +part5(); diff --git a/Examples/test-suite/javascript/rename2_runme.js b/Examples/test-suite/javascript/rename2_runme.js new file mode 100644 index 000000000..bc6a95a59 --- /dev/null +++ b/Examples/test-suite/javascript/rename2_runme.js @@ -0,0 +1,68 @@ +var rename = require("./rename2"); + +function part1() { + var xyz = new rename.XYZInt(); + notxyz = new rename.NotXYZInt(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother2(); + xyz.opT2(); + xyz.tMethod2(0); + xyz.tMethodNotXYZ2(notxyz); + xyz.opNotXYZ2(); + xyz.opXYZ2(); +} + +function part2() { + var xyz = new rename.XYZDouble(); + var notxyz = new rename.NotXYZDouble(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother1(); + xyz.opT1(); + xyz.tMethod1(0); + xyz.tMethodNotXYZ1(notxyz); + xyz.opNotXYZ1(); + xyz.opXYZ1(); +} + +function part3(){ + var xyz = new rename.XYZKlass(); + var notxyz = new rename.NotXYZKlass(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother3(); + xyz.opT3(); + xyz.tMethod3(new rename.Klass()); + xyz.tMethodNotXYZ3(notxyz); + xyz.opNotXYZ3(); + xyz.opXYZ3(); +} + +function part4() { + var xyz = new rename.XYZEnu(); + var notxyz = new rename.NotXYZEnu(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother4(); + xyz.opT4(); + xyz.tMethod4(rename.En1); + xyz.tMethodNotXYZ4(notxyz); + xyz.opNotXYZ4(); + xyz.opXYZ4(); +} + +function part5() { + var abc = new rename.ABC(); + abc.methodABC(abc); + var k = new rename.Klass(); + abc.methodKlass(k); + var a = abc.opABC(); + k = abc.opKlass(); +} + +part1(); +part2(); +part3(); +part4(); +part5(); diff --git a/Examples/test-suite/javascript/rename3_runme.js b/Examples/test-suite/javascript/rename3_runme.js new file mode 100644 index 000000000..9e57e80ea --- /dev/null +++ b/Examples/test-suite/javascript/rename3_runme.js @@ -0,0 +1,68 @@ +var rename = require("./rename3"); + +function part1() { + var xyz = new rename.XYZInt(); + notxyz = new rename.NotXYZInt(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother2(); + xyz.opT2(); + xyz.tMethod2(0); + xyz.tMethodNotXYZ2(notxyz); + xyz.opNotXYZ2(); + xyz.opXYZ2(); +} + +function part2() { + var xyz = new rename.XYZDouble(); + var notxyz = new rename.NotXYZDouble(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother1(); + xyz.opT1(); + xyz.tMethod1(0); + xyz.tMethodNotXYZ1(notxyz); + xyz.opNotXYZ1(); + xyz.opXYZ1(); +} + +function part3(){ + var xyz = new rename.XYZKlass(); + var notxyz = new rename.NotXYZKlass(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother3(); + xyz.opT3(); + xyz.tMethod3(new rename.Klass()); + xyz.tMethodNotXYZ3(notxyz); + xyz.opNotXYZ3(); + xyz.opXYZ3(); +} + +function part4() { + var xyz = new rename.XYZEnu(); + var notxyz = new rename.NotXYZEnu(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother4(); + xyz.opT4(); + xyz.tMethod4(rename.En1); + xyz.tMethodNotXYZ4(notxyz); + xyz.opNotXYZ4(); + xyz.opXYZ4(); +} + +function part5() { + var abc = new rename.ABC(); + abc.methodABC(abc); + var k = new rename.Klass(); + abc.methodKlass(k); + var a = abc.opABC(); + k = abc.opKlass(); +} + +part1(); +part2(); +part3(); +part4(); +part5(); diff --git a/Examples/test-suite/javascript/rename4_runme.js b/Examples/test-suite/javascript/rename4_runme.js new file mode 100644 index 000000000..d651fc7a1 --- /dev/null +++ b/Examples/test-suite/javascript/rename4_runme.js @@ -0,0 +1,68 @@ +var rename = require("./rename4"); + +function part1() { + var xyz = new rename.XYZInt(); + notxyz = new rename.NotXYZInt(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother2(); + xyz.opT2(); + xyz.tMethod2(0); + xyz.tMethodNotXYZ2(notxyz); + xyz.opNotXYZ2(); + xyz.opXYZ2(); +} + +function part2() { + var xyz = new rename.XYZDouble(); + var notxyz = new rename.NotXYZDouble(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother1(); + xyz.opT1(); + xyz.tMethod1(0); + xyz.tMethodNotXYZ1(notxyz); + xyz.opNotXYZ1(); + xyz.opXYZ1(); +} + +function part3(){ + var xyz = new rename.XYZKlass(); + var notxyz = new rename.NotXYZKlass(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother3(); + xyz.opT3(); + xyz.tMethod3(new rename.Klass()); + xyz.tMethodNotXYZ3(notxyz); + xyz.opNotXYZ3(); + xyz.opXYZ3(); +} + +function part4() { + var xyz = new rename.XYZEnu(); + var notxyz = new rename.NotXYZEnu(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother4(); + xyz.opT4(); + xyz.tMethod4(rename.En1); + xyz.tMethodNotXYZ4(notxyz); + xyz.opNotXYZ4(); + xyz.opXYZ4(); +} + +function part5() { + var abc = new rename.ABC(); + abc.methodABC(abc); + var k = new rename.Klass(); + abc.methodKlass(k); + var a = abc.opABC(); + k = abc.opKlass(); +} + +part1(); +part2(); +part3(); +part4(); +part5(); From 108143951da3859e0c056780706b6841231febb3 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 9 Sep 2013 13:55:08 +0300 Subject: [PATCH 0301/1048] Activate Javascript test-cases `rename_simple` and `rename_scope`. These reveal current deficiencies in the Javascript generator with `%rename`ing. --- Examples/test-suite/javascript/Makefile.in | 2 + .../javascript/rename_scope_runme.js | 17 +++++++ .../javascript/rename_simple_runme.js | 50 +++++++++++++++++++ 3 files changed, 69 insertions(+) create mode 100644 Examples/test-suite/javascript/rename_scope_runme.js create mode 100644 Examples/test-suite/javascript/rename_simple_runme.js diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index 7c6b9ad4e..5d7fba02e 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -51,6 +51,8 @@ CPP_TEST_CASES = \ rename2 \ rename3 \ rename4 \ + rename_simple \ + rename_scope \ ret_by_value \ struct_value \ template_static \ diff --git a/Examples/test-suite/javascript/rename_scope_runme.js b/Examples/test-suite/javascript/rename_scope_runme.js new file mode 100644 index 000000000..c0226df69 --- /dev/null +++ b/Examples/test-suite/javascript/rename_scope_runme.js @@ -0,0 +1,17 @@ +var rename_scope = require("./rename_scope"); + +var a = new rename_scope.Natural_UP(); +var b = new rename_scope.Natural_BP(); + +if (a.rtest() !== 1) { + throw new Error("a.rtest(): Expected 1, was " + a.rtest()); +} + +if (b.rtest() !== 1) { + throw new Error("b.rtest(): Expected 1, was " + b.rtest()); +} + +var f = rename_scope.equals; +if (f === undefined) { + throw new Error("Equality operator has not been renamed."); +} diff --git a/Examples/test-suite/javascript/rename_simple_runme.js b/Examples/test-suite/javascript/rename_simple_runme.js new file mode 100644 index 000000000..918dd68a5 --- /dev/null +++ b/Examples/test-suite/javascript/rename_simple_runme.js @@ -0,0 +1,50 @@ +var rename_simple = require("./rename_simple"); +var NewStruct = rename_simple.NewStruct; + +var s = new NewStruct(); + +// renamed instance variable +if (s.NewInstanceVariable !== 111) { + throw new Error("NewInstanceVariable: Expected 111, was " + s.NewInstanceVariable); +} + +// renamed instance method +if (s.NewInstanceMethod() !== 222) { + throw new Error("NewInstanceMethod(): Expected 222, was " + s.NewInstanceMethod()); +} + +// renamed static method +if (NewStruct.NewStaticMethod() !== 333) { + throw new Error("NewInstanceMethod(): Expected 333, was " + NewStruct.NewStaticMethod()); +} + +// renamed static variable +if (NewStruct.NewStaticVariable !== 444) { + throw new Error("NewInstanceMethod(): Expected 444, was " + NewStruct.NewStaticVariable); +} + +// renamed global function +if (rename_simple.NewFunction() !== 555) { + throw new Error("rename_simple.NewFunction(): Expected 555, was " + rename_simple.NewFunction()); +} + +// renamed global variable +if (rename_simple.NewGlobalVariable !== 666) { + throw new Error("rename_simple.NewGlobalVariable: Expected 666, was " + rename_simple.NewGlobalVariable); +} + +// setting renamed variables +s.NewInstanceVariable = 1111; +if (s.NewInstanceVariable !== 1111) { + throw new Error("NewInstanceVariable: Expected 1111, was " + s.NewInstanceVariable); +} + +NewStruct.NewStaticVariable = 4444; +if (NewStruct.NewStaticVariable !== 4444) { + throw new Error("NewInstanceMethod(): Expected 4444, was " + NewStruct.NewStaticVariable); +} + +rename_simple.NewGlobalVariable = 6666; +if (rename_simple.NewGlobalVariable !== 6666) { + throw new Error("rename_simple.NewGlobalVariable: Expected 6666, was " + rename_simple.NewGlobalVariable); +} From b6c9c97b96bc3039ccb291d76a64d009fc81fbb7 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 9 Sep 2013 15:05:11 +0300 Subject: [PATCH 0302/1048] Fix Javascript generator to use %renamed variable names. --- Examples/test-suite/javascript/Makefile.in | 2 +- Source/Modules/javascript.cxx | 12 +++++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index 5d7fba02e..49dd18054 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -44,7 +44,6 @@ CPP_TEST_CASES = \ cpp_static \ director_alternating \ enum_template \ - infinity \ namespace_virtual_method \ overload_copy \ rename1 \ @@ -68,6 +67,7 @@ CPP_TEST_CASES = \ javascript_unicode BROKEN_TEST_CASES = \ + infinity \ preproc_include SKIP_CPP_CASES = @SKIP_CPP_CASES@ diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 54135d852..5bd22f710 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -793,8 +793,18 @@ int JSEmitter::enterFunction(Node *n) { int JSEmitter::enterVariable(Node *n) { + // reset the state information for variables. state.variable(true); - state.variable(NAME, Swig_scopename_last(Getattr(n, "name"))); + + // Retrieve a pure symbol name. Using 'sym:name' as a basis, as it considers %renamings. + + if (Equal(Getattr(n, "view"), "memberconstantHandler")) { + // Note: this is kind of hacky/experimental + // For constants/enums 'sym:name' contains e.g., 'Foo_Hello' instead of 'Hello' + state.variable(NAME, Getattr(n, "memberconstantHandler:sym:name")); + } else { + state.variable(NAME, Swig_scopename_last(Getattr(n, "sym:name"))); + } if(Equal(Getattr(n, "storage"), "static")) { SetFlag(state.variable(), IS_STATIC); From fc4d9b665c5839df06501e736163bfeadb7503d1 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 9 Sep 2013 16:28:29 +0300 Subject: [PATCH 0303/1048] Fix v8 generator to use a non clashing name for built-in 'equals' method. --- Lib/javascript/v8/javascripthelpers.swg | 2 +- Lib/javascript/v8/javascriptruntime.swg | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/Lib/javascript/v8/javascripthelpers.swg b/Lib/javascript/v8/javascripthelpers.swg index 52f3f106f..8da6627e2 100644 --- a/Lib/javascript/v8/javascripthelpers.swg +++ b/Lib/javascript/v8/javascripthelpers.swg @@ -25,7 +25,7 @@ v8::Handle SWIGV8_CreateClassTemplate(const char* symbol) inst_templ->SetInternalFieldCount(1); v8::Handle equals_templ = class_templ->PrototypeTemplate(); - equals_templ->Set(v8::String::NewSymbol("equals"), v8::FunctionTemplate::New(_wrap_equals)); + equals_templ->Set(v8::String::NewSymbol("equals"), v8::FunctionTemplate::New(_SWIGV8_wrap_equals)); v8::Handle cptr_templ = class_templ->PrototypeTemplate(); cptr_templ->Set(v8::String::NewSymbol("getCPtr"), v8::FunctionTemplate::New(_wrap_getCPtr)); diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index 31ce84a04..c34b62108 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -297,9 +297,9 @@ v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, in #define SWIG_GetInstancePtr(obj, ptr) SWIG_V8_GetInstancePtr(obj, ptr) #if (SWIG_V8_VERSION < 0x031900) -v8::Handle _wrap_equals(const v8::Arguments &args) { +v8::Handle _SWIGV8_wrap_equals(const v8::Arguments &args) { #else -void _wrap_equals(const v8::FunctionCallbackInfo& args) { +void _SWIGV8_wrap_equals(const v8::FunctionCallbackInfo& args) { #endif v8::HandleScope scope; v8::Handle jsresult; @@ -309,11 +309,11 @@ void _wrap_equals(const v8::FunctionCallbackInfo& args) { int res1; int res2; - if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for _wrap_equals."); + if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for equals."); res1 = SWIG_GetInstancePtr(args.Holder(), &arg1); if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ERROR, "Could not get pointer from 'this' object for _wrap_equals."); + SWIG_exception_fail(SWIG_ERROR, "Could not get pointer from 'this' object for equals."); } res2 = SWIG_GetInstancePtr(args[0], &arg2); if (!SWIG_IsOK(res2)) { From 407d8ef5acff62578c701da74cfdf9a752baffd1 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 9 Sep 2013 17:34:53 +0300 Subject: [PATCH 0304/1048] Clean up in `javascripttypemaps.swg`. - following the same layout/order as pytypemaps - added typemaps for `long long` and `unsigned long long`, which are only copies of those for `long` and `unsigned long` and hence are just experimental. --- Lib/javascript/jsc/javascriptfragments.swg | 23 ++++ ...primitives.swg => javascriptprimtypes.swg} | 96 +++++++++++++-- Lib/javascript/jsc/javascripttypemaps.swg | 41 +++++-- Lib/javascript/v8/javascriptfragments.swg | 23 ++++ ...primitives.swg => javascriptprimtypes.swg} | 114 ++++++++++++++---- Lib/javascript/v8/javascripttypemaps.swg | 43 +++++-- 6 files changed, 287 insertions(+), 53 deletions(-) create mode 100644 Lib/javascript/jsc/javascriptfragments.swg rename Lib/javascript/jsc/{javascriptprimitives.swg => javascriptprimtypes.swg} (53%) create mode 100644 Lib/javascript/v8/javascriptfragments.swg rename Lib/javascript/v8/{javascriptprimitives.swg => javascriptprimtypes.swg} (55%) diff --git a/Lib/javascript/jsc/javascriptfragments.swg b/Lib/javascript/jsc/javascriptfragments.swg new file mode 100644 index 000000000..4778bf033 --- /dev/null +++ b/Lib/javascript/jsc/javascriptfragments.swg @@ -0,0 +1,23 @@ +/* + + Create a file with this name, 'javascriptfragments.swg', in your working + directory and add all the %fragments you want to take precedence + over the default ones defined by swig. + + For example, if you add: + + %fragment(SWIG_AsVal_frag(int),"header") { + SWIGINTERNINLINE int + SWIG_AsVal(int)(PyObject *obj, int *val) + { + ; + } + } + + this will replace the code used to retrieve an integer value for all + the typemaps that need it, including: + + int, std::vector, std::list >, etc. + + +*/ diff --git a/Lib/javascript/jsc/javascriptprimitives.swg b/Lib/javascript/jsc/javascriptprimtypes.swg similarity index 53% rename from Lib/javascript/jsc/javascriptprimitives.swg rename to Lib/javascript/jsc/javascriptprimtypes.swg index f61e83272..2c23cc07f 100644 --- a/Lib/javascript/jsc/javascriptprimitives.swg +++ b/Lib/javascript/jsc/javascriptprimtypes.swg @@ -1,5 +1,11 @@ +/* ------------------------------------------------------------ + * Primitive Types + * ------------------------------------------------------------ */ + +/* boolean */ + %fragment(SWIG_From_frag(bool),"header") { -SWIGINTERNINLINE +SWIGINTERNINLINE JSValueRef SWIG_From_dec(bool)(bool value) { return JSValueMakeBoolean(context, value); @@ -19,6 +25,8 @@ int SWIG_AsVal_dec(bool)(JSValueRef obj, bool *val) } } +/* int */ + %fragment(SWIG_From_frag(int),"header") { SWIGINTERNINLINE JSValueRef SWIG_From_dec(int)(int value) @@ -27,9 +35,11 @@ SWIGINTERNINLINE JSValueRef } } +/* long */ + %fragment(SWIG_From_frag(long),"header") { SWIGINTERNINLINE JSValueRef - SWIG_From_dec(long)(long value) +SWIG_From_dec(long)(long value) { return JSValueMakeNumber(context, value); } @@ -44,7 +54,7 @@ SWIG_AsVal_dec(long)(JSValueRef obj, long* val) return SWIG_TypeError; } if(val) *val = (long) JSValueToNumber(context, obj, NULL); - + return SWIG_OK; } } @@ -53,35 +63,97 @@ SWIG_AsVal_dec(long)(JSValueRef obj, long* val) %fragment(SWIG_From_frag(unsigned long),"header", fragment=SWIG_From_frag(long)) { -SWIGINTERNINLINE JSValueRef +SWIGINTERNINLINE JSValueRef SWIG_From_dec(unsigned long)(unsigned long value) { return (value > LONG_MAX) ? - JSValueMakeNumber(context, value) : JSValueMakeNumber(context, %numeric_cast(value,long)); + JSValueMakeNumber(context, value) : JSValueMakeNumber(context, %numeric_cast(value,long)); } } %fragment(SWIG_AsVal_frag(unsigned long),"header", fragment="SWIG_CanCastAsInteger") { SWIGINTERN int -SWIG_AsVal_dec(unsigned long)(JSValueRef obj, unsigned long *val) +SWIG_AsVal_dec(unsigned long)(JSValueRef obj, unsigned long *val) { if(!JSValueIsNumber(context, obj)) { return SWIG_TypeError; } - + long longVal = (long) JSValueToNumber(context, obj, NULL); - + if(longVal < 0) { return SWIG_OverflowError; } - - if(val) *val = longVal; - + + if(val) *val = longVal; + return SWIG_OK; } } +/* long long */ +// Note: these are copied from 'long' and probably need fixing + +%fragment(SWIG_From_frag(long long),"header") { +SWIGINTERNINLINE JSValueRef +SWIG_From_dec(long long)(long long value) +{ + return JSValueMakeNumber(context, value); +} +} + +%fragment(SWIG_AsVal_frag(long long),"header", + fragment="SWIG_CanCastAsInteger") { +SWIGINTERN int +SWIG_AsVal_dec(long long)(JSValueRef obj, long long* val) +{ + if (!JSValueIsNumber(context, obj)) { + return SWIG_TypeError; + } + if(val) *val = (long long) JSValueToNumber(context, obj, NULL); + + return SWIG_OK; +} +} + +/* unsigned long long */ +// Note: these are copied from 'unsigned long' and probably need fixing + +%fragment(SWIG_From_frag(unsigned long long),"header", + fragment=SWIG_From_frag(long long), + fragment="") { +SWIGINTERN JSValueRef +SWIG_From_dec(unsigned long long)(unsigned long long value) +{ + return (value > LONG_MAX) ? + JSValueMakeNumber(context, value) : JSValueMakeNumber(context, %numeric_cast(value,long)); +} +} + +%fragment(SWIG_AsVal_frag(unsigned long long),"header", + fragment="SWIG_CanCastAsInteger") { +SWIGINTERN int +SWIG_AsVal_dec(unsigned long long)(JSValueRef obj, unsigned long long *val) +{ + if(!JSValueIsNumber(context, obj)) { + return SWIG_TypeError; + } + + long long longVal = (unsigned long long) JSValueToNumber(context, obj, NULL); + + if(longVal < 0) { + return SWIG_OverflowError; + } + + if(val) *val = longVal; + + return SWIG_OK; +} +} + +/* double */ + %fragment(SWIG_From_frag(double),"header") { SWIGINTERN JSValueRef SWIG_From_dec(double) (double val) @@ -98,7 +170,7 @@ SWIG_AsVal_dec(double)(JSValueRef obj, double *val) return SWIG_TypeError; } if(val) *val = JSValueToNumber(context, obj, NULL); - + return SWIG_OK; } } diff --git a/Lib/javascript/jsc/javascripttypemaps.swg b/Lib/javascript/jsc/javascripttypemaps.swg index 9bde8eb2a..aa0a829f9 100644 --- a/Lib/javascript/jsc/javascripttypemaps.swg +++ b/Lib/javascript/jsc/javascripttypemaps.swg @@ -1,21 +1,46 @@ +/* ------------------------------------------------------------ + * Typemap specializations for Javascript + * ------------------------------------------------------------ */ +/* ------------------------------------------------------------ + * Fragment section + * ------------------------------------------------------------ */ + +/* These macros are necessary to provide an extra parameter + to SWIG_AsVal_dec functions (JSContextRef context). +*/ #define SWIG_FROM_DECL_ARGS SWIG_JSC_FROM_DECL_ARGS #define SWIG_FROM_CALL_ARGS SWIG_JSC_FROM_CALL_ARGS #define SWIG_AS_DECL_ARGS SWIG_JSC_AS_DECL_ARGS #define SWIG_AS_CALL_ARGS SWIG_JSC_AS_CALL_ARGS -#define SWIG_Object JSValueRef -#define VOID_Object JSValueMakeUndefined(context) -#define SWIG_AppendOutput(result, obj) -#define SWIG_SetConstant(name, obj) -#define SWIG_Raise(obj, type, desc) SWIG_Javascript_Raise(context, exception, type) /* Include fundamental fragemt definitions */ %include -/* Python fragments for fundamental types */ -%include - +/* Look for user fragments file. */ +%include + +/* Javascript fragments for fundamental types */ +%include + +/* Javascript fragments for char* strings */ %include +/* ------------------------------------------------------------ + * Unified typemap section + * ------------------------------------------------------------ */ + +#define SWIG_Object JSValueRef +#define VOID_Object JSValueMakeUndefined(context) + +/* append output */ +#define SWIG_AppendOutput(result, obj) + +/* set constant */ +#define SWIG_SetConstant(name, obj) + +/* raise */ +#define SWIG_Raise(obj, type, desc) SWIG_Javascript_Raise(context, exception, type) + /* Include the unified typemap library */ %include diff --git a/Lib/javascript/v8/javascriptfragments.swg b/Lib/javascript/v8/javascriptfragments.swg new file mode 100644 index 000000000..4778bf033 --- /dev/null +++ b/Lib/javascript/v8/javascriptfragments.swg @@ -0,0 +1,23 @@ +/* + + Create a file with this name, 'javascriptfragments.swg', in your working + directory and add all the %fragments you want to take precedence + over the default ones defined by swig. + + For example, if you add: + + %fragment(SWIG_AsVal_frag(int),"header") { + SWIGINTERNINLINE int + SWIG_AsVal(int)(PyObject *obj, int *val) + { + ; + } + } + + this will replace the code used to retrieve an integer value for all + the typemaps that need it, including: + + int, std::vector, std::list >, etc. + + +*/ diff --git a/Lib/javascript/v8/javascriptprimitives.swg b/Lib/javascript/v8/javascriptprimtypes.swg similarity index 55% rename from Lib/javascript/v8/javascriptprimitives.swg rename to Lib/javascript/v8/javascriptprimtypes.swg index f34bbb75a..5e0187460 100644 --- a/Lib/javascript/v8/javascriptprimitives.swg +++ b/Lib/javascript/v8/javascriptprimtypes.swg @@ -1,6 +1,12 @@ +/* ------------------------------------------------------------ + * Primitive Types + * ------------------------------------------------------------ */ + +/* boolean */ + %fragment(SWIG_From_frag(bool),"header") { -SWIGINTERNINLINE -v8::Handle +SWIGINTERNINLINE +v8::Handle SWIG_From_dec(bool)(bool value) { return v8::Boolean::New(value); @@ -15,12 +21,14 @@ int SWIG_AsVal_dec(bool)(v8::Handle obj, bool *val) if(!obj->IsBoolean()) { return SWIG_ERROR; } - + if (val) *val = obj->BooleanValue(); return SWIG_OK; } } +/* int */ + %fragment(SWIG_From_frag(int),"header") { SWIGINTERNINLINE v8::Handle SWIG_From_dec(int)(int value) @@ -30,18 +38,19 @@ v8::Handle SWIG_From_dec(int)(int value) } %fragment(SWIG_AsVal_frag(int),"header") { -SWIGINTERN +SWIGINTERN int SWIG_AsVal_dec(int)(v8::Handle valRef, int* val) { if (!valRef->IsNumber()) { return SWIG_TypeError; } if(val) *val = valRef->IntegerValue(); - + return SWIG_OK; } } +/* long */ %fragment(SWIG_From_frag(long),"header") { SWIGINTERNINLINE @@ -53,14 +62,14 @@ v8::Handle SWIG_From_dec(long)(long value) %fragment(SWIG_AsVal_frag(long),"header", fragment="SWIG_CanCastAsInteger") { -SWIGINTERN +SWIGINTERN int SWIG_AsVal_dec(long)(v8::Handle obj, long* val) { if (!obj->IsNumber()) { return SWIG_TypeError; } if(val) *val = (long) obj->IntegerValue(); - + return SWIG_OK; } } @@ -69,37 +78,98 @@ int SWIG_AsVal_dec(long)(v8::Handle obj, long* val) %fragment(SWIG_From_frag(unsigned long),"header", fragment=SWIG_From_frag(long)) { -SWIGINTERNINLINE +SWIGINTERNINLINE v8::Handle SWIG_From_dec(unsigned long)(unsigned long value) { return (value > LONG_MAX) ? - v8::Integer::NewFromUnsigned(value) : v8::Integer::New(%numeric_cast(value,long)); + v8::Integer::NewFromUnsigned(value) : v8::Integer::New(%numeric_cast(value,long)); } } %fragment(SWIG_AsVal_frag(unsigned long),"header", fragment="SWIG_CanCastAsInteger") { -SWIGINTERN -int SWIG_AsVal_dec(unsigned long)(v8::Handle obj, unsigned long *val) +SWIGINTERN +int SWIG_AsVal_dec(unsigned long)(v8::Handle obj, unsigned long *val) { if(!obj->IsNumber()) { return SWIG_TypeError; } - + long longVal = (long) obj->NumberValue(); - + if(longVal < 0) { return SWIG_OverflowError; } - - if(val) *val = longVal; - + + if(val) *val = longVal; + return SWIG_OK; } } +/* long long */ +// Note: these are copied from 'long' and probably need fixing + +%fragment(SWIG_From_frag(long long),"header") { +SWIGINTERNINLINE +v8::Handle SWIG_From_dec(long long)(long long value) +{ + return v8::Number::New(value); +} +} + +%fragment(SWIG_AsVal_frag(long long),"header", + fragment="SWIG_CanCastAsInteger") { +SWIGINTERN +int SWIG_AsVal_dec(long)(v8::Handle obj, long long* val) +{ + if (!obj->IsNumber()) { + return SWIG_TypeError; + } + if(val) *val = (long long) obj->IntegerValue(); + + return SWIG_OK; +} +} + +/* unsigned long long */ +// Note: these are copied from 'unsigned long' and probably need fixing + +%fragment(SWIG_From_frag(unsigned long long),"header", + fragment=SWIG_From_frag(long long)) { +SWIGINTERNINLINE +v8::Handle SWIG_From_dec(unsigned long long)(unsigned long long value) +{ + return (value > LONG_MAX) ? + v8::Integer::NewFromUnsigned(value) : v8::Integer::New(%numeric_cast(value,long)); +} +} + +%fragment(SWIG_AsVal_frag(unsigned long long),"header", + fragment="SWIG_CanCastAsInteger") { +SWIGINTERN +int SWIG_AsVal_dec(unsigned long)(v8::Handle obj, unsigned long long *val) +{ + if(!obj->IsNumber()) { + return SWIG_TypeError; + } + + long long longVal = (long long) obj->NumberValue(); + + if(longVal < 0) { + return SWIG_OverflowError; + } + + if(val) *val = longVal; + + return SWIG_OK; +} +} + +/* double */ + %fragment(SWIG_From_frag(double),"header") { -SWIGINTERN +SWIGINTERN v8::Handle SWIG_From_dec(double) (double val) { return v8::Number::New(val); @@ -107,21 +177,15 @@ v8::Handle SWIG_From_dec(double) (double val) } %fragment(SWIG_AsVal_frag(double),"header") { -SWIGINTERN +SWIGINTERN int SWIG_AsVal_dec(double)(v8::Handle obj, double *val) { if(!obj->IsNumber()) { return SWIG_TypeError; } if(val) *val = obj->NumberValue(); - + return SWIG_OK; } } -%typemap(in) char * -%{ - v8::String::Utf8Value _$1($input); - $1 = *_$1; -%} - diff --git a/Lib/javascript/v8/javascripttypemaps.swg b/Lib/javascript/v8/javascripttypemaps.swg index 479a1f076..b12e5c899 100644 --- a/Lib/javascript/v8/javascripttypemaps.swg +++ b/Lib/javascript/v8/javascripttypemaps.swg @@ -1,16 +1,43 @@ -#define SWIG_Object v8::Handle -#define VOID_Object v8::Undefined() -#define SWIG_AppendOutput(result, obj) -#define SWIG_SetConstant(name, obj) -#define SWIG_Raise(obj, type, desc) SWIG_V8_Raise(type) +/* ------------------------------------------------------------ + * Typemap specializations for Javascript + * ------------------------------------------------------------ */ + +/* ------------------------------------------------------------ + * Fragment section + * ------------------------------------------------------------ */ /* Include fundamental fragemt definitions */ %include -/* Python fragments for fundamental types */ -%include - +/* Look for user fragments file. */ +%include + +/* Javascript fragments for fundamental types */ +%include + +/* Javascript fragments for char* strings */ %include + +/* ------------------------------------------------------------ + * Unified typemap section + * ------------------------------------------------------------ */ + +/* Javascript types */ + +#define SWIG_Object v8::Handle +#define VOID_Object v8::Undefined() + +/* Overload of the output/constant/exception/dirout handling */ + +/* append output */ +#define SWIG_AppendOutput(result, obj) + +/* set constant */ +#define SWIG_SetConstant(name, obj) + +/* raise */ +#define SWIG_Raise(obj, type, desc) SWIG_V8_Raise(type) + /* Include the unified typemap library */ %include From 3c5946d998f2bcecc88f04de8df7a6f3da292b32 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 9 Sep 2013 17:38:44 +0300 Subject: [PATCH 0305/1048] Redefined set of Javascript smoke tests. --- Examples/test-suite/javascript/Makefile.in | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index 49dd18054..ad08b2360 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -24,7 +24,8 @@ endif ifneq (,$(SMOKE)) C_TEST_CASES = \ - preproc + preproc \ + preproc_include CPP_TEST_CASES = \ abstract_access \ @@ -42,14 +43,9 @@ CPP_TEST_CASES = \ cpp_enum \ cpp_namespace \ cpp_static \ - director_alternating \ enum_template \ namespace_virtual_method \ overload_copy \ - rename1 \ - rename2 \ - rename3 \ - rename4 \ rename_simple \ rename_scope \ ret_by_value \ @@ -67,8 +63,7 @@ CPP_TEST_CASES = \ javascript_unicode BROKEN_TEST_CASES = \ - infinity \ - preproc_include + infinity SKIP_CPP_CASES = @SKIP_CPP_CASES@ SKIP_C_CASES = @SKIP_C_CASES@ From 571c516a0b096564b070350c9b90255db3422768 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 9 Sep 2013 22:25:51 +0300 Subject: [PATCH 0306/1048] Some fixes for the Javascript generator. - added missing `exception.i` - added missing generator block `wrappers` for v8 --- Lib/javascript/jsc/exception.i | 1 + Lib/javascript/v8/exception.i | 1 + Source/Modules/javascript.cxx | 1 + 3 files changed, 3 insertions(+) create mode 100644 Lib/javascript/jsc/exception.i create mode 100644 Lib/javascript/v8/exception.i diff --git a/Lib/javascript/jsc/exception.i b/Lib/javascript/jsc/exception.i new file mode 100644 index 000000000..0246cfde8 --- /dev/null +++ b/Lib/javascript/jsc/exception.i @@ -0,0 +1 @@ +%include diff --git a/Lib/javascript/v8/exception.i b/Lib/javascript/v8/exception.i new file mode 100644 index 000000000..0246cfde8 --- /dev/null +++ b/Lib/javascript/v8/exception.i @@ -0,0 +1 @@ +%include diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 5bd22f710..876978a42 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1875,6 +1875,7 @@ int V8Emitter::initialize(Node *n) Swig_register_filebyname("begin", f_wrap_cpp); Swig_register_filebyname("runtime", f_runtime); Swig_register_filebyname("header", f_header); + Swig_register_filebyname("wrapper", f_wrappers); Swig_register_filebyname("init", f_init); Swig_register_filebyname("post-init", f_post_init); From e5ad9cdc0527b21cbabaad02a22efd8418459d99 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 9 Sep 2013 22:26:30 +0300 Subject: [PATCH 0307/1048] Added two more Javascript tests. - `abstract_inherit` - `char_strings` --- .../javascript/abstract_inherit_runme.js | 40 +++++++++++++++++++ .../javascript/char_strings_runme.js | 11 +++++ 2 files changed, 51 insertions(+) create mode 100644 Examples/test-suite/javascript/abstract_inherit_runme.js create mode 100644 Examples/test-suite/javascript/char_strings_runme.js diff --git a/Examples/test-suite/javascript/abstract_inherit_runme.js b/Examples/test-suite/javascript/abstract_inherit_runme.js new file mode 100644 index 000000000..3af2eae74 --- /dev/null +++ b/Examples/test-suite/javascript/abstract_inherit_runme.js @@ -0,0 +1,40 @@ +var abstract_inherit = require("./abstract_inherit"); + +// Shouldn't be able to instantiate any of these classes +// since none of them implements the pure virtual function +// declared in the base class (Foo). +var Foo = abstract_inherit.Foo; +var Bar = abstract_inherit.Bar; +var Spam = abstract_inherit.Spam; + +var caughtException = false; +try { + new Foo(); +} catch (err) { + caughtException = true; +} +if (!caughtException) { + throw new Error("Foo should be instantiated as it is abstract"); +} + +caughtException = false; +try { + new Bar(); +} catch (err) { + caughtException = true; +} + +if (!caughtException) { + throw new Error("Bar should be instantiated as it is abstract"); +} + +caughtException = false; +try { + new Spam(); +} catch (err) { + caughtException = true; +} + +if (!caughtException) { + throw new Error("Spam should be instantiated as it is abstract"); +} diff --git a/Examples/test-suite/javascript/char_strings_runme.js b/Examples/test-suite/javascript/char_strings_runme.js new file mode 100644 index 000000000..fe17cb982 --- /dev/null +++ b/Examples/test-suite/javascript/char_strings_runme.js @@ -0,0 +1,11 @@ +var char_strings = require("char_strings"); + +var assertIsEqual = function(expected, actual) { + if (expected !== actual) { + throw new Error("Expected "+expected+", was "+actual); + } +}; + +assertIsEqual("hi there", char_strings.CharPingPong("hi there")); +assertIsEqual("hi there", char_strings.CharArrayPingPong("hi there")); +assertIsEqual("hi there", char_strings.CharArrayDimsPingPong("hi there")); From be35d94fdb8b274b443e2467d8a1b6d2dd0723c6 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 10 Sep 2013 11:53:12 +0300 Subject: [PATCH 0308/1048] Add support for PackedData to Javascript generator. --- Lib/javascript/jsc/javascriptcode.swg | 10 +- Lib/javascript/jsc/javascriptrun.swg | 255 +++++++++++++ Lib/javascript/jsc/javascriptruntime.swg | 181 +-------- Lib/javascript/jsc/javascripttypemaps.swg | 8 + Lib/javascript/v8/javascriptcode.swg | 1 - Lib/javascript/v8/javascriptrun.swg | 444 ++++++++++++++++++++++ Lib/javascript/v8/javascriptruntime.swg | 320 +--------------- 7 files changed, 718 insertions(+), 501 deletions(-) create mode 100644 Lib/javascript/jsc/javascriptrun.swg create mode 100644 Lib/javascript/v8/javascriptrun.swg diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index a55f24d33..2660e0e5e 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -107,7 +107,7 @@ JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size_t argc %{ void $jswrapper(JSObjectRef thisObject) { - SWIG_PRV_DATA* t = (SWIG_PRV_DATA*) JSObjectGetPrivate(thisObject); + SwigPrivData* t = (SwigPrivData*) JSObjectGetPrivate(thisObject); if(t && t->swigCMemOwn) free (($jstype)t->swigCObject); if(t) free(t); } @@ -123,7 +123,7 @@ void $jswrapper(JSObjectRef thisObject) %{ void $jswrapper(JSObjectRef thisObject) { - SWIG_PRV_DATA* t = (SWIG_PRV_DATA*) JSObjectGetPrivate(thisObject); + SwigPrivData* t = (SwigPrivData*) JSObjectGetPrivate(thisObject); if(t && t->swigCMemOwn) { $jstype arg1 = ($jstype)t->swigCObject; ${destructor_action} @@ -287,6 +287,12 @@ bool SWIGJSC_INIT (JSGlobalContextRef context, JSObjectRef *exports) { _SwigObject_objectDefinition.staticValues = _SwigObject_values; _SwigObject_classRef = JSClassCreate(&_SwigObject_objectDefinition); + /* Initialize the PackedData class */ + _SwigPackedData_objectDefinition.staticFunctions = _SwigPackedData_functions; + _SwigPackedData_objectDefinition.staticValues = _SwigPackedData_values; + _SwigPackedData_objectDefinition.finalize = _wrap_SwigPackedData_delete; + _SwigPackedData_classRef = JSClassCreate(&_SwigPackedData_objectDefinition); + /* Create objects for namespaces */ $jscreatenamespaces diff --git a/Lib/javascript/jsc/javascriptrun.swg b/Lib/javascript/jsc/javascriptrun.swg new file mode 100644 index 000000000..3038fcd71 --- /dev/null +++ b/Lib/javascript/jsc/javascriptrun.swg @@ -0,0 +1,255 @@ +/*****************************************************************************/ +/* Errors and exceptions +/* +/*****************************************************************************/ + +#define SWIG_Error(code, msg) SWIG_JSC_exception(context, exception, code, msg) +#define SWIG_exception(code, msg) SWIG_JSC_exception(context, exception, code, msg) +#define SWIG_fail goto fail + +void SWIG_Javascript_Raise(JSContextRef context, JSValueRef *exception, const char* type) { + JSStringRef message = JSStringCreateWithUTF8CString(type); + *exception = JSValueMakeString(context, message); + JSStringRelease(message); +} + +void SWIG_JSC_exception(JSContextRef context, JSValueRef *exception, int code, const char* msg) { + SWIG_Javascript_Raise(context, exception, msg); +} + +/*****************************************************************************/ +/* The parent class of all Proxies +/* +/*****************************************************************************/ + +typedef struct { + bool swigCMemOwn; + void *swigCObject; + swig_type_info *info; +} SwigPrivData; + +JSValueRef _wrap_SwigObject_disown(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + JSValueRef jsresult; + + JSObjectRef obj = JSValueToObject(context, thisObject, NULL); + SwigPrivData *cdata = (SwigPrivData *) JSObjectGetPrivate(obj); + + cdata->swigCMemOwn = false; + + jsresult = JSValueMakeUndefined(context); + return jsresult; +} + +JSValueRef _wrap_SwigObject_getCPtr(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + JSValueRef jsresult; + long result; + + JSObjectRef obj = JSValueToObject(context, thisObject, NULL); + SwigPrivData *cdata = (SwigPrivData*) JSObjectGetPrivate(obj); + + result = (long) cdata->swigCObject; + jsresult = JSValueMakeNumber(context, result); + + return jsresult; +} + +JSValueRef _wrap_SwigObject_equals(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + JSValueRef jsresult; + bool result; + + JSObjectRef obj = JSValueToObject(context, thisObject, NULL); + SwigPrivData *cdata = (SwigPrivData*) JSObjectGetPrivate(obj); + + JSObjectRef obj2 = JSValueToObject(context, argv[0], NULL); + SwigPrivData *cdata2 = (SwigPrivData*) JSObjectGetPrivate(obj2); + + result = (cdata->swigCObject == cdata2->swigCObject); + jsresult = JSValueMakeBoolean(context, result); + + return jsresult; +} + +JSStaticValue _SwigObject_values[] = { + { + 0, 0, 0, 0 + } +}; + +JSStaticFunction _SwigObject_functions[] = { + { + "disown",_wrap_SwigObject_disown, kJSPropertyAttributeNone + }, + { + "equals",_wrap_SwigObject_equals, kJSPropertyAttributeNone + }, + { + "getCPtr",_wrap_SwigObject_getCPtr, kJSPropertyAttributeNone + }, + { + 0, 0, 0 + } +}; + +JSClassDefinition _SwigObject_objectDefinition; + +JSClassRef _SwigObject_classRef; + + +int SWIG_JSC_ConvertInstancePtr(JSContextRef context, JSObjectRef objRef, void** ptr, swig_type_info *info, int flags) { + SwigPrivData *cdata = (SwigPrivData *) JSObjectGetPrivate(objRef); + if(cdata == NULL) { + return SWIG_ERROR; + } + if(cdata->info != info) { + bool type_valid = false; + swig_cast_info *t = info->cast; + while(t != NULL) { + if(t->type == cdata->info) { + type_valid = true; + break; + } + t = t->next; + } + if(!type_valid) { + return SWIG_TypeError; + } + } + + *ptr = cdata->swigCObject; + + if(flags & SWIG_POINTER_DISOWN) { + cdata->swigCMemOwn = false; + } + + return SWIG_OK; +} + +int SWIG_JSC_ConvertPtr(JSContextRef context, JSValueRef valRef, void** ptr, swig_type_info *info, int flags) { + if(!JSValueIsObject(context, valRef)) { + return SWIG_TypeError; + } + + JSObjectRef objRef = JSValueToObject(context, valRef, NULL); + if(objRef == NULL) { + return SWIG_ERROR; + } + + return SWIG_JSC_ConvertInstancePtr(context, objRef, ptr, info, flags); +} + +JSObjectRef SWIG_JSC_NewPointerObj(JSContextRef context, void *ptr, swig_type_info *info, int flags) { + + JSClassRef classRef; + if(info->clientdata == NULL) { + classRef = _SwigObject_classRef; + } else { + classRef = (JSClassRef) info->clientdata; + } + + JSObjectRef result = JSObjectMake(context, classRef, NULL); + + SwigPrivData* cdata = (SwigPrivData*) malloc(sizeof(SwigPrivData)); + cdata->swigCObject = ptr; + cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; + cdata->info = info; + + JSObjectSetPrivate(result, cdata); + + return result; +} + +#define SWIG_ConvertPtr(obj, ptr, info, flags) SWIG_JSC_ConvertPtr(context, obj, ptr, info, flags) +#define SWIG_NewPointerObj(ptr, info, flags) SWIG_JSC_NewPointerObj(context, ptr, info, flags) + +#define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_JSC_ConvertInstancePtr(context, obj, pptr, type, flags) +#define SWIG_NewInstanceObj(thisvalue, type, flags) SWIG_JSC_NewPointerObj(context, thisvalue, type, flags) + +/*****************************************************************************/ +/* A class for packed data +/* +/*****************************************************************************/ + +typedef struct { + void *data; + size_t size; + swig_type_info *type; +} SwigPackedData; + +JSStaticValue _SwigPackedData_values[] = { + { + 0, 0, 0, 0 + } +}; +JSStaticFunction _SwigPackedData_functions[] = { + { + 0, 0, 0 + } +}; +JSClassDefinition _SwigPackedData_objectDefinition; +JSClassRef _SwigPackedData_classRef; + +SWIGRUNTIMEINLINE +int SwigJSCPacked_Check(JSContextRef context, JSValueRef valRef) { + return JSValueIsObjectOfClass(context, valRef, _SwigPackedData_classRef); +} + +SWIGRUNTIME +swig_type_info* SwigJSCPacked_UnpackData(JSContextRef context, JSValueRef valRef, void *ptr, size_t size) { + if (SwigJSCPacked_Check(context, valRef)) { + JSObjectRef objRef = JSValueToObject(context, valRef, NULL); + SwigPackedData *sobj = (SwigPackedData *) JSObjectGetPrivate(objRef); + if (sobj->size != size) return 0; + memcpy(ptr, sobj->data, size); + return sobj->type; + } else { + return 0; + } +} + +SWIGRUNTIME +int SWIG_JSC_ConvertPacked(JSContextRef context, JSValueRef valRef, void *ptr, size_t sz, swig_type_info *ty) { + swig_type_info *to = SwigJSCPacked_UnpackData(context, valRef, 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; +} + +SWIGRUNTIME +JSValueRef SWIG_JSC_NewPackedObj(JSContextRef context, void *data, size_t size, swig_type_info *type) { + + JSClassRef classRef = _SwigObject_classRef; + JSObjectRef result = JSObjectMake(context, classRef, NULL); + + SwigPackedData* cdata = (SwigPackedData*) malloc(sizeof(SwigPackedData)); + cdata->data = data; + cdata->size = size; + cdata->type = type; + + JSObjectSetPrivate(result, cdata); + + return result; +} + +/* SwigPackedData wrappers */ + +void _wrap_SwigPackedData_delete(JSObjectRef obj) +{ + SwigPackedData* cdata = (SwigPackedData*) JSObjectGetPrivate(obj); + if (cdata) { + free(cdata->data); + } +} + +/* for C++ member pointers, ie, member methods */ + +#define SWIG_ConvertMember(obj, ptr, sz, ty) SWIG_JSC_ConvertPacked(context, obj, ptr, sz, ty) +#define SWIG_NewMemberObj(ptr, sz, type) SWIG_JSC_NewPackedObj(context, ptr, sz, type) diff --git a/Lib/javascript/jsc/javascriptruntime.swg b/Lib/javascript/jsc/javascriptruntime.swg index 88379415a..8f8390890 100644 --- a/Lib/javascript/jsc/javascriptruntime.swg +++ b/Lib/javascript/jsc/javascriptruntime.swg @@ -14,183 +14,6 @@ %} %insert(runtime) "swigrun.swg"; /* SWIG API */ -%insert(runtime) "swigerrors.swg"; /* SWIG errors */ +%insert(runtime) "swigerrors.swg"; /* SWIG errors */ -%insert(runtime) %{ -#define SWIG_Error(code, msg) SWIG_JSC_exception(context, exception, code, msg) -#define SWIG_exception(code, msg) SWIG_JSC_exception(context, exception, code, msg) -#define SWIG_fail goto fail - -#define SWIG_JSC_FROM_DECL_ARGS(arg1) (JSContextRef context, arg1) -#define SWIG_JSC_FROM_CALL_ARGS(arg1) (context, arg1) -#define SWIG_JSC_AS_DECL_ARGS(arg1, arg2) (JSContextRef context, arg1, arg2) -#define SWIG_JSC_AS_CALL_ARGS(arg1, arg2) (context, arg1, arg2) -%} - -%insert(runtime) %{ -typedef struct { - bool swigCMemOwn; - void *swigCObject; - swig_type_info *info; -}SWIG_PRV_DATA; -%} - -%insert(runtime) %{ - -void SWIG_Javascript_Raise(JSContextRef context, JSValueRef *exception, const char* type) { - JSStringRef message = JSStringCreateWithUTF8CString(type); - *exception = JSValueMakeString(context, message); - JSStringRelease(message); -} - -void SWIG_JSC_exception(JSContextRef context, JSValueRef *exception, int code, const char* msg) { - SWIG_Javascript_Raise(context, exception, msg); -} - -%} - -%insert(runtime) %{ - -JSValueRef _wrap_SwigObject_disown(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) -{ - JSValueRef jsresult; - - JSObjectRef obj = JSValueToObject(context, thisObject, NULL); - SWIG_PRV_DATA *cdata = (SWIG_PRV_DATA *) JSObjectGetPrivate(obj); - - cdata->swigCMemOwn = false; - - jsresult = JSValueMakeUndefined(context); - return jsresult; -} - -JSValueRef _wrap_SwigObject_getCPtr(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) -{ - JSValueRef jsresult; - long result; - - JSObjectRef obj = JSValueToObject(context, thisObject, NULL); - SWIG_PRV_DATA *cdata = (SWIG_PRV_DATA*) JSObjectGetPrivate(obj); - - result = (long) cdata->swigCObject; - jsresult = JSValueMakeNumber(context, result); - - return jsresult; -} - -JSValueRef _wrap_SwigObject_equals(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) -{ - JSValueRef jsresult; - bool result; - - JSObjectRef obj = JSValueToObject(context, thisObject, NULL); - SWIG_PRV_DATA *cdata = (SWIG_PRV_DATA*) JSObjectGetPrivate(obj); - - JSObjectRef obj2 = JSValueToObject(context, argv[0], NULL); - SWIG_PRV_DATA *cdata2 = (SWIG_PRV_DATA*) JSObjectGetPrivate(obj2); - - result = (cdata->swigCObject == cdata2->swigCObject); - jsresult = JSValueMakeBoolean(context, result); - - return jsresult; -} - -JSStaticValue _SwigObject_values[] = { - { - 0, 0, 0, 0 - } -}; - -JSStaticFunction _SwigObject_functions[] = { - { - "disown",_wrap_SwigObject_disown, kJSPropertyAttributeNone - }, - { - "equals",_wrap_SwigObject_equals, kJSPropertyAttributeNone - }, - { - "getCPtr",_wrap_SwigObject_getCPtr, kJSPropertyAttributeNone - }, - { - 0, 0, 0 - } -}; - -JSClassDefinition _SwigObject_objectDefinition; - -JSClassRef _SwigObject_classRef; - -%} - - -%insert(runtime) %{ -int SWIG_JSC_ConvertInstancePtr(JSContextRef context, JSObjectRef objRef, void** ptr, swig_type_info *info, int flags) { - SWIG_PRV_DATA *cdata = (SWIG_PRV_DATA *) JSObjectGetPrivate(objRef); - if(cdata == NULL) { - return SWIG_ERROR; - } - if(cdata->info != info) { - bool type_valid = false; - swig_cast_info *t = info->cast; - while(t != NULL) { - if(t->type == cdata->info) { - type_valid = true; - break; - } - t = t->next; - } - if(!type_valid) { - return SWIG_TypeError; - } - } - - *ptr = cdata->swigCObject; - - if(flags & SWIG_POINTER_DISOWN) { - cdata->swigCMemOwn = false; - } - - return SWIG_OK; -} - -int SWIG_JSC_ConvertPtr(JSContextRef context, JSValueRef valRef, void** ptr, swig_type_info *info, int flags) { - if(!JSValueIsObject(context, valRef)) { - return SWIG_TypeError; - } - - JSObjectRef objRef = JSValueToObject(context, valRef, NULL); - if(objRef == NULL) { - return SWIG_ERROR; - } - - return SWIG_JSC_ConvertInstancePtr(context, objRef, ptr, info, flags); -} - -JSObjectRef SWIG_JSC_NewPointerObj(JSContextRef context, void *ptr, swig_type_info *info, int flags) { - - JSClassRef classRef; - if(info->clientdata == NULL) { - classRef = _SwigObject_classRef; - } else { - classRef = (JSClassRef) info->clientdata; - } - - JSObjectRef result = JSObjectMake(context, classRef, NULL); - - SWIG_PRV_DATA* cdata = (SWIG_PRV_DATA*) malloc(sizeof(SWIG_PRV_DATA)); - cdata->swigCObject = ptr; - cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; - cdata->info = info; - - JSObjectSetPrivate(result, cdata); - - return result; -} - -#define SWIG_ConvertPtr(obj, ptr, info, flags) SWIG_JSC_ConvertPtr(context, obj, ptr, info, flags) -#define SWIG_NewPointerObj(ptr, info, flags) SWIG_JSC_NewPointerObj(context, ptr, info, flags) - -#define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_JSC_ConvertInstancePtr(context, obj, pptr, type, flags) -#define SWIG_NewInstanceObj(thisvalue, type, flags) SWIG_JSC_NewPointerObj(context, thisvalue, type, flags) - -%} +%insert(runtime) "javascriptrun.swg"; /* SWIG errors */ diff --git a/Lib/javascript/jsc/javascripttypemaps.swg b/Lib/javascript/jsc/javascripttypemaps.swg index aa0a829f9..12e78dc2f 100644 --- a/Lib/javascript/jsc/javascripttypemaps.swg +++ b/Lib/javascript/jsc/javascripttypemaps.swg @@ -8,6 +8,7 @@ /* These macros are necessary to provide an extra parameter to SWIG_AsVal_dec functions (JSContextRef context). + They must be defined before including `typemaps/fragments.swg` */ #define SWIG_FROM_DECL_ARGS SWIG_JSC_FROM_DECL_ARGS #define SWIG_FROM_CALL_ARGS SWIG_JSC_FROM_CALL_ARGS @@ -42,5 +43,12 @@ /* raise */ #define SWIG_Raise(obj, type, desc) SWIG_Javascript_Raise(context, exception, type) +%insert("runtime") %{ +#define SWIG_JSC_FROM_DECL_ARGS(arg1) (JSContextRef context, arg1) +#define SWIG_JSC_FROM_CALL_ARGS(arg1) (context, arg1) +#define SWIG_JSC_AS_DECL_ARGS(arg1, arg2) (JSContextRef context, arg1, arg2) +#define SWIG_JSC_AS_CALL_ARGS(arg1, arg2) (context, arg1, arg2) +%} + /* Include the unified typemap library */ %include diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index d12f56f09..58ed18d0d 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -137,7 +137,6 @@ void $jswrapper(v8::Isolate *isolate, v8::Persistent< v8::Object > * object, SWI } delete proxy; - object.Clear(); #if (SWIG_V8_VERSION < 0x031900) object.Dispose(); diff --git a/Lib/javascript/v8/javascriptrun.swg b/Lib/javascript/v8/javascriptrun.swg new file mode 100644 index 000000000..227977b16 --- /dev/null +++ b/Lib/javascript/v8/javascriptrun.swg @@ -0,0 +1,444 @@ +/* ---------------------------------------------------------------------------*/ +/* Error handling +/* +/* ---------------------------------------------------------------------------*/ + +#define SWIG_Error(code, msg) SWIGV8_ErrorHandler.error(code, msg) +#define SWIG_exception(code, msg) SWIGV8_ErrorHandler.error(code, msg) +#define SWIG_fail goto fail +#define SWIGV8_OVERLOAD false + +void SWIG_V8_Raise(const char* msg) { + v8::ThrowException(v8::Exception::Error(v8::String::New(msg))); +} + +/* + Note: There are two contexts for handling errors. + A static V8ErrorHandler is used in not overloaded methods. + For overloaded methods the throwing type checking mechanism is used + during dispatching. As V8 exceptions can not be resetted properly + the trick is to use a dynamic ErrorHandler with same local name as the global + one. + + - See defintion of SWIG_Error above. + - See code templates 'JS_function_dispatcher', 'JS_functionwrapper_overload', + and 'JS_function_dispatch_case' in javascriptcode.swg + +*/ +class V8ErrorHandler { +public: + virtual ~V8ErrorHandler() {} + virtual void error(int code, const char* msg) { + SWIG_V8_Raise(msg); + } +}; +// this is used in usually +V8ErrorHandler SWIGV8_ErrorHandler; + +// instances of this are used in overloaded functions +class OverloadErrorHandler: public V8ErrorHandler { +public: + virtual void error(int code, const char* msg) { + err = v8::Exception::Error(v8::String::New(msg)); + if(code != SWIG_TypeError) { + v8::ThrowException(err); + } + } + v8::Handle err; +}; + +// Note: these typedefs and defines are used to deal with v8 API changes since version 3.19.00 + +#if (SWIG_V8_VERSION < 0x031900) +typedef v8::Handle SwigV8ReturnValue; +typedef v8::Arguments SwigV8Arguments; +typedef v8::AccessorInfo SwigV8PropertyCallbackInfo; +#define SWIGV8_RETURN(val) return scope.Close(val) +#define SWIGV8_RETURN_INFO(val, info) return scope.Close(val) +#else +typedef void SwigV8ReturnValue; +typedef v8::FunctionCallbackInfo SwigV8Arguments; +typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfo; +#define SWIGV8_RETURN(val) args.GetReturnValue().Set(val); return +#define SWIGV8_RETURN_INFO(val, info) info.GetReturnValue().Set(val); return +#endif + + +/* ---------------------------------------------------------------------------*/ +/* Basic Proxy object +/* +/* ---------------------------------------------------------------------------*/ + +// Note: to trigger the v8 gc more often one can tell v8 about the memory consumption +// TODO: we could add a v8 specific parameter to control this value +#define SWIGV8_AVG_OBJ_SIZE 1000 + +class SWIGV8_Proxy { +public: + SWIGV8_Proxy(): swigCMemOwn(false), swigCObject(0), info(0) { + v8::V8::AdjustAmountOfExternalAllocatedMemory(SWIGV8_AVG_OBJ_SIZE); + }; + + ~SWIGV8_Proxy() { +#if (SWIG_V8_VERSION < 0x031900 || SWIG_V8_VERSION >= 0x032100) + handle.ClearWeak(); + handle.Dispose(); +#else + handle.ClearWeak(v8::Isolate::GetCurrent()); + handle.Dispose(v8::Isolate::GetCurrent()); +#endif + + handle.Clear(); + v8::V8::AdjustAmountOfExternalAllocatedMemory(-SWIGV8_AVG_OBJ_SIZE); + } + + bool swigCMemOwn; + void *swigCObject; + swig_type_info *info; + v8::Persistent handle; +}; + +class SWIGV8_ClientData { +public: + v8::Persistent class_templ; + +#if (SWIG_V8_VERSION < 0x031900) + void (*dtor) (v8::Persistent< v8::Value> object, void *parameter); +#else + void (*dtor) (v8::Isolate *isolate, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy); +#endif +}; + +v8::Persistent SWIGV8_SWIGTYPE_Proxy_class_templ; + +int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_type_info *info, int flags) { + v8::HandleScope scope; + + if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; + +#if (SWIG_V8_VERSION < 0x031900) + v8::Handle cdataRef = objRef->GetInternalField(0); + SWIGV8_Proxy *cdata = static_cast(v8::External::Unwrap(cdataRef)); +#else + SWIGV8_Proxy *cdata = static_cast(objRef->GetAlignedPointerFromInternalField(0)); +#endif + + if(cdata == NULL) { + return SWIG_ERROR; + } + if(cdata->info != info) { + swig_cast_info *tc = SWIG_TypeCheckStruct(cdata->info, info); + if (!tc && cdata->info->name) { + tc = SWIG_TypeCheck(cdata->info->name, info); + } + bool type_valid = tc != 0; + if(!type_valid) { + return SWIG_TypeError; + } + } + *ptr = cdata->swigCObject; + if(flags & SWIG_POINTER_DISOWN) { + cdata->swigCMemOwn = false; + } + return SWIG_OK; +} + +#if (SWIG_V8_VERSION < 0x031900) +void SWIGV8_Proxy_DefaultDtor(v8::Persistent< v8::Value > object, void *parameter) +#else +void SWIGV8_Proxy_DefaultDtor(v8::Isolate *, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy) +#endif +{ +#if (SWIG_V8_VERSION < 0x031900) + SWIGV8_Proxy *proxy = static_cast(parameter); +#endif + + delete proxy; +} + +int SWIG_V8_GetInstancePtr(v8::Handle valRef, void** ptr) { + if(!valRef->IsObject()) { + return SWIG_TypeError; + } + v8::Handle objRef = valRef->ToObject(); + + if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; + +#if (SWIG_V8_VERSION < 0x031900) + v8::Handle cdataRef = objRef->GetInternalField(0); + SWIGV8_Proxy *cdata = static_cast(v8::External::Unwrap(cdataRef)); +#else + SWIGV8_Proxy *cdata = static_cast(objRef->GetAlignedPointerFromInternalField(0)); +#endif + + if(cdata == NULL) { + return SWIG_ERROR; + } + + *ptr = cdata->swigCObject; + + return SWIG_OK; +} + +void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info *info, int flags) { + SWIGV8_Proxy* cdata = new SWIGV8_Proxy(); + cdata->swigCObject = ptr; + cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; + cdata->info = info; + +#if (SWIG_V8_VERSION < 0x031900) + obj->SetPointerInInternalField(0, cdata); + cdata->handle = v8::Persistent::New(obj); +#else + obj->SetAlignedPointerInInternalField(0, cdata); + cdata->handle.Reset(v8::Isolate::GetCurrent(), obj); +#endif + +#if (SWIG_V8_VERSION < 0x031900) + // clientdata must be set for owned data as we need to register the dtor + if(cdata->swigCMemOwn && (SWIGV8_ClientData*)info->clientdata) { + cdata->handle.MakeWeak(cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); + } else { + cdata->handle.MakeWeak(cdata, SWIGV8_Proxy_DefaultDtor); + } + cdata->handle.MarkIndependent(); +#else + if(cdata->swigCMemOwn && (SWIGV8_ClientData*)info->clientdata) { + cdata->handle.MakeWeak(v8::Isolate::GetCurrent(), cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); + } else { + cdata->handle.MakeWeak(v8::Isolate::GetCurrent(), cdata, SWIGV8_Proxy_DefaultDtor); + } + +#if (SWIG_V8_VERSION < 0x032100) + cdata->handle.MarkIndependent(v8::Isolate::GetCurrent()); +#else + cdata->handle.MarkIndependent(); +#endif + +#endif +} + +int SWIG_V8_ConvertPtr(v8::Handle valRef, void** ptr, swig_type_info *info, int flags) { + v8::HandleScope scope; + + if(!valRef->IsObject()) { + return SWIG_TypeError; + } + v8::Handle objRef = valRef->ToObject(); + return SWIG_V8_ConvertInstancePtr(objRef, ptr, info, flags); +} + +v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, int flags) { + v8::HandleScope scope; + v8::Handle class_templ; + +#if (SWIG_V8_VERSION < 0x031900) + if(info->clientdata != 0) { + class_templ = ((SWIGV8_ClientData*) info->clientdata)->class_templ; + } else { + class_templ = SWIGV8_SWIGTYPE_Proxy_class_templ; + } +#else + v8::Isolate *iso = v8::Isolate::GetCurrent(); + + if(info->clientdata != 0) { + class_templ = v8::Handle::New(iso, ((SWIGV8_ClientData*) info->clientdata)->class_templ); + } else { + class_templ = v8::Handle::New(iso, SWIGV8_SWIGTYPE_Proxy_class_templ); + } +#endif + + v8::Handle result = class_templ->InstanceTemplate()->NewInstance(); + SWIGV8_SetPrivateData(result, ptr, info, flags); + + return scope.Close(result); +} + +#define SWIG_ConvertPtr(obj, ptr, info, flags) SWIG_V8_ConvertPtr(obj, ptr, info, flags) +#define SWIG_NewPointerObj(ptr, info, flags) SWIG_V8_NewPointerObj(ptr, info, flags) + +#define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_V8_ConvertInstancePtr(obj, pptr, type, flags) +#define SWIG_NewInstanceObj(thisvalue, type, flags) SWIG_V8_NewPointerObj(thisvalue, type, flags) + +#define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_V8_ConvertPtr(obj, pptr, type, 0) +#define SWIG_NewFunctionPtrObj(ptr, type) SWIG_V8_NewPointerObj(ptr, type, 0) + +#define SWIG_GetInstancePtr(obj, ptr) SWIG_V8_GetInstancePtr(obj, ptr) + +#if (SWIG_V8_VERSION < 0x031900) +v8::Handle _SWIGV8_wrap_equals(const v8::Arguments &args) { +#else +void _SWIGV8_wrap_equals(const v8::FunctionCallbackInfo& args) { +#endif + v8::HandleScope scope; + v8::Handle jsresult; + void *arg1 = (void *) 0 ; + void *arg2 = (void *) 0 ; + bool result; + int res1; + int res2; + + if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for equals."); + + res1 = SWIG_GetInstancePtr(args.Holder(), &arg1); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ERROR, "Could not get pointer from 'this' object for equals."); + } + res2 = SWIG_GetInstancePtr(args[0], &arg2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "equals" "', argument " "1"" of type '" "void *""'"); + } + + result = (bool)(arg1 == arg2); + jsresult = v8::Boolean::New(result); + + SWIGV8_RETURN(jsresult); + goto fail; +fail: + SWIGV8_RETURN(v8::Undefined()); +} + +#if (SWIG_V8_VERSION < 0x031900) +v8::Handle _wrap_getCPtr(const v8::Arguments &args) { +#else +void _wrap_getCPtr(const v8::FunctionCallbackInfo& args) { +#endif + v8::HandleScope scope; + v8::Handle jsresult; + void *arg1 = (void *) 0 ; + long result; + int res1; + + res1 = SWIG_GetInstancePtr(args.Holder(), &arg1); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "getCPtr" "', argument " "1"" of type '" "void *""'"); + } + + result = (long)arg1; + jsresult = v8::Number::New(result); + + SWIGV8_RETURN(jsresult); + goto fail; +fail: + SWIGV8_RETURN(v8::Undefined()); +} + +/* ---------------------------------------------------------------------------*/ +/* PackedData object +/* +/* ---------------------------------------------------------------------------*/ + +class SwigV8PackedData { +public: + SwigV8PackedData(void *data, size_t size, swig_type_info *type): data(data), size(size), type(type) {}; + + ~SwigV8PackedData() { + }; + + void* data; + size_t size; + swig_type_info *type; + + v8::Persistent handle; +}; + +SWIGRUNTIMEINLINE +int SwigV8Packed_Check(v8::Handle valRef) { + v8::HandleScope scope; + v8::Handle objRef = valRef->ToObject(); + if(objRef->InternalFieldCount() < 1) return false; + v8::Handle flag = objRef->GetHiddenValue(v8::String::New("__swig__packed_data__")); + return (flag->IsBoolean() && flag->BooleanValue()); +} + +SWIGRUNTIME +swig_type_info* SwigV8Packed_UnpackData(v8::Handle valRef, void *ptr, size_t size) { + if (SwigV8Packed_Check(valRef)) { + v8::HandleScope scope; + SwigV8PackedData *sobj; + + v8::Handle objRef = valRef->ToObject(); + +#if (SWIG_V8_VERSION < 0x031900) + v8::Handle cdataRef = objRef->GetInternalField(0); + sobj = static_cast(v8::External::Unwrap(cdataRef)); +#else + sobj = static_cast(objRef->GetAlignedPointerFromInternalField(0)); +#endif + if (sobj == NULL || sobj->size != size) return 0; + memcpy(ptr, sobj->data, size); + return sobj->type; + } else { + return 0; + } +} + +SWIGRUNTIME +int SWIGV8_ConvertPacked(v8::Handle valRef, void *ptr, size_t sz, swig_type_info *ty) { + swig_type_info *to = SwigV8Packed_UnpackData(valRef, ptr, sz); + if (!to) return SWIG_ERROR; + if (ty) { + if (to != ty) { + /* check type cast? */ + swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); + if (!tc) return SWIG_ERROR; + } + } + return SWIG_OK; +} + +#if (SWIG_V8_VERSION < 0x031900) +void _wrap_SwigV8PackedData_delete(v8::Persistent< v8::Value > object, void *parameter) +{ + SwigV8PackedData *cdata = static_cast(parameter); +#else +void _wrap_SwigV8PackedData_delete(v8::Isolate *isolate, v8::Persistent< v8::Object > * object, SwigV8PackedData *proxy) +{ +#endif + + delete cdata; + + object.Clear(); +#if (SWIG_V8_VERSION < 0x031900) + object.Dispose(); +#elif (SWIG_V8_VERSION < 0x032100) + object->Dispose(isolate); +#else + object->Dispose(); +#endif +} + +SWIGRUNTIME +v8::Handle SWIGV8_NewPackedObj(void *data, size_t size, swig_type_info *type) { + v8::HandleScope scope; + + SwigV8PackedData* cdata = new SwigV8PackedData(data, size, type); + v8::Handle obj = v8::Object::New(); + + obj->SetHiddenValue(v8::String::New("__swig__packed_data__"), v8::Boolean::New(true)); + +#if (SWIG_V8_VERSION < 0x031900) + obj->SetPointerInInternalField(0, cdata); + cdata->handle = v8::Persistent::New(obj); +#else + obj->SetAlignedPointerInInternalField(0, cdata); + cdata->handle.Reset(v8::Isolate::GetCurrent(), obj); +#endif + +#if (SWIG_V8_VERSION < 0x031900) + cdata->handle.MakeWeak(cdata, _wrap_SwigV8PackedData_delete); + cdata->handle.MarkIndependent(); +#else + cdata->handle.MakeWeak(v8::Isolate::GetCurrent(), cdata, _wrap_SwigV8PackedData_delete); +# if (SWIG_V8_VERSION < 0x032100) + cdata->handle.MarkIndependent(v8::Isolate::GetCurrent()); +# else + cdata->handle.MarkIndependent(); +# endif +#endif + + return scope.Close(obj); +} + +#define SWIG_ConvertMember(obj, ptr, sz, ty) SWIGV8_ConvertPacked(obj, ptr, sz, ty) +#define SWIG_NewMemberObj(ptr, sz, type) SWIGV8_NewPackedObj(ptr, sz, type) diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index c34b62108..8df5816a9 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -1,7 +1,6 @@ /* ----------------------------------------------------------------------------- * javascriptruntime.swg * - * Javascript support code * ----------------------------------------------------------------------------- */ %define %swig_v8_define_version(version) @@ -35,322 +34,5 @@ %insert(runtime) "swigrun.swg"; /* SWIG API */ %insert(runtime) "swigerrors.swg"; /* SWIG errors */ -%insert(runtime) %{ -#if (SWIG_V8_VERSION < 0x031900) -typedef v8::Handle SwigV8ReturnValue; -typedef v8::Arguments SwigV8Arguments; -typedef v8::AccessorInfo SwigV8PropertyCallbackInfo; -#define SWIGV8_RETURN(val) return scope.Close(val) -#define SWIGV8_RETURN_INFO(val, info) return scope.Close(val) -#else -typedef void SwigV8ReturnValue; -typedef v8::FunctionCallbackInfo SwigV8Arguments; -typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfo; -#define SWIGV8_RETURN(val) args.GetReturnValue().Set(val); return -#define SWIGV8_RETURN_INFO(val, info) info.GetReturnValue().Set(val); return -#endif -%} +%insert(runtime) "javascriptrun.swg" -%insert(runtime) %{ -#define SWIG_Error(code, msg) SWIGV8_ErrorHandler.error(code, msg) -#define SWIG_exception(code, msg) SWIGV8_ErrorHandler.error(code, msg) -#define SWIG_fail goto fail -#define SWIGV8_OVERLOAD false - -void SWIG_V8_Raise(const char* msg) { - v8::ThrowException(v8::Exception::Error(v8::String::New(msg))); -} - -/* - Note: There are two contexts for handling errors. - A static V8ErrorHandler is used in not overloaded methods. - For overloaded methods the throwing type checking mechanism is used - during dispatching. As V8 exceptions can not be resetted properly - the trick is to use a dynamic ErrorHandler with same local name as the global - one. - - - See defintion of SWIG_Error above. - - See code templates 'JS_function_dispatcher', 'JS_functionwrapper_overload', - and 'JS_function_dispatch_case' in javascriptcode.swg - -*/ -class V8ErrorHandler { -public: - virtual ~V8ErrorHandler() {} - virtual void error(int code, const char* msg) { - SWIG_V8_Raise(msg); - } -}; -// this is used in usually -V8ErrorHandler SWIGV8_ErrorHandler; - -// instances of this are used in overloaded functions -class OverloadErrorHandler: public V8ErrorHandler { -public: - virtual void error(int code, const char* msg) { - err = v8::Exception::Error(v8::String::New(msg)); - if(code != SWIG_TypeError) { - v8::ThrowException(err); - } - } - v8::Handle err; -}; -%} - -%insert(runtime) %{ - -// Note: to trigger the v8 gc more often one can tell v8 about the memory consumption -// TODO: we could add a v8 specific parameter to control this value -#define SWIGV8_AVG_OBJ_SIZE 1000 - -class SWIGV8_Proxy { -public: - SWIGV8_Proxy(): swigCMemOwn(false), swigCObject(0), info(0) { - v8::V8::AdjustAmountOfExternalAllocatedMemory(SWIGV8_AVG_OBJ_SIZE); - }; - - ~SWIGV8_Proxy() { -#if (SWIG_V8_VERSION < 0x031900 || SWIG_V8_VERSION >= 0x032100) - handle.ClearWeak(); - handle.Dispose(); -#else - handle.ClearWeak(v8::Isolate::GetCurrent()); - handle.Dispose(v8::Isolate::GetCurrent()); -#endif - - handle.Clear(); - v8::V8::AdjustAmountOfExternalAllocatedMemory(-SWIGV8_AVG_OBJ_SIZE); - } - - bool swigCMemOwn; - void *swigCObject; - swig_type_info *info; - v8::Persistent handle; -}; - -class SWIGV8_ClientData { -public: - v8::Persistent class_templ; - -#if (SWIG_V8_VERSION < 0x031900) - void (*dtor) (v8::Persistent< v8::Value> object, void *parameter); -#else - void (*dtor) (v8::Isolate *isolate, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy); -#endif -}; - -v8::Persistent SWIGV8_SWIGTYPE_Proxy_class_templ; - -int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_type_info *info, int flags) { - v8::HandleScope scope; - - if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; - -#if (SWIG_V8_VERSION < 0x031900) - v8::Handle cdataRef = objRef->GetInternalField(0); - SWIGV8_Proxy *cdata = static_cast(v8::External::Unwrap(cdataRef)); -#else - SWIGV8_Proxy *cdata = static_cast(objRef->GetAlignedPointerFromInternalField(0)); -#endif - - if(cdata == NULL) { - return SWIG_ERROR; - } - if(cdata->info != info) { - swig_cast_info *tc = SWIG_TypeCheckStruct(cdata->info, info); - if (!tc && cdata->info->name) { - tc = SWIG_TypeCheck(cdata->info->name, info); - } - bool type_valid = tc != 0; - if(!type_valid) { - return SWIG_TypeError; - } - } - *ptr = cdata->swigCObject; - if(flags & SWIG_POINTER_DISOWN) { - cdata->swigCMemOwn = false; - } - return SWIG_OK; -} - -#if (SWIG_V8_VERSION < 0x031900) -void SWIGV8_Proxy_DefaultDtor(v8::Persistent< v8::Value > object, void *parameter) -#else -void SWIGV8_Proxy_DefaultDtor(v8::Isolate *, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy) -#endif -{ -#if (SWIG_V8_VERSION < 0x031900) - SWIGV8_Proxy *proxy = static_cast(parameter); -#endif - - delete proxy; -} - -int SWIG_V8_GetInstancePtr(v8::Handle valRef, void** ptr) { - if(!valRef->IsObject()) { - return SWIG_TypeError; - } - v8::Handle objRef = valRef->ToObject(); - - if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; - -#if (SWIG_V8_VERSION < 0x031900) - v8::Handle cdataRef = objRef->GetInternalField(0); - SWIGV8_Proxy *cdata = static_cast(v8::External::Unwrap(cdataRef)); -#else - SWIGV8_Proxy *cdata = static_cast(objRef->GetAlignedPointerFromInternalField(0)); -#endif - - if(cdata == NULL) { - return SWIG_ERROR; - } - - *ptr = cdata->swigCObject; - - return SWIG_OK; -} - -void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info *info, int flags) { - SWIGV8_Proxy* cdata = new SWIGV8_Proxy(); - cdata->swigCObject = ptr; - cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; - cdata->info = info; - -#if (SWIG_V8_VERSION < 0x031900) - obj->SetPointerInInternalField(0, cdata); - cdata->handle = v8::Persistent::New(obj); -#else - obj->SetAlignedPointerInInternalField(0, cdata); - cdata->handle.Reset(v8::Isolate::GetCurrent(), obj); -#endif - -#if (SWIG_V8_VERSION < 0x031900) - // clientdata must be set for owned data as we need to register the dtor - if(cdata->swigCMemOwn && (SWIGV8_ClientData*)info->clientdata) { - cdata->handle.MakeWeak(cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); - } else { - cdata->handle.MakeWeak(cdata, SWIGV8_Proxy_DefaultDtor); - } - cdata->handle.MarkIndependent(); -#else - if(cdata->swigCMemOwn && (SWIGV8_ClientData*)info->clientdata) { - cdata->handle.MakeWeak(v8::Isolate::GetCurrent(), cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); - } else { - cdata->handle.MakeWeak(v8::Isolate::GetCurrent(), cdata, SWIGV8_Proxy_DefaultDtor); - } - -# if (SWIG_V8_VERSION < 0x032100) - cdata->handle.MarkIndependent(v8::Isolate::GetCurrent()); -# else - cdata->handle.MarkIndependent(); -# endif - -#endif -} - -int SWIG_V8_ConvertPtr(v8::Handle valRef, void** ptr, swig_type_info *info, int flags) { - v8::HandleScope scope; - - if(!valRef->IsObject()) { - return SWIG_TypeError; - } - v8::Handle objRef = valRef->ToObject(); - return SWIG_V8_ConvertInstancePtr(objRef, ptr, info, flags); -} - -v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, int flags) { - v8::HandleScope scope; - v8::Handle class_templ; - - -#if (SWIG_V8_VERSION < 0x031900) - if(info->clientdata != 0) { - class_templ = ((SWIGV8_ClientData*) info->clientdata)->class_templ; - } else { - class_templ = SWIGV8_SWIGTYPE_Proxy_class_templ; - } -#else - v8::Isolate *iso = v8::Isolate::GetCurrent(); - - if(info->clientdata != 0) { - class_templ = v8::Handle::New(iso, ((SWIGV8_ClientData*) info->clientdata)->class_templ); - } else { - class_templ = v8::Handle::New(iso, SWIGV8_SWIGTYPE_Proxy_class_templ); - } -#endif - - v8::Handle result = class_templ->InstanceTemplate()->NewInstance(); - SWIGV8_SetPrivateData(result, ptr, info, flags); - - return scope.Close(result); -} - -#define SWIG_ConvertPtr(obj, ptr, info, flags) SWIG_V8_ConvertPtr(obj, ptr, info, flags) -#define SWIG_NewPointerObj(ptr, info, flags) SWIG_V8_NewPointerObj(ptr, info, flags) - -#define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_V8_ConvertInstancePtr(obj, pptr, type, flags) -#define SWIG_NewInstanceObj(thisvalue, type, flags) SWIG_V8_NewPointerObj(thisvalue, type, flags) - -#define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_V8_ConvertPtr(obj, pptr, type, 0) -#define SWIG_NewFunctionPtrObj(ptr, type) SWIG_V8_NewPointerObj(ptr, type, 0) - -#define SWIG_GetInstancePtr(obj, ptr) SWIG_V8_GetInstancePtr(obj, ptr) - -#if (SWIG_V8_VERSION < 0x031900) -v8::Handle _SWIGV8_wrap_equals(const v8::Arguments &args) { -#else -void _SWIGV8_wrap_equals(const v8::FunctionCallbackInfo& args) { -#endif - v8::HandleScope scope; - v8::Handle jsresult; - void *arg1 = (void *) 0 ; - void *arg2 = (void *) 0 ; - bool result; - int res1; - int res2; - - if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for equals."); - - res1 = SWIG_GetInstancePtr(args.Holder(), &arg1); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ERROR, "Could not get pointer from 'this' object for equals."); - } - res2 = SWIG_GetInstancePtr(args[0], &arg2); - if (!SWIG_IsOK(res2)) { - SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "equals" "', argument " "1"" of type '" "void *""'"); - } - - result = (bool)(arg1 == arg2); - jsresult = v8::Boolean::New(result); - - SWIGV8_RETURN(jsresult); - goto fail; -fail: - SWIGV8_RETURN(v8::Undefined()); -} - -#if (SWIG_V8_VERSION < 0x031900) -v8::Handle _wrap_getCPtr(const v8::Arguments &args) { -#else -void _wrap_getCPtr(const v8::FunctionCallbackInfo& args) { -#endif - v8::HandleScope scope; - v8::Handle jsresult; - void *arg1 = (void *) 0 ; - long result; - int res1; - - res1 = SWIG_GetInstancePtr(args.Holder(), &arg1); - if (!SWIG_IsOK(res1)) { - SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "getCPtr" "', argument " "1"" of type '" "void *""'"); - } - - result = (long)arg1; - jsresult = v8::Number::New(result); - - SWIGV8_RETURN(jsresult); - goto fail; -fail: - SWIGV8_RETURN(v8::Undefined()); -} -%} From 001f38c6a9ebd19dee26196e9b0ee2421b8cbe5f Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 10 Sep 2013 13:29:16 +0300 Subject: [PATCH 0309/1048] Fix settings for building nodejs tests. Removed the `-node` command line flag. Instead one has to use `-v8 -DBUILDING_NODE_EXTENSION=1`. --- Examples/test-suite/javascript/Makefile.in | 2 +- .../javascript/node_template/binding.gyp.in | 3 +++ Lib/javascript/jsc/javascriptrun.swg | 24 +++++++++---------- Lib/javascript/v8/javascriptrun.swg | 24 +++++++++---------- Source/Modules/javascript.cxx | 7 ------ 5 files changed, 28 insertions(+), 32 deletions(-) diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index ad08b2360..48ce7cdbb 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -88,7 +88,7 @@ ifeq ("node",$(JSENGINE)) __setup = \ if [ ! -f $(srcdir)/$*/binding.gyp ]; then \ sh ./setup_test.sh $*; \ - $(SWIG) -c++ -javascript -node -o $*/$*_wrap.cxx ../$*.i; \ + $(SWIG) -c++ -javascript -v8 -DBUILDING_NODE_EXTENSION=1 -I$(top_srcdir)/Examples/test-suite -includeall -o $*/$*_wrap.cxx ../$*.i; \ fi nodejs_swig_and_compile = \ diff --git a/Examples/test-suite/javascript/node_template/binding.gyp.in b/Examples/test-suite/javascript/node_template/binding.gyp.in index 2895d3080..dffd52c6c 100644 --- a/Examples/test-suite/javascript/node_template/binding.gyp.in +++ b/Examples/test-suite/javascript/node_template/binding.gyp.in @@ -4,6 +4,9 @@ "target_name": "$testcase", "sources":[ "$testcase_wrap.cxx" ], "include_dirs": ["../.."], + 'defines': [ + 'BUILDING_NODE_EXTENSION=1', + ], 'conditions': [ ['OS=="mac"', { diff --git a/Lib/javascript/jsc/javascriptrun.swg b/Lib/javascript/jsc/javascriptrun.swg index 3038fcd71..c8f16f36f 100644 --- a/Lib/javascript/jsc/javascriptrun.swg +++ b/Lib/javascript/jsc/javascriptrun.swg @@ -1,7 +1,7 @@ -/*****************************************************************************/ -/* Errors and exceptions -/* -/*****************************************************************************/ +/* ---------------------------------------------------------------------------- + * Errors and exceptions + * + * ---------------------------------------------------------------------------*/ #define SWIG_Error(code, msg) SWIG_JSC_exception(context, exception, code, msg) #define SWIG_exception(code, msg) SWIG_JSC_exception(context, exception, code, msg) @@ -17,10 +17,10 @@ void SWIG_JSC_exception(JSContextRef context, JSValueRef *exception, int code, c SWIG_Javascript_Raise(context, exception, msg); } -/*****************************************************************************/ -/* The parent class of all Proxies -/* -/*****************************************************************************/ +/* ---------------------------------------------------------------------------- + * The parent class of all Proxies + * + * ---------------------------------------------------------------------------*/ typedef struct { bool swigCMemOwn; @@ -167,10 +167,10 @@ JSObjectRef SWIG_JSC_NewPointerObj(JSContextRef context, void *ptr, swig_type_in #define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_JSC_ConvertInstancePtr(context, obj, pptr, type, flags) #define SWIG_NewInstanceObj(thisvalue, type, flags) SWIG_JSC_NewPointerObj(context, thisvalue, type, flags) -/*****************************************************************************/ -/* A class for packed data -/* -/*****************************************************************************/ +/* ---------------------------------------------------------------------------- + * A class for packed data + * + * ---------------------------------------------------------------------------*/ typedef struct { void *data; diff --git a/Lib/javascript/v8/javascriptrun.swg b/Lib/javascript/v8/javascriptrun.swg index 227977b16..bab81613c 100644 --- a/Lib/javascript/v8/javascriptrun.swg +++ b/Lib/javascript/v8/javascriptrun.swg @@ -1,7 +1,7 @@ -/* ---------------------------------------------------------------------------*/ -/* Error handling -/* -/* ---------------------------------------------------------------------------*/ +/* --------------------------------------------------------------------------- + * Error handling + * + * ---------------------------------------------------------------------------*/ #define SWIG_Error(code, msg) SWIGV8_ErrorHandler.error(code, msg) #define SWIG_exception(code, msg) SWIGV8_ErrorHandler.error(code, msg) @@ -64,10 +64,10 @@ typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfo; #endif -/* ---------------------------------------------------------------------------*/ -/* Basic Proxy object -/* -/* ---------------------------------------------------------------------------*/ +/* --------------------------------------------------------------------------- + * Basic Proxy object + * + * ---------------------------------------------------------------------------*/ // Note: to trigger the v8 gc more often one can tell v8 about the memory consumption // TODO: we could add a v8 specific parameter to control this value @@ -323,10 +323,10 @@ fail: SWIGV8_RETURN(v8::Undefined()); } -/* ---------------------------------------------------------------------------*/ -/* PackedData object -/* -/* ---------------------------------------------------------------------------*/ +/* --------------------------------------------------------------------------- + * PackedData object + * + * ---------------------------------------------------------------------------*/ class SwigV8PackedData { public: diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 876978a42..0a8b4931e 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -532,11 +532,6 @@ void JAVASCRIPT::main(int argc, char *argv[]) { Swig_mark_arg(i); mode = JSEmitter::V8; SWIG_library_directory("javascript/v8"); - } else if (strcmp(argv[i], "-node") == 0) { - Swig_mark_arg(i); - mode = JSEmitter::V8; - SWIG_library_directory("javascript/v8"); - Preprocessor_define("BUILDING_NODE_EXTENSION 1", 0); } else if (strcmp(argv[i], "-jsc") == 0) { Swig_mark_arg(i); mode = JSEmitter::JavascriptCore; @@ -544,8 +539,6 @@ void JAVASCRIPT::main(int argc, char *argv[]) { } else if (strcmp(argv[i], "-debug-codetemplates") == 0) { Swig_mark_arg(i); js_template_enable_debug = true; - } else if (strcmp(argv[i], "-no-moduleobject") == 0) { - Swig_mark_arg(i); } } } From dd84e6f9e0b67737ca1031cd6bbb4dcc4eb84340 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 10 Sep 2013 14:16:36 +0300 Subject: [PATCH 0310/1048] Some fixes and cleanup in Javascript generator. - v8 generator uses the correct mangled name for class templates - removed symbols for template variables in favor of using the string literals directly, as it is easier to understand when debugging. --- Lib/javascript/v8/javascriptcode.swg | 2 +- Source/Modules/javascript.cxx | 288 +++++++++++---------------- 2 files changed, 121 insertions(+), 169 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 58ed18d0d..1b06dbdc8 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -337,7 +337,7 @@ fail: $jsmangledname_clientData.class_templ.Reset(v8::Isolate::GetCurrent(), $jsmangledname_class); #endif $jsmangledname_clientData.dtor = $jsdtor; - SWIGTYPE$jsmangledtype->clientdata = &$jsmangledname_clientData; + SWIGTYPE_$jsmangledtype->clientdata = &$jsmangledname_clientData; %} diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 0a8b4931e..f86c4aeef 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -23,39 +23,6 @@ bool js_template_enable_debug = false; #define DTOR "dtor" #define ARGCOUNT "wrap:argc" -// variables used in code templates -// ATTENTION: be aware of prefix collisions when defining those variables -#define T_NAME "$jsname" -#define T_NAME_MANGLED "$jsmangledname" -#define T_TYPE "$jstype" -#define T_TYPE_MANGLED "$jsmangledtype" -#define T_WRAPPER "$jswrapper" -#define T_CTOR "$jsctor" -#define T_DTOR "$jsdtor" -#define T_GETTER "$jsgetter" -#define T_SETTER "$jssetter" -#define T_DISPATCH_CASES "$jsdispatchcases" -#define T_BASECLASS "$jsbaseclass" -#define T_NAMESPACE "$jsnspace" -#define T_PARENT "$jsparent" -#define T_OVERLOAD "$jsoverloadext" -#define T_ARGCOUNT "$jsargcount" -#define T_LOCALS "$jslocals" -#define T_CODE "$jscode" -#define T_FREE "$jsfree" - -// v8 specific variables used in templates -#define V8_NAME_SPACES "$jsv8nspaces" -#define V8_CLASS_TEMPLATES "$jsv8classtemplates" -#define V8_WRAPPERS "$jsv8wrappers" -#define V8_INHERITANCE "$jsv8inheritance" -#define V8_CLASS_INSTANCES "$jsv8classinstances" -#define V8_STATIC_WRAPPERS "$jsv8staticwrappers" -#define V8_REGISTER_CLASSES "$jsv8registerclasses" -#define V8_REGISTER_NS "$jsv8registernspaces" - -#define FLAG_NO_MODULE_OBJECT "NO_MODULE_OBJECT" - /** * A convenience class to manage state variables for emitters. * The implementation delegates to swig Hash DOHs and provides @@ -521,11 +488,6 @@ void JAVASCRIPT::main(int argc, char *argv[]) { int mode = -1; - // Note: creating a module object is not supported anymore. - // instead the initializer is called with an externally created object - // This makes it obsolete to handle node extensions differently - bool createModuleObject = false; - for (int i = 1; i < argc; i++) { if (argv[i]) { if (strcmp(argv[i], "-v8") == 0) { @@ -564,10 +526,6 @@ void JAVASCRIPT::main(int argc, char *argv[]) { } } - if(!createModuleObject) { - SetFlag(emitter->getState().global(), FLAG_NO_MODULE_OBJECT); - } - // Add a symbol to the parser for conditional compilation Preprocessor_define("SWIGJAVASCRIPT 1", 0); @@ -655,12 +613,8 @@ int JSEmitter::initialize(Node * /*n*/) { Delete(namespaces); } namespaces = NewHash(); - Hash *global_namespace; -// if(State::IsSet(state.global(FLAG_NO_MODULE_OBJECT))) { - global_namespace = createNamespaceEntry("exports", 0); -// } else { -// global_namespace = createNamespaceEntry(Char(Getattr(n, "name")), "global"); -// } + Hash *global_namespace = createNamespaceEntry("exports", 0); + Setattr(namespaces, "::", global_namespace); current_namespace = global_namespace; @@ -845,16 +799,16 @@ int JSEmitter::emitCtor(Node *n) { emitCleanupCode(n, wrapper, params); - t_ctor.replace(T_WRAPPER, wrap_name) - .replace(T_TYPE_MANGLED, state.clazz(TYPE_MANGLED)) - .replace(T_LOCALS, wrapper->locals) - .replace(T_CODE, wrapper->code) - .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)) + t_ctor.replace("$jswrapper", wrap_name) + .replace("$jsmangledtype", state.clazz(TYPE_MANGLED)) + .replace("$jslocals", wrapper->locals) + .replace("$jscode", wrapper->code) + .replace("$jsargcount", Getattr(n, ARGCOUNT)) .pretty_print(f_wrappers); Template t_ctor_case(getTemplate("js_ctor_dispatch_case")); - t_ctor_case.replace(T_WRAPPER, wrap_name) - .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)); + t_ctor_case.replace("$jswrapper", wrap_name) + .replace("$jsargcount", Getattr(n, ARGCOUNT)); Append(state.clazz(CTOR_DISPATCHERS), t_ctor_case.str()); DelWrapper(wrapper); @@ -864,9 +818,9 @@ int JSEmitter::emitCtor(Node *n) { if (!Getattr(n, "sym:nextSibling")) { String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); Template t_mainctor(getTemplate("js_ctor_dispatcher")); - t_mainctor.replace(T_WRAPPER, wrap_name) - .replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) - .replace(T_DISPATCH_CASES, state.clazz(CTOR_DISPATCHERS)) + t_mainctor.replace("$jswrapper", wrap_name) + .replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsdispatchcases", state.clazz(CTOR_DISPATCHERS)) .pretty_print(f_wrappers); state.clazz(CTOR, wrap_name); } @@ -980,9 +934,9 @@ int JSEmitter::emitDtor(Node *n) { Template t_dtor = getTemplate("js_dtoroverride"); state.clazz(DTOR, wrap_name); t_dtor.replace("${classname_mangled}", state.clazz(NAME_MANGLED)) - .replace(T_WRAPPER, wrap_name) - .replace(T_FREE, free) - .replace(T_TYPE, ctype); + .replace("$jswrapper", wrap_name) + .replace("$jsfree", free) + .replace("$jstype", ctype); t_dtor.replace("${destructor_action}", destructor_action); Wrapper_pretty_print(t_dtor.str(), f_wrappers); @@ -990,10 +944,10 @@ int JSEmitter::emitDtor(Node *n) { else { Template t_dtor = getTemplate("js_dtor"); state.clazz(DTOR, wrap_name); - t_dtor.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) - .replace(T_WRAPPER, wrap_name) - .replace(T_FREE, free) - .replace(T_TYPE, ctype) + t_dtor.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jswrapper", wrap_name) + .replace("$jsfree", free) + .replace("$jstype", ctype) .pretty_print(f_wrappers); } @@ -1025,9 +979,9 @@ int JSEmitter::emitGetter(Node *n, bool is_member, bool is_static) { emitCleanupCode(n, wrapper, params); - t_getter.replace(T_WRAPPER, wrap_name) - .replace(T_LOCALS, wrapper->locals) - .replace(T_CODE, wrapper->code) + t_getter.replace("$jswrapper", wrap_name) + .replace("$jslocals", wrapper->locals) + .replace("$jscode", wrapper->code) .pretty_print(f_wrappers); DelWrapper(wrapper); @@ -1063,9 +1017,9 @@ int JSEmitter::emitSetter(Node *n, bool is_member, bool is_static) { emitCleanupCode(n, wrapper, params); - t_setter.replace(T_WRAPPER, wrap_name) - .replace(T_LOCALS, wrapper->locals) - .replace(T_CODE, wrapper->code) + t_setter.replace("$jswrapper", wrap_name) + .replace("$jslocals", wrapper->locals) + .replace("$jscode", wrapper->code) .pretty_print(f_wrappers); DelWrapper(wrapper); @@ -1102,9 +1056,9 @@ int JSEmitter::emitConstant(Node *n) { assert(value != NULL); marshalOutput(n, wrapper, action, value, false); - t_getter.replace(T_WRAPPER, wrap_name) - .replace(T_LOCALS, wrapper->locals) - .replace(T_CODE, wrapper->code) + t_getter.replace("$jswrapper", wrap_name) + .replace("$jslocals", wrapper->locals) + .replace("$jscode", wrapper->code) .pretty_print(f_wrappers); exitVariable(n); @@ -1142,10 +1096,10 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { emitCleanupCode(n, wrapper, params); - t_function.replace(T_WRAPPER, wrap_name) - .replace(T_LOCALS, wrapper->locals) - .replace(T_CODE, wrapper->code) - .replace(T_ARGCOUNT, Getattr(n, ARGCOUNT)) + t_function.replace("$jswrapper", wrap_name) + .replace("$jslocals", wrapper->locals) + .replace("$jscode", wrapper->code) + .replace("$jsargcount", Getattr(n, ARGCOUNT)) .pretty_print(f_wrappers); @@ -1170,8 +1124,8 @@ int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { { // handle function overloading Template t_dispatch_case = getTemplate("js_function_dispatch_case"); - t_dispatch_case.replace(T_WRAPPER, siblname) - .replace(T_ARGCOUNT, Getattr(sibl, ARGCOUNT)); + t_dispatch_case.replace("$jswrapper", siblname) + .replace("$jsargcount", Getattr(sibl, ARGCOUNT)); Append(wrapper->code, t_dispatch_case.str()); } @@ -1197,12 +1151,12 @@ int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { Setattr(n, "wrap:name", wrap_name); state.function(WRAPPER_NAME, wrap_name); - t_function.replace(T_LOCALS, wrapper->locals) - .replace(T_CODE, wrapper->code); + t_function.replace("$jslocals", wrapper->locals) + .replace("$jscode", wrapper->code); // call this here, to replace all variables - t_function.replace(T_WRAPPER, wrap_name) - .replace(T_NAME, state.function(NAME)) + t_function.replace("$jswrapper", wrap_name) + .replace("$jsname", state.function(NAME)) .pretty_print(f_wrappers); // Delete the state variable @@ -1544,7 +1498,7 @@ int JSCEmitter::dump(Node *n) { Swig_banner(f_wrap_cpp); Template initializer_define(getTemplate("js_initializer_define")); - initializer_define.replace(T_NAME, module).pretty_print(f_header); + initializer_define.replace("$jsname", module).pretty_print(f_header); SwigType_emit_type_table(f_runtime, f_wrappers); @@ -1556,7 +1510,7 @@ int JSCEmitter::dump(Node *n) { // compose the initializer function using a template Template initializer(getTemplate("js_initializer")); - initializer.replace(T_NAME, module) + initializer.replace("$jsname", module) .replace("$jsregisterclasses", state.global(INITIALIZER)) .replace("$jscreatenamespaces", state.global(CREATE_NAMESPACES)) .replace("$jsregisternamespaces", state.global(REGISTER_NAMESPACES)) @@ -1608,8 +1562,8 @@ int JSCEmitter::exitFunction(Node *n) { } } - t_function.replace(T_NAME, state.function(NAME)) - .replace(T_WRAPPER, state.function(WRAPPER_NAME)); + t_function.replace("$jsname", state.function(NAME)) + .replace("$jswrapper", state.function(WRAPPER_NAME)); if (is_member) { if (GetFlag(state.function(), IS_STATIC)) { @@ -1634,9 +1588,9 @@ int JSCEmitter::enterVariable(Node *n) { int JSCEmitter::exitVariable(Node *n) { Template t_variable(getTemplate("jsc_variable_declaration")); - t_variable.replace(T_NAME, state.variable(NAME)) - .replace(T_GETTER, state.variable(GETTER)) - .replace(T_SETTER, state.variable(SETTER)); + t_variable.replace("$jsname", state.variable(NAME)) + .replace("$jsgetter", state.variable(GETTER)) + .replace("$jssetter", state.variable(SETTER)); if (GetFlag(n, "ismember")) { if (GetFlag(state.variable(), IS_STATIC) @@ -1660,7 +1614,7 @@ int JSCEmitter::enterClass(Node *n) { state.clazz(STATIC_FUNCTIONS, NewString("")); Template t_class_decl = getTemplate("jsc_class_declaration"); - t_class_decl.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) + t_class_decl.replace("$jsmangledname", state.clazz(NAME_MANGLED)) .pretty_print(f_wrappers); return SWIG_OK; @@ -1668,7 +1622,7 @@ int JSCEmitter::enterClass(Node *n) { int JSCEmitter::exitClass(Node *n) { Template t_class_tables(getTemplate("jsc_class_tables")); - t_class_tables.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) + t_class_tables.replace("$jsmangledname", state.clazz(NAME_MANGLED)) .replace("$jsclassvariables", state.clazz(MEMBER_VARIABLES)) .replace("$jsclassfunctions", state.clazz(MEMBER_FUNCTIONS)) .replace("$jsstaticclassfunctions", state.clazz(STATIC_FUNCTIONS)) @@ -1682,8 +1636,8 @@ int JSCEmitter::exitClass(Node *n) { // for abstract classes add a vetoing ctor if(GetFlag(state.clazz(), IS_ABSTRACT)) { Template t_veto_ctor(getTemplate("js_veto_ctor")); - t_veto_ctor.replace(T_WRAPPER, state.clazz(CTOR)) - .replace(T_NAME, state.clazz(NAME)) + t_veto_ctor.replace("$jswrapper", state.clazz(CTOR)) + .replace("$jsname", state.clazz(NAME)) .pretty_print(f_wrappers); } @@ -1697,11 +1651,11 @@ int JSCEmitter::exitClass(Node *n) { Delete(base_name_mangled); base_name_mangled = SwigType_manglestr(Getattr(base_class, "name")); } - t_classtemplate.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) - .replace(T_TYPE_MANGLED, state.clazz(TYPE_MANGLED)) - .replace(T_BASECLASS, base_name_mangled) - .replace(T_CTOR, state.clazz(CTOR)) - .replace(T_DTOR, state.clazz(DTOR)) + t_classtemplate.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsmangledtype", state.clazz(TYPE_MANGLED)) + .replace("$jsbaseclass", base_name_mangled) + .replace("$jsctor", state.clazz(CTOR)) + .replace("$jsdtor", state.clazz(DTOR)) .pretty_print(state.global(INITIALIZER)); Delete(base_name_mangled); @@ -1710,9 +1664,9 @@ int JSCEmitter::exitClass(Node *n) { /* adds a class registration statement to initializer function */ Template t_registerclass(getTemplate("jsc_class_registration")); - t_registerclass.replace(T_NAME, state.clazz(NAME)) - .replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) - .replace(T_NAMESPACE, Getattr(current_namespace, NAME_MANGLED)) + t_registerclass.replace("$jsname", state.clazz(NAME)) + .replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsnspace", Getattr(current_namespace, NAME_MANGLED)) .pretty_print(state.global(INITIALIZER)); return SWIG_OK; @@ -1741,19 +1695,19 @@ int JSCEmitter::emitNamespaces() { Template namespace_definition(getTemplate("jsc_nspace_declaration")); namespace_definition.replace("$jsglobalvariables", variables) .replace("$jsglobalfunctions", functions) - .replace(T_NAMESPACE, name_mangled) + .replace("$jsnspace", name_mangled) .pretty_print(f_wrap_cpp); Template t_createNamespace(getTemplate("jsc_nspace_definition")); - t_createNamespace.replace(T_NAME_MANGLED, name_mangled); + t_createNamespace.replace("$jsmangledname", name_mangled); Append(state.global(CREATE_NAMESPACES), t_createNamespace.str()); // Don't register 'exports' as namespace. It is return to the application. if (!Equal("exports", name)) { Template t_registerNamespace(getTemplate("jsc_nspace_registration")); - t_registerNamespace.replace(T_NAME_MANGLED, name_mangled) - .replace(T_NAME, name) - .replace(T_PARENT, parent_mangled); + t_registerNamespace.replace("$jsmangledname", name_mangled) + .replace("$jsname", name) + .replace("$jsparent", parent_mangled); Append(state.global(REGISTER_NAMESPACES), t_registerNamespace.str()); } @@ -1882,7 +1836,7 @@ int V8Emitter::dump(Node *) SwigType_emit_type_table(f_runtime, f_wrappers); - // Let's not and say we did + // This is important to have proxies for classes that have not been exposed to swig // emitUndefined(); Printv(f_wrap_cpp, f_runtime, "\n", 0); @@ -1895,15 +1849,15 @@ int V8Emitter::dump(Node *) // compose the initializer function using a template // filled with sub-parts Template initializer(getTemplate("js_initializer")); - initializer.replace(T_NAME, moduleName) - .replace(V8_NAME_SPACES, f_init_namespaces) - .replace(V8_CLASS_TEMPLATES, f_init_class_templates) - .replace(V8_WRAPPERS, f_init_wrappers) - .replace(V8_INHERITANCE, f_init_inheritance) - .replace(V8_CLASS_INSTANCES, f_init_class_instances) - .replace(V8_STATIC_WRAPPERS, f_init_static_wrappers) - .replace(V8_REGISTER_CLASSES, f_init_register_classes) - .replace(V8_REGISTER_NS, f_init_register_namespaces) + initializer.replace("$jsname", moduleName) + .replace("$jsv8nspaces", f_init_namespaces) + .replace("$jsv8classtemplates", f_init_class_templates) + .replace("$jsv8wrappers", f_init_wrappers) + .replace("$jsv8inheritance", f_init_inheritance) + .replace("$jsv8classinstances", f_init_class_instances) + .replace("$jsv8staticwrappers", f_init_static_wrappers) + .replace("$jsv8registerclasses", f_init_register_classes) + .replace("$jsv8registernspaces", f_init_register_namespaces) .pretty_print(f_init); Printv(f_wrap_cpp, f_init, 0); @@ -1943,7 +1897,7 @@ int V8Emitter::enterClass(Node *n) // emit declaration of a v8 class template Template t_decl_class(getTemplate("jsv8_declare_class_template")); - t_decl_class.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) + t_decl_class.replace("$jsmangledname", state.clazz(NAME_MANGLED)) .trim() .pretty_print(f_class_templates); @@ -1954,8 +1908,8 @@ int V8Emitter::exitClass(Node *n) { if(GetFlag(state.clazz(), IS_ABSTRACT)) { Template t_veto_ctor(getTemplate("js_veto_ctor")); - t_veto_ctor.replace(T_WRAPPER, state.clazz(CTOR)) - .replace(T_NAME, state.clazz(NAME)) + t_veto_ctor.replace("$jswrapper", state.clazz(CTOR)) + .replace("$jsname", state.clazz(NAME)) .pretty_print(f_wrappers); } @@ -1965,20 +1919,18 @@ int V8Emitter::exitClass(Node *n) SwigType_remember_clientdata(state.clazz(TYPE_MANGLED), clientData); // emit definition of v8 class template - String *p_classtype = state.clazz(TYPE); - String *p_classtype_str = SwigType_manglestr(p_classtype); Template t_def_class = getTemplate("jsv8_define_class_template"); - t_def_class.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) - .replace(T_NAME, state.clazz(NAME)) - .replace(T_TYPE_MANGLED, p_classtype_str) - .replace(T_DTOR, state.clazz(DTOR)) + t_def_class.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsname", state.clazz(NAME)) + .replace("$jsmangledtype", state.clazz(TYPE_MANGLED)) + .replace("$jsdtor", state.clazz(DTOR)) .trim() .pretty_print(f_init_class_templates); Template t_class_instance = getTemplate("jsv8_create_class_instance"); - t_class_instance.replace(T_NAME, state.clazz(NAME)) - .replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) - .replace(T_CTOR, state.clazz(CTOR)) + t_class_instance.replace("$jsname", state.clazz(NAME)) + .replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsctor", state.clazz(CTOR)) .trim() .pretty_print(f_init_class_instances); @@ -1990,8 +1942,8 @@ int V8Emitter::exitClass(Node *n) Template t_inherit = getTemplate("jsv8_inherit"); String *base_name_mangled = SwigType_manglestr(base_name); - t_inherit.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) - .replace(T_BASECLASS, base_name_mangled) + t_inherit.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsbaseclass", base_name_mangled) .trim() .pretty_print(f_init_inheritance); Delete(base_name_mangled); @@ -1999,9 +1951,9 @@ int V8Emitter::exitClass(Node *n) // emit registeration of class template Template t_register = getTemplate("jsv8_register_class"); - t_register.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) - .replace(T_NAME, state.clazz(NAME)) - .replace(T_PARENT, Getattr(current_namespace, "name_mangled")) + t_register.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsname", state.clazz(NAME)) + .replace("$jsparent", Getattr(current_namespace, "name_mangled")) .trim() .pretty_print(f_init_register_classes); @@ -2023,18 +1975,18 @@ int V8Emitter::exitVariable(Node* n) if(GetFlag(n, "ismember")) { if(GetFlag(state.variable(), IS_STATIC) || Equal(Getattr(n, "nodeType"), "enumitem") ) { Template t_register = getTemplate("jsv8_register_static_variable"); - t_register.replace(T_PARENT, state.clazz(NAME_MANGLED)) - .replace(T_NAME, state.variable(NAME)) - .replace(T_GETTER, state.variable(GETTER)) - .replace(T_SETTER, state.variable(SETTER)) + t_register.replace("$jsparent", state.clazz(NAME_MANGLED)) + .replace("$jsname", state.variable(NAME)) + .replace("$jsgetter", state.variable(GETTER)) + .replace("$jssetter", state.variable(SETTER)) .trim() .pretty_print(f_init_static_wrappers); } else { Template t_register = getTemplate("jsv8_register_member_variable"); - t_register.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) - .replace(T_NAME, state.variable(NAME)) - .replace(T_GETTER, state.variable(GETTER)) - .replace(T_SETTER, state.variable(SETTER)) + t_register.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsname", state.variable(NAME)) + .replace("$jsgetter", state.variable(GETTER)) + .replace("$jssetter", state.variable(SETTER)) .trim() .pretty_print(f_init_wrappers); } @@ -2042,10 +1994,10 @@ int V8Emitter::exitVariable(Node* n) // Note: a global variable is treated like a static variable // with the parent being a nspace object (instead of class object) Template t_register = getTemplate("jsv8_register_static_variable"); - t_register.replace(T_PARENT, Getattr(current_namespace, NAME)) - .replace(T_NAME, state.variable(NAME)) - .replace(T_GETTER, state.variable(GETTER)) - .replace(T_SETTER, state.variable(SETTER)) + t_register.replace("$jsparent", Getattr(current_namespace, NAME)) + .replace("$jsname", state.variable(NAME)) + .replace("$jsgetter", state.variable(GETTER)) + .replace("$jssetter", state.variable(SETTER)) .trim() .pretty_print(f_init_wrappers); } @@ -2073,16 +2025,16 @@ int V8Emitter::exitFunction(Node* n) if(is_member) { if(GetFlag(state.function(), IS_STATIC)) { Template t_register = getTemplate("jsv8_register_static_function"); - t_register.replace(T_PARENT, state.clazz(NAME_MANGLED)) - .replace(T_NAME, state.function(NAME)) - .replace(T_WRAPPER, state.function(WRAPPER_NAME)) + t_register.replace("$jsparent", state.clazz(NAME_MANGLED)) + .replace("$jsname", state.function(NAME)) + .replace("$jswrapper", state.function(WRAPPER_NAME)) .trim() .pretty_print(f_init_static_wrappers); } else { Template t_register = getTemplate("jsv8_register_member_function"); - t_register.replace(T_NAME_MANGLED, state.clazz(NAME_MANGLED)) - .replace(T_NAME, state.function(NAME)) - .replace(T_WRAPPER, state.function(WRAPPER_NAME)) + t_register.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsname", state.function(NAME)) + .replace("$jswrapper", state.function(WRAPPER_NAME)) .trim() .pretty_print(f_init_wrappers); } @@ -2090,9 +2042,9 @@ int V8Emitter::exitFunction(Node* n) // Note: a global function is treated like a static function // with the parent being a nspace object instead of class object Template t_register = getTemplate("jsv8_register_static_function"); - t_register.replace(T_PARENT, Getattr(current_namespace, NAME)) - .replace(T_NAME, state.function(NAME)) - .replace(T_WRAPPER, state.function(WRAPPER_NAME)) + t_register.replace("$jsparent", Getattr(current_namespace, NAME)) + .replace("$jsname", state.function(NAME)) + .replace("$jswrapper", state.function(WRAPPER_NAME)) .trim() .pretty_print(f_init_static_wrappers); } @@ -2175,16 +2127,16 @@ int V8Emitter::emitNamespaces() { if (do_create) { // create namespace object and register it to the parent scope Template t_create_ns = getTemplate("jsv8_create_namespace"); - t_create_ns.replace(T_NAME_MANGLED, name_mangled) + t_create_ns.replace("$jsmangledname", name_mangled) .trim() .pretty_print(f_init_namespaces); } if (do_register) { Template t_register_ns = getTemplate("jsv8_register_namespace"); - t_register_ns.replace(T_NAME_MANGLED, name_mangled) - .replace(T_NAME, name) - .replace(T_PARENT, parent_mangled) + t_register_ns.replace("$jsmangledname", name_mangled) + .replace("$jsname", name) + .replace("$jsparent", parent_mangled) .trim(); // prepend in order to achieve reversed order of registration statements @@ -2213,24 +2165,24 @@ void V8Emitter::emitUndefined() { // emit clientData declaration Template clientDataDecl = getTemplate("jsv8_declare_class_template"); - clientDataDecl.replace(T_NAME_MANGLED, mangled_name) + clientDataDecl.replace("$jsmangledname", mangled_name) .trim() .pretty_print(f_class_templates); // emit an extra dtor for unknown types Template t_dtor = getTemplate("js_dtor"); - t_dtor.replace(T_NAME_MANGLED, mangled_name) - .replace(T_WRAPPER, dtor) - .replace(T_FREE, free) + t_dtor.replace("$jsmangledname", mangled_name) + .replace("$jswrapper", dtor) + .replace("$jsfree", free) .trim() .pretty_print(f_wrappers); // create a class template and initialize clientData Template clientDataDef = getTemplate("jsv8_define_class_template"); - clientDataDef.replace(T_NAME_MANGLED, mangled_name) - .replace(T_NAME, mangled_name) - .replace(T_TYPE_MANGLED, type_mangled) - .replace(T_DTOR, dtor) + clientDataDef.replace("$jsmangledname", mangled_name) + .replace("$jsname", mangled_name) + .replace("$jsmangledtype", type_mangled) + .replace("$jsdtor", dtor) .trim() .pretty_print(f_init_class_templates); From c53e3e4dab9b6ab61e63880476721c61ec9ff940 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 10 Sep 2013 14:45:33 +0300 Subject: [PATCH 0311/1048] Fix configuration for nodejs based tests. - use $(SWIGOPT) - less verbose --- Examples/test-suite/javascript/Makefile.in | 23 ++++++++----------- .../javascript/node_template/binding.gyp.in | 2 +- 2 files changed, 11 insertions(+), 14 deletions(-) diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index 48ce7cdbb..70c404e61 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -10,9 +10,9 @@ top_builddir = @top_builddir@ SWIG = $(top_builddir)/preinst_swig ifneq (, $(ENGINE)) - JSENGINE = $(ENGINE) + JSENGINE=$(ENGINE) else - JSENGINE = "node" + JSENGINE=node endif # Note: the javascript generator is not ready yet for the real game. @@ -74,8 +74,6 @@ endif include $(srcdir)/../common.mk -SWIGOPT += -$(JSENGINE) - _setup = \ if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ echo "$(ACTION)ing testcase $* (with run test) under javascript ($(JSENGINE))" ; \ @@ -83,19 +81,16 @@ _setup = \ echo "$(ACTION)ing testcase $* under javascript ($(JSENGINE))" ; \ fi; -ifeq ("node",$(JSENGINE)) +ifeq (node,$(JSENGINE)) + + SWIGOPT += -v8 -DBUILDING_NODE_EXTENSION=1 __setup = \ - if [ ! -f $(srcdir)/$*/binding.gyp ]; then \ - sh ./setup_test.sh $*; \ - $(SWIG) -c++ -javascript -v8 -DBUILDING_NODE_EXTENSION=1 -I$(top_srcdir)/Examples/test-suite -includeall -o $*/$*_wrap.cxx ../$*.i; \ - fi + sh ./setup_test.sh $*; \ + $(SWIG) -c++ -javascript $(SWIGOPT) ../$*.i; nodejs_swig_and_compile = \ - if [ ! -f $(srcdir)/$*/build/Makefile ]; then \ - node-gyp --loglevel=silent --directory $* configure; \ - fi; \ - node-gyp --loglevel=silent --directory $* build; \ + node-gyp --loglevel=silent --directory $* configure build 1>>/dev/null run_testcase = \ if [ -f $(srcdir)/$*$(SCRIPTSUFFIX) ]; then \ @@ -122,6 +117,8 @@ ifeq ("node",$(JSENGINE)) else + SWIGOPT += -$(JSENGINE) + run_testcase = \ if [ -f $(srcdir)/$*$(SCRIPTSUFFIX) ]; then \ $(top_srcdir)/Tools/javascript/javascript -$(JSENGINE) $(srcdir)/$*$(SCRIPTSUFFIX); \ diff --git a/Examples/test-suite/javascript/node_template/binding.gyp.in b/Examples/test-suite/javascript/node_template/binding.gyp.in index dffd52c6c..435381043 100644 --- a/Examples/test-suite/javascript/node_template/binding.gyp.in +++ b/Examples/test-suite/javascript/node_template/binding.gyp.in @@ -2,7 +2,7 @@ "targets": [ { "target_name": "$testcase", - "sources":[ "$testcase_wrap.cxx" ], + "sources":[ "../$testcase_wrap.cxx" ], "include_dirs": ["../.."], 'defines': [ 'BUILDING_NODE_EXTENSION=1', From 09a210e037c8d5ca46ee4edc4c904f11b04cb893 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Thu, 12 Sep 2013 04:09:21 +0300 Subject: [PATCH 0312/1048] Bugfix in Javascript generator: detect member setter/getters correctly. --- Source/Modules/javascript.cxx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index f86c4aeef..8d53d99ec 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -667,16 +667,18 @@ int JSEmitter::emitWrapperFunction(Node *n) { String *kind = Getattr(n, "kind"); if (kind) { - bool is_member = GetFlag(n, "ismember"); if (Cmp(kind, "function") == 0) { + bool is_member = GetFlag(n, "ismember"); bool is_static = GetFlag(state.function(), IS_STATIC); ret = emitFunction(n, is_member, is_static); } else if (Cmp(kind, "variable") == 0) { bool is_static = GetFlag(state.variable(), IS_STATIC); bool is_setter = GetFlag(n, "wrap:issetter"); if (is_setter) { + bool is_member = GetFlag(n, "memberset"); ret = emitSetter(n, is_member, is_static); } else { + bool is_member = GetFlag(n, "memberget"); ret = emitGetter(n, is_member, is_static); } } else { From 8bf95c4356b61da9f510245310a0bd3c1fafe36f Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Thu, 12 Sep 2013 05:09:35 +0300 Subject: [PATCH 0313/1048] Bugfix for Javascript generator: avoid duplicate action code generation. --- Source/Modules/javascript.cxx | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 8d53d99ec..7b21c42fb 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -791,12 +791,15 @@ int JSEmitter::emitCtor(Node *n) { ParmList *params = Getattr(n, "parms"); emit_parameter_variables(params, wrapper); emit_attach_parmmaps(params, wrapper); + // HACK: in test-case `ignore_parameter` emit_attach_parmmaps generated an extra line of applied typemap. + // Deleting wrapper->code here, to reset, and as it seemed to have no side effect elsewhere + Delete(wrapper->code); + wrapper->code = NewString(""); Printf(wrapper->locals, "%sresult;", SwigType_str(Getattr(n, "type"), 0)); - String *action = emit_action(n); marshalInputArgs(n, params, wrapper, Ctor, true, false); - + String *action = emit_action(n); Printv(wrapper->code, action, "\n", 0); emitCleanupCode(n, wrapper, params); @@ -1049,13 +1052,14 @@ int JSEmitter::emitConstant(Node *n) { Setattr(n, "wrap:name", wrap_name); // prepare code part - String *action = NewString(""); String *value = Getattr(n, "rawval"); if (value == NULL) { value = Getattr(n, "rawvalue"); if (value == NULL) value = Getattr(n, "value"); } assert(value != NULL); + + String *action = NewString(""); marshalOutput(n, wrapper, action, value, false); t_getter.replace("$jswrapper", wrap_name) @@ -1091,9 +1095,13 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { emit_parameter_variables(params, wrapper); emit_attach_parmmaps(params, wrapper); - // prepare code part - String *action = emit_action(n); + // HACK: in test-case `ignore_parameter` emit_attach_parmmaps generated an extra line of applied typemap. + // Deleting wrapper->code here, to reset, and as it seemed to have no side effect elsewhere + Delete(wrapper->code); + wrapper->code = NewString(""); + marshalInputArgs(n, params, wrapper, Function, is_member, is_static); + String *action = emit_action(n); marshalOutput(n, wrapper, action); emitCleanupCode(n, wrapper, params); From 1a04e488bc5e17de266181f6b39e00e114f9ae8a Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Thu, 12 Sep 2013 05:40:59 +0300 Subject: [PATCH 0314/1048] Fix Javascript generator for smartpointeraccessed variables. --- Source/Modules/javascript.cxx | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 7b21c42fb..d7b6b9ce7 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -673,6 +673,10 @@ int JSEmitter::emitWrapperFunction(Node *n) { ret = emitFunction(n, is_member, is_static); } else if (Cmp(kind, "variable") == 0) { bool is_static = GetFlag(state.variable(), IS_STATIC); + // HACK: smartpointeraccessed static variables are not treated as statics + if (GetFlag(n, "allocate:smartpointeraccess")) { + is_static = false; + } bool is_setter = GetFlag(n, "wrap:issetter"); if (is_setter) { bool is_member = GetFlag(n, "memberset"); From acfed20eba1c72571f65048c62653bf339d5564b Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Thu, 12 Sep 2013 05:10:23 +0200 Subject: [PATCH 0315/1048] Bugfix Javascript generator: valid name for dispatcher functions. --- Source/Modules/javascript.cxx | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index d7b6b9ce7..0ca740caf 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1146,21 +1146,17 @@ int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { } while ((sibl = Getattr(sibl, "sym:nextSibling"))); - - - Template t_function(getTemplate("js_function_dispatcher")); -// String *wrap_name = Swig_name_wrapper(Getattr(n, "name")); - - - String *fun_name = Getattr(n, "sym:name"); - - Node *methodclass = Swig_methodclass(n); - String *class_name = Getattr(methodclass, "sym:name"); - - String *new_string = NewStringf("%s_%s", class_name, fun_name); - String *wrap_name = Swig_name_wrapper(new_string); + // Note: this dispatcher function gets called after the last overloaded function has been created. + // At this time, n.wrap:name contains the name of the last wrapper function. + // To get a valid function name for the dispatcher function we take the last wrapper name and + // substract the extension "sym:overname", + String *wrap_name = NewString(Getattr(n, "wrap:name")); + String *overname = Getattr(n, "sym:overname"); + int l1 = Len(wrap_name); + int l2 = Len(overname); + Delslice(wrap_name, l1-l2, l1); Setattr(n, "wrap:name", wrap_name); state.function(WRAPPER_NAME, wrap_name); From 477b2393b10f664696b8cf1e49c2b98deab39d79 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Thu, 12 Sep 2013 05:26:22 +0200 Subject: [PATCH 0316/1048] Add stub 'typemaps.i' files. --- Lib/javascript/jsc/typemaps.i | 0 Lib/javascript/v8/typemaps.i | 0 2 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 Lib/javascript/jsc/typemaps.i create mode 100644 Lib/javascript/v8/typemaps.i diff --git a/Lib/javascript/jsc/typemaps.i b/Lib/javascript/jsc/typemaps.i new file mode 100644 index 000000000..e69de29bb diff --git a/Lib/javascript/v8/typemaps.i b/Lib/javascript/v8/typemaps.i new file mode 100644 index 000000000..e69de29bb From 89fd7ed9c1b1c1e0a1a5344018ab9d0a5ce711b0 Mon Sep 17 00:00:00 2001 From: Vladimir Menshakov Date: Sat, 14 Sep 2013 16:17:21 +0400 Subject: [PATCH 0317/1048] fixed newer v8 compilation --- Lib/javascript/v8/javascriptrun.swg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/javascript/v8/javascriptrun.swg b/Lib/javascript/v8/javascriptrun.swg index bab81613c..fbdb75c3a 100644 --- a/Lib/javascript/v8/javascriptrun.swg +++ b/Lib/javascript/v8/javascriptrun.swg @@ -392,7 +392,7 @@ void _wrap_SwigV8PackedData_delete(v8::Persistent< v8::Value > object, void *par { SwigV8PackedData *cdata = static_cast(parameter); #else -void _wrap_SwigV8PackedData_delete(v8::Isolate *isolate, v8::Persistent< v8::Object > * object, SwigV8PackedData *proxy) +void _wrap_SwigV8PackedData_delete(v8::Isolate *isolate, v8::Persistent< v8::Object > * object, SwigV8PackedData *cdata) { #endif From 325b5445d67ccf60855aac970ecb6ba913e2b32b Mon Sep 17 00:00:00 2001 From: Vladimir Menshakov Date: Sat, 14 Sep 2013 16:19:47 +0400 Subject: [PATCH 0318/1048] removed Clear before Dispose from newer v8 code, consider the following code: template void Persistent::Dispose() { if (this->IsEmpty()) return; //Clear will trigger this V8::DisposeGlobal(reinterpret_cast(this->val_)); ... } --- Lib/javascript/v8/javascriptrun.swg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/javascript/v8/javascriptrun.swg b/Lib/javascript/v8/javascriptrun.swg index fbdb75c3a..5be16add5 100644 --- a/Lib/javascript/v8/javascriptrun.swg +++ b/Lib/javascript/v8/javascriptrun.swg @@ -398,8 +398,8 @@ void _wrap_SwigV8PackedData_delete(v8::Isolate *isolate, v8::Persistent< v8::Obj delete cdata; - object.Clear(); #if (SWIG_V8_VERSION < 0x031900) + object.Clear(); object.Dispose(); #elif (SWIG_V8_VERSION < 0x032100) object->Dispose(isolate); From bb7bd50eabdf5cc2f07640227713ef75dc1c8fce Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 16 Sep 2013 00:55:43 +0200 Subject: [PATCH 0319/1048] Add support for IN/OUTPUT typemaps. --- Lib/javascript/jsc/javascriptrun.swg | 40 ++++++ Lib/javascript/jsc/javascripttypemaps.swg | 2 +- Lib/javascript/jsc/typemaps.i | 148 ++++++++++++++++++++++ Lib/javascript/v8/javascriptrun.swg | 18 +++ Lib/javascript/v8/javascripttypemaps.swg | 4 +- Lib/javascript/v8/typemaps.i | 148 ++++++++++++++++++++++ Source/Modules/javascript.cxx | 44 ++++--- 7 files changed, 382 insertions(+), 22 deletions(-) diff --git a/Lib/javascript/jsc/javascriptrun.swg b/Lib/javascript/jsc/javascriptrun.swg index c8f16f36f..0e68b7618 100644 --- a/Lib/javascript/jsc/javascriptrun.swg +++ b/Lib/javascript/jsc/javascriptrun.swg @@ -253,3 +253,43 @@ void _wrap_SwigPackedData_delete(JSObjectRef obj) #define SWIG_ConvertMember(obj, ptr, sz, ty) SWIG_JSC_ConvertPacked(context, obj, ptr, sz, ty) #define SWIG_NewMemberObj(ptr, sz, type) SWIG_JSC_NewPackedObj(context, ptr, sz, type) + + +/* --------------------------------------------------------------------------- + * Support for IN/OUTPUT typemaps (see Lib/typemaps/inoutlist.swg) + * + * ---------------------------------------------------------------------------*/ + +unsigned int SWIGJSC_ArrayLength(JSContextRef context, JSObjectRef arr) { + static JSStringRef LENGTH = 0; + JSValueRef exception = NULL; + JSValueRef js_length; + double length; + + if (LENGTH == 0) { + LENGTH = JSStringCreateWithUTF8CString("length"); + } + + js_length = JSObjectGetProperty(context, arr, LENGTH, &exception); + if (exception == 0 && JSValueIsNumber(context, js_length)) { + length = JSValueToNumber(context, js_length, 0); + return (unsigned int) length; + } else { + return 0; + } +} + +SWIGRUNTIME +JSValueRef SWIGJSC_AppendOutput(JSContextRef context, JSValueRef value, JSValueRef obj) { + JSObjectRef arr; + unsigned int length; + + if (JSValueIsUndefined(context, value)) { + arr = JSObjectMakeArray(context, 0, 0, 0); + } else { + arr = JSValueToObject(context, value, 0); + } + + length = SWIGJSC_ArrayLength(context, arr); + JSObjectSetPropertyAtIndex(context, arr, length, obj, 0); +} diff --git a/Lib/javascript/jsc/javascripttypemaps.swg b/Lib/javascript/jsc/javascripttypemaps.swg index 12e78dc2f..e8fbbeca8 100644 --- a/Lib/javascript/jsc/javascripttypemaps.swg +++ b/Lib/javascript/jsc/javascripttypemaps.swg @@ -35,7 +35,7 @@ #define VOID_Object JSValueMakeUndefined(context) /* append output */ -#define SWIG_AppendOutput(result, obj) +#define SWIG_AppendOutput(result, obj) SWIGJSC_AppendOutput(context, result, obj) /* set constant */ #define SWIG_SetConstant(name, obj) diff --git a/Lib/javascript/jsc/typemaps.i b/Lib/javascript/jsc/typemaps.i index e69de29bb..d3d8afb19 100644 --- a/Lib/javascript/jsc/typemaps.i +++ b/Lib/javascript/jsc/typemaps.i @@ -0,0 +1,148 @@ +/* ----------------------------------------------------------------------------- + * typemaps.i + * + * Pointer handling + * These mappings provide support for input/output arguments and common + * uses for C/C++ pointers. + * ----------------------------------------------------------------------------- */ + +// INPUT typemaps. +// These remap a C pointer to be an "INPUT" value which is passed by value +// instead of reference. + +/* +The following methods can be applied to turn a pointer into a simple +"input" value. That is, instead of passing a pointer to an object, +you would use a real value instead. + + int *INPUT + short *INPUT + long *INPUT + long long *INPUT + unsigned int *INPUT + unsigned short *INPUT + unsigned long *INPUT + unsigned long long *INPUT + unsigned char *INPUT + bool *INPUT + float *INPUT + double *INPUT + +To use these, suppose you had a C function like this : + + double fadd(double *a, double *b) { + return *a+*b; + } + +You could wrap it with SWIG as follows : + + %include + double fadd(double *INPUT, double *INPUT); + +or you can use the %apply directive : + + %include + %apply double *INPUT { double *a, double *b }; + double fadd(double *a, double *b); + +*/ + +// OUTPUT typemaps. These typemaps are used for parameters that +// are output only. The output value is appended to the result as +// a list element. + +/* +The following methods can be applied to turn a pointer into an "output" +value. When calling a function, no input value would be given for +a parameter, but an output value would be returned. In the case of +multiple output values, they are returned in the form of a Python tuple. + + int *OUTPUT + short *OUTPUT + long *OUTPUT + long long *OUTPUT + unsigned int *OUTPUT + unsigned short *OUTPUT + unsigned long *OUTPUT + unsigned long long *OUTPUT + unsigned char *OUTPUT + bool *OUTPUT + float *OUTPUT + double *OUTPUT + +For example, suppose you were trying to wrap the modf() function in the +C math library which splits x into integral and fractional parts (and +returns the integer part in one of its parameters).K: + + double modf(double x, double *ip); + +You could wrap it with SWIG as follows : + + %include + double modf(double x, double *OUTPUT); + +or you can use the %apply directive : + + %include + %apply double *OUTPUT { double *ip }; + double modf(double x, double *ip); + +The Python output of the function would be a tuple containing both +output values. + +*/ + +// INOUT +// Mappings for an argument that is both an input and output +// parameter + +/* +The following methods can be applied to make a function parameter both +an input and output value. This combines the behavior of both the +"INPUT" and "OUTPUT" methods described earlier. Output values are +returned in the form of a Python tuple. + + int *INOUT + short *INOUT + long *INOUT + long long *INOUT + unsigned int *INOUT + unsigned short *INOUT + unsigned long *INOUT + unsigned long long *INOUT + unsigned char *INOUT + bool *INOUT + float *INOUT + double *INOUT + +For example, suppose you were trying to wrap the following function : + + void neg(double *x) { + *x = -(*x); + } + +You could wrap it with SWIG as follows : + + %include + void neg(double *INOUT); + +or you can use the %apply directive : + + %include + %apply double *INOUT { double *x }; + void neg(double *x); + +Unlike C, this mapping does not directly modify the input value (since +this makes no sense in Python). Rather, the modified input value shows +up as the return value of the function. Thus, to apply this function +to a Python variable you might do this : + + x = neg(x) + +Note : previous versions of SWIG used the symbol 'BOTH' to mark +input/output arguments. This is still supported, but will be slowly +phased out in future releases. + +*/ + +%include diff --git a/Lib/javascript/v8/javascriptrun.swg b/Lib/javascript/v8/javascriptrun.swg index bab81613c..14936986f 100644 --- a/Lib/javascript/v8/javascriptrun.swg +++ b/Lib/javascript/v8/javascriptrun.swg @@ -442,3 +442,21 @@ v8::Handle SWIGV8_NewPackedObj(void *data, size_t size, swig_type_inf #define SWIG_ConvertMember(obj, ptr, sz, ty) SWIGV8_ConvertPacked(obj, ptr, sz, ty) #define SWIG_NewMemberObj(ptr, sz, type) SWIGV8_NewPackedObj(ptr, sz, type) + + +/* --------------------------------------------------------------------------- + * Support for IN/OUTPUT typemaps (see Lib/typemaps/inoutlist.swg) + * + * ---------------------------------------------------------------------------*/ + +SWIGRUNTIME +v8::Handle SWIGV8_AppendOutput(v8::Handle result, v8::Handle obj) { + v8::HandleScope scope; + if (result->IsUndefined()) { + result = v8::Array::New(); + } + v8::Handle arr = v8::Handle::Cast(result); + arr->Set(arr->Length(), obj); + + return scope.Close(arr); +} diff --git a/Lib/javascript/v8/javascripttypemaps.swg b/Lib/javascript/v8/javascripttypemaps.swg index b12e5c899..90317a1c7 100644 --- a/Lib/javascript/v8/javascripttypemaps.swg +++ b/Lib/javascript/v8/javascripttypemaps.swg @@ -31,13 +31,13 @@ /* Overload of the output/constant/exception/dirout handling */ /* append output */ -#define SWIG_AppendOutput(result, obj) +#define SWIG_AppendOutput(result, obj) SWIGV8_AppendOutput(result, obj) /* set constant */ #define SWIG_SetConstant(name, obj) /* raise */ #define SWIG_Raise(obj, type, desc) SWIG_V8_Raise(type) - + /* Include the unified typemap library */ %include diff --git a/Lib/javascript/v8/typemaps.i b/Lib/javascript/v8/typemaps.i index e69de29bb..d3d8afb19 100644 --- a/Lib/javascript/v8/typemaps.i +++ b/Lib/javascript/v8/typemaps.i @@ -0,0 +1,148 @@ +/* ----------------------------------------------------------------------------- + * typemaps.i + * + * Pointer handling + * These mappings provide support for input/output arguments and common + * uses for C/C++ pointers. + * ----------------------------------------------------------------------------- */ + +// INPUT typemaps. +// These remap a C pointer to be an "INPUT" value which is passed by value +// instead of reference. + +/* +The following methods can be applied to turn a pointer into a simple +"input" value. That is, instead of passing a pointer to an object, +you would use a real value instead. + + int *INPUT + short *INPUT + long *INPUT + long long *INPUT + unsigned int *INPUT + unsigned short *INPUT + unsigned long *INPUT + unsigned long long *INPUT + unsigned char *INPUT + bool *INPUT + float *INPUT + double *INPUT + +To use these, suppose you had a C function like this : + + double fadd(double *a, double *b) { + return *a+*b; + } + +You could wrap it with SWIG as follows : + + %include + double fadd(double *INPUT, double *INPUT); + +or you can use the %apply directive : + + %include + %apply double *INPUT { double *a, double *b }; + double fadd(double *a, double *b); + +*/ + +// OUTPUT typemaps. These typemaps are used for parameters that +// are output only. The output value is appended to the result as +// a list element. + +/* +The following methods can be applied to turn a pointer into an "output" +value. When calling a function, no input value would be given for +a parameter, but an output value would be returned. In the case of +multiple output values, they are returned in the form of a Python tuple. + + int *OUTPUT + short *OUTPUT + long *OUTPUT + long long *OUTPUT + unsigned int *OUTPUT + unsigned short *OUTPUT + unsigned long *OUTPUT + unsigned long long *OUTPUT + unsigned char *OUTPUT + bool *OUTPUT + float *OUTPUT + double *OUTPUT + +For example, suppose you were trying to wrap the modf() function in the +C math library which splits x into integral and fractional parts (and +returns the integer part in one of its parameters).K: + + double modf(double x, double *ip); + +You could wrap it with SWIG as follows : + + %include + double modf(double x, double *OUTPUT); + +or you can use the %apply directive : + + %include + %apply double *OUTPUT { double *ip }; + double modf(double x, double *ip); + +The Python output of the function would be a tuple containing both +output values. + +*/ + +// INOUT +// Mappings for an argument that is both an input and output +// parameter + +/* +The following methods can be applied to make a function parameter both +an input and output value. This combines the behavior of both the +"INPUT" and "OUTPUT" methods described earlier. Output values are +returned in the form of a Python tuple. + + int *INOUT + short *INOUT + long *INOUT + long long *INOUT + unsigned int *INOUT + unsigned short *INOUT + unsigned long *INOUT + unsigned long long *INOUT + unsigned char *INOUT + bool *INOUT + float *INOUT + double *INOUT + +For example, suppose you were trying to wrap the following function : + + void neg(double *x) { + *x = -(*x); + } + +You could wrap it with SWIG as follows : + + %include + void neg(double *INOUT); + +or you can use the %apply directive : + + %include + %apply double *INOUT { double *x }; + void neg(double *x); + +Unlike C, this mapping does not directly modify the input value (since +this makes no sense in Python). Rather, the modified input value shows +up as the return value of the function. Thus, to apply this function +to a Python variable you might do this : + + x = neg(x) + +Note : previous versions of SWIG used the symbol 'BOTH' to mark +input/output arguments. This is still supported, but will be slowly +phased out in future releases. + +*/ + +%include diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 0ca740caf..2996d6230 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -235,9 +235,9 @@ protected: virtual void marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) = 0; - virtual void emitInputTypemap(Node *n, Parm *p, Wrapper *wrapper, String *arg); + virtual void emitInputTypemap(Node *n, Parm *params, Wrapper *wrapper, String *arg); - virtual void marshalOutput(Node *n, Wrapper *wrapper, String *actioncode, const String *cresult=0, bool emitReturnVariable = true); + virtual void marshalOutput(Node *n, ParmList *params, Wrapper *wrapper, String *actioncode, const String *cresult=0, bool emitReturnVariable = true); virtual void emitCleanupCode(Node *n, Wrapper *wrapper, ParmList *params); @@ -984,7 +984,7 @@ int JSEmitter::emitGetter(Node *n, bool is_member, bool is_static) { // prepare code part String *action = emit_action(n); marshalInputArgs(n, params, wrapper, Getter, is_member, is_static); - marshalOutput(n, wrapper, action); + marshalOutput(n, params, wrapper, action); emitCleanupCode(n, wrapper, params); @@ -1064,7 +1064,7 @@ int JSEmitter::emitConstant(Node *n) { assert(value != NULL); String *action = NewString(""); - marshalOutput(n, wrapper, action, value, false); + marshalOutput(n, 0, wrapper, action, value, false); t_getter.replace("$jswrapper", wrap_name) .replace("$jslocals", wrapper->locals) @@ -1099,14 +1099,15 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { emit_parameter_variables(params, wrapper); emit_attach_parmmaps(params, wrapper); - // HACK: in test-case `ignore_parameter` emit_attach_parmmaps generated an extra line of applied typemap. - // Deleting wrapper->code here, to reset, and as it seemed to have no side effect elsewhere + // HACK: in test-case `ignore_parameter` emit_attach_parmmaps generates an extra line of applied typemap. + // Deleting wrapper->code here fixes the problem, and seems to have no side effect elsewhere Delete(wrapper->code); wrapper->code = NewString(""); marshalInputArgs(n, params, wrapper, Function, is_member, is_static); String *action = emit_action(n); - marshalOutput(n, wrapper, action); + + marshalOutput(n, params, wrapper, action); emitCleanupCode(n, wrapper, params); @@ -1210,9 +1211,11 @@ void JSEmitter::emitInputTypemap(Node *n, Parm *p, Wrapper *wrapper, String *arg } } -void JSEmitter::marshalOutput(Node *n, Wrapper *wrapper, String *actioncode, const String *cresult, bool emitReturnVariable) { +void JSEmitter::marshalOutput(Node *n, ParmList *params, Wrapper *wrapper, String *actioncode, const String *cresult, bool emitReturnVariable) { SwigType *type = Getattr(n, "type"); String *tm; + Parm *p; + // adds a declaration for the result variable if(emitReturnVariable) emit_return_variable(n, type, wrapper); // if not given, use default result identifier ('result') for output typemap @@ -1226,7 +1229,6 @@ void JSEmitter::marshalOutput(Node *n, Wrapper *wrapper, String *actioncode, co } if (tm) { - Replaceall(tm, "$result", "jsresult"); Replaceall(tm, "$objecttype", Swig_scopename_last(SwigType_str(SwigType_strip_qualifiers(type), 0))); if (should_own) { @@ -1242,22 +1244,26 @@ void JSEmitter::marshalOutput(Node *n, Wrapper *wrapper, String *actioncode, co } else { Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(type, 0), Getattr(n, "name")); } + + if (params) { + for (p = params; p;) { + if ((tm = Getattr(p, "tmap:argout"))) { + Replaceall(tm, "$input", Getattr(p, "emit:input")); + Printv(wrapper->code, tm, "\n", NIL); + p = Getattr(p, "tmap:argout:next"); + } else { + p = nextSibling(p); + } + } + } + + Replaceall(wrapper->code, "$result", "jsresult"); } void JSEmitter::emitCleanupCode(Node *n, Wrapper *wrapper, ParmList *params) { Parm *p; String *tm; - for (p = params; p;) { - if ((tm = Getattr(p, "tmap:argout"))) { - Replaceall(tm, "$input", Getattr(p, "emit:input")); - Printv(wrapper->code, tm, "\n", NIL); - p = Getattr(p, "tmap:argout:next"); - } else { - p = nextSibling(p); - } - } - for (p = params; p;) { if ((tm = Getattr(p, "tmap:freearg"))) { //addThrows(n, "tmap:freearg", p); From b7f827e42ce3073d44f163877f7712782740d1bf Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 16 Sep 2013 01:23:03 +0200 Subject: [PATCH 0320/1048] Fix typemap declarations for (unsigned) long long. --- Lib/javascript/jsc/javascriptprimtypes.swg | 12 +++++++++--- Lib/javascript/v8/javascriptprimtypes.swg | 19 +++++++++++++------ 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/Lib/javascript/jsc/javascriptprimtypes.swg b/Lib/javascript/jsc/javascriptprimtypes.swg index 2c23cc07f..7e9898a24 100644 --- a/Lib/javascript/jsc/javascriptprimtypes.swg +++ b/Lib/javascript/jsc/javascriptprimtypes.swg @@ -95,7 +95,9 @@ SWIG_AsVal_dec(unsigned long)(JSValueRef obj, unsigned long *val) /* long long */ // Note: these are copied from 'long' and probably need fixing -%fragment(SWIG_From_frag(long long),"header") { +%fragment(SWIG_From_frag(long long),"header", + fragment=SWIG_From_frag(long), + fragment="") { SWIGINTERNINLINE JSValueRef SWIG_From_dec(long long)(long long value) { @@ -104,7 +106,9 @@ SWIG_From_dec(long long)(long long value) } %fragment(SWIG_AsVal_frag(long long),"header", - fragment="SWIG_CanCastAsInteger") { + fragment=SWIG_AsVal_frag(long), + fragment="SWIG_CanCastAsInteger", + fragment="") { SWIGINTERN int SWIG_AsVal_dec(long long)(JSValueRef obj, long long* val) { @@ -132,7 +136,9 @@ SWIG_From_dec(unsigned long long)(unsigned long long value) } %fragment(SWIG_AsVal_frag(unsigned long long),"header", - fragment="SWIG_CanCastAsInteger") { + fragment=SWIG_AsVal_frag(unsigned long), + fragment="SWIG_CanCastAsInteger", + fragment="") { SWIGINTERN int SWIG_AsVal_dec(unsigned long long)(JSValueRef obj, unsigned long long *val) { diff --git a/Lib/javascript/v8/javascriptprimtypes.swg b/Lib/javascript/v8/javascriptprimtypes.swg index 5e0187460..706a799b7 100644 --- a/Lib/javascript/v8/javascriptprimtypes.swg +++ b/Lib/javascript/v8/javascriptprimtypes.swg @@ -110,7 +110,9 @@ int SWIG_AsVal_dec(unsigned long)(v8::Handle obj, unsigned long *val) /* long long */ // Note: these are copied from 'long' and probably need fixing -%fragment(SWIG_From_frag(long long),"header") { +%fragment(SWIG_From_frag(long long),"header", + fragment=SWIG_From_frag(long), + fragment="") { SWIGINTERNINLINE v8::Handle SWIG_From_dec(long long)(long long value) { @@ -119,9 +121,11 @@ v8::Handle SWIG_From_dec(long long)(long long value) } %fragment(SWIG_AsVal_frag(long long),"header", - fragment="SWIG_CanCastAsInteger") { + fragment=SWIG_AsVal_frag(long), + fragment="SWIG_CanCastAsInteger", + fragment="") { SWIGINTERN -int SWIG_AsVal_dec(long)(v8::Handle obj, long long* val) +int SWIG_AsVal_dec(long long)(v8::Handle obj, long long* val) { if (!obj->IsNumber()) { return SWIG_TypeError; @@ -136,7 +140,8 @@ int SWIG_AsVal_dec(long)(v8::Handle obj, long long* val) // Note: these are copied from 'unsigned long' and probably need fixing %fragment(SWIG_From_frag(unsigned long long),"header", - fragment=SWIG_From_frag(long long)) { + fragment=SWIG_From_frag(long long), + fragment="") { SWIGINTERNINLINE v8::Handle SWIG_From_dec(unsigned long long)(unsigned long long value) { @@ -146,9 +151,11 @@ v8::Handle SWIG_From_dec(unsigned long long)(unsigned long long value } %fragment(SWIG_AsVal_frag(unsigned long long),"header", - fragment="SWIG_CanCastAsInteger") { + fragment=SWIG_AsVal_frag(unsigned long), + fragment="SWIG_CanCastAsInteger", + fragment="") { SWIGINTERN -int SWIG_AsVal_dec(unsigned long)(v8::Handle obj, unsigned long long *val) +int SWIG_AsVal_dec(unsigned long long)(v8::Handle obj, unsigned long long *val) { if(!obj->IsNumber()) { return SWIG_TypeError; From bf416876ddf24249f75eff9854e551d789dfab42 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 16 Sep 2013 01:33:19 +0200 Subject: [PATCH 0321/1048] Bugfix for JSC %typemap(out) std::string&. --- Lib/javascript/jsc/std_string.i | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/javascript/jsc/std_string.i b/Lib/javascript/jsc/std_string.i index a23396fe6..fb1bd62b5 100755 --- a/Lib/javascript/jsc/std_string.i +++ b/Lib/javascript/jsc/std_string.i @@ -63,7 +63,7 @@ namespace std { %typemap(out) const string & %{ - $result = SWIGJSC_stringToValue(context, $1); + $result = SWIGJSC_stringToValue(context, *$1); %} } From 973042302b017111b06305bedafe47798fcfad86 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 16 Sep 2013 01:57:55 +0200 Subject: [PATCH 0322/1048] Removed dead code. --- Source/Modules/javascript.cxx | 74 ----------------------------------- 1 file changed, 74 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 2996d6230..e2ca9026a 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -241,8 +241,6 @@ protected: virtual void emitCleanupCode(Node *n, Wrapper *wrapper, ParmList *params); - void registerProxyType(SwigType* type); - /** * Helper function to retrieve the first parent class node. */ @@ -269,8 +267,6 @@ protected: Hash *namespaces; Hash *current_namespace; - Hash *undefined_types; - String *defaultResultName; File *f_wrappers; @@ -562,7 +558,6 @@ JSEmitter::JSEmitter() : templates(NewHash()), namespaces(NULL), current_namespace(NULL), - undefined_types(NewHash()), defaultResultName(NewString("result")), f_wrappers(NULL) { @@ -1176,20 +1171,6 @@ int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { return SWIG_OK; } -void JSEmitter::registerProxyType(SwigType* type) { - SwigType *ftype = SwigType_typedef_resolve_all(type); - if(Language::instance()->classLookup(ftype)) return; - - // TODO: confused... more try and error... understand and fix eventually - SwigType *p_ftype = SwigType_add_pointer(ftype); - - // register undefined wrappers - SwigType_remember_clientdata(p_ftype, 0); - Setattr(undefined_types, SwigType_manglestr(p_ftype), p_ftype); - - Delete(ftype); -} - void JSEmitter::emitInputTypemap(Node *n, Parm *p, Wrapper *wrapper, String *arg) { // Get input typemap for current param String *tm = Getattr(p, "tmap:in"); @@ -1223,10 +1204,6 @@ void JSEmitter::marshalOutput(Node *n, ParmList *params, Wrapper *wrapper, Strin tm = Swig_typemap_lookup_out("out", n, cresult, wrapper, actioncode); bool should_own = GetFlag(n, "feature:new"); - bool needs_proxy = GetFlag(n, "tmap:out:SWIGTYPE"); - if(needs_proxy) { - registerProxyType(type); - } if (tm) { Replaceall(tm, "$objecttype", Swig_scopename_last(SwigType_str(SwigType_strip_qualifiers(type), 0))); @@ -1760,7 +1737,6 @@ protected: virtual void marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static); virtual int emitNamespaces(); - virtual void emitUndefined(); private: @@ -1852,9 +1828,6 @@ int V8Emitter::dump(Node *) SwigType_emit_type_table(f_runtime, f_wrappers); - // This is important to have proxies for classes that have not been exposed to swig - // emitUndefined(); - Printv(f_wrap_cpp, f_runtime, "\n", 0); Printv(f_wrap_cpp, f_header, "\n", 0); Printv(f_wrap_cpp, f_class_templates, "\n", 0); @@ -2163,53 +2136,6 @@ int V8Emitter::emitNamespaces() { return SWIG_OK; } -void V8Emitter::emitUndefined() { - Iterator ki; - for (ki = First(undefined_types); ki.item; ki = Next(ki)) { - String *mangled_name = NewStringf("SWIGTYPE%s", ki.key); - SwigType *type = ki.item; - String *dtor = Swig_name_destroy("", mangled_name); - String *type_mangled = ki.key; - String *ctype = SwigType_lstr(type, ""); - - String *free = NewString(""); - if(SwigType_isarray(type)) { - Printf(free, "delete [] (%s)", ctype); - } else { - Printf(free, "delete (%s)", ctype); - } - - // emit clientData declaration - Template clientDataDecl = getTemplate("jsv8_declare_class_template"); - clientDataDecl.replace("$jsmangledname", mangled_name) - .trim() - .pretty_print(f_class_templates); - - // emit an extra dtor for unknown types - Template t_dtor = getTemplate("js_dtor"); - t_dtor.replace("$jsmangledname", mangled_name) - .replace("$jswrapper", dtor) - .replace("$jsfree", free) - .trim() - .pretty_print(f_wrappers); - - // create a class template and initialize clientData - Template clientDataDef = getTemplate("jsv8_define_class_template"); - clientDataDef.replace("$jsmangledname", mangled_name) - .replace("$jsname", mangled_name) - .replace("$jsmangledtype", type_mangled) - .replace("$jsdtor", dtor) - .trim() - .pretty_print(f_init_class_templates); - - Delete(mangled_name); - Delete(dtor); - Delete(free); - Delete(ctype); - - } -} - JSEmitter *swig_javascript_create_V8Emitter() { return new V8Emitter(); } From 80ce36c445c704a105a70d6820baefb74a7cd0ec Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 16 Sep 2013 02:27:51 +0200 Subject: [PATCH 0323/1048] Make JSC inheritance definition more robust. --- Lib/javascript/jsc/javascriptcode.swg | 15 ++++++++++++++- Source/Modules/javascript.cxx | 17 ++++++++++++----- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index 2660e0e5e..42837f7f4 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -394,11 +394,24 @@ JSStaticFunction $jsmangledname_functions[] = { $jsmangledname_classDefinition.finalize = $jsdtor; $jsmangledname_objectDefinition.staticValues = $jsmangledname_values; $jsmangledname_objectDefinition.staticFunctions = $jsmangledname_functions; - $jsmangledname_objectDefinition.parentClass = $jsbaseclass_classRef; + $jsclass_inheritance JSClassRef $jsmangledname_classRef = JSClassCreate(&$jsmangledname_objectDefinition); SWIGTYPE_$jsmangledtype->clientdata = $jsmangledname_classRef; %} +%fragment ("jsc_class_inherit", templates) +%{ + if (SWIGTYPE_p$jsbaseclassmangled != NULL) { + $jsmangledname_objectDefinition.parentClass = (JSClassRef) SWIGTYPE_p$jsbaseclassmangled->clientdata; + } +%} + +%fragment ("jsc_class_noinherit", templates) +%{ + $jsmangledname_objectDefinition.parentClass = _SwigObject_classRef; +%} + + /* ----------------------------------------------------------------------------- * jsc_register_class: template for registration of a class * - $jsname: class name diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index e2ca9026a..038094a12 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1638,19 +1638,26 @@ int JSCEmitter::exitClass(Node *n) { Template t_classtemplate(getTemplate("jsc_class_definition")); /* prepare registration of base class */ - String *base_name_mangled = NewString("_SwigObject"); + String *jsclass_inheritance = NewString(""); Node *base_class = getBaseClass(n); if (base_class != NULL) { - Delete(base_name_mangled); - base_name_mangled = SwigType_manglestr(Getattr(base_class, "name")); + Template t_inherit(getTemplate("jsc_class_inherit")); + t_inherit.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsbaseclassmangled", SwigType_manglestr(Getattr(base_class, "name"))) + .pretty_print(jsclass_inheritance); + } else { + Template t_inherit(getTemplate("jsc_class_noinherit")); + t_inherit.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .pretty_print(jsclass_inheritance); } + t_classtemplate.replace("$jsmangledname", state.clazz(NAME_MANGLED)) .replace("$jsmangledtype", state.clazz(TYPE_MANGLED)) - .replace("$jsbaseclass", base_name_mangled) + .replace("$jsclass_inheritance", jsclass_inheritance) .replace("$jsctor", state.clazz(CTOR)) .replace("$jsdtor", state.clazz(DTOR)) .pretty_print(state.global(INITIALIZER)); - Delete(base_name_mangled); + Delete(jsclass_inheritance); /* Note: this makes sure that there is a swig_type added for this class */ SwigType_remember_clientdata(state.clazz(TYPE_MANGLED), NewString("0")); From 1f07195812f79a20bb1f37178e596dd0bab8ef2e Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 16 Sep 2013 03:53:00 +0200 Subject: [PATCH 0324/1048] Rearrange generation of init block to have custom init code within the initializer body. --- Lib/javascript/jsc/javascriptcode.swg | 50 ----------------- Lib/javascript/jsc/javascriptinit.swg | 54 ++++++++++++++++++- Lib/javascript/v8/javascriptcode.swg | 68 ----------------------- Lib/javascript/v8/javascriptinit.swg | 78 +++++++++++++++++++++++++-- Source/Modules/javascript.cxx | 12 +++-- 5 files changed, 137 insertions(+), 125 deletions(-) diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index 42837f7f4..60c52b2b3 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -263,56 +263,6 @@ int $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObjec } %} -%fragment ("js_initializer_define", "templates") %{ -#define SWIGJSC_INIT $jsname_initialize -%} - -/* ----------------------------------------------------------------------------- - * js_initializer: template for the module initializer function - * - $jsname: module name - * - $jscreatenamespaces: part with code for creating namespace objects - * - $jscreateclasses: part with code for creating classes - * - $jsregisternamespaces: part with code for registration of namespaces - * ----------------------------------------------------------------------------- */ -%fragment ("js_initializer", "templates") %{ -#ifdef __cplusplus -extern "C" { -#endif - -bool SWIGJSC_INIT (JSGlobalContextRef context, JSObjectRef *exports) { - SWIG_InitializeModule(0); - - /* Initialize the base swig type object */ - _SwigObject_objectDefinition.staticFunctions = _SwigObject_functions; - _SwigObject_objectDefinition.staticValues = _SwigObject_values; - _SwigObject_classRef = JSClassCreate(&_SwigObject_objectDefinition); - - /* Initialize the PackedData class */ - _SwigPackedData_objectDefinition.staticFunctions = _SwigPackedData_functions; - _SwigPackedData_objectDefinition.staticValues = _SwigPackedData_values; - _SwigPackedData_objectDefinition.finalize = _wrap_SwigPackedData_delete; - _SwigPackedData_classRef = JSClassCreate(&_SwigPackedData_objectDefinition); - - /* Create objects for namespaces */ - $jscreatenamespaces - - /* Register classes */ - $jsregisterclasses - - /* Register namespaces */ - $jsregisternamespaces - - *exports = exports_object; - - return true; -} - -#ifdef __cplusplus -} -#endif - -%} - /* ----------------------------------------------------------------------------- * jsc_variable_declaration: template for a variable table entry * - $jsname: name of the variable diff --git a/Lib/javascript/jsc/javascriptinit.swg b/Lib/javascript/jsc/javascriptinit.swg index 69bc3a9b1..a32ba336c 100644 --- a/Lib/javascript/jsc/javascriptinit.swg +++ b/Lib/javascript/jsc/javascriptinit.swg @@ -9,7 +9,59 @@ SWIG_JSC_GetModule(void) { #define SWIG_GetModule(clientdata) SWIG_JSC_GetModule() #define SWIG_SetModule(clientdata, pointer) SWIG_JSC_SetModule(pointer) - %} %insert(init) "swiginit.swg" + +%fragment ("js_initializer_define", "templates") %{ +#define SWIGJSC_INIT $jsname_initialize +%} + +// Open the initializer function +%insert(init) +%{ + +#ifdef __cplusplus +extern "C" { +#endif + +bool SWIGJSC_INIT (JSGlobalContextRef context, JSObjectRef *exports) { + SWIG_InitializeModule(0); +%} + +/* ----------------------------------------------------------------------------- + * js_initializer: template for the module initializer function + * - $jsname: module name + * - $jscreatenamespaces: part with code for creating namespace objects + * - $jscreateclasses: part with code for creating classes + * - $jsregisternamespaces: part with code for registration of namespaces + * ----------------------------------------------------------------------------- */ +%fragment ("js_initializer", "templates") %{ + /* Initialize the base swig type object */ + _SwigObject_objectDefinition.staticFunctions = _SwigObject_functions; + _SwigObject_objectDefinition.staticValues = _SwigObject_values; + _SwigObject_classRef = JSClassCreate(&_SwigObject_objectDefinition); + + /* Initialize the PackedData class */ + _SwigPackedData_objectDefinition.staticFunctions = _SwigPackedData_functions; + _SwigPackedData_objectDefinition.staticValues = _SwigPackedData_values; + _SwigPackedData_objectDefinition.finalize = _wrap_SwigPackedData_delete; + _SwigPackedData_classRef = JSClassCreate(&_SwigPackedData_objectDefinition); + + /* Create objects for namespaces */ + $jscreatenamespaces + + /* Register classes */ + $jsregisterclasses + + /* Register namespaces */ + $jsregisternamespaces + + *exports = exports_object; + + return true; +} +#ifdef __cplusplus +} +#endif +%} diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index 1b06dbdc8..c05c6daf3 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -464,71 +464,3 @@ fail: %{ SWIGV8_AddStaticVariable($jsparent_obj, "$jsname", $jsgetter, $jssetter); %} - -/* ----------------------------------------------------------------------------- - * js_initializer: template for the module initializer function - * - $jsname: module name - * - $jsv8nspaces: part with code creating namespace objects - * - $jsv8classtemplates: part with code creating class templates - * - $jsv8wrappers: part with code that registers wrapper functions - * - $jsv8inheritance: part with inherit statements - * - $jsv8classinstances: part with code creating class objects - * - $jsv8staticwrappers: part with code adding static functions to class objects - * - $jsv8registerclasses: part with code that registers class objects in namespaces - * - $jsv8registernspaces: part with code that registers namespaces in parent namespaces - * ----------------------------------------------------------------------------- */ -%fragment("js_initializer", "templates") -%{ - -// Note: 'extern "C"'' disables name mangling which makes it easier to load the symbol manually -// TODO: is it ok to do that? -extern "C" -#if (NODE_MODULE_VERSION < 0x000C) -void $jsname_initialize(v8::Handle exports) -#else -void $jsname_initialize(v8::Handle exports, v8::Handle /*module*/) -#endif -{ - SWIG_InitializeModule(static_cast(&exports)); - - v8::HandleScope scope; - v8::Handle exports_obj = exports; - - // a class template for creating proxies of undefined types - -#if (SWIG_V8_VERSION < 0x031900) - SWIGV8_SWIGTYPE_Proxy_class_templ = v8::Persistent::New(SWIGV8_CreateClassTemplate("SwigProxy")); -#else - SWIGV8_SWIGTYPE_Proxy_class_templ.Reset(v8::Isolate::GetCurrent(), SWIGV8_CreateClassTemplate("SwigProxy")); -#endif - - /* create objects for namespaces */ - $jsv8nspaces - - /* create class templates */ - $jsv8classtemplates - - /* register wrapper functions */ - $jsv8wrappers - - /* setup inheritances */ - $jsv8inheritance - - /* class instances */ - $jsv8classinstances - - /* add static class functions and variables */ - $jsv8staticwrappers - - /* register classes */ - $jsv8registerclasses - - /* create and register namespace objects */ - $jsv8registernspaces -} - -#if defined(BUILDING_NODE_EXTENSION) -NODE_MODULE($jsname, $jsname_initialize); -#endif - -%} diff --git a/Lib/javascript/v8/javascriptinit.swg b/Lib/javascript/v8/javascriptinit.swg index 13ec1aff8..de1fe91f4 100644 --- a/Lib/javascript/v8/javascriptinit.swg +++ b/Lib/javascript/v8/javascriptinit.swg @@ -22,7 +22,7 @@ SWIG_V8_GetModule(void *) { } v8::Local moduleinfo_extern = v8::Local::Cast(moduleinfo); - + if (moduleinfo_extern.IsEmpty()) { // Something's not right @@ -41,6 +41,78 @@ SWIG_V8_GetModule(void *) { %} -%insert(init) %{/************ BEGIN: "swiginit.swg" *******************/ %} %insert(init) "swiginit.swg" -%insert(init) %{/************ END: "swiginit.swg" *******************/ %} + +// Open the initializer function definition here + +%fragment ("js_initializer_define", "templates") %{ +#define SWIGV8_INIT $jsname_initialize +%} + +%insert(init) %{ +// Note: 'extern "C"'' disables name mangling which makes it easier to load the symbol manually +// TODO: is it ok to do that? +extern "C" +#if (NODE_MODULE_VERSION < 0x000C) +void SWIGV8_INIT (v8::Handle exports) +#else +void SWIGV8_INIT (v8::Handle exports, v8::Handle /*module*/) +#endif +{ + SWIG_InitializeModule(static_cast(&exports)); + + v8::HandleScope scope; + v8::Handle exports_obj = exports; +%} + + +/* ----------------------------------------------------------------------------- + * js_initializer: template for the module initializer function + * - $jsname: module name + * - $jsv8nspaces: part with code creating namespace objects + * - $jsv8classtemplates: part with code creating class templates + * - $jsv8wrappers: part with code that registers wrapper functions + * - $jsv8inheritance: part with inherit statements + * - $jsv8classinstances: part with code creating class objects + * - $jsv8staticwrappers: part with code adding static functions to class objects + * - $jsv8registerclasses: part with code that registers class objects in namespaces + * - $jsv8registernspaces: part with code that registers namespaces in parent namespaces + * ----------------------------------------------------------------------------- */ +%fragment("js_initializer", "templates") +%{ + // a class template for creating proxies of undefined types +#if (SWIG_V8_VERSION < 0x031900) + SWIGV8_SWIGTYPE_Proxy_class_templ = v8::Persistent::New(SWIGV8_CreateClassTemplate("SwigProxy")); +#else + SWIGV8_SWIGTYPE_Proxy_class_templ.Reset(v8::Isolate::GetCurrent(), SWIGV8_CreateClassTemplate("SwigProxy")); +#endif + + /* create objects for namespaces */ + $jsv8nspaces + + /* create class templates */ + $jsv8classtemplates + + /* register wrapper functions */ + $jsv8wrappers + + /* setup inheritances */ + $jsv8inheritance + + /* class instances */ + $jsv8classinstances + + /* add static class functions and variables */ + $jsv8staticwrappers + + /* register classes */ + $jsv8registerclasses + + /* create and register namespace objects */ + $jsv8registernspaces +} + +#if defined(BUILDING_NODE_EXTENSION) +NODE_MODULE($jsname, $jsname_initialize); +#endif +%} diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 038094a12..d9ec51247 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1828,11 +1828,17 @@ int V8Emitter::initialize(Node *n) return SWIG_OK; } -int V8Emitter::dump(Node *) +int V8Emitter::dump(Node *n) { + /* Get the module name */ + String *module = Getattr(n, "name"); + // write the swig banner Swig_banner(f_wrap_cpp); + Template initializer_define(getTemplate("js_initializer_define")); + initializer_define.replace("$jsname", module).pretty_print(f_header); + SwigType_emit_type_table(f_runtime, f_wrappers); Printv(f_wrap_cpp, f_runtime, "\n", 0); @@ -1853,8 +1859,8 @@ int V8Emitter::dump(Node *) .replace("$jsv8classinstances", f_init_class_instances) .replace("$jsv8staticwrappers", f_init_static_wrappers) .replace("$jsv8registerclasses", f_init_register_classes) - .replace("$jsv8registernspaces", f_init_register_namespaces) - .pretty_print(f_init); + .replace("$jsv8registernspaces", f_init_register_namespaces); + Printv(f_init, initializer.str(), 0); Printv(f_wrap_cpp, f_init, 0); From b6426bde2501e6304193644ddc6e8c933db4412e Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 16 Sep 2013 04:12:06 +0200 Subject: [PATCH 0325/1048] Add cdata.i typemaps. --- Lib/javascript/jsc/cdata.i | 1 + Lib/javascript/v8/cdata.i | 1 + 2 files changed, 2 insertions(+) create mode 100644 Lib/javascript/jsc/cdata.i create mode 100644 Lib/javascript/v8/cdata.i diff --git a/Lib/javascript/jsc/cdata.i b/Lib/javascript/jsc/cdata.i new file mode 100644 index 000000000..367965990 --- /dev/null +++ b/Lib/javascript/jsc/cdata.i @@ -0,0 +1 @@ +%include diff --git a/Lib/javascript/v8/cdata.i b/Lib/javascript/v8/cdata.i new file mode 100644 index 000000000..367965990 --- /dev/null +++ b/Lib/javascript/v8/cdata.i @@ -0,0 +1 @@ +%include From 3e28d1e28f81688184cf2c362fa01b7efaaad790 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 16 Sep 2013 04:12:42 +0200 Subject: [PATCH 0326/1048] Let v8 generated code include stdlib.h --- Lib/javascript/v8/javascriptruntime.swg | 1 + 1 file changed, 1 insertion(+) diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg index 8df5816a9..2e18d19bf 100644 --- a/Lib/javascript/v8/javascriptruntime.swg +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -29,6 +29,7 @@ #include #include +#include %} %insert(runtime) "swigrun.swg"; /* SWIG API */ From eb9523b5caef732bbd1b259850e16dc8a9e11564 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 16 Sep 2013 04:12:55 +0200 Subject: [PATCH 0327/1048] Add missing macros. --- Lib/javascript/jsc/javascriptrun.swg | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Lib/javascript/jsc/javascriptrun.swg b/Lib/javascript/jsc/javascriptrun.swg index 0e68b7618..3463d2351 100644 --- a/Lib/javascript/jsc/javascriptrun.swg +++ b/Lib/javascript/jsc/javascriptrun.swg @@ -167,6 +167,9 @@ JSObjectRef SWIG_JSC_NewPointerObj(JSContextRef context, void *ptr, swig_type_in #define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_JSC_ConvertInstancePtr(context, obj, pptr, type, flags) #define SWIG_NewInstanceObj(thisvalue, type, flags) SWIG_JSC_NewPointerObj(context, thisvalue, type, flags) +#define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_JSC_ConvertPtr(context, obj, pptr, type, 0) +#define SWIG_NewFunctionPtrObj(ptr, type) SWIG_JSC_NewPointerObj(context, ptr, type, 0) + /* ---------------------------------------------------------------------------- * A class for packed data * From 147cec70f1226dead5d93afd711b99bc9e81827f Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 16 Sep 2013 04:54:57 +0200 Subject: [PATCH 0328/1048] Replace $symname in generated function wrappers. --- Source/Modules/javascript.cxx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index d9ec51247..97542d93a 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1081,7 +1081,8 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { bool is_overloaded = GetFlag(n, "sym:overloaded"); // prepare the function wrapper name - String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); + String *iname = Getattr(n, "sym:name"); + String *wrap_name = Swig_name_wrapper(iname); if (is_overloaded) { t_function = getTemplate("js_overloaded_function"); Append(wrap_name, Getattr(n, "sym:overname")); @@ -1106,6 +1107,8 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { emitCleanupCode(n, wrapper, params); + Replaceall(wrapper->code, "$symname", iname); + t_function.replace("$jswrapper", wrap_name) .replace("$jslocals", wrapper->locals) .replace("$jscode", wrapper->code) From 0528fd3ac3f6205ce642fa6997908df160030608 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 16 Sep 2013 11:46:00 +0200 Subject: [PATCH 0329/1048] Bugfix for Javascript generator. --- Lib/javascript/v8/javascriptcode.swg | 4 +++- Source/Modules/javascript.cxx | 11 +++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg index c05c6daf3..9bcb33176 100644 --- a/Lib/javascript/v8/javascriptcode.swg +++ b/Lib/javascript/v8/javascriptcode.swg @@ -337,7 +337,9 @@ fail: $jsmangledname_clientData.class_templ.Reset(v8::Isolate::GetCurrent(), $jsmangledname_class); #endif $jsmangledname_clientData.dtor = $jsdtor; - SWIGTYPE_$jsmangledtype->clientdata = &$jsmangledname_clientData; + if (SWIGTYPE_$jsmangledtype->clientdata == 0) { + SWIGTYPE_$jsmangledtype->clientdata = &$jsmangledname_clientData; + } %} diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 97542d93a..99030a772 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -416,6 +416,10 @@ int JAVASCRIPT::constantWrapper(Node *n) { if (Equal(Getattr(n, "kind"), "function")) { return SWIG_OK; } + // TODO: the emitter for constants must be implemented in a cleaner way + // currently we treat it like a read-only variable + // however, there is a remaining bug with function pointer constants + // which could be fixed with a cleaner approach emitter->emitConstant(n); return SWIG_OK; @@ -706,7 +710,8 @@ int JSEmitter::enterClass(Node *n) { state.clazz(true); state.clazz(NAME, Getattr(n, "sym:name")); - state.clazz(NAME_MANGLED, SwigType_manglestr(Getattr(n, "name"))); + //state.clazz(NAME_MANGLED, SwigType_manglestr(Getattr(n, "name"))); + state.clazz(NAME_MANGLED, Getattr(n, "sym:name")); state.clazz(TYPE, NewString(Getattr(n, "classtype"))); String *type = SwigType_manglestr(Getattr(n, "classtypeobj")); @@ -1921,7 +1926,9 @@ int V8Emitter::exitClass(Node *n) /* Note: this makes sure that there is a swig_type added for this class */ String *clientData = NewString(""); Printf(clientData, "&%s_clientData", state.clazz(NAME_MANGLED)); - SwigType_remember_clientdata(state.clazz(TYPE_MANGLED), clientData); + + /* Note: this makes sure that there is a swig_type added for this class */ + SwigType_remember_clientdata(state.clazz(TYPE_MANGLED), NewString("0")); // emit definition of v8 class template Template t_def_class = getTemplate("jsv8_define_class_template"); From dd4ed7f3d6bc6a13c271ac7ffb629115414113ec Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 16 Sep 2013 11:46:52 +0200 Subject: [PATCH 0330/1048] Disable testcase 'typemap_variables' for v8. It uses output typemaps that are not compatible with the v8 API. --- Examples/test-suite/javascript/Makefile.in | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index 70c404e61..940016726 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -62,9 +62,6 @@ CPP_TEST_CASES = \ using2 \ javascript_unicode -BROKEN_TEST_CASES = \ - infinity - SKIP_CPP_CASES = @SKIP_CPP_CASES@ SKIP_C_CASES = @SKIP_C_CASES@ SKIP_CPP_STD_CASES = @SKIP_CPP_STD_CASES@ @@ -81,6 +78,13 @@ _setup = \ echo "$(ACTION)ing testcase $* under javascript ($(JSENGINE))" ; \ fi; +ifeq (v8,$(ENGINE)) + + typemap_variables.cpptest: + echo "skipping testcase typemap_variables under javascript (v8)." + +endif + ifeq (node,$(JSENGINE)) SWIGOPT += -v8 -DBUILDING_NODE_EXTENSION=1 @@ -141,6 +145,7 @@ ifeq (v8,$(ENGINE)) $(_setup) +$(swig_and_compile_cpp) $(run_testcase) + endif ifeq (jsc,$(ENGINE)) From b99e8613ad7103bd99d7f6c7e24b774c73467201 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 16 Sep 2013 21:56:52 +0200 Subject: [PATCH 0331/1048] Bugfix in argument marshalling. --- Source/Modules/javascript.cxx | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 99030a772..3d85fc974 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -235,7 +235,7 @@ protected: virtual void marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) = 0; - virtual void emitInputTypemap(Node *n, Parm *params, Wrapper *wrapper, String *arg); + virtual String *emitInputTypemap(Node *n, Parm *params, Wrapper *wrapper, String *arg); virtual void marshalOutput(Node *n, ParmList *params, Wrapper *wrapper, String *actioncode, const String *cresult=0, bool emitReturnVariable = true); @@ -1179,7 +1179,7 @@ int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { return SWIG_OK; } -void JSEmitter::emitInputTypemap(Node *n, Parm *p, Wrapper *wrapper, String *arg) { +String *JSEmitter::emitInputTypemap(Node *n, Parm *p, Wrapper *wrapper, String *arg) { // Get input typemap for current param String *tm = Getattr(p, "tmap:in"); SwigType *type = Getattr(p, "type"); @@ -1197,7 +1197,10 @@ void JSEmitter::emitInputTypemap(Node *n, Parm *p, Wrapper *wrapper, String *arg Printf(wrapper->code, "%s\n", tm); } else { Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(type, 0)); + Swig_print(p); } + + return tm; } void JSEmitter::marshalOutput(Node *n, ParmList *params, Wrapper *wrapper, String *actioncode, const String *cresult, bool emitReturnVariable) { @@ -1413,6 +1416,7 @@ JSCEmitter::~JSCEmitter() { void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) { Parm *p; + String *tm; // determine an offset index, as members have an extra 'this' argument // except: static members and ctors. @@ -1429,7 +1433,7 @@ void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Ma // process arguments int i = 0; - for (p = parms; p; p = nextSibling(p), i++) { + for (p = parms; p; i++) { String *arg = NewString(""); switch (mode) { case Getter: @@ -1453,8 +1457,13 @@ void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Ma default: throw "Illegal state."; } - emitInputTypemap(n, p, wrapper, arg); + tm = emitInputTypemap(n, p, wrapper, arg); Delete(arg); + if (tm) { + p = Getattr(p, "tmap:in:next"); + } else { + p = nextSibling(p); + } } } @@ -2066,6 +2075,7 @@ int V8Emitter::exitFunction(Node* n) void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) { Parm *p; + String *tm; int startIdx = 0; if (is_member && !is_static && mode!=Ctor) { @@ -2109,8 +2119,14 @@ void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Mar default: throw "Illegal state."; } - emitInputTypemap(n, p, wrapper, arg); + + tm = emitInputTypemap(n, p, wrapper, arg); Delete(arg); + if (tm) { + p = Getattr(p, "tmap:in:next"); + } else { + p = nextSibling(p); + } } } From b3c198ccee3dad34f75c4617900e53e1770f0ee9 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 16 Sep 2013 22:28:14 +0200 Subject: [PATCH 0332/1048] Fix regression. --- Source/Modules/javascript.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 3d85fc974..3807e072a 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1197,7 +1197,6 @@ String *JSEmitter::emitInputTypemap(Node *n, Parm *p, Wrapper *wrapper, String * Printf(wrapper->code, "%s\n", tm); } else { Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(type, 0)); - Swig_print(p); } return tm; @@ -2089,7 +2088,7 @@ void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Mar Setattr(n, ARGCOUNT, argcount); int i = 0; - for (p = parms; p; p = nextSibling(p), i++) { + for (p = parms; p; i++) { String *arg = NewString(""); switch (mode) { case Getter: @@ -2122,6 +2121,7 @@ void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Mar tm = emitInputTypemap(n, p, wrapper, arg); Delete(arg); + if (tm) { p = Getattr(p, "tmap:in:next"); } else { From d34a6da08c1dd59ad14731f4ea6a7e8b3b6dd8b7 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 17 Sep 2013 01:53:22 +0200 Subject: [PATCH 0333/1048] Disable warnings for some v8 test-cases. --- Examples/test-suite/javascript/Makefile.in | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index 940016726..d7e7fce40 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -80,9 +80,16 @@ _setup = \ ifeq (v8,$(ENGINE)) + # This test can not be run with v8 as it uses v8 API incompatible output typemaps typemap_variables.cpptest: echo "skipping testcase typemap_variables under javascript (v8)." + # with v8 we have to generate C++ wrappers only + # these tests did raise warnings which are ignored + nested.ctest: SWIGOPT += -w312,-325 + nested_structs.ctest: SWIGOPT += -w312,-325 + unions.ctest: SWIGOPT += -w312,-325 + endif ifeq (node,$(JSENGINE)) From 173c4b3bbaec6afcb8d01dc59785664c124aa084 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 20 Sep 2013 19:39:30 +0100 Subject: [PATCH 0334/1048] 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 8bf966a65c2120d2bf050857587e7e7bd7cafd58 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 24 Sep 2013 01:47:13 +0200 Subject: [PATCH 0335/1048] Fix %nspace support and activated relevant tests. --- Examples/test-suite/director_nspace.i | 16 +-- Examples/test-suite/javascript/Makefile.in | 2 + .../javascript/nspace_extend_runme.js | 27 ++++++ .../test-suite/javascript/nspace_runme.js | 77 +++++++++++++++ Examples/test-suite/nspace.i | 2 +- Examples/test-suite/nspace_extend.i | 2 +- Source/Modules/javascript.cxx | 97 +++++++++++++------ 7 files changed, 181 insertions(+), 42 deletions(-) create mode 100644 Examples/test-suite/javascript/nspace_extend_runme.js create mode 100644 Examples/test-suite/javascript/nspace_runme.js diff --git a/Examples/test-suite/director_nspace.i b/Examples/test-suite/director_nspace.i index 6814a43a3..264604877 100644 --- a/Examples/test-suite/director_nspace.i +++ b/Examples/test-suite/director_nspace.i @@ -15,10 +15,10 @@ namespace Bar FooBar() {} FooBar(const FooBar&) {} virtual ~FooBar() {} - + std::string FooBarDo() { return "Bar::Foo2::Foo2Bar()"; } }; - + class Foo { public: virtual ~Foo() {} @@ -37,7 +37,7 @@ namespace Bar %include // nspace feature only supported by these languages -#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGD) +#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGD) || defined(SWIGJAVASCRIPT) %nspace Bar::Foo; %nspace Bar::FooBar; #else @@ -47,17 +47,17 @@ namespace Bar %feature("director") Bar::Foo; namespace Bar -{ +{ class FooBar { public: FooBar(); FooBar(const FooBar&); virtual ~FooBar(); - + std::string FooBarDo(); - + }; - + class Foo { public: @@ -67,7 +67,7 @@ namespace Bar virtual std::string fooBar(FooBar* fb); virtual Foo makeFoo(); virtual FooBar makeFooBar(); - + static Foo* get_self(Foo *self_); }; } diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index d7e7fce40..40aa0ec86 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -45,6 +45,8 @@ CPP_TEST_CASES = \ cpp_static \ enum_template \ namespace_virtual_method \ + nspace \ + nspace_extend \ overload_copy \ rename_simple \ rename_scope \ diff --git a/Examples/test-suite/javascript/nspace_extend_runme.js b/Examples/test-suite/javascript/nspace_extend_runme.js new file mode 100644 index 000000000..ab81c19d3 --- /dev/null +++ b/Examples/test-suite/javascript/nspace_extend_runme.js @@ -0,0 +1,27 @@ +var nspace_extend = require("./nspace_extend"); + +// constructors and destructors +var color1 = new nspace_extend.Outer.Inner1.Color(); +var color = new nspace_extend.Outer.Inner1.Color(color1); +delete color1; + +// class methods +color.colorInstanceMethod(20.0); +nspace_extend.Outer.Inner1.Color.colorStaticMethod(20.0); +var created = nspace_extend.Outer.Inner1.Color.create(); + + +// constructors and destructors +var color2 = new nspace_extend.Outer.Inner2.Color(); +color = new nspace_extend.Outer.Inner2.Color(color2); +delete color2; + +// class methods +color.colorInstanceMethod(20.0); +nspace_extend.Outer.Inner2.Color.colorStaticMethod(20.0); +created = nspace_extend.Outer.Inner2.Color.create(); + +// Same class different namespaces +var col1 = new nspace_extend.Outer.Inner1.Color(); +var col2 = nspace_extend.Outer.Inner2.Color.create(); +col2.colors(col1, col1, col2, col2, col2); diff --git a/Examples/test-suite/javascript/nspace_runme.js b/Examples/test-suite/javascript/nspace_runme.js new file mode 100644 index 000000000..929a6b21d --- /dev/null +++ b/Examples/test-suite/javascript/nspace_runme.js @@ -0,0 +1,77 @@ +var nspace = require("./nspace"); + +var color1 = new nspace.Outer.Inner1.Color(); +var color = new nspace.Outer.Inner1.Color(color1); +delete color1; + +// class methods +color.colorInstanceMethod(20.0); +nspace.Outer.Inner1.Color.colorStaticMethod(20.0); +var created = nspace.Outer.Inner1.Color.create(); + +// class enums +var someClass = new nspace.Outer.SomeClass(); +var channel = someClass.GetInner1ColorChannel(); +if (channel != nspace.Outer.Inner1.Color.Transmission) { + throw new Error("Failed."); +} + +// class anonymous enums +var val1 = nspace.Outer.Inner1.Color.ColorEnumVal1; +var val2 = nspace.Outer.Inner1.Color.ColorEnumVal2; +if (val1 !== 0 || val2 !== 0x22) { + throw new Error("Failed."); +} + +// instance member variables +color.instanceMemberVariable = 123; +if (color.instanceMemberVariable !== 123) { + throw new Error("Failed."); +} + +// static member variables +nspace.Outer.Inner1.Color.staticMemberVariable = 789; +if (nspace.Outer.Inner1.Color.staticMemberVariable !== 789) { + throw new Error("Failed."); +} + +if (nspace.Outer.Inner1.Color.staticConstMemberVariable !== 222) { + throw new Error("Failed."); +} + +if (nspace.Outer.Inner1.Color.staticConstEnumMemberVariable !== nspace.Outer.Inner1.Color.Transmission) { + throw new Error("Failed."); +} + +// Same class different namespaces +var col1 = new nspace.Outer.Inner1.Color(); +var col2 = nspace.Outer.Inner2.Color.create(); +col2.colors(col1, col1, col2, col2, col2); + +// TODO: why isn't it scoped in the namespace??? +nspace.namespaceFunction(color); +nspace.Outer.Inner1.namespaceVar = 111; +if (nspace.Outer.Inner1.namespaceVar !== 111) { + throw new Error("Failed."); +} + +// global enums +var outerChannel1 = someClass.GetInner1Channel(); +if (outerChannel1 != nspace.Outer.Inner1.Transmission1) { + throw new Error("Failed."); +} + +var outerChannel2 = someClass.GetInner2Channel(); +if (outerChannel2 !== nspace.Outer.Inner2.Transmission2) { + throw new Error("Failed."); +} + +// turn feature off / ignoring +var ns = new nspace.Outer.namespce(); +var nons = new nspace.NoNSpacePlease(); + +// Derived class +var blue3 = new nspace.Outer.Inner3.Blue(); +blue3.blueInstanceMethod(); +var blue4 = new nspace.Outer.Inner4.Blue(); +blue4.blueInstanceMethod(); diff --git a/Examples/test-suite/nspace.i b/Examples/test-suite/nspace.i index 2e10542d3..9bffc21ff 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(SWIGJAVASCRIPT) #if defined(SWIGJAVA) SWIG_JAVABODY_PROXY(public, public, SWIGTYPE) diff --git a/Examples/test-suite/nspace_extend.i b/Examples/test-suite/nspace_extend.i index 1965ef8f6..7c1b075ed 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(SWIGJAVASCRIPT) #if defined(SWIGJAVA) SWIG_JAVABODY_PROXY(public, public, SWIGTYPE) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 3807e072a..13a0aab7d 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -396,7 +396,6 @@ int JAVASCRIPT::variableHandler(Node *n) { * --------------------------------------------------------------------- */ int JAVASCRIPT::globalvariableHandler(Node *n) { - emitter->switchNamespace(n); Language::globalvariableHandler(n); @@ -410,6 +409,7 @@ int JAVASCRIPT::globalvariableHandler(Node *n) { * --------------------------------------------------------------------- */ int JAVASCRIPT::constantWrapper(Node *n) { + emitter->switchNamespace(n); // Note: callbacks trigger this wrapper handler // TODO: handle callback declarations @@ -464,7 +464,6 @@ int JAVASCRIPT::fragmentDirective(Node *n) { * --------------------------------------------------------------------- */ int JAVASCRIPT::top(Node *n) { - emitter->initialize(n); Language::top(n); @@ -482,7 +481,6 @@ int JAVASCRIPT::top(Node *n) { * --------------------------------------------------------------------- */ void JAVASCRIPT::main(int argc, char *argv[]) { - // Set javascript subdirectory in SWIG library SWIG_library_directory("javascript"); @@ -667,7 +665,7 @@ int JSEmitter::emitWrapperFunction(Node *n) { if (kind) { if (Cmp(kind, "function") == 0) { - bool is_member = GetFlag(n, "ismember"); + bool is_member = GetFlag(n, "ismember") | GetFlag(n, "feature:extend"); bool is_static = GetFlag(state.function(), IS_STATIC); ret = emitFunction(n, is_member, is_static); } else if (Cmp(kind, "variable") == 0) { @@ -707,18 +705,23 @@ int JSEmitter::emitWrapperFunction(Node *n) { } int JSEmitter::enterClass(Node *n) { - state.clazz(true); state.clazz(NAME, Getattr(n, "sym:name")); - //state.clazz(NAME_MANGLED, SwigType_manglestr(Getattr(n, "name"))); - state.clazz(NAME_MANGLED, Getattr(n, "sym:name")); + state.clazz("nspace", current_namespace); + + // Creating a mangled name using the current namespace and the symbol name + String *mangled_name = NewString(""); + Printf(mangled_name, "%s_%s", Getattr(current_namespace, NAME_MANGLED), Getattr(n, "sym:name")); + state.clazz(NAME_MANGLED, SwigType_manglestr(mangled_name)); + Delete(mangled_name); + state.clazz(TYPE, NewString(Getattr(n, "classtype"))); String *type = SwigType_manglestr(Getattr(n, "classtypeobj")); String *classtype_mangled = NewString(""); Printf(classtype_mangled, "p%s", type); - Delete(type); state.clazz(TYPE_MANGLED, classtype_mangled); + Delete(type); String *ctor_wrapper = NewString("_wrap_new_veto_"); Append(ctor_wrapper, state.clazz(NAME)); @@ -734,23 +737,19 @@ int JSEmitter::enterClass(Node *n) { } int JSEmitter::enterFunction(Node *n) { - state.function(true); state.function(NAME, Getattr(n, "sym:name")); if(Equal(Getattr(n, "storage"), "static")) { SetFlag(state.function(), IS_STATIC); } - return SWIG_OK; } int JSEmitter::enterVariable(Node *n) { - // reset the state information for variables. state.variable(true); // Retrieve a pure symbol name. Using 'sym:name' as a basis, as it considers %renamings. - if (Equal(Getattr(n, "view"), "memberconstantHandler")) { // Note: this is kind of hacky/experimental // For constants/enums 'sym:name' contains e.g., 'Foo_Hello' instead of 'Hello' @@ -763,10 +762,12 @@ int JSEmitter::enterVariable(Node *n) { SetFlag(state.variable(), IS_STATIC); } - if (!Language::instance()->is_assignable(n) - // FIXME: test "arrays_global" does not compile with that as it is not allowed to assign to char[] - // probably some error in char[] typemap - || Equal(Getattr(n, "type"), "a().char")) { + if (!Language::instance()->is_assignable(n)) { + SetFlag(state.variable(), IS_IMMUTABLE); + } + + // FIXME: test "arrays_global" does not compile with that as it is not allowed to assign to char[] + if (Equal(Getattr(n, "type"), "a().char")) { SetFlag(state.variable(), IS_IMMUTABLE); } @@ -1273,23 +1274,43 @@ void JSEmitter::emitCleanupCode(Node *n, Wrapper *wrapper, ParmList *params) { } int JSEmitter::switchNamespace(Node *n) { + // HACK: somehow this gets called when member functions are processed...ignoring + if (GetFlag(n, "ismember")) { + return SWIG_OK; + } + String *nspace = Getattr(n, "sym:nspace"); + + // if nspace is deactivated, everything goes into the global scope if (!GetFlag(n, "feature:nspace")) { current_namespace = Getattr(namespaces, "::"); - } else { - String *scope = Swig_scopename_prefix(Getattr(n, "name")); - if (scope) { - // if the scope is not yet registered - // create (parent) namespaces recursively - if (!Getattr(namespaces, scope)) { - createNamespace(scope); - } - current_namespace = Getattr(namespaces, scope); - } else { - current_namespace = Getattr(namespaces, "::"); + return SWIG_OK; + } + + if (nspace == NULL) { + // enums and constants do not have 'sym:nspace' set + // so we try to get the namespace from the qualified name + if(Equal(Getattr(n, "nodeType"), "enumitem")) { + nspace = Swig_scopename_prefix(Getattr(n, "name")); } } + if (nspace == NULL) { + current_namespace = Getattr(namespaces, "::"); + return SWIG_OK; + } + + String *scope = NewString(nspace); + // replace "." with "::" that we can use Swig_scopename_last + Replaceall(scope, ".", "::"); + + // if the scope is not yet registered + // create (parent) namespaces recursively + if (!Getattr(namespaces, scope)) { + createNamespace(scope); + } + current_namespace = Getattr(namespaces, scope); + return SWIG_OK; } @@ -1434,6 +1455,12 @@ void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Ma int i = 0; for (p = parms; p; i++) { String *arg = NewString(""); + String *type = Getattr(p, "type"); + + // ignore varargs + if (SwigType_isvarargs(type)) + break; + switch (mode) { case Getter: case Function: @@ -1556,7 +1583,7 @@ int JSCEmitter::enterFunction(Node *n) { int JSCEmitter::exitFunction(Node *n) { Template t_function = getTemplate("jsc_function_declaration"); - bool is_member = GetFlag(n, "ismember"); + bool is_member = GetFlag(n, "ismember") | GetFlag(n, "feature:extend"); bool is_overloaded = GetFlag(n, "sym:overloaded"); // handle overloaded functions @@ -1682,7 +1709,7 @@ int JSCEmitter::exitClass(Node *n) { Template t_registerclass(getTemplate("jsc_class_registration")); t_registerclass.replace("$jsname", state.clazz(NAME)) .replace("$jsmangledname", state.clazz(NAME_MANGLED)) - .replace("$jsnspace", Getattr(current_namespace, NAME_MANGLED)) + .replace("$jsnspace", Getattr(state.clazz("nspace"),NAME_MANGLED)) .pretty_print(state.global(INITIALIZER)); return SWIG_OK; @@ -1973,7 +2000,7 @@ int V8Emitter::exitClass(Node *n) Template t_register = getTemplate("jsv8_register_class"); t_register.replace("$jsmangledname", state.clazz(NAME_MANGLED)) .replace("$jsname", state.clazz(NAME)) - .replace("$jsparent", Getattr(current_namespace, "name_mangled")) + .replace("$jsparent", Getattr(state.clazz("nspace"),NAME_MANGLED)) .trim() .pretty_print(f_init_register_classes); @@ -2014,7 +2041,7 @@ int V8Emitter::exitVariable(Node* n) // Note: a global variable is treated like a static variable // with the parent being a nspace object (instead of class object) Template t_register = getTemplate("jsv8_register_static_variable"); - t_register.replace("$jsparent", Getattr(current_namespace, NAME)) + t_register.replace("$jsparent", Getattr(current_namespace, NAME_MANGLED)) .replace("$jsname", state.variable(NAME)) .replace("$jsgetter", state.variable(GETTER)) .replace("$jssetter", state.variable(SETTER)) @@ -2027,7 +2054,7 @@ int V8Emitter::exitVariable(Node* n) int V8Emitter::exitFunction(Node* n) { - bool is_member = GetFlag(n, "ismember"); + bool is_member = GetFlag(n, "ismember") | GetFlag(n, "feature:extend"); // create a dispatcher for overloaded functions bool is_overloaded = GetFlag(n, "sym:overloaded"); @@ -2090,6 +2117,12 @@ void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Mar int i = 0; for (p = parms; p; i++) { String *arg = NewString(""); + String *type = Getattr(p, "type"); + + // ignore varargs + if (SwigType_isvarargs(type)) + break; + switch (mode) { case Getter: if (is_member && !is_static && i == 0) { From b9ecf75f17c05bc58d6e6347877b5aedd92d2d28 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 24 Sep 2013 01:50:13 +0200 Subject: [PATCH 0336/1048] Fix emitter for member pointer constants. However, I am not happy with the constant emitter in general. Should not return dynamic values but register constant wrappers statically. --- Source/Modules/javascript.cxx | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 13a0aab7d..05912a69e 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1044,30 +1044,37 @@ int JSEmitter::emitSetter(Node *n, bool is_member, bool is_static) { int JSEmitter::emitConstant(Node *n) { Wrapper *wrapper = NewWrapper(); + SwigType *type = Getattr(n, "type"); + String *name = Getattr(n, "name"); + String *iname = Getattr(n, "sym:name"); + String *wname = Swig_name_wrapper(name); + String *rawval = Getattr(n, "rawval"); + String *value = rawval ? rawval : Getattr(n, "value"); Template t_getter(getTemplate("js_getter")); // call the variable methods as a constants are // registred in same way enterVariable(n); + state.variable(GETTER, wname); + // TODO: why do we need this? + Setattr(n, "wrap:name", wname); - // prepare function wrapper name - String *wrap_name = Swig_name_wrapper(Getattr(n, "name")); - state.variable(GETTER, wrap_name); - Setattr(n, "wrap:name", wrap_name); - - // prepare code part - String *value = Getattr(n, "rawval"); - if (value == NULL) { - value = Getattr(n, "rawvalue"); - if (value == NULL) value = Getattr(n, "value"); + // special treatment of member pointers + if (SwigType_type(type) == T_MPOINTER) { + // TODO: this could go into a code-template + String *mpointer_wname = NewString(""); + Printf(mpointer_wname, "_wrapConstant_%s", iname); + Setattr(n, "memberpointer:constant:wrap:name", mpointer_wname); + String *str = SwigType_str(type, mpointer_wname); + Printf(f_wrappers, "static %s = %s;\n", str, value); + Delete(str); + value = mpointer_wname; } - assert(value != NULL); - String *action = NewString(""); - marshalOutput(n, 0, wrapper, action, value, false); + marshalOutput(n, 0, wrapper, NewString(""), value, false); - t_getter.replace("$jswrapper", wrap_name) + t_getter.replace("$jswrapper", wname) .replace("$jslocals", wrapper->locals) .replace("$jscode", wrapper->code) .pretty_print(f_wrappers); From 2efe63ebb2c87e2e8cde445ffdf964f6cc38869e Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 24 Sep 2013 01:50:33 +0200 Subject: [PATCH 0337/1048] Add some test runners. --- .../test-suite/javascript/callback_runme.js | 30 +++++++++++++ .../test-suite/javascript/disown_runme.js | 22 ++++++++++ .../javascript/dynamic_cast_runme.js | 12 +++++ Examples/test-suite/javascript/empty_runme.js | 1 + .../test-suite/javascript/varargs_runme.js | 44 +++++++++++++++++++ 5 files changed, 109 insertions(+) create mode 100644 Examples/test-suite/javascript/callback_runme.js create mode 100644 Examples/test-suite/javascript/disown_runme.js create mode 100644 Examples/test-suite/javascript/dynamic_cast_runme.js create mode 100644 Examples/test-suite/javascript/empty_runme.js create mode 100644 Examples/test-suite/javascript/varargs_runme.js diff --git a/Examples/test-suite/javascript/callback_runme.js b/Examples/test-suite/javascript/callback_runme.js new file mode 100644 index 000000000..9b1ef01a3 --- /dev/null +++ b/Examples/test-suite/javascript/callback_runme.js @@ -0,0 +1,30 @@ +var callback = require("./callback"); + +if (callback.foo(2) !== 2) { + throw new Error("Failed."); +} +if (callback.A_bar(2) !== 4) { + throw new Error("Failed."); +} +if (callback.foobar(3, callback.foo) != callback.foo(3)) { + throw new Error("Failed."); +} +if (callback.foobar(3, foo) != callback.foo(3)) { + throw new Error("Failed."); +} +if (callback.foobar(3, callback.A_bar) != callback.A_bar(3)) { + throw new Error("Failed."); +} +if (callback.foobar(3, callback.foof) != callback.foof(3)) { + throw new Error("Failed."); +} +if (callback.foobar_i(3, callback.foo_i) != callback.foo_i(3)) { + throw new Error("Failed."); +} +if (callback.foobar_d(3.5, callback.foo_d) != callback.foo_d(3.5)) { + throw new Error("Failed."); +} +var a = new callback.A(); +if (callback.foobarm(3, a, callback.A.foom_cb_ptr) != a.foom(3)) { + throw new Error("Failed."); +} diff --git a/Examples/test-suite/javascript/disown_runme.js b/Examples/test-suite/javascript/disown_runme.js new file mode 100644 index 000000000..a4a6fd880 --- /dev/null +++ b/Examples/test-suite/javascript/disown_runme.js @@ -0,0 +1,22 @@ +var disown = require("./disown"); + +var a = new disown.A(); +var tmp = a.thisown; +a.thisown = 0 +if (a.thisown) { + throw new Error("Failed."); +} +a.thisown = 1 +if (!a.thisown) { + throw new Error("Failed."); +} +a.thisown = tmp +if (a.thisown != tmp) { + throw new Error("Failed."); +} + +var b = new disown.B(); +b.acquire(a); +if (a.thisown) { + throw new Error("Failed."); +} diff --git a/Examples/test-suite/javascript/dynamic_cast_runme.js b/Examples/test-suite/javascript/dynamic_cast_runme.js new file mode 100644 index 000000000..0029cb0f8 --- /dev/null +++ b/Examples/test-suite/javascript/dynamic_cast_runme.js @@ -0,0 +1,12 @@ +var dynamic_cast = require("./dynamic_cast"); + +var f = new dynamic_cast.Foo(); +var b = new dynamic_cast.Bar(); + +var x = f.blah(); +var y = b.blah(); + +var a = dynamic_cast.do_test(y); +if (a != "Bar::test") { + throw new Error("Failed."); +} diff --git a/Examples/test-suite/javascript/empty_runme.js b/Examples/test-suite/javascript/empty_runme.js new file mode 100644 index 000000000..db06b3902 --- /dev/null +++ b/Examples/test-suite/javascript/empty_runme.js @@ -0,0 +1 @@ +var empty = require("./empty"); \ No newline at end of file diff --git a/Examples/test-suite/javascript/varargs_runme.js b/Examples/test-suite/javascript/varargs_runme.js new file mode 100644 index 000000000..69d761e63 --- /dev/null +++ b/Examples/test-suite/javascript/varargs_runme.js @@ -0,0 +1,44 @@ +var varargs = require("./varargs"); + +if (varargs.test("Hello") != "Hello") { + throw new Error("Failed"); +} + +var f = new varargs.Foo("Greetings") +if (f.str != "Greetings") { + throw new Error("Failed"); +} + +if (f.test("Hello") != "Hello") { + throw new Error("Failed"); +} + +if (varargs.test_def("Hello",1) != "Hello") { + throw new Error("Failed"); +} + +if (varargs.test_def("Hello") != "Hello") { + throw new Error("Failed"); +} + +if (varargs.test_plenty("Hello") != "Hello") { + throw new Error("Failed"); +} + +if (varargs.test_plenty("Hello", 1) != "Hello") { + throw new Error("Failed"); +} + +if (varargs.test_plenty("Hello", 1, 2) != "Hello") { + throw new Error("Failed"); +} + +var thrown = false; +try { + varargs.test_plenty("Hello", 1, 2, 3); +} catch (err) { + thrown = true; +} +if (!thrown) { + throw new Error("Failed"); +} From dc62a69775f7eff6a11e7ca7f162ae960b53e671 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 24 Sep 2013 03:55:10 +0200 Subject: [PATCH 0338/1048] Fix bug with typedefd function pointers. --- Source/Modules/javascript.cxx | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 05912a69e..8a77a0b48 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -664,7 +664,12 @@ int JSEmitter::emitWrapperFunction(Node *n) { String *kind = Getattr(n, "kind"); if (kind) { - if (Cmp(kind, "function") == 0) { + + if (Equal(kind, "function") + // HACK: sneaky.ctest revealed that typedef'd (global) functions must be + // detected via the 'view' attribute. + || (Equal(kind, "variable") && Equal(Getattr(n, "view"), "globalfunctionHandler")) + ) { bool is_member = GetFlag(n, "ismember") | GetFlag(n, "feature:extend"); bool is_static = GetFlag(state.function(), IS_STATIC); ret = emitFunction(n, is_member, is_static); From 51b36d1a1f0c9efe3ef3d25c8bd8c3dfecfa4a52 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 24 Sep 2013 03:55:51 +0200 Subject: [PATCH 0339/1048] Add non pretty printing function to Templates. --- Source/Modules/javascript.cxx | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 8a77a0b48..239981219 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -78,6 +78,8 @@ public: Template& replace(const String *pattern, const String *repl); + Template& print(DOH *doh); + Template& pretty_print(DOH *doh); void operator=(const Template& t); @@ -1092,7 +1094,6 @@ int JSEmitter::emitConstant(Node *n) { } int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { - Wrapper *wrapper = NewWrapper(); Template t_function(getTemplate("js_function")); @@ -2038,8 +2039,8 @@ int V8Emitter::exitVariable(Node* n) .replace("$jsname", state.variable(NAME)) .replace("$jsgetter", state.variable(GETTER)) .replace("$jssetter", state.variable(SETTER)) - .trim() - .pretty_print(f_init_static_wrappers); + .trim(). + print(f_init_static_wrappers); } else { Template t_register = getTemplate("jsv8_register_member_variable"); t_register.replace("$jsmangledname", state.clazz(NAME_MANGLED)) @@ -2047,7 +2048,7 @@ int V8Emitter::exitVariable(Node* n) .replace("$jsgetter", state.variable(GETTER)) .replace("$jssetter", state.variable(SETTER)) .trim() - .pretty_print(f_init_wrappers); + .print(f_init_wrappers); } } else { // Note: a global variable is treated like a static variable @@ -2058,7 +2059,7 @@ int V8Emitter::exitVariable(Node* n) .replace("$jsgetter", state.variable(GETTER)) .replace("$jssetter", state.variable(SETTER)) .trim() - .pretty_print(f_init_wrappers); + .print(f_init_wrappers); } return SWIG_OK; @@ -2088,14 +2089,14 @@ int V8Emitter::exitFunction(Node* n) .replace("$jsname", state.function(NAME)) .replace("$jswrapper", state.function(WRAPPER_NAME)) .trim() - .pretty_print(f_init_static_wrappers); + .print(f_init_static_wrappers); } else { Template t_register = getTemplate("jsv8_register_member_function"); t_register.replace("$jsmangledname", state.clazz(NAME_MANGLED)) .replace("$jsname", state.function(NAME)) .replace("$jswrapper", state.function(WRAPPER_NAME)) .trim() - .pretty_print(f_init_wrappers); + .print(f_init_wrappers); } } else { // Note: a global function is treated like a static function @@ -2423,6 +2424,11 @@ Template& Template::replace(const String *pattern, const String *repl) { return *this; } +Template& Template::print(DOH *doh) { + Printv(doh, str(), 0); + return *this; +} + Template& Template::pretty_print(DOH *doh) { Wrapper_pretty_print(str(), doh); return *this; From 335d926c449d22821eb916d0f862062b925c2ca6 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 24 Sep 2013 03:56:19 +0200 Subject: [PATCH 0340/1048] Add stub std_deque.i files. --- Lib/javascript/jsc/std_deque.i | 1 + Lib/javascript/v8/std_deque.i | 1 + 2 files changed, 2 insertions(+) create mode 100644 Lib/javascript/jsc/std_deque.i create mode 100644 Lib/javascript/v8/std_deque.i diff --git a/Lib/javascript/jsc/std_deque.i b/Lib/javascript/jsc/std_deque.i new file mode 100644 index 000000000..cb98f6c2f --- /dev/null +++ b/Lib/javascript/jsc/std_deque.i @@ -0,0 +1 @@ +%include diff --git a/Lib/javascript/v8/std_deque.i b/Lib/javascript/v8/std_deque.i new file mode 100644 index 000000000..cb98f6c2f --- /dev/null +++ b/Lib/javascript/v8/std_deque.i @@ -0,0 +1 @@ +%include From 7adf93ef0f86babb564b1458228f5b4666f414dc Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Thu, 26 Sep 2013 04:13:32 +0200 Subject: [PATCH 0341/1048] Fix test configuration for nodejs. --- Examples/test-suite/javascript/Makefile.in | 20 +++++++++++++------ .../javascript/char_strings_runme.js | 2 +- .../javascript/node_template/binding.gyp.in | 2 ++ Examples/test-suite/javascript/setup_test.sh | 2 +- 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index 40aa0ec86..1010a49e7 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -80,11 +80,11 @@ _setup = \ echo "$(ACTION)ing testcase $* under javascript ($(JSENGINE))" ; \ fi; -ifeq (v8,$(ENGINE)) +ifneq (jsc,$(ENGINE)) # This test can not be run with v8 as it uses v8 API incompatible output typemaps typemap_variables.cpptest: - echo "skipping testcase typemap_variables under javascript (v8)." + echo "skipping testcase typemap_variables under javascript ($(JSENGINE))." # with v8 we have to generate C++ wrappers only # these tests did raise warnings which are ignored @@ -98,8 +98,18 @@ ifeq (node,$(JSENGINE)) SWIGOPT += -v8 -DBUILDING_NODE_EXTENSION=1 + # shut up some warnings + # contract macro has an empty 'else' at the end... + aggregate.cpptest: GYP_CFLAGS = \"-Wno-empty-body\" + contract_wrap.cpptest: GYP_CFLAGS = \"-Wno-empty-body\" + + # dunno... ignoring generously + apply_signed_char.cpptest: GYP_CFLAGS = \"Wno-ignored-qualifiers\" + constant_pointers.cpptest: GYP_CFLAGS = \"Wno-ignored-qualifiers\" + enum_thorough.cpptest: GYP_CFLAGS = \"-Wno-ignored-qualifiers\" + __setup = \ - sh ./setup_test.sh $*; \ + sh ./setup_test.sh $* $(GYP_CFLAGS); \ $(SWIG) -c++ -javascript $(SWIGOPT) ../$*.i; nodejs_swig_and_compile = \ @@ -124,9 +134,6 @@ ifeq (node,$(JSENGINE)) %.multicpptest: $(_setup) - $(__setup) - $(nodejs_swig_and_compile) - $(run_testcase) else @@ -171,3 +178,4 @@ clean: rm -f *_wrap.cxx rm -f *_wrap.c rm -f *.so + rm -f *.o diff --git a/Examples/test-suite/javascript/char_strings_runme.js b/Examples/test-suite/javascript/char_strings_runme.js index fe17cb982..cca50d851 100644 --- a/Examples/test-suite/javascript/char_strings_runme.js +++ b/Examples/test-suite/javascript/char_strings_runme.js @@ -1,4 +1,4 @@ -var char_strings = require("char_strings"); +var char_strings = require("./char_strings"); var assertIsEqual = function(expected, actual) { if (expected !== actual) { diff --git a/Examples/test-suite/javascript/node_template/binding.gyp.in b/Examples/test-suite/javascript/node_template/binding.gyp.in index 435381043..209774ae0 100644 --- a/Examples/test-suite/javascript/node_template/binding.gyp.in +++ b/Examples/test-suite/javascript/node_template/binding.gyp.in @@ -18,6 +18,8 @@ ], ['OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="solaris"', { + 'cflags': [ "-Wno-unused-variable", "-Wno-unused-but-set-variable", "-Wno-unused-but-set-parameter", $cflags], + 'cflags_cc': [ "-Wno-unused-variable", "-Wno-unused-but-set-variable", "-Wno-unused-but-set-parameter", $cflags], 'cflags!': [ '-fno-exceptions' ], 'cflags_cc!': [ '-fno-exceptions', '-fno-rtti' ] } diff --git a/Examples/test-suite/javascript/setup_test.sh b/Examples/test-suite/javascript/setup_test.sh index 3f45d814a..913a74c4b 100644 --- a/Examples/test-suite/javascript/setup_test.sh +++ b/Examples/test-suite/javascript/setup_test.sh @@ -2,5 +2,5 @@ if [ ! -d $1 ]; then mkdir $1; fi -sed s/\$testcase/$1/ node_template/binding.gyp.in > $1/binding.gyp +sed -e "s/\$testcase/$1/" -e "s/\$cflags/$2/" < node_template/binding.gyp.in > $1/binding.gyp sed s/\$testcase/$1/ node_template/index.js.in > $1/index.js From 582bd297690605d98ae758d164cc48e299ae34b3 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Thu, 26 Sep 2013 04:55:34 +0200 Subject: [PATCH 0342/1048] Trying to install former working version of nodejs. --- .travis.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index a38965992..3b8500aee 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,9 +4,9 @@ compiler: node_js: -0.10.12 before_script: - - "sudo add-apt-repository -y ppa:chris-lea/node.js" - - "sudo apt-get update" - - "sudo apt-get install -y nodejs" + - "sudo apt-get install rlwrap" + - "wget https://launchpad.net/~chris-lea/+archive/node.js/+build/4936691/+files/nodejs_0.10.18-1chl1~precise1_amd64.deb" + - "sudo dpkg -i nodejs_0.10.18-1chl1~precise1_amd64.deb" - "sudo npm install -g node-gyp" - "sudo apt-get install libv8-3.7.12.22 libv8-dev" - "sudo apt-get install libwebkitgtk-dev" From c2d3da2eeca2d1923d9c69dda70a8ce2f1b2cf1e Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Thu, 26 Sep 2013 05:14:34 +0200 Subject: [PATCH 0343/1048] Fix test configuration. --- Examples/test-suite/javascript/Makefile.in | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index 1010a49e7..49652f0bd 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -101,11 +101,11 @@ ifeq (node,$(JSENGINE)) # shut up some warnings # contract macro has an empty 'else' at the end... aggregate.cpptest: GYP_CFLAGS = \"-Wno-empty-body\" - contract_wrap.cpptest: GYP_CFLAGS = \"-Wno-empty-body\" + contract.cpptest: GYP_CFLAGS = \"-Wno-empty-body\" # dunno... ignoring generously - apply_signed_char.cpptest: GYP_CFLAGS = \"Wno-ignored-qualifiers\" - constant_pointers.cpptest: GYP_CFLAGS = \"Wno-ignored-qualifiers\" + apply_signed_char.cpptest: GYP_CFLAGS = \"-Wno-ignored-qualifiers\" + constant_pointers.cpptest: GYP_CFLAGS = \"-Wno-ignored-qualifiers\" enum_thorough.cpptest: GYP_CFLAGS = \"-Wno-ignored-qualifiers\" __setup = \ From 6a366cc050f25b3d358d8f4d85e37011ada82726 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 27 Sep 2013 03:23:37 +0200 Subject: [PATCH 0344/1048] Fix regression. --- Source/Modules/javascript.cxx | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 239981219..70bb12f68 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1571,18 +1571,12 @@ int JSCEmitter::dump(Node *n) { } int JSCEmitter::close() { - /* strings */ Delete(f_runtime); Delete(f_header); Delete(f_wrappers); Delete(f_init); - Delete(namespaces); - - /* files */ - Close(f_wrap_cpp); Delete(f_wrap_cpp); - return SWIG_OK; } @@ -1927,7 +1921,6 @@ int V8Emitter::dump(Node *n) int V8Emitter::close() { - // strings Delete(f_runtime); Delete(f_header); Delete(f_class_templates); @@ -1941,11 +1934,7 @@ int V8Emitter::close() Delete(f_init_register_namespaces); Delete(f_init); Delete(f_post_init); - - // files - Close(f_wrap_cpp); Delete(f_wrap_cpp); - return SWIG_OK; } From 00053169cd5d69c42b1b1bbf58336776e1820c97 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 27 Sep 2013 02:44:53 +0200 Subject: [PATCH 0345/1048] CMake configuration. --- CMakeLists.txt | 173 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 173 insertions(+) create mode 100644 CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 000000000..1bf7a2c76 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,173 @@ +project(swig) +cmake_minimum_required(VERSION 2.8) + +# Project wide configuration variables +# ------------------------------------ + +set(SWIG_VERSION 2.0.6) +set(SWIG_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/Source" CACHE INTERNAL "Path of swig sources" FORCE) + +# Configure +# --------- + +include(CheckIncludeFiles) +include(CheckIncludeFile) +include(CheckTypeSize) +include(CheckSymbolExists) +include(CheckLibraryExists) +include(CheckCSourceCompiles) + +# HACK: didn't get the bool check working for Visual Studio 2008 +if(MSVC) +set(HAVE_BOOL 1) +else() +set(CMAKE_EXTRA_INCLUDE_FILES stdbool.h) +check_type_size("bool" HAVE_BOOL) +set(CMAKE_EXTRA_INCLUDE_FILES) +endif() + +check_include_file("inttypes.h" HAVE_INTTYPES_H) +check_include_file("memory.h" HAVE_MEMORY_H) +check_include_file("stddef.h" HAVE_STDDEF_H) +check_include_file("stdint.h" HAVE_STDINT_H) +check_include_file("stdlib.h" HAVE_STDLIB_H) +check_include_file("string.h" HAVE_STRING_H) +check_include_file("strings.h" HAVE_STRINGS_H) +check_include_file("sys/stat.h" HAVE_SYS_STAT_H) +check_include_file("sys/types.h" HAVE_SYS_TYPES_H) +check_include_file("unistd.h" HAVE_UNISTD_H) +check_include_files( "stdlib.h;stdarg.h;string.h;float.h" HAVE_STDC_HEADERS ) + +check_library_exists(dl dlopen "" HAVE_LIBDL) + +configure_file(${CMAKE_CURRENT_SOURCE_DIR}/Tools/swigconfig.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/Source/Include/swigconfig.h) + +# Compiler flags +# -------------- + +include_directories("${SWIG_SOURCE_DIR}/CParse" + "${SWIG_SOURCE_DIR}/Include" + "${SWIG_SOURCE_DIR}/DOH" + "${SWIG_SOURCE_DIR}/Swig" + "${SWIG_SOURCE_DIR}/Preprocessor" + "${SWIG_SOURCE_DIR}/Modules" + "${PROJECT_BINARY_DIR}/Source/Include" +) + +# Pre-Build +# --------- + +# Copy Lib directory into the build dist folder +file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/Dist) +file(COPY ${PROJECT_SOURCE_DIR}/Lib DESTINATION ${PROJECT_BINARY_DIR}/Dist) + +# add the command to generate the source code (depends on bison) +file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/Source/CParse) +add_custom_command ( + OUTPUT ${PROJECT_BINARY_DIR}/Source/CParse/parser.c + DEPENDS ${SWIG_SOURCE_DIR}/CParse/parser.y + COMMAND bison -o ${PROJECT_BINARY_DIR}/Source/CParse/parser.c --defines=${PROJECT_BINARY_DIR}/Source/Include/parser.h ${SWIG_SOURCE_DIR}/CParse/parser.y +) +set_property(SOURCE ${PROJECT_BINARY_DIR}/Source/CParse/parser.c PROPERTY GENERATED 1) +set_property(SOURCE ${PROJECT_BINARY_DIR}/Source/CParse/parser.h PROPERTY GENERATED 1) + +# generate swigwarn.swg +file(READ ${SWIG_SOURCE_DIR}/Include/swigwarn.h SWIG_WARN_H) +string(REGEX REPLACE "#define WARN([^ \\t]*)[ \\t]*([0-9]+)" "%define SWIGWARN\\1 \\2 %enddef" SWIG_WARN_SWG ${SWIG_WARN_H}) +file(WRITE ${PROJECT_BINARY_DIR}/Dist/Lib/swigwarn.swg ${SWIG_WARN_SWG}) +set_property(SOURCE ${PROJECT_BINARY_DIR}/Dist/Lib/swigwarn.swg PROPERTY GENERATED 1) + +# Libraries +# --------- + +add_library(cparse "${SWIG_SOURCE_DIR}/CParse/cscanner.c" + "${SWIG_SOURCE_DIR}/CParse/templ.c" + "${SWIG_SOURCE_DIR}/CParse/util.c" + "${PROJECT_BINARY_DIR}/Source/CParse/parser.c" + "${PROJECT_BINARY_DIR}/Source/CParse/parser.h" +) + +add_library(preprocessor "${SWIG_SOURCE_DIR}/Preprocessor/cpp.c" + "${SWIG_SOURCE_DIR}/Preprocessor/expr.c" +) + +add_library(doh "${SWIG_SOURCE_DIR}/DOH/base.c" + "${SWIG_SOURCE_DIR}/DOH/file.c" + "${SWIG_SOURCE_DIR}/DOH/fio.c" + "${SWIG_SOURCE_DIR}/DOH/hash.c" + "${SWIG_SOURCE_DIR}/DOH/list.c" + "${SWIG_SOURCE_DIR}/DOH/memory.c" + "${SWIG_SOURCE_DIR}/DOH/string.c" + "${SWIG_SOURCE_DIR}/DOH/void.c" +) + +add_library(core "${SWIG_SOURCE_DIR}/Swig/cwrap.c" + "${SWIG_SOURCE_DIR}/Swig/deprecate.c" + "${SWIG_SOURCE_DIR}/Swig/error.c" + "${SWIG_SOURCE_DIR}/Swig/fragment.c" + "${SWIG_SOURCE_DIR}/Swig/getopt.c" + "${SWIG_SOURCE_DIR}/Swig/include.c" + "${SWIG_SOURCE_DIR}/Swig/misc.c" + "${SWIG_SOURCE_DIR}/Swig/naming.c" + "${SWIG_SOURCE_DIR}/Swig/parms.c" + "${SWIG_SOURCE_DIR}/Swig/scanner.c" + "${SWIG_SOURCE_DIR}/Swig/stype.c" + "${SWIG_SOURCE_DIR}/Swig/symbol.c" + "${SWIG_SOURCE_DIR}/Swig/tree.c" + "${SWIG_SOURCE_DIR}/Swig/typemap.c" + "${SWIG_SOURCE_DIR}/Swig/typeobj.c" + "${SWIG_SOURCE_DIR}/Swig/typesys.c" + "${SWIG_SOURCE_DIR}/Swig/wrapfunc.c" +) + +add_library(modules "${SWIG_SOURCE_DIR}/Modules/allegrocl.cxx" + "${SWIG_SOURCE_DIR}/Modules/allocate.cxx" + "${SWIG_SOURCE_DIR}/Modules/browser.cxx" + "${SWIG_SOURCE_DIR}/Modules/cffi.cxx" + "${SWIG_SOURCE_DIR}/Modules/chicken.cxx" + "${SWIG_SOURCE_DIR}/Modules/clisp.cxx" + "${SWIG_SOURCE_DIR}/Modules/contract.cxx" + "${SWIG_SOURCE_DIR}/Modules/csharp.cxx" + "${SWIG_SOURCE_DIR}/Modules/d.cxx" + "${SWIG_SOURCE_DIR}/Modules/directors.cxx" + "${SWIG_SOURCE_DIR}/Modules/emit.cxx" + "${SWIG_SOURCE_DIR}/Modules/go.cxx" + "${SWIG_SOURCE_DIR}/Modules/guile.cxx" + "${SWIG_SOURCE_DIR}/Modules/java.cxx" + "${SWIG_SOURCE_DIR}/Modules/javascript.cxx" + "${SWIG_SOURCE_DIR}/Modules/lang.cxx" + "${SWIG_SOURCE_DIR}/Modules/lua.cxx" + "${SWIG_SOURCE_DIR}/Modules/modula3.cxx" + "${SWIG_SOURCE_DIR}/Modules/module.cxx" + "${SWIG_SOURCE_DIR}/Modules/mzscheme.cxx" + "${SWIG_SOURCE_DIR}/Modules/ocaml.cxx" + "${SWIG_SOURCE_DIR}/Modules/octave.cxx" + "${SWIG_SOURCE_DIR}/Modules/overload.cxx" + "${SWIG_SOURCE_DIR}/Modules/perl5.cxx" + "${SWIG_SOURCE_DIR}/Modules/php.cxx" + "${SWIG_SOURCE_DIR}/Modules/pike.cxx" + "${SWIG_SOURCE_DIR}/Modules/python.cxx" + "${SWIG_SOURCE_DIR}/Modules/r.cxx" + "${SWIG_SOURCE_DIR}/Modules/ruby.cxx" + "${SWIG_SOURCE_DIR}/Modules/s-exp.cxx" + "${SWIG_SOURCE_DIR}/Modules/tcl8.cxx" + "${SWIG_SOURCE_DIR}/Modules/typepass.cxx" + "${SWIG_SOURCE_DIR}/Modules/uffi.cxx" + "${SWIG_SOURCE_DIR}/Modules/utils.cxx" + "${SWIG_SOURCE_DIR}/Modules/xml.cxx" + "${PROJECT_BINARY_DIR}/Source/Include/swigconfig.h" + "${SWIG_SOURCE_DIR}/Include/swigwarn.h" +) + +add_executable(swig + "${SWIG_SOURCE_DIR}/Modules/main.cxx" + "${SWIG_SOURCE_DIR}/Modules/swigmain.cxx" +) + +target_link_libraries(swig cparse preprocessor doh core modules) + +# copy binary into Dist folder +get_property(SWIG_EXECUTABLE TARGET swig PROPERTY LOCATION) +add_custom_command(TARGET swig POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy ${SWIG_EXECUTABLE} ${PROJECT_BINARY_DIR}/Dist +) From ecf9f96079067386a5f8bc83fadd4ac9e03f551c Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 27 Sep 2013 02:45:22 +0200 Subject: [PATCH 0346/1048] Javascript documentation. --- .../Javascript/MappingC++ToJavascript.md | 220 ++++ .../V8_CodeGeneratorSpecification.md | 1063 ++++++++++++++++ Doc/Manual/Javascript.html | 770 ++++++++++++ Doc/Manual/Javascript.md | 1103 +++++++++++++++++ Doc/Manual/pandoc_template.html | 56 + 5 files changed, 3212 insertions(+) create mode 100644 Doc/Devel/Javascript/MappingC++ToJavascript.md create mode 100644 Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md create mode 100644 Doc/Manual/Javascript.html create mode 100644 Doc/Manual/Javascript.md create mode 100644 Doc/Manual/pandoc_template.html diff --git a/Doc/Devel/Javascript/MappingC++ToJavascript.md b/Doc/Devel/Javascript/MappingC++ToJavascript.md new file mode 100644 index 000000000..c77064933 --- /dev/null +++ b/Doc/Devel/Javascript/MappingC++ToJavascript.md @@ -0,0 +1,220 @@ +# Mapping C++ language features to Javascript + +## Namespaces + +A namespace is represented as a static instance (global variable) +containing other namespaces, global variables and functions +and class templates + +### Example: + +C++: + +~~~~c++ +namespace foo { + int x; + namespace bar { + double y; + } +} +~~~~ + +Javascript: + +~~~~javascript +var foo = new Object(); +foo.x = 0; +foo.bar = new Object(); +foo.bar.y = 0.0; +~~~~ + +## Global variables and functions + +Global variables and functions are properties of other context objects +(global or namespaces). + +### Example: + +C++: + +~~~~c++ +int x; +namespace foo { + void bar(); +} +~~~~ + +Javascript: + +~~~~javascript +var x = 0; +var foo = new Object(); +foo.bar = function() { + return undefined; +} +~~~~ + +## Classes + +Classes are defined as class templates and instantiated using the `new` +operator. +Class members are set in the constructor function using the `this` reference. +Private class members are set using the `var` keyword. + +### Example: + +C++: + +~~~~c++ +class Foo { + int bar(); + +private: + int x; +} +~~~~ + +Javascript: + +~~~~javascript +var Foo = function() { + var x = 42; + this.bar = function() { return x; }; +}; + +var foo = new Foo(); +foo.bar(); +~~~~ + +## Static class members and functions + +Static variables and functions should be added to the class template object. + +~~~~c++ +class Foo { + static std::string foo(); + std::string bar(); +} +~~~~ + +Javascript: + +~~~~javascript +var Foo = function() { + this.bar = function() { + return "bar"; + } +}; +Foo.foo = function() { + return "foo"; +}; + +var foo = new Foo(); +foo.foo() +> TypeError: Object [object Object] has no method 'foo' +Foo.foo() +> "foo" +foo.bar(); +> "bar" +~~~~ + +## Inheritance + +Javascript uses a prototype based inheritance mechanism. This limits +feature support to single inheritance. + +### Example: + +C++: + +~~~~c++ +class Foo { +public: + int foo(); + +private: + int x; +} + +class Bar: public Foo { +public: + int bar(); +} +~~~~ + +Javascript: + +~~~~javascript +var Foo = function() { + var x = 42; + this.foo = function() { return x; }; +}; + +var Bar = function() { + this.bar = function() { return 6; }; +} +Bar.prototype = new Foo(); +Bar.prototype.constructor = Bar; + +var foo = new Foo(); +var bar = new Bar(); + +foo.foo() +> 42 +foo.bar() +> TypeError: Object [object Object] has no method 'bar' +bar.foo() +> 42 +bar.bar() +> 6 +~~~~ + +## Virtual methods + +The prototype mechanism of Javascript allows method overriding which is +needed to map the concept of virtual functions. + +### Example: + +C++: + +~~~~c++ +class Foo { +public: + virtual int foo(); +} + +class Bar: public Foo { +public: + virtual int foo(); +} +~~~~ + +Javascript: + +~~~~javascript +var Foo = function() { + this.foo = function() { return 1; }; +}; + +var Bar = function() {} +Bar.prototype = new Foo(); +Bar.prototype.constructor = Bar; +Bar.prototype.foo = function() { return 42; }; + +var foo = new Foo(); +var bar = new Bar(); + +foo.foo() +> 1 +bar.foo() +> 42 +~~~~ + +## Overloading + +In Javascript like in other scripting languages method overloading is not +available. I.e., there can only be one function for one function name. +Therefore, it is necessary to implement a method dispatching mechanism +for these methods. + diff --git a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md new file mode 100644 index 000000000..63027b74d --- /dev/null +++ b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md @@ -0,0 +1,1063 @@ +Javascript: Specification of a Code Generator for V8 +==================================================== + +The aim of this is to evolve a specification for a code generator. + +## Top Level structure + +The generated code consists of the following blocks: + +~~~~ + + + + + + + + + + +~~~~ + +- `HELPER_FUNCTIONS`: static, from swg-file +- `INCLUDES`: static, module property +- `CLASS_TEMPLATES`: dynamically growing, on class declarations +- `FUNCTION_WRAPPERS`: dynamically growing, on method declarations +- `INITIALIZER`: dynamically growing, aggregates everything (to be specified in more detail) + +### INCLUDES + +~~~~ +#include + + +~~~~ + +`USER_DEFINED_INCLUDES`: a module property + +### CLASS_TEMPLATES + +Static references to class templates which are (should be) read-only and can be reused. + +~~~~ +v8::Persistent SWIGV8_${NAME_MANGLED}; +~~~~ + +Notes: + - it is very important to consider namespaces from the beginning. + `NAME_MANGLED` is the mangled qualified class name, e.g., `foo_bar_MyClass` for `foo::bar::MyClass`, + which is retrieved ny `Swig_string_mangle(Getattr(n, "name"))` + - namespaces do not need a function template, as they will not be + instantiated + +## FUNCTION_WRAPPERS + +There are different types of function wrappers: + + - Global Functions (global/namespace/class) + - Constructors / Destructors + - Getters / Settters + - Member Functions + +### Global Functions + +~~~~ +v8::Handle wrap_${NAME_MANGLED}(const v8::Arguments &args) { + v8::HandleScope scope; + v8::Handle ret; + ${LOCALS} + ${CODE} + return scope.Close(ret); +} +~~~~ + +- `LOCALS`: declarations for input and output arguments +- `CODE` contains input marshalling, the action, and output marshalling + +### Constructors + +~~~~ +v8::Handle ${NAME_MANGLED}_new(const v8::Arguments& args) { + v8::HandleScope scope; + v8::Handle self = args.Holder(); + ${LOCALS} + ${CODE} + self->SetInternalField(0, v8::External::New(ptr)); + return self; +} +~~~~ + +- `LOCALS`: declarations for input arguments +- `CODE` contains input marshalling, and the action + +### Destructors + +TODO: I haven't found out yet how a descrtuctor can be registered + +### Getters + +~~~~ +v8::Handle ${NAME_MANGLED}_get(v8::Local property, const v8::AccessorInfo& info) { + v8::HandleScope scope; + v8::Handle ret; + ${LOCALS} + ${CODE} + return scope.Close(ret); +} +~~~~ + +- `NAME_MANGLED`: the qualified mangled name of the variable, E.g., `foo::x -> foo_x`, `A.x -> A_x` +- `LOCALS`: declarations for output arguments +- `CODE` contains the action, and output marshalling + +### Setters + +~~~~ +void ${NAME_MANGLED}_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { + ${LOCALS} + ${CODE} +} +~~~~ +- `NAME_MANGLED`: the qualified mangled name of the variable, E.g., `foo::x -> foo_x`, `A.x -> A_x` +- `LOCALS`: declarations for input arguments +- `CODE` contains input marshalling, and the action + +### Functions + +~~~~ +v8::Handle ${NAME_MANGLED}(const Arguments &args) { + v8::HandleScope scope; + v8::Handle ret; + ${LOCALS} + ${CODE} + return scope.Close(ret); +} +~~~~ + +- `NAME_MANGLED`: the qualified mangled name of the variable, E.g., `foo::x -> foo_x`, `A.x -> A_x` +- `LOCALS`: declarations for input arguments +- `CODE` contains input marshalling, the action, and output marshalling + + +### Overloading + +TODO: if a function or a ctor is overloaded, a dispatcher function +must be generated which calls overloading wrappers depending on number +and type of input arguments. + + +## Initializer + +~~~~ +void ${MODULE}_Initialize(v8::Handle context) +{ + v8::HandleScope scope; + + // register the module in globale context + v8::Local global = context->Global(); + + ${PART_NAMESPACES} + + ${PART_CLASS_TEMPLATES} + + ${PART_WRAPPERS} + + ${PART_INHERITANCE} + + ${PART_REGISTER_CLASSES} + + ${PART_REGISTER_NS} +} +~~~~ + +### Namespaces + +Namespaces are objects without class templates. I.e., instances are created, +referenced locally, used as contexts for other registrations, and stored +in the according parent contexts. + +~~~~~ +v8::Handle ${NAME_MANGLED} = v8::ObjectTemplate::New(); +~~~~~ + +### Class Templates + +~~~~ +SWIGV8_${NAME_MANGLED} = SWIGV8_CreateClassTemplate("${NAME_UNQUALIFIED}" , ${NAME_MANGLED}_new); +~~~~ + +- `NAME_UNQUALIFIED`: the class name without context, i.e., namespaces + +### Inheritance + +~~~~ +SWIGV8_${NAME_MANGLED}->Inherit(SWIGV8_${BASE_CLASS}); +~~~~ + +- Note: multiple inheritance is not possible; thus we will always take the first parent class + +### Registration + +The registration part consists of registering classes at contexts (i.e., global or namespace), +methods and properties at classes or contexts, and namespaces as objects at +parent contexts. + +#### Global Variable + +~~~~ +${CONTEXT}->SetAccessor(v8::String::NewSymbol("${NAME_UNQUALIFIED}"), ${GETTER}, ${SETTER}); +~~~~ + +- `CONTEXT`: either global, or the according namespace template +- `${SETTER} = 0` for read-only variables + +#### Global Function + +~~~~ +SWIGV8_AddGlobalFunction(${CONTEXT}, "${NAME_UNQUALIFIED}", wrap_${NAME_QUALIFIED}); +~~~~ + +- `CONTEXT`: either global, or the according namespace template + +#### Class + +~~~~ +${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}", SWIGV8_${NAME_MANGLED}->GetFunction())); +~~~~ + +- Note: every class template has an associated ctor function wrapper, which is registered here +- `CONTEXT`: either global, or the according namespace instance + +#### Class method + +~~~~ +SWIGV8_AddClassMethod(SWIGV8_${CLASSNAME_MANGLED}, "${NAME_UNQUALIFIED}", wrap_${NAME_MANGLED}); +~~~~ + +Note: implemented in static helper function + +#### Class variable + +~~~~ +SWIGV8_AddProperty(SWIGV8_${CLASSNAME_MANGLED}, "${NAME_UNQUALIFIED}", ${GETTER}, ${SETTER}); +~~~~ + +- `GETTER`: the name of the generated wrapper for the property getter +- `SETTER`: the name of the generated wrapper for property setter; optional (i.e., maybe `NULL`) + +### Namespace + +~~~~ +${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}", ${NAME_MANGLED}->NewInstance())); +~~~~ + +Note: it is important to register the namespace objects in reverse order, +e.g., + +~~~~ +namespace foo { + namespace bar {} +} +~~~~ + +would be registered in this order: + +~~~~ +foo->Set(v8::String::NewSymbol("bar", bar->NewInstance())); +global->Set(v8::String::NewSymbol("foo", foo->NewInstance())); +~~~~ + +## HELPER_FUNCTIONS + +A lot of boiler-plate code can be shifted into static helper functions: + +~~~~ + +/** + * Creates a class template for a class without extra initialization function. + */ +v8::Persistent SWIGV8_CreateClassTemplate(const char* symbol, v8::InvocationCallback func) +{ + v8::Local class_templ = v8::FunctionTemplate::New(func); + class_templ->SetClassName(v8::String::NewSymbol(symbol)); + + v8::Handle inst_templ = class_templ->InstanceTemplate(); + inst_templ->SetInternalFieldCount(1); + + return v8::Persistent::New(class_templ); +} + +/** + * Registers a class method with given name for a given class template. + */ +void SWIGV8_AddMemberFunction(v8::Handle class_templ, + const char* symbol, + v8::InvocationCallback func) +{ + v8::Handle proto_templ = class_templ->PrototypeTemplate(); + proto_templ->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(func)); +} + +/** + * Registers a class property with given name for a given class template. + */ +void SWIGV8_AddMemberVariable(v8::Handle class_templ, + const char* varname, + v8::AccessorGetter getter, + v8::AccessorSetter setter) +{ + v8::Handle proto_templ = class_templ->InstanceTemplate(); + proto_templ->SetAccessor(v8::String::New(varname), getter, setter); +} + + +/** + * Adds a property with given name to a given context. + */ +void SWIGV8_AddGlobalVariable(v8::Handle context, + const char* varname, + v8::AccessorGetter getter, + v8::AccessorSetter setter) +{ + context->SetAccessor(v8::String::NewSymbol(varname), getter, setter); +} + +/** + * Adds a function with given name to a given context. + */ +void SWIGV8_AddGlobalFunction(v8::Handle context, + const char* symbol, + v8::InvocationCallback func) +{ + context->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(func)->GetFunction()); +} + +template +static T* SWIGV8_UnwrapThisPointer (v8::Handle handle) +{ + // assert(!handle.IsEmpty()); + // assert(handle->InternalFieldCount() > 0); + v8::Local wrap = v8::Local::Cast(handle->GetInternalField(0)); + return static_cast(wrap->Value()); +} + +~~~~ + +------------------------- + +Examples +======== + +In this chapter manually coded wrappers are presented. +This has been useful for studying the addressed code generation on basis +of examples. + +## Global variable + +~~~~~ +static double Foo = 42.0; + +void Foo_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { + v8::HandleScope scope; + double arg1 ; + arg1 = value->NumberValue(); + Foo = arg1; +} + +v8::Handle Foo_get(v8::Local property, const v8::AccessorInfo& info) { + v8::HandleScope scope; + v8::Handle ret; + double result; + + result = Foo; + + ret = v8::Number::New(result); + return scope.Close(ret); +} + +int GlobalVar_Initialize(v8::Handle context) { + + v8::Local global = context->Global(); + global->SetAccessor(v8::String::New("Foo"), Foo_get, Foo_set); + + return 0; +} +~~~~~ + +## Global functions + +~~~~~ + +static double foo(int bla) { + return (bla * 2.1); +} + +v8::Handle wrap_foo(const v8::Arguments &args) { + v8::HandleScope scope; + v8::Handle ret; + + int arg1 ; + double result; + + arg1 = args[0]->Int32Value(); + + result = foo(arg1); + + ret = v8::Number::New(result); + + return scope.Close(ret); +} + +int GlobalFunc_Initialize(v8::Handle context) { + + v8::Local global = context->Global(); + + global->Set(v8::String::NewSymbol("foo"), v8::FunctionTemplate::New(wrap_foo)->GetFunction()); + + return 0; +} +~~~~~ + + +## Namespaces + +~~~~~ + +namespace foo { + static double bar = 42.0; +} + +void foo_bar_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { + v8::HandleScope scope; + + double arg1 ; + arg1 = value->NumberValue(); + foo::bar = arg1; + +} + +v8::Handle foo_bar_get(v8::Local property, const v8::AccessorInfo& info) { + v8::HandleScope scope; + v8::Handle ret; + double result; + + result = foo::bar; + + ret = v8::Number::New(result); + return scope.Close(ret); +} + +int Namespace_Initialize(v8::Handle context) { + + v8::Local global = context->Global(); + + v8::Handle foo = v8::ObjectTemplate::New(); + + foo->SetAccessor(v8::String::New("bar"), foo_bar_get, foo_bar_set); + + global->Set(v8::String::New("foo"), foo->NewInstance()); + return 0; +} + +~~~~~ + +## Class + +~~~~~ + +class A { +public: + A() { + x = 42; + } + + ~A() {} + + double foo(bool a) { + if(a) + return 11.11; + else + return 22.22; + } + + int x; +}; + +v8::Handle A_new(const v8::Arguments& args) { + v8::HandleScope scope; + v8::Handle self = args.Holder(); + A *result; + result = new A(); + self->SetInternalField(0, v8::External::New(result)); + return self; +} + +void A_x_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { + v8::HandleScope scope; + A *arg1; + int arg2; + + arg1 = SWIGV8_UnwrapThisPointer(info.Holder()); + arg2 = value->Int32Value(); + + arg1->x = arg2; + +} + +v8::Handle A_x_get(v8::Local property, const v8::AccessorInfo& info) { + v8::HandleScope scope; + v8::Handle jsresult; + A *arg1; + int result; + + arg1 = SWIGV8_UnwrapThisPointer(info.Holder()); + result = arg1->x; + + jsresult = v8::Int32::New(result); + return scope.Close(jsresult); +} + +v8::Handle wrap_A_foo(const v8::Arguments& args) +{ + v8::HandleScope scope; + v8::Handle jsresult; + A *arg1; + double arg2; + double result; + + arg1 = SWIGV8_UnwrapThisPointer(args.Holder()); + arg2 = args[0]->NumberValue(); + + result = arg1->foo(arg2); + + jsresult = v8::Number::New(result); + return scope.Close(jsresult); +} + +int Class_Initialize(v8::Handle context) { + + v8::Local global = context->Global(); + + v8::Persistent class_A = SWIGV8_CreateClassTemplate("A", A_new); + SWIGV8_AddMemberVariable(class_A, "x", A_x_get, A_x_set); + SWIGV8_AddMemberFunction(class_A, "foo", wrap_A_foo); + + global->Set(v8::String::NewSymbol("A"), class_A->GetFunction()); + + return 0; +} + +~~~~~ + +## Static variables and functions + +Static variables and functions are implemented similar to global ones. +They are added to the class object instead of the class template. +Therefore, these are only accessible via the class object and not via +instances of this class. + +~~~~~ + +class A { +public: + A() { + x = 7; + } + + ~A() {} + + static int foo() { + return 42; + } + + static int x; +}; + +int A::x = 7; + +v8::Handle A_new(const v8::Arguments& args) { + v8::HandleScope scope; + v8::Handle self = args.Holder(); + A *result; + result = new A(); + self->SetInternalField(0, v8::External::New(result)); + return self; +} + +void A_x_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { + v8::HandleScope scope; + int arg1; + + arg1 = value->Int32Value(); + + A::x = arg1; + +} + +v8::Handle A_x_get(v8::Local property, const v8::AccessorInfo& info) { + v8::HandleScope scope; + v8::Handle jsresult; + int result; + + result = A::x; + + jsresult = v8::Int32::New(result); + return scope.Close(jsresult); +} + +v8::Handle wrap_A_foo(const v8::Arguments& args) +{ + v8::HandleScope scope; + v8::Handle jsresult; + int result; + + result = A::foo(); + + jsresult = v8::Number::New(result); + return scope.Close(jsresult); +} + +int Class_Initialize(v8::Handle context) { + + v8::Local global = context->Global(); + + v8::Persistent classtempl_A = SWIGV8_CreateClassTemplate("A", A_new); + + v8::Handle class_A = classtempl_A->GetFunction(); + + SWIGV8_AddGlobalVariable(class_A, "x", A_x_get, A_x_set); + SWIGV8_AddGlobalFunction(class_A, "foo", wrap_A_foo); + + global->Set(v8::String::NewSymbol("A"), class_A); + + return 0; +} + +~~~~~ + +## Inheritance + +~~~~~ +class A { +public: + A() {} + + ~A() {} + + double foo() { + return 11.11; + } +}; + +class B: public A { +public: + B() {} + ~B() {} + + int bar() { + return 7; + } +}; + +... (left out function wrappers) ... + +int Class_Initialize(v8::Handle context) { + + v8::Local global = context->Global(); + + v8::Persistent class_A = SWIGV8_CreateClassTemplate("A", A_new); + v8::Persistent class_B = SWIGV8_CreateClassTemplate("B", B_new); + + SWIGV8_AddMemberFunction(class_A, "foo", wrap_A_foo); + SWIGV8_AddMemberFunction(class_B, "bar", wrap_B_bar); + + class_B->Inherit(class_A); + + global->Set(v8::String::NewSymbol("A"), class_A->GetFunction()); + global->Set(v8::String::NewSymbol("B"), class_B->GetFunction()); + + return 0; +} +~~~~~ + +## String arguments + +At a first stage all strings are treated as Utf8. +For proper handling strings as return values I have to study +other modules. + +~~~~~ +int my_strlen(const char* s) { + return strlen(s); +} + +// creates a new string +const char* foo(int a) { + char* result = new char[a+1]; + result[a] = 0; + memset(result, 'a', a); + return result; +} + +v8::Handle wrap_my_strlen(const v8::Arguments& args) +{ + v8::HandleScope scope; + v8::Handle jsresult; + const char* arg1; + int result; + + v8::String::Utf8Value utf8(args[0]); + + result = my_strlen(*utf8); + + jsresult = v8::Number::New(result); + return scope.Close(jsresult); +} + +v8::Handle wrap_foo(const v8::Arguments& args) +{ + v8::HandleScope scope; + v8::Handle jsresult; + int arg1; + const char* result; + + arg1 = args[0]->Int32Value(); + result = foo(arg1); + + jsresult = v8::String::New(result); + + return scope.Close(jsresult); +} + +int Strings_Initialize(v8::Handle context) { + + v8::Local global = context->Global(); + + SWIGV8_AddGlobalFunction(global, "strlen", wrap_my_strlen); + SWIGV8_AddGlobalFunction(global, "foo", wrap_foo); + + return 0; +} +~~~~~ + +------------------------- + +Control flow analysis +===================== + +## Global variables + +### Example: +~~~~ +int x; + +namespace foo { + double y; +} +~~~~ + +### Control flow: +Command: +~~~~ +swig -analyze -c++ functionWrapper +before globalvariableHandler +before example.i +~~~~ + +~~~~ +enter top() of example +enter variableHandler() of x +enter globalvariableHandler() of x + | sym:name - "x" + | name - "x" + | type - "int" + + enter variableWrapper() of x + + enter functionWrapper() of x + | name - "x" + | sym:name - "x_set" + | parms - int + | wrap:action - "x = arg1;" + | type - "void" + exit functionWrapper() of x + + enter functionWrapper() of x + | name - "x" + | sym:name - "x_get" + | type - "int" + exit functionWrapper() of x + exit variableWrapper() of x +exit globalvariableHandler() of x +exit variableHandler() of x + +enter variableHandler() of foo::y +enter globalvariableHandler() of foo::y + | sym:name - "y" + | name - "foo::y" + | type - "double" + + enter variableWrapper() of foo::y + enter functionWrapper() of foo::y + | name - "foo::y" + | sym:name - "y_set" + | parms - double + | wrap:action - "foo::y = arg1;" + | type - "void" + exit functionWrapper() of foo::y + + enter functionWrapper() of foo::y + | name - "foo::y" + | sym:name - "y_get" + | wrap:action - "result = (double)foo::y;" + | type - "double" + exit functionWrapper() of foo::y + exit variableWrapper() of foo::y +exit globalvariableHandler() of foo::y +exit variableHandler() of foo::y +exit top() of example + +~~~~ + +## Simple class + +### Example: + +~~~~ +class A { +public: + A(); + ~A(); +}; + +namespace foo { + class B { + }; +} +~~~~ + +### Control flow: + +~~~~ +enter top() of example + enter classHandler() of A + enter constructorHandler() of A + enter functionWrapper() of A + | name - "A" + | sym:name - "new_A" + | access - "public" + | wrap:action - "result = (A *)new A();" + | type - "p.A" + exit functionWrapper() of A + exit constructorHandler() of A + enter destructorHandler() of ~A + enter functionWrapper() of ~A + | name - "~A" + | sym:name - "delete_A" + | parms - A * + | wrap:action - "delete arg1;" + exit functionWrapper() of ~A + exit destructorHandler() of ~A +exit classHandler() of A +enter classHandler() of foo::B + enter constructorHandler() of foo::B::B + enter functionWrapper() of foo::B::B + | name - "foo::B::B" + | sym:name - "new_B" + | access - "public" + | wrap:action - "result = (foo::B *)new foo::B();" + | type - "p.foo::B" + exit functionWrapper() of foo::B::B + exit constructorHandler() of foo::B::B + enter destructorHandler() of foo::B::~B + enter functionWrapper() of foo::B::~B + | name - "foo::B::~B" + | sym:name - "delete_B" + | parms - foo::B * + | wrap:action - "delete arg1;" + | type - "void" + exit functionWrapper() of foo::B::~B + exit destructorHandler() of foo::B::~B +exit classHandler() of foo::B +exit top() of example + +~~~~ + +### Example + +~~~~ +class A { +public: + int x; +}; +~~~~ + + +### Control flow + +~~~~ +enter top() of example +enter classHandler() of A + enter variableHandler() of x + enter membervariableHandler() of x + enter functionWrapper() of x + | name - "x" + | sym:name - "A_x_set" + | access - "public" + | parms - A *,int + | wrap:action - "if (arg1) (arg1)->x = arg2;" + | type - "void" + | memberset - "1" + exit functionWrapper() of x + enter functionWrapper() of x + | name - "x" + | sym:name - "A_x_get" + | access - "public" + | parms - A * + | wrap:action - "result = (int) ((arg1)->x);" + | type - "int" + | memberset - "1" + | memberget - "1" + exit functionWrapper() of x + exit membervariableHandler() of x + exit variableHandler() of x + enter constructorHandler() of A::A + enter functionWrapper() of A::A + exit functionWrapper() of A::A + exit constructorHandler() of A::A + enter destructorHandler() of A::~A + enter functionWrapper() of A::~A + exit functionWrapper() of A::~A + exit destructorHandler() of A::~A +exit classHandler() of A +exit top() of example +~~~~ + +## Class method + +### Example + +~~~~ +class A { +public: + void foo(int x, double y); +private: + void bar(); +}; +~~~~ + +### Control flow + +~~~~ +enter top() of example +enter classHandler() of A + enter functionHandler() of foo + enter memberfunctionHandler() of foo + enter functionWrapper() of foo + | name - "foo" + | sym:name - "A_foo" + | access - "public" + | parms - A *,int,double + | wrap:action - "(arg1)->foo(arg2,arg3);" + | type - "void" + exit functionWrapper() of foo + exit memberfunctionHandler() of foo + exit functionHandler() of foo +... +exit classHandler() of A +exit top() of example +~~~~ + +## Static class variable and method + +### Example + +~~~~ +class A { +public: + static int x; + + static void foo(); +}; +~~~~ + +### Control flow + +~~~~ +enter top() of example +enter classHandler() of A + enter variableHandler() of x + enter staticmembervariableHandler() of x + enter variableWrapper() of A::x + enter functionWrapper() of A::x + | name - "A::x" + | sym:name - "A_x_set" + | parms - int + | wrap:action - "A::x = arg1;" + | type - "void" + exit functionWrapper() of A::x + enter functionWrapper() of A::x + +++ cdecl ---------------------------------------- + | name - "A::x" + | ismember - "1" + | sym:name - "A_x_get" + | variableWrapper:sym:name - "A_x" + | wrap:action - "result = (int)A::x;" + | type - "int" + exit functionWrapper() of A::x + exit variableWrapper() of A::x + exit staticmembervariableHandler() of x + exit variableHandler() of x + enter functionHandler() of foo + enter staticmemberfunctionHandler() of foo + enter globalfunctionHandler() of A::foo + enter functionWrapper() of A::foo + | name - "A::foo" + | sym:name - "A_foo" + | wrap:action - "A::foo();" + | type - "void" + exit functionWrapper() of A::foo + exit globalfunctionHandler() of A::foo + exit staticmemberfunctionHandler() of foo + exit functionHandler() of foo + enter constructorHandler() of A::A + exit constructorHandler() of A::A + enter destructorHandler() of A::~A + exit destructorHandler() of A::~A +exit classHandler() of A +exit top() of example +~~~~ + +## Inheritance + +### Example + +~~~~ +class A { +}; + +class B: public A { +}; +~~~~ + +### Control flow + +~~~~ +enter top() of example +enter classHandler() of A + +++ class ---------------------------------------- + | name - "A" + | sym:name - "A" +... +exit classHandler() of A +enter classHandler() of B + | name - "B" + | sym:name - "B" + | privatebaselist - 0xf1238f10 + | protectedbaselist - 0xf1238ef0 + | baselist - 0xf1238ed0 + | bases - 0xf1239830 + | allbases - 0xf1239c30 +... +exit classHandler() of B +exit top() of example +~~~~ diff --git a/Doc/Manual/Javascript.html b/Doc/Manual/Javascript.html new file mode 100644 index 000000000..a53e2a7cd --- /dev/null +++ b/Doc/Manual/Javascript.html @@ -0,0 +1,770 @@ + + + + + + + SWIG AND JAVASCRIPT + + + + + +
    +

    Overview

    +

    This chapter describes SWIG support for Javascript. The module is designed to support JavascriptCore and V8 as target engine. Currently only JavascriptCore support is implemented. JavaScriptCore is the built-in JavaScript engine for WebKit, whereas V8 is the engine used by Chromium.

    +

    JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. Its arguably the most popular language for web development. C++, on the other hand, is statically typed, compiled, general purpose programming language. The approach I followed here is "Test driven" where I have written the examples/test-cases to be supported for Javascript one-by-one and implemented the required module files in parallel. The support for Javascript would be added similar to other supported target languages in swig. Swig comes with an "Examples" directory for Javascript like other supported language. The directory contains examples for every supported feature of the target language. There is also a test-suite directory for javascript which contains additional tests.

    +

    Preliminaries

    +

    In order to use this module, you will need to have installed javascriptcore and you can install it by installing package libwebkit-dev You can find out some necessary compiler/linker flag by

    +
    pkg-config javascriptcoregtk-1.0 --cflags --libs
    +
    +

    Using the module

    +

    To generate an extension for JavascriptCore one would call swig as follows

    +

    swig -c++ -javascript -jsc example.i +
    +

    This generates a C++ source file containing the wrapper.

    +

    How does Javascript talk to C++?

    +

    JavascriptCore provides a C-API which allows to extend a Javascript interpreter with native methods and structures. Normally, this is used to implement the builtin features of the language. However, by extending the interpreter, it is also possible to add your own commands and variables. A reference manual of this API can be found here.

    +

    Typically, when you add a new command to the javascript interpreter you need to do two things: first you need to write a special "wrapper" function that serves as the glue between the interpreter and the underlying C function. Then you need to give the interpreter information about the wrapper by providing details about the name of the function, arguments, and so forth. The next few sections illustrate the process.

    +

    Wrapper functions

    +

    Suppose you have an ordinary C function like this :

    +

    int fact(int n) { + if (n <= 1) return 1; + else return n*fact(n-1); +} +
    +

    In order to access this function from a scripting language, it is necessary to write a special "wrapper" function that serves as the glue between the scripting language and the underlying C function. A wrapper function must do three things :

    +
      +
    • Gather function arguments and make sure they are valid.
    • +
    • Call the C function.
    • +
    • Convert the return value into a form recognized by the javascript.
    • +
    +

    As an example, the javascript wrapper function for the fact() function above example might look like the following :

    +

    JSValueRef wrap_fact(JSContextRef context, JSObjectRef function, JSObjectRef globalobj, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + int arg1 = (int)JSValueToNumber(context, argv[0], NULL); + int arg2 = (int)JSValueToNumber(context, argv[1], NULL); + int result = (int)fact(arg1,arg2); + JSValueRef jsresult = JSValueMakeNumber(context, result); + return jsresult; +} +
    +

    Once you have created a wrapper function, the final step is to tell the javascript about the new function. This is done by register function called by the javascript when the module is loaded. For example, adding the above function to the javascript interpreter requires code like the following :

    +

    bool jsc_registerFunction(JSGlobalContextRef context, JSObjectRef object, + const char* functionName, JSObjectCallAsFunctionCallback callback) +{ + JSStringRef js_globalvarsclassname = JSStringCreateWithUTF8CString(globalvarsclassname); + JSObjectSetProperty(context,js_globalvarsclassname,JSObjectMakeFunctionWithCallback(context, + js_globalvarsclassname, callback), kJSPropertyAttributeNone,NULL); + JSStringRelease(jsstring); + return true; +} + +int example_init(JSContextRef context) { + JSObjectRef global; + ... + jsc_registerFunction(context, global, "fact", wrap_fact); + ... +} +
    +

    When executed, javascript will now have a new command called "fact" that you can use like any other Javascript command. Although the process of adding a new function to javascript has been illustrated, the procedure is almost identical for Perl and Python. Both require special wrappers to be written and both need additional initialization code.

    +

    Variable Linking

    +

    Variable linking refers to the problem of mapping a C/C++ global variable to a variable in the scripting language interpreter. For example, suppose you had the following variable:

    +

    double Foo = 3.5; +
    +

    To provide such access, variables are commonly manipulated using a pair of get/set functions. For example, whenever the value of a variable is read, a "get" function is invoked. Similarly, whenever the value of a variable is changed, a "set" function is called.

    +

    bool Foo_set(JSContextRef context, JSObjectRef globalobj, JSStringRef propertyName, JSValueRef value, + JSValueRef* exception) +{ + JSValueRef jsresult; + double arg1 = (double)JSValueToNumber(context, value, NULL); + Foo = arg1; + jscresult = JSValueMakeUndefined(context); + return jsresult; +} + +JSValueRef Foo_get(JSContextRef context, JSObjectRef globalobj, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + double result = (double)Foo; + jsresult = JSValueMakeNumber(context, result); + return jsresult; +} +
    +

    In many languages, calls to the get/set functions can be attached to evaluation and assignment operators. Therefore, evaluating a variable such as Foo might implicitly call the get function. Similarly, typing Foo = 4 would call the underlying set function to change the value.

    +

    A tour of basic C/C++ wrapping

    +

    By default, SWIG tries to build a very natural javascript interface to your C/C++ code. Functions are wrapped as functions, classes are wrapped as classes, and so forth. This section briefly covers the essential aspects of this wrapping.

    +

    Modules

    +

    The SWIG %module directive specifies the name of the Javascript module. If you specify %module example, then everything is wrapped into a Javascript 'example' module. Underneath the covers, this module consists of a cpp source file example.cpp. When choosing a module name, make sure you don't use the same name as a built-in Javascript command or standard module name.

    +

    Global variables

    +

    C/C++ global variables are fully supported by SWIG. However, the underlying mechanism is somewhat different than you might expect due to the way that javascript works.

    +

    // SWIG interface file with global variables +%module example +... +%inline %{ +extern double Foo; +extern int gcd(int x, int y); +%} +... +
    +

    Now look at the javascript:

    +

    print("Global variable Foo=" + example.Foo); +example.Foo = 3.1415926; +print("Variable Foo changed to=" + example.Foo); +print("GCD of x and y is=" + example.gcd(x,y)); +
    +

    Constants and enums

    +

    C/C++ constants are installed as javascript objects containing the appropriate value. To create a constant, use #define, enum, or the %constant directive. For example:

    +

    #define ICONST 42 +#define FCONST 2.1828 +%constant int iconst = 37; +
    +

    In javascript they are treated as:

    +

    print("ICONST = " + example.ICONST + " (should be 42)\n"); +print("FCONST = " + example.FCONST + " (should be 2.1828)\n"); +print("iconst = " + example.iconst + " (should be 37)\n"); +
    +

    For enums, make sure that the definition of the enumeration actually appears in a header file or in the wrapper file somehow---if you just stick an enum in a SWIG interface without also telling the C compiler about it, the wrapper code won't compile. Enums are treated as constants.So if we have enums in c++ as:

    +

    void enum_test(color c, Foo::speed s); +
    +

    In javascript they are treated as:

    +

    example.enum_test(example.RED, example.Foo.IMPULSE); +example.enum_test(example.BLUE, example.Foo.WARP); +example.enum_test(example.GREEN, example.Foo.LUDICROUS); +
    +

    Inside the class

    +

    For class enums as below:

    +

    class Foo { +public: +Foo() { } +enum speed { IMPULSE, WARP, LUDICROUS }; +} +
    +

    In javascript they are treated as:

    +

    print(" Foo_IMPULSE =" + example.Foo.IMPULSE); +print(" Foo_WARP =" + example.Foo.WARP); +print(" Foo_LUDICROUS =" + example.Foo.LUDICROUS); +
    +

    Pointers

    +

    C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Here is a rather simple interface

    +

    /* File : example.i */ +%module example +%{ +extern void add(int *, int *, int *); +%} +
    +

    When wrapped, you will be able to use the functions in a natural way from javascript. For example:

    +

    // Call the add() function with some pointers +example.add(a, b, c); +
    +

    // In javascript the code look like as:

    +

    a = example.new_intp(); +example.intp_assign(a,37); +
    +
      +
    • The first one creates an int-pointer instance.
    • +
    • The second one assigns it the value 37.
    • +
    +

    C++ classes

    +

    C++ classes are wrapped by javascript classes as well. For example, if you have this class,

    +

    class Circle +{ +public: + Circle(); + Circle(double r); + double area(); + double radius; +}; +
    +

    you can use it in javascript like this:

    +

    print("Creating some objects:"); +c = new example.Circle(10); +print("area = " + c.area()); +
    +

    Class data members are accessed in the same manner as C structures.

    +

    Static class members and functions are mapped to javascript in a straight-forward manner:

    +

    class Spam { +public: + static void foo(); + static int bar; +}; +
    +

    In javascript, the static member can be access in this way:

    +

    // ----- Access a static member ----- +print("\nA access of static member is" + example.Spam.Foo); // access static member as properties of the class object. +
    +

    C++ inheritance

    +

    SWIG is fully aware of issues related to C++ inheritance. Therefore, if you have classes like this

    +

    class A { +public: + void foo(); + virtual void bar(); +}; +class B: public A { +public: + virtual void bar(); +}; +
    +

    Those classes are wrapped into a hierarchy of javascript classes that reflect the same inheritance structure. All of the usual javascript utility functions work normally:

    +

    var a = new example.A(); +a.foo(); +a.bar(); +var b = new example.B(); +b.foo(); +b.bar(); +print("b.cPtr = " + b.getCPtr()); +
    +

    C++ overloaded functions

    +

    C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example, if you have two functions like this:

    +

    void f(int val) { + std::cout << "Called f(int)." << std::endl; +} +void f(int val1, int val2) { + std::cout << "Called f(int, int)." << std::endl; +} +void f(const char* s) { + std::cout << "Called f(const char*)." << std::endl; +} +
    +

    You can use them in javascript in a straightforward manner:

    +

    example.f(1); +example.f(1, 2); +example.f("bla"); +
    +

    C++ operators

    +

    Certain C++ overloaded operators can be handled automatically by SWIG. Though, in javascript operator overloading is not possible. Instead one has to make use of the %rename feature.

    +

    For example, consider a class like this:

    +

    /* File : example.h */ +#include <math.h> +class Complex { +private: + double rpart, ipart; +public: + Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { } + Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { } + Complex &operator=(const Complex &c) { + rpart = c.rpart; + ipart = c.ipart; + return *this; + } + Complex operator+(const Complex &c) const { + return Complex(rpart+c.rpart, ipart+c.ipart); + } + Complex operator-(const Complex &c) const { + return Complex(rpart-c.rpart, ipart-c.ipart); + } + Complex operator*(const Complex &c) const { + return Complex(rpart*c.rpart - ipart*c.ipart, + rpart*c.ipart + c.rpart*ipart); + } + Complex operator-() const { + return Complex(-rpart, -ipart); + } + + double re() const { return rpart; } + double im() const { return ipart; } +}; +
    +

    When wrapped, it works like you expect:

    +

    a = new example.Complex(2,3); +b = new example.Complex(-5,10); + +print ("a =" + a); +print ("b =" + b); + +c = a.plus(b); + +print("c =" + c); +print("a*b =" + a.times(b)); +print("a-c =" + a.minus(c)); + +e = example.Complex.copy(a.minus(c)); +print("e =" + e); + +// Big expression +f = a.plus(b).times(c.plus(b.times(e))).plus(a.uminus()); +print("f =" + f); +
    +

    One restriction with operator overloading support is that SWIG is not able to fully handle operators that aren't defined as part of the class. For example, if you had code like this

    +

    class Complex { +... +friend Complex operator+(double, const Complex &c); +... +}; +
    +

    then SWIG ignores it and issues a warning. You can still wrap the operator, but you may have to encapsulate it in a special function. For example:

    +

    %rename(Complex_add_dc) operator+(double, const Complex &);

    +

    There are ways to make this operator appear as part of the class using the %extend directive.

    +

    C++ namespaces:

    +

    SWIG is aware of C++ namespaces, but namespace names do not appear in the module nor do namespaces result in a module that is broken up into submodules or packages. For example, if you have a file like this,

    +

    %module example +namespace nspace { +extern int gcd(int x, int y); +extern double Foo; +class Circle +{ +public: + Circle(); + Circle(double r); + double area(); + double radius; + }; +} +
    +

    for namespaces, you use the %feature directive in interface file. %feature attaches a new attribute to any parse tree node that matches given prototype.

    +

    /* File : example.i */ +%module example +%{ +#include "example.h" +%} +%feature("nspace", 1); +%include "example.h" +
    +

    it works in javascript as follows:

    +

    print("Global variable Foo=" + example.nspace.Foo); +example.nspace.Foo = 5; +print("Variable Foo changed to " + example.nspace.Foo); +print("GCD of number 6,18 is " + example.nspace.gcd(6,18)); +print("Creating some objects:"); +c = new example.nspace.Circle(10); +print("area = " + c.area()); +
    +

    If your program has more than one namespace, name conflicts (if any) can be resolved using %rename For example:

    +

    %rename(Bar_spam) Bar::spam; +namespace Foo { + int spam(); +} +namespace Bar { + int spam(); +} +
    +

    If you have more than one namespace and your want to keep their symbols separate, consider wrapping them as separate SWIG modules. For example, make the module name the same as the namespace and create extension modules for each namespace separately. If your program utilizes thousands of small deeply nested namespaces each with identical symbol names, well, then you get what you deserve. SWIG resolves overloaded functions and methods using a disambiguation scheme that ranks and sorts declarations according to a set of type-precedence rules. The order in which declarations appear in the input does not matter except in situations where ambiguity arises--in this case, the first declaration takes precedence.

    +

    C++ templates

    +

    C++ templates don't present a huge problem for SWIG. However, in order to create wrappers, you have to tell SWIG to create wrappers for a particular template instantiation. To do this, you use the %template directive. For example:

    +

    /* File : example.i */ +%module example +%{ +#include "example.h" +%} +/* Let's just grab the original header file here */ +%include "example.h" + +/* Now instantiate some specific template declarations */ +%template(maxint) max<int>; +%template(maxdouble) max<double>; +%template(vecint) vector<int>; +%template(vecdouble) vector<double>; +
    +

    In javascript:

    +

    //Call some templated functions +print(example.maxint(3,7)); +print(example.maxdouble(3.14,2.18)); + +// Create some class + +iv = new example.vecint(100); +dv = new example.vecdouble(1000); + +for(i=0;i<=100;i++) + iv.setitem(i,2*i); + +for(i=0;i<=1000;i++) + dv.setitem(i, 1.0/(i+1)); + +sum = 0; +for(i=0;i<=100;i++) + sum = sum + iv.getitem(i); + +print(sum); + +sum = 0.0; +for(i=0;i<=1000;i++) + sum = sum + dv.getitem(i); +print(sum); +
    +

    Exception handling

    +

    The SWIG %exception directive can be used to create a user-definable exception handler for converting exceptions in your C/C++ program into javascript exceptions. The chapter on customization features contains more details, but suppose you have a C++ class like the following:

    +

    Since several methods in this class can throw an exception for an out-of-bounds access, you might want to catch this in the javascript extension by writing the following in an interface file:

    +

    /* File : example.i */ +%module example +%{ +#include "example.h" +%} +%include "std_string.i" + +/* Let's just grab the original header file here */ +%include "example.h" +
    +

    Actually in JS there is no support for typed exceptions.For now there is support for integer and string exception. Example for integer exception

    +

    JSValueRef jsc_gcd(JSContextRef context, JSObjectRef function, JSObjectRef globalobj, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ +int arg1 = (int)JSValueToNumber(context, argv[0], NULL); +int arg2 = (int)JSValueToNumber(context, argv[1], NULL); +*exception = JSValueMakeNumber(context, 13); +int result = (int)gcd(arg1,arg2); +JSValueRef jsresult = JSValueMakeNumber(context, result); +
    +

    and for string exception:

    +

    JSValueRef wrap_gcd(JSContextRef context, JSObjectRef function, JSObjectRef globalobj, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ +int arg1 = (int)JSValueToNumber(context, argv[0], NULL); +int arg2 = (int)JSValueToNumber(context, argv[1], NULL); +JSStringRef message = JSStringCreateWithUTF8CString("This is a test error."); +*exception = JSValueMakeString(context, message); +JSStringRelease(message); +int result = (int)gcd(arg1,arg2); +JSValueRef jscresult = JSValueMakeNumber(context, result); +return jsresult; +} +
    +

    How to use generated modules?

    +

    Basically there is no standard extension mechanism in Javascript. We provided a custom interpreter with extension abilities. If JSC is embedded into a custom application, one has to make use of a generated module initializer function that allows easy extension of interpreter. The basic approach is as follows:

    +

    Basic Mechanism

    +
      +
    • Creating the context
    • +
    • Calling module initializer
    • +
    • Evaluate Javascript
    • +
    +

    Creating the context

    +

    JSGlobalContextRef context = JSGlobalContextCreate(NULL); +JSObjectRef globalObject = JSContextGetGlobalObject(context); +... +
    +

    Calling module initializer

    +

    extern int example_init(JSGlobalContextRef context); + ... + example_init(context); + ... +
    +

    Evaluate Javascript

    +

    // Evaluate the javascript +char* scriptContent = jsccreateStringWithContentsOfFile(scriptPath.c_str()); +JSStringRef jsScript; +if(!scriptContent) { + printf("FAIL: runme script could not be loaded.\n"); + failed = 1; + } + else { + JSValueRef ex; + jsScript = JSStringCreateWithUTF8CString(scriptContent); + JSValueRef jsResult = JSEvaluateScript(context, jsScript, 0, 0, 0, &ex); + if (!jsResult && ex) { + jsc_printError(context, ex, scriptPath); + failed = 1; + } + } + if (scriptContent != NULL) { + free(scriptContent); + } + JSStringRelease(jsScript); + JSGlobalContextRelease(context); + globalObject = 0; + for(std::vector<HANDLE>::iterator it = loaded_modules.begin(); + it != loaded_modules.end(); ++it) { + HANDLE handle = *it; + dlclose(handle); + } + if (failed) { + printf("FAIL: Some tests failed.\n"); + return 1; + } +} +
    +

    Typemaps

    +

    A typemap is nothing more than a code generation rule that is attached to a specific C datatype. For example, to convert integers from javascript to C, you might define a typemap like this:

    +

    %typemap(in) int { + $1 = ($1_ltype)JSValueToNumber(context, $input, NULL); %} + printf("Received an integer : %d\n",$1); +} +
    +

    Typemaps are always associated with some specific aspect of code generation. In this case, the "in" method refers to the conversion of input arguments to C/C++. The datatype int is the datatype to which the typemap will be applied. The supplied C code is used to convert values. In this code a number of special variable prefaced by a $ are used. The $1 variable is placeholder for a local variable of type int.

    +

    Javascript typemaps

    +

    The previous section illustrated an "in" typemap for converting javascript objects to C. A variety of different typemap methods are defined by the javascript module. For example, to convert a C integer back into a javascript object, you might define an "out" typemap like this:

    +

    %typemap(out) int { + $result = JSValueMakeNumber(context, $1); +} +
    +

    The Javascript module makes use of Swig's unified template library.

    +

    Typemap variables

    +

    Within typemap code, a number of special variables prefaced with a $ may appear. A full list of variables can be found in the "Typemaps" chapter. This is a list of the most common variables:

    +

    $1: A C local variable corresponding to the actual type specified in the %typemap directive. For input values, this is a C local variable that's supposed to hold an argument value. For output values, this is the raw result that's supposed to be returned to Javascript.

    +

    $input: A javascript Object * holding a raw javascript object with an argument or variable value.

    +

    $result: A javascript Object * that holds the result to be returned to javascript.

    +

    $1_name: The parameter name that was matched.

    +

    $1_type: The actual C datatype matched by the typemap.

    +

    $1_ltype: An assignable version of the datatype matched by the typemap (a type that can appear on the left-hand-side of a C assignment operation). This type is stripped of qualifiers and may be an altered version of $1_type. All arguments and local variables in wrapper functions are declared using this type so that their values can be properly assigned.

    +

    $symname: The javascript name of the wrapper function being created.

    +

    Javascript: Specification of a Code Generator for JSC

    +

    The module implementation tries to accomplish a separation of logic and code generation by making use of code templates. In the following, the templates are explained.

    +

    Top Level structure

    +

    The generated code consists of the following blocks:

    +

    <RUNTIME> +<INCLUDES> +<HELPER_FUNCTIONS> +<FUNCTION_WRAPPERS> +<INITIALIZER> +
    +
      +
    • RUNTIME: runtime code generated by swig
    • +
    • HELPER_FUNCTIONS: static, from swg-file
    • +
    • INCLUDES: static, module property
    • +
    • FUNCTION_WRAPPERS: dynamically growing, on method declarations
    • +
    • INITIALIZER: dynamically growing, aggregates everything
    • +
    +

    INCLUDES

    +

    #include <JavaScriptCore/JavaScript.h> +<USER_DEFINED_INCLUDES> +
    +

    USER_DEFINED_INCLUDES: a module property

    +

    HELPER_FUNCTIONS

    +

    A lot of boiler-plate code can be shifted into static helper functions:

    +

    bool JS_registerClass(JSGlobalContextRef& context, JSObjectRef& parentObject,const char* className, + JSClassDefinition* definition) { + JSStringRef js_className = JSStringCreateWithUTF8CString(className); + JSObjectRef classObject = JSObjectMake(context, JSClassCreate(definition), NULL); + JSObjectSetProperty(context, parentObject,js_className, classObject,kJSPropertyAttributeNone, NULL); + JSStringRelease(js_className); + return true; +} + +bool JS_registerNamespace(JSGlobalContextRef& context,JSObjectRef& namespaceObj,JSObjectRef& parentNamespace,const char* name) +{ + JSStringRef js_name = JSStringCreateWithUTF8CString(name); + JSObjectSetProperty(context, parentNamespace,js_name, namespaceObj,kJSPropertyAttributeNone, NULL); + JSStringRelease(js_name); + return true; +} + +bool JS_registerFunction(JSGlobalContextRef context, JSObjectRef object, const char* functionName, JSObjectCallAsFunctionCallback callback) +{ + JSStringRef js_functionName = JSStringCreateWithUTF8CString(functionName); + JSObjectSetProperty(context,object,js_functionName,JSObjectMakeFunctionWithCallback(context, + js_functionName, callback), kJSPropertyAttributeNone, NULL); + JSStringRelease(js_functionName); + return true; +} +bool JS_veto_set_variable(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + char buffer[256]; + char msg[512]; + int res; + JSStringGetUTF8CString(propertyName, buffer, 256); + res = sprintf(msg, "Tried to write read-only variable: %s.", buffer); + if(res<0) { + SWIG_exception(SWIG_ERROR, "Tried to write read-only variable."); + } else { + SWIG_exception(SWIG_ERROR, msg); + } + return false; +} + +JSValueRef JS_CharPtrToJSValue(JSContextRef context, char* cstr) { + JSValueRef val; + JSStringRef jsstring = JSStringCreateWithUTF8CString((char*) cstr); + val = JSValueMakeString(context, jsstring); + JSStringRelease(jsstring); + return val; +} +
    +

    FUNCTION_WRAPPERS

    +

    There are different types of function wrappers: - Member Functions - Getproperty / Setproperty - Global Functions (global/namespace/class) - Constructors / Destructors

    +

    Member Functions

    +

    JSValueRef ${functionname}(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + ${LOCALS} + ${CODE} + return jsresult; + + goto fail; + fail: + return NULL; +} +
    +
      +
    • functionname: the name of generated wrapper for function
    • +
    • LOCALS: declarations for input arguments
    • +
    • CODE: contains input marshalling, the action, and output marshalling
    • +
    +

    Setproperty

    +

    bool ${setname}(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + ${LOCALS} + ${CODE} + return jsresult; + + goto fail; + fail: + return NULL; +} +
    +
      +
    • setname: the name of the generated wrapper for setproperty.
    • +
    • LOCALS: declarations for input arguments
    • +
    • CODE: contains input marshalling, and the action
    • +
    +

    Getproperty

    +

    JSValueRef ${getname}(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + ${LOCALS} + ${CODE} + return jsresult; + + goto fail; + fail: + return NULL; +} +
    +
      +
    • getname: the name of the generated wrapper for the getproperty
    • +
    • LOCALS: declarations for output arguments
    • +
    • CODE: contains the action, and output marshalling
    • +
    +

    Global Functions

    +

    JSStaticValue ${namespace}_values[] = { + ${jsglobalvariables} + { 0, 0, 0, 0 } +}; +JSStaticFunction ${namespace}_functions[] = { + ${jsglobalfunctions} + { 0, 0, 0 } +}; +JSClassDefinition ${namespace}_classDefinition; +
    +

    Variable declaration

    +

    {"${propertyname}",${getname}, ${setname}, kJSPropertyAttributeNone} +
    +

    This is used to fill variable definition tables. kJSPropertyAttributeNone is JSC specific and means that the variable has a getter and setter. Even for read-only variables a setter is used which throws an exception.

    +

    Constructor

    +

    ~~

    +

    JSObjectRef wrap_createclassnamemangled{overloadext}(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { ${LOCALS} ${CODE} return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_${type_mangled}, SWIG_POINTER_OWN);

    +
    goto fail;
    +fail:
    +return NULL;
    +
    +

    }

    +
    - `classname_mangled` is the mangled qualified class name,   e.g., `foo::A -> foo_A`
    +- `LOCALS`: declarations for input arguments 
    +- `CODE`: contains input marshalling, and the action 
    +
    +## Destructors
    +
    +

    void wrap${classname_mangled}_finalize(JSObjectRef thisObject) { SWIG_PRV_DATA* t = (SWIG_PRV_DATA*)JSObjectGetPrivate(thisObject); if(t && t->swigCMemOwn) delete (${type}*)(t->swigCObject); if(t) delete t; }

    +

    - `classname_mangled` is the mangled qualified class name, e.g., `foo::A -> foo_A` + +## Initializer +
    +

    bool ${modulename}_initialize(JSGlobalContextRef context) { SWIG_InitializeModule(0);

    +
    JSObjectRef global_object = JSContextGetGlobalObject(context);
    +
    +/* Initialize the base swig type object */
    +_SwigObject_objectDefinition.staticFunctions = _SwigObject_functions;
    +_SwigObject_objectDefinition.staticValues = _SwigObject_values;
    +_SwigObject_classRef = JSClassCreate(&_SwigObject_objectDefinition);
    +
    +/* Create objects for namespaces */
    +${create_namespaces}
    +
    +/* Create classes */
    +${initializercode}
    +
    +/* Register namespaces */
    +${register_namespaces}
    +
    +return true;
    +
    +

    }

    +

    ## Class template defintions + +A class is specified by a static part (`*_classDefinition`) and a dynamic part (`*_objectDefinition`). +
    +

    ${classname_mangled}_classDefinition.staticFunctions = ${classname_mangled}_staticFunctions; ${classname_mangled}_classDefinition.staticValues = ${classname_mangled}_staticValues; ${classname_mangled}_classDefinition.callAsConstructor = _wrap_create_${classname_mangled}; ${classname_mangled}_objectDefinition.staticValues = ${classname_mangled}_values; ${classname_mangled}_objectDefinition.staticFunctions = ${classname_mangled}_functions; ${classname_mangled}_objectDefinition.parentClass = ${base_classname}_classRef; JSClassRef ${classname_mangled}_classRef = JSClassCreate(&${classname_mangled}objectDefinition); SWIGTYPE${classtype_mangled}->clientdata = ${classname_mangled}_classRef;%}

    +

    Notes: +- `classname_mangled` is the mangled qualified class name, e.g., `foo::A -> foo_A` + which is retrieved by `Swig_name_mangle(Getattr(n, "name"))` +- ClassDefinitions are built using the staticValues array and the staticFunction array. The staticValues and staticFunctions arrays are the simplest and most efficient means for vending custom properties to the class object. + +## Inheritance +
    +

    {${classname_mangled}_objectDefinition.parentClass = ${base_classname}_classRef};

    +

    - `classname_mangled` is the mangled qualified class name, e.g., `foo::A -> foo_A` +- Note: multiple inheritance is not possible; thus we will always take the first parent class + +## Namespaces + +Namespaces are objects without class templates. i.e., instances are created, referenced locally, used as contexts for other registrations, and stored in the according parent contexts. +
    +

    ${namespace}_classDefinition.staticFunctions = ${namespace}_functions; ${namespace}_classDefinition.staticValues = ${namespace}_values; JSObjectRef ${namespace}_object = JSObjectMake(context, JSClassCreate(&${namespace}_classDefinition), NULL);

    +

    ## Registration + +The registration part consists of registering classes at contexts (i.e., global or namespace), methods and properties at classes or contexts, and namespaces as objects at parent contexts. + +* Global functions +
    +

    JS_registerFunction(${context}, ${context_object}, "${functionname}", ${functionwrapper}

    +

    * Classes +
    +

    JS_registerClass(context, ${namespace}_object, "${classname}", &${classname_mangled}_classDefinition)

    +

    Note: every class template has an associated constructor function wrapper, which is registered here + +* Namespaces +
    +

    ${namespace}_classDefinition.staticFunctions = ${namespace}_functions; ${namespace}_classDefinition.staticValues = ${namespace}_values; JSObjectRef ${namespace}_object = JSObjectMake(context, JSClassCreate(&${namespace}_classDefinition), NULL);

    +

    Namespaces are registered using: +
    +

    JS_registerNamespace(context, ${namespace}_object, ${parent_namespace}_object, "${namespace}");

    +

    ~~

    +
    + + diff --git a/Doc/Manual/Javascript.md b/Doc/Manual/Javascript.md new file mode 100644 index 000000000..a01c630d8 --- /dev/null +++ b/Doc/Manual/Javascript.md @@ -0,0 +1,1103 @@ +% SWIG AND JAVASCRIPT + +# Overview + +This chapter describes SWIG support for Javascript. +The module is designed to support JavascriptCore and V8 as target engine. +Currently only JavascriptCore support is implemented. +JavaScriptCore is the built-in JavaScript engine for WebKit, whereas V8 is the engine used by Chromium. + +JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. Its arguably the most popular language for web development. C++, on the other hand, is statically typed, compiled, general purpose programming language. +The approach I followed here is "Test driven" where I have written the examples/test-cases to be supported for Javascript one-by-one and implemented the required module files in parallel. +The support for Javascript would be added similar to other supported target languages in swig. Swig comes with an "Examples" directory for Javascript like other supported language. The directory contains examples for every supported feature of the target language. There is also a test-suite directory for javascript which contains additional tests. + +# Preliminaries + +In order to use this module, you will need to have installed javascriptcore and you can install it by installing package libwebkit-dev +You can find out some necessary compiler/linker flag by + + pkg-config javascriptcoregtk-1.0 --cflags --libs + +## Using the module + +To generate an extension for JavascriptCore one would call swig as follows + +~~~~ + +swig -c++ -javascript -jsc example.i + +~~~~ + +This generates a C++ source file containing the wrapper. + +## How does Javascript talk to C++? + +JavascriptCore provides a C-API which allows to extend a Javascript interpreter with native methods and structures. Normally, this is used to implement the builtin features of the language. However, by extending the interpreter, it is also possible to add your own commands and variables. A reference manual of this API can be found +[here](http://developer.apple.com/library/mac/#documentation/Carbon/Reference/WebKit_JavaScriptCore_Ref/_index.html). + +Typically, when you add a new command to the javascript interpreter you need to do two things: first you need to write a special "wrapper" function that serves as the glue between the interpreter and the underlying C function. Then you need to give the interpreter information about the wrapper by providing details about the name of the function, arguments, and so forth. The next few sections illustrate the process. + +## Wrapper functions + +Suppose you have an ordinary C function like this : + +~~~~ + +int fact(int n) { + if (n <= 1) return 1; + else return n*fact(n-1); +} + +~~~~ + +In order to access this function from a scripting language, it is necessary to write a special "wrapper" function that serves as the glue between the scripting language and the underlying C function. A wrapper function must do three things : + + - Gather function arguments and make sure they are valid. + - Call the C function. + - Convert the return value into a form recognized by the javascript. + +As an example, the javascript wrapper function for the fact() function above example might look like the following : + +~~~~ + +JSValueRef wrap_fact(JSContextRef context, JSObjectRef function, JSObjectRef globalobj, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + int arg1 = (int)JSValueToNumber(context, argv[0], NULL); + int arg2 = (int)JSValueToNumber(context, argv[1], NULL); + int result = (int)fact(arg1,arg2); + JSValueRef jsresult = JSValueMakeNumber(context, result); + return jsresult; +} + +~~~~ + +Once you have created a wrapper function, the final step is to tell the javascript about the new function. This is done by register function called by the javascript when the module is loaded. For example, adding the above function to the javascript interpreter requires code like the following : + +~~~~ + +bool jsc_registerFunction(JSGlobalContextRef context, JSObjectRef object, + const char* functionName, JSObjectCallAsFunctionCallback callback) +{ + JSStringRef js_globalvarsclassname = JSStringCreateWithUTF8CString(globalvarsclassname); + JSObjectSetProperty(context,js_globalvarsclassname,JSObjectMakeFunctionWithCallback(context, + js_globalvarsclassname, callback), kJSPropertyAttributeNone,NULL); + JSStringRelease(jsstring); + return true; +} + +int example_init(JSContextRef context) { + JSObjectRef global; + ... + jsc_registerFunction(context, global, "fact", wrap_fact); + ... +} + +~~~~ + +When executed, javascript will now have a new command called "fact" that you can use like any other Javascript command. +Although the process of adding a new function to javascript has been illustrated, the procedure is almost identical for Perl and Python. Both require special wrappers to be written and both need additional initialization code. + +## Variable Linking + +Variable linking refers to the problem of mapping a C/C++ global variable to a variable in the scripting language interpreter. For example, suppose you had the following variable: + +~~~~ + +double Foo = 3.5; + +~~~~ + +To provide such access, variables are commonly manipulated using a pair of get/set functions. For example, whenever the value of a variable is read, a "get" function is invoked. Similarly, whenever the value of a variable is changed, a "set" function is called. + +~~~~ + +bool Foo_set(JSContextRef context, JSObjectRef globalobj, JSStringRef propertyName, JSValueRef value, + JSValueRef* exception) +{ + JSValueRef jsresult; + double arg1 = (double)JSValueToNumber(context, value, NULL); + Foo = arg1; + jscresult = JSValueMakeUndefined(context); + return jsresult; +} + +JSValueRef Foo_get(JSContextRef context, JSObjectRef globalobj, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + double result = (double)Foo; + jsresult = JSValueMakeNumber(context, result); + return jsresult; +} + +~~~~ + +In many languages, calls to the get/set functions can be attached to evaluation and assignment operators. Therefore, evaluating a variable such as Foo might implicitly call the get function. Similarly, typing Foo = 4 would call the underlying set function to change the value. + +# A tour of basic C/C++ wrapping + +By default, SWIG tries to build a very natural javascript interface to your C/C++ code. Functions are wrapped as functions, classes are wrapped as classes, and so forth. This section briefly covers the essential aspects of this wrapping. + +## Modules + +The SWIG %module directive specifies the name of the Javascript module. If you specify `%module example`, then everything is wrapped into a Javascript 'example' module. Underneath the covers, this module consists of a cpp source file example.cpp. When choosing a module name, make sure you don't use the same name as a built-in Javascript command or standard module name. + +## Global variables + +C/C++ global variables are fully supported by SWIG. However, the underlying mechanism is somewhat different than you might expect due to the way that javascript works. + +~~~~ + +// SWIG interface file with global variables +%module example +... +%inline %{ +extern double Foo; +extern int gcd(int x, int y); +%} +... + +~~~~ + +Now look at the javascript: + +~~~~ + +print("Global variable Foo=" + example.Foo); +example.Foo = 3.1415926; +print("Variable Foo changed to=" + example.Foo); +print("GCD of x and y is=" + example.gcd(x,y)); + +~~~~ + +## Constants and enums + +C/C++ constants are installed as javascript objects containing the appropriate value. To create a constant, use #define, enum, or the %constant directive. For example: + +~~~~ + +#define ICONST 42 +#define FCONST 2.1828 +%constant int iconst = 37; + +~~~~ + +In javascript they are treated as: + +~~~~ + +print("ICONST = " + example.ICONST + " (should be 42)\n"); +print("FCONST = " + example.FCONST + " (should be 2.1828)\n"); +print("iconst = " + example.iconst + " (should be 37)\n"); + +~~~~ + +For enums, make sure that the definition of the enumeration actually appears in a header file or in the wrapper file somehow---if you just stick an enum in a SWIG interface without also telling the C compiler about it, the wrapper code won't compile. +Enums are treated as constants.So if we have enums in c++ as: + +~~~~ + +void enum_test(color c, Foo::speed s); + +~~~~ + +In javascript they are treated as: + +~~~~ + +example.enum_test(example.RED, example.Foo.IMPULSE); +example.enum_test(example.BLUE, example.Foo.WARP); +example.enum_test(example.GREEN, example.Foo.LUDICROUS); + +~~~~ + +### Inside the class +For class enums as below: + +~~~~ + +class Foo { +public: +Foo() { } +enum speed { IMPULSE, WARP, LUDICROUS }; +} + +~~~~ + +In javascript they are treated as: + +~~~~ + +print(" Foo_IMPULSE =" + example.Foo.IMPULSE); +print(" Foo_WARP =" + example.Foo.WARP); +print(" Foo_LUDICROUS =" + example.Foo.LUDICROUS); + +~~~~ + +## Pointers + +C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Here is a rather simple interface + +~~~~ + +/* File : example.i */ +%module example +%{ +extern void add(int *, int *, int *); +%} + +~~~~ + +When wrapped, you will be able to use the functions in a natural way from javascript. For example: + +~~~~ + +// Call the add() function with some pointers +example.add(a, b, c); + +~~~~ + +// In javascript the code look like as: + +~~~~ + +a = example.new_intp(); +example.intp_assign(a,37); + +~~~~ + +- The first one creates an int-pointer instance. +- The second one assigns it the value 37. + +### C++ classes + +C++ classes are wrapped by javascript classes as well. For example, if you have this class, + +~~~~ + +class Circle +{ +public: + Circle(); + Circle(double r); + double area(); + double radius; +}; + +~~~~ + +you can use it in javascript like this: + +~~~~ + +print("Creating some objects:"); +c = new example.Circle(10); +print("area = " + c.area()); + +~~~~ + +Class data members are accessed in the same manner as C structures. + +Static class members and functions are mapped to javascript in a straight-forward manner: + +~~~~ + +class Spam { +public: + static void foo(); + static int bar; +}; + +~~~~ + +In javascript, the static member can be access in this way: + +~~~~ + +// ----- Access a static member ----- +print("\nA access of static member is" + example.Spam.Foo); // access static member as properties of the class object. + +~~~~ + +## C++ inheritance + +SWIG is fully aware of issues related to C++ inheritance. Therefore, if you have classes like this + +~~~~ + +class A { +public: + void foo(); + virtual void bar(); +}; +class B: public A { +public: + virtual void bar(); +}; + +~~~~ + +Those classes are wrapped into a hierarchy of javascript classes that reflect the same inheritance structure. All of the usual javascript utility functions work normally: + +~~~~ + +var a = new example.A(); +a.foo(); +a.bar(); +var b = new example.B(); +b.foo(); +b.bar(); +print("b.cPtr = " + b.getCPtr()); + +~~~~ + +## C++ overloaded functions + +C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example, if you have two functions like this: + +~~~~ + +void f(int val) { + std::cout << "Called f(int)." << std::endl; +} +void f(int val1, int val2) { + std::cout << "Called f(int, int)." << std::endl; +} +void f(const char* s) { + std::cout << "Called f(const char*)." << std::endl; +} + +~~~~ + +You can use them in javascript in a straightforward manner: + +~~~~ + +example.f(1); +example.f(1, 2); +example.f("bla"); + +~~~~ + +## C++ operators + +Certain C++ overloaded operators can be handled automatically by SWIG. Though, in javascript operator overloading is not possible. Instead one has to make use of the `%rename` feature. + +For example, consider a class like this: + +~~~~ + +/* File : example.h */ +#include +class Complex { +private: + double rpart, ipart; +public: + Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { } + Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { } + Complex &operator=(const Complex &c) { + rpart = c.rpart; + ipart = c.ipart; + return *this; + } + Complex operator+(const Complex &c) const { + return Complex(rpart+c.rpart, ipart+c.ipart); + } + Complex operator-(const Complex &c) const { + return Complex(rpart-c.rpart, ipart-c.ipart); + } + Complex operator*(const Complex &c) const { + return Complex(rpart*c.rpart - ipart*c.ipart, + rpart*c.ipart + c.rpart*ipart); + } + Complex operator-() const { + return Complex(-rpart, -ipart); + } + + double re() const { return rpart; } + double im() const { return ipart; } +}; + +~~~~ + +When wrapped, it works like you expect: + +~~~~ + +a = new example.Complex(2,3); +b = new example.Complex(-5,10); + +print ("a =" + a); +print ("b =" + b); + +c = a.plus(b); + +print("c =" + c); +print("a*b =" + a.times(b)); +print("a-c =" + a.minus(c)); + +e = example.Complex.copy(a.minus(c)); +print("e =" + e); + +// Big expression +f = a.plus(b).times(c.plus(b.times(e))).plus(a.uminus()); +print("f =" + f); + +~~~~ + +One restriction with operator overloading support is that SWIG is not able to fully handle operators that aren't defined as part of the class. For example, if you had code like this + +~~~~ + +class Complex { +... +friend Complex operator+(double, const Complex &c); +... +}; + +~~~~ + +then SWIG ignores it and issues a warning. You can still wrap the operator, but you may have to encapsulate it in a special function. For example: + +%rename(Complex_add_dc) operator+(double, const Complex &); + +There are ways to make this operator appear as part of the class using the %extend directive. + +## C++ namespaces: + +SWIG is aware of C++ namespaces, but namespace names do not appear in the module nor do namespaces result in a module that is broken up into submodules or packages. For example, if you have a file like this, + +~~~~ + +%module example +namespace nspace { +extern int gcd(int x, int y); +extern double Foo; +class Circle +{ +public: + Circle(); + Circle(double r); + double area(); + double radius; + }; +} + +~~~~ + +for namespaces, you use the %feature directive in interface file. %feature attaches a new attribute to any parse tree node that matches given prototype. + +~~~~ + +/* File : example.i */ +%module example +%{ +#include "example.h" +%} +%feature("nspace", 1); +%include "example.h" + +~~~~ + +it works in javascript as follows: + +~~~~ + +print("Global variable Foo=" + example.nspace.Foo); +example.nspace.Foo = 5; +print("Variable Foo changed to " + example.nspace.Foo); +print("GCD of number 6,18 is " + example.nspace.gcd(6,18)); +print("Creating some objects:"); +c = new example.nspace.Circle(10); +print("area = " + c.area()); + +~~~~ + +If your program has more than one namespace, name conflicts (if any) can be resolved using %rename For example: + +~~~~ + +%rename(Bar_spam) Bar::spam; +namespace Foo { + int spam(); +} +namespace Bar { + int spam(); +} + +~~~~ + +If you have more than one namespace and your want to keep their symbols separate, consider wrapping them as separate SWIG modules. For example, make the module name the same as the namespace and create extension modules for each namespace separately. If your program utilizes thousands of small deeply nested namespaces each with identical symbol names, well, then you get what you deserve. +SWIG resolves overloaded functions and methods using a disambiguation scheme that ranks and sorts declarations according to a set of type-precedence rules. The order in which declarations appear in the input does not matter except in situations where ambiguity arises--in this case, the first declaration takes precedence. + +## C++ templates + +C++ templates don't present a huge problem for SWIG. However, in order to create wrappers, you have to tell SWIG to create wrappers for a particular template instantiation. To do this, you use the %template directive. For example: + +~~~~ + +/* File : example.i */ +%module example +%{ +#include "example.h" +%} +/* Let's just grab the original header file here */ +%include "example.h" + +/* Now instantiate some specific template declarations */ +%template(maxint) max; +%template(maxdouble) max; +%template(vecint) vector; +%template(vecdouble) vector; + +~~~~ + +In javascript: + +~~~~ + +//Call some templated functions +print(example.maxint(3,7)); +print(example.maxdouble(3.14,2.18)); + +// Create some class + +iv = new example.vecint(100); +dv = new example.vecdouble(1000); + +for(i=0;i<=100;i++) + iv.setitem(i,2*i); + +for(i=0;i<=1000;i++) + dv.setitem(i, 1.0/(i+1)); + +sum = 0; +for(i=0;i<=100;i++) + sum = sum + iv.getitem(i); + +print(sum); + +sum = 0.0; +for(i=0;i<=1000;i++) + sum = sum + dv.getitem(i); +print(sum); + +~~~~ + +## Exception handling + +The SWIG %exception directive can be used to create a user-definable exception handler for converting exceptions in your C/C++ program into javascript exceptions. The chapter on customization features contains more details, but suppose you have a C++ class like the following: + +Since several methods in this class can throw an exception for an out-of-bounds access, you might want to catch this in the javascript extension by writing the following in an interface file: + +~~~~ + +/* File : example.i */ +%module example +%{ +#include "example.h" +%} +%include "std_string.i" + +/* Let's just grab the original header file here */ +%include "example.h" + +~~~~ + +Actually in JS there is no support for typed exceptions.For now there is support for integer and string +exception. Example for integer exception + +~~~~ + +JSValueRef jsc_gcd(JSContextRef context, JSObjectRef function, JSObjectRef globalobj, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ +int arg1 = (int)JSValueToNumber(context, argv[0], NULL); +int arg2 = (int)JSValueToNumber(context, argv[1], NULL); +*exception = JSValueMakeNumber(context, 13); +int result = (int)gcd(arg1,arg2); +JSValueRef jsresult = JSValueMakeNumber(context, result); + +~~~~ + +and for string exception: + +~~~~ + +JSValueRef wrap_gcd(JSContextRef context, JSObjectRef function, JSObjectRef globalobj, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ +int arg1 = (int)JSValueToNumber(context, argv[0], NULL); +int arg2 = (int)JSValueToNumber(context, argv[1], NULL); +JSStringRef message = JSStringCreateWithUTF8CString("This is a test error."); +*exception = JSValueMakeString(context, message); +JSStringRelease(message); +int result = (int)gcd(arg1,arg2); +JSValueRef jscresult = JSValueMakeNumber(context, result); +return jsresult; +} + +~~~~ + +## How to use generated modules? + +Basically there is no standard extension mechanism in Javascript. We provided a custom interpreter with extension abilities. If JSC is embedded into a custom application, one has to make use of a generated module initializer function that allows easy extension of interpreter. +The basic approach is as follows: + +### Basic Mechanism +- Creating the context +- Calling module initializer +- Evaluate Javascript + +#### Creating the context + +~~~~ + +JSGlobalContextRef context = JSGlobalContextCreate(NULL); +JSObjectRef globalObject = JSContextGetGlobalObject(context); +... + +~~~~ + +### Calling module initializer + +~~~~ + + extern int example_init(JSGlobalContextRef context); + ... + example_init(context); + ... + +~~~~ + +### Evaluate Javascript + +~~~~ + +// Evaluate the javascript +char* scriptContent = jsccreateStringWithContentsOfFile(scriptPath.c_str()); +JSStringRef jsScript; +if(!scriptContent) { + printf("FAIL: runme script could not be loaded.\n"); + failed = 1; + } + else { + JSValueRef ex; + jsScript = JSStringCreateWithUTF8CString(scriptContent); + JSValueRef jsResult = JSEvaluateScript(context, jsScript, 0, 0, 0, &ex); + if (!jsResult && ex) { + jsc_printError(context, ex, scriptPath); + failed = 1; + } + } + if (scriptContent != NULL) { + free(scriptContent); + } + JSStringRelease(jsScript); + JSGlobalContextRelease(context); + globalObject = 0; + for(std::vector::iterator it = loaded_modules.begin(); + it != loaded_modules.end(); ++it) { + HANDLE handle = *it; + dlclose(handle); + } + if (failed) { + printf("FAIL: Some tests failed.\n"); + return 1; + } +} + +~~~~ + +## Typemaps + +A typemap is nothing more than a code generation rule that is attached to a specific C datatype. For example, to convert integers from javascript to C, you might define a typemap like this: + +~~~~ + +%typemap(in) int { + $1 = ($1_ltype)JSValueToNumber(context, $input, NULL); %} + printf("Received an integer : %d\n",$1); +} + +~~~~ + +Typemaps are always associated with some specific aspect of code generation. In this case, the "in" method refers to the conversion of input arguments to C/C++. The datatype int is the datatype to which the typemap will be applied. The supplied C code is used to convert values. In this code a number of special variable prefaced by a $ are used. The $1 variable is placeholder for a local variable of type int. + +## Javascript typemaps + +The previous section illustrated an "in" typemap for converting javascript objects to C. A variety of different typemap methods are defined by the javascript module. For example, to convert a C integer back into a javascript object, you might define an "out" typemap like this: + +~~~~ + +%typemap(out) int { + $result = JSValueMakeNumber(context, $1); +} + +~~~~ + +The Javascript module makes use of Swig's unified template library. + +## Typemap variables + +Within typemap code, a number of special variables prefaced with a $ may appear. A full list of variables can be found in the "Typemaps" chapter. This is a list of the most common variables: + +`$1`: +A C local variable corresponding to the actual type specified in the %typemap directive. For input values, this is a C local variable that's supposed to hold an argument value. For output values, this is the raw result that's supposed to be returned to Javascript. + +`$input`: +A javascript Object * holding a raw javascript object with an argument or variable value. + +`$result`: +A javascript Object * that holds the result to be returned to javascript. + +`$1_name`: +The parameter name that was matched. + +`$1_type`: +The actual C datatype matched by the typemap. + +`$1_ltype`: +An assignable version of the datatype matched by the typemap (a type that can appear on the left-hand-side of a C assignment operation). This type is stripped of qualifiers and may be an altered version of `$1_type`. All arguments and local variables in wrapper functions are declared using this type so that their values can be properly assigned. + +`$symname`: +The javascript name of the wrapper function being created. + +# Javascript: Specification of a Code Generator for JSC + +The module implementation tries to accomplish a separation of logic and code generation by making +use of code templates. In the following, the templates are explained. + +# Top Level structure + +The generated code consists of the following blocks: + +~~~~ + + + + + + + +~~~~ + +- `RUNTIME`: runtime code generated by swig +- `HELPER_FUNCTIONS`: static, from swg-file +- `INCLUDES`: static, module property +- `FUNCTION_WRAPPERS`: dynamically growing, on method declarations +- `INITIALIZER`: dynamically growing, aggregates everything + +## INCLUDES + +~~~~ + +#include + + +~~~~ + +`USER_DEFINED_INCLUDES`: a module property + +## `HELPER_FUNCTIONS` + +A lot of boiler-plate code can be shifted into static helper functions: + +~~~~ + +bool JS_registerClass(JSGlobalContextRef& context, JSObjectRef& parentObject,const char* className, + JSClassDefinition* definition) { + JSStringRef js_className = JSStringCreateWithUTF8CString(className); + JSObjectRef classObject = JSObjectMake(context, JSClassCreate(definition), NULL); + JSObjectSetProperty(context, parentObject,js_className, classObject,kJSPropertyAttributeNone, NULL); + JSStringRelease(js_className); + return true; +} + +bool JS_registerNamespace(JSGlobalContextRef& context,JSObjectRef& namespaceObj,JSObjectRef& parentNamespace,const char* name) +{ + JSStringRef js_name = JSStringCreateWithUTF8CString(name); + JSObjectSetProperty(context, parentNamespace,js_name, namespaceObj,kJSPropertyAttributeNone, NULL); + JSStringRelease(js_name); + return true; +} + +bool JS_registerFunction(JSGlobalContextRef context, JSObjectRef object, const char* functionName, JSObjectCallAsFunctionCallback callback) +{ + JSStringRef js_functionName = JSStringCreateWithUTF8CString(functionName); + JSObjectSetProperty(context,object,js_functionName,JSObjectMakeFunctionWithCallback(context, + js_functionName, callback), kJSPropertyAttributeNone, NULL); + JSStringRelease(js_functionName); + return true; +} +bool JS_veto_set_variable(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + char buffer[256]; + char msg[512]; + int res; + JSStringGetUTF8CString(propertyName, buffer, 256); + res = sprintf(msg, "Tried to write read-only variable: %s.", buffer); + if(res<0) { + SWIG_exception(SWIG_ERROR, "Tried to write read-only variable."); + } else { + SWIG_exception(SWIG_ERROR, msg); + } + return false; +} + +JSValueRef JS_CharPtrToJSValue(JSContextRef context, char* cstr) { + JSValueRef val; + JSStringRef jsstring = JSStringCreateWithUTF8CString((char*) cstr); + val = JSValueMakeString(context, jsstring); + JSStringRelease(jsstring); + return val; +} + +~~~~ + +## `FUNCTION_WRAPPERS` + +There are different types of function wrappers: +- Member Functions +- Getproperty / Setproperty +- Global Functions (global/namespace/class) +- Constructors / Destructors + + +## Member Functions + +~~~~ + +JSValueRef ${functionname}(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + ${LOCALS} + ${CODE} + return jsresult; + + goto fail; + fail: + return NULL; +} + +~~~~ + +- `functionname`: the name of generated wrapper for function +- `LOCALS`: declarations for input arguments +- `CODE`: contains input marshalling, the action, and output marshalling + +## Setproperty + +~~~~ + +bool ${setname}(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + ${LOCALS} + ${CODE} + return jsresult; + + goto fail; + fail: + return NULL; +} + +~~~~ + +- `setname`: the name of the generated wrapper for setproperty. +- `LOCALS`: declarations for input arguments +- `CODE`: contains input marshalling, and the action + +## Getproperty + +~~~~ + +JSValueRef ${getname}(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + ${LOCALS} + ${CODE} + return jsresult; + + goto fail; + fail: + return NULL; +} + +~~~~ + +- `getname`: the name of the generated wrapper for the getproperty +- `LOCALS`: declarations for output arguments +- `CODE`: contains the action, and output marshalling + + +## Global Functions + +~~~~ + +JSStaticValue ${namespace}_values[] = { + ${jsglobalvariables} + { 0, 0, 0, 0 } +}; +JSStaticFunction ${namespace}_functions[] = { + ${jsglobalfunctions} + { 0, 0, 0 } +}; +JSClassDefinition ${namespace}_classDefinition; + +~~~~ + +## Variable declaration + +~~~~ + +{"${propertyname}",${getname}, ${setname}, kJSPropertyAttributeNone} + +~~~~ + +This is used to fill variable definition tables. +`kJSPropertyAttributeNone` is JSC specific and means that the variable has a getter and setter. +Even for read-only variables a setter is used which throws an exception. + +## Constructor + +~~~~ + +JSObjectRef _wrap_create_${classname_mangled}${overloadext}(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + ${LOCALS} + ${CODE} + return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_${type_mangled}, SWIG_POINTER_OWN); + + goto fail; + fail: + return NULL; +} + +~~~~ +- `classname_mangled` is the mangled qualified class name, e.g., `foo::A -> foo_A` +- `LOCALS`: declarations for input arguments +- `CODE`: contains input marshalling, and the action + +## Destructors + +~~~~ + +void _wrap_${classname_mangled}_finalize(JSObjectRef thisObject) +{ + SWIG_PRV_DATA* t = (SWIG_PRV_DATA*)JSObjectGetPrivate(thisObject); + if(t && t->swigCMemOwn) delete (${type}*)(t->swigCObject); + if(t) delete t; +} + +~~~~ + +- `classname_mangled` is the mangled qualified class name, e.g., `foo::A -> foo_A` + +## Initializer + +~~~~ + +bool ${modulename}_initialize(JSGlobalContextRef context) { + SWIG_InitializeModule(0); + + JSObjectRef global_object = JSContextGetGlobalObject(context); + + /* Initialize the base swig type object */ + _SwigObject_objectDefinition.staticFunctions = _SwigObject_functions; + _SwigObject_objectDefinition.staticValues = _SwigObject_values; + _SwigObject_classRef = JSClassCreate(&_SwigObject_objectDefinition); + + /* Create objects for namespaces */ + ${create_namespaces} + + /* Create classes */ + ${initializercode} + + /* Register namespaces */ + ${register_namespaces} + + return true; +} + +~~~~ + +## Class template defintions + +A class is specified by a static part (`*_classDefinition`) and a dynamic part (`*_objectDefinition`). + +~~~~ + +${classname_mangled}_classDefinition.staticFunctions = ${classname_mangled}_staticFunctions; + ${classname_mangled}_classDefinition.staticValues = ${classname_mangled}_staticValues; + ${classname_mangled}_classDefinition.callAsConstructor = _wrap_create_${classname_mangled}; + ${classname_mangled}_objectDefinition.staticValues = ${classname_mangled}_values; + ${classname_mangled}_objectDefinition.staticFunctions = ${classname_mangled}_functions; + ${classname_mangled}_objectDefinition.parentClass = ${base_classname}_classRef; + JSClassRef ${classname_mangled}_classRef = JSClassCreate(&${classname_mangled}_objectDefinition); + SWIGTYPE_${classtype_mangled}->clientdata = ${classname_mangled}_classRef;%} + +~~~~ + +Notes: +- `classname_mangled` is the mangled qualified class name, e.g., `foo::A -> foo_A` + which is retrieved by `Swig_name_mangle(Getattr(n, "name"))` +- ClassDefinitions are built using the staticValues array and the staticFunction array. The staticValues and staticFunctions arrays are the simplest and most efficient means for vending custom properties to the class object. + +## Inheritance + +~~~~ + +{${classname_mangled}_objectDefinition.parentClass = ${base_classname}_classRef}; + +~~~~ + +- `classname_mangled` is the mangled qualified class name, e.g., `foo::A -> foo_A` +- Note: multiple inheritance is not possible; thus we will always take the first parent class + +## Namespaces + +Namespaces are objects without class templates. i.e., instances are created, referenced locally, used as contexts for other registrations, and stored in the according parent contexts. + +~~~~ + + ${namespace}_classDefinition.staticFunctions = ${namespace}_functions; + ${namespace}_classDefinition.staticValues = ${namespace}_values; + JSObjectRef ${namespace}_object = JSObjectMake(context, JSClassCreate(&${namespace}_classDefinition), NULL); + +~~~~ + +## Registration + +The registration part consists of registering classes at contexts (i.e., global or namespace), methods and properties at classes or contexts, and namespaces as objects at parent contexts. + +* Global functions + +~~~~ + +JS_registerFunction(${context}, ${context_object}, "${functionname}", ${functionwrapper} + +~~~~ + +* Classes + +~~~~ + +JS_registerClass(context, ${namespace}_object, "${classname}", &${classname_mangled}_classDefinition) + +~~~~ + +Note: every class template has an associated constructor function wrapper, which is registered here + +* Namespaces + +~~~~ + +${namespace}_classDefinition.staticFunctions = ${namespace}_functions; +${namespace}_classDefinition.staticValues = ${namespace}_values; +JSObjectRef ${namespace}_object = JSObjectMake(context, JSClassCreate(&${namespace}_classDefinition), NULL); + +~~~~ + +Namespaces are registered using: + +~~~~ + +JS_registerNamespace(context, ${namespace}_object, ${parent_namespace}_object, "${namespace}"); + +~~~~ + diff --git a/Doc/Manual/pandoc_template.html b/Doc/Manual/pandoc_template.html new file mode 100644 index 000000000..390bfc51c --- /dev/null +++ b/Doc/Manual/pandoc_template.html @@ -0,0 +1,56 @@ + + + + + + +$for(author-meta)$ + +$endfor$ +$if(date-meta)$ + +$endif$ + $if(title-prefix)$$title-prefix$ - $endif$$if(pagetitle)$$pagetitle$$endif$ +$if(highlighting-css)$ + +$endif$ +$for(css)$ + +$endfor$ +$if(math)$ + $math$ +$endif$ +$for(header-includes)$ + $header-includes$ +$endfor$ + + +$for(include-before)$ +$include-before$ +$endfor$ +$if(title)$ +
    +

    $title$

    +$for(author)$ +

    $author$

    +$endfor$ +$if(date)$ +

    $date$

    +$endif$ +
    +$endif$ +$if(toc)$ +
    +$toc$ +
    +$endif$ +
    +$body$ +
    +$for(include-after)$ +$include-after$ +$endfor$ + + From 48af60d82904f1eef37b9beac03f8412947e883e Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 27 Sep 2013 02:46:11 +0200 Subject: [PATCH 0347/1048] Javascript examples. --- Examples/javascript/check.list | 13 +++ Examples/javascript/class/Makefile | 21 +++++ Examples/javascript/class/binding.gyp | 8 ++ Examples/javascript/class/example.cxx | 28 +++++++ Examples/javascript/class/example.h | 34 ++++++++ Examples/javascript/class/example.i | 10 +++ Examples/javascript/class/runme.js | 46 +++++++++++ Examples/javascript/constant/Makefile | 21 +++++ Examples/javascript/constant/binding.gyp | 8 ++ Examples/javascript/constant/example.h | 8 ++ Examples/javascript/constant/example.i | 24 ++++++ Examples/javascript/constant/runme.js | 14 ++++ Examples/javascript/enum/Makefile | 21 +++++ Examples/javascript/enum/binding.gyp | 8 ++ Examples/javascript/enum/example.cxx | 37 +++++++++ Examples/javascript/enum/example.h | 13 +++ Examples/javascript/enum/example.i | 11 +++ Examples/javascript/enum/runme.js | 34 ++++++++ Examples/javascript/exception/Makefile | 21 +++++ Examples/javascript/exception/binding.gyp | 8 ++ Examples/javascript/exception/example.cxx | 1 + Examples/javascript/exception/example.h | 53 ++++++++++++ Examples/javascript/exception/example.i | 12 +++ Examples/javascript/exception/runme.js | 64 +++++++++++++++ Examples/javascript/functor/Makefile | 21 +++++ Examples/javascript/functor/binding.gyp | 8 ++ Examples/javascript/functor/example.cxx | 0 Examples/javascript/functor/example.i | 25 ++++++ Examples/javascript/functor/runme.js | 15 ++++ Examples/javascript/namespace/Makefile | 21 +++++ Examples/javascript/namespace/binding.gyp | 8 ++ Examples/javascript/namespace/example.cxx | 36 ++++++++ Examples/javascript/namespace/example.h | 20 +++++ Examples/javascript/namespace/example.i | 10 +++ Examples/javascript/namespace/runme.js | 10 +++ Examples/javascript/operator/Makefile | 21 +++++ Examples/javascript/operator/binding.gyp | 8 ++ Examples/javascript/operator/example.h | 36 ++++++++ Examples/javascript/operator/example.i | 34 ++++++++ Examples/javascript/operator/runme.js | 25 ++++++ Examples/javascript/overload/Makefile | 21 +++++ Examples/javascript/overload/binding.gyp | 8 ++ Examples/javascript/overload/example.h | 28 +++++++ Examples/javascript/overload/example.i | 16 ++++ Examples/javascript/overload/runme.js | 9 ++ Examples/javascript/overload/swig_gdb.log | 0 Examples/javascript/pointer/Makefile | 21 +++++ Examples/javascript/pointer/binding.gyp | 8 ++ Examples/javascript/pointer/example.cxx | 16 ++++ Examples/javascript/pointer/example.i | 30 +++++++ Examples/javascript/pointer/runme.js | 35 ++++++++ Examples/javascript/pointer/typemaps.i | 0 Examples/javascript/reference/Makefile | 21 +++++ Examples/javascript/reference/binding.gyp | 8 ++ Examples/javascript/reference/example.cxx | 46 +++++++++++ Examples/javascript/reference/example.h | 26 ++++++ Examples/javascript/reference/example.i | 42 ++++++++++ Examples/javascript/reference/runme.js | 67 +++++++++++++++ Examples/javascript/reference/swig_gdb.log | 22 +++++ Examples/javascript/simple/Makefile | 21 +++++ Examples/javascript/simple/binding.gyp | 8 ++ Examples/javascript/simple/example.cxx | 18 ++++ Examples/javascript/simple/example.i | 7 ++ Examples/javascript/simple/runme.js | 26 ++++++ Examples/javascript/template/Makefile | 21 +++++ Examples/javascript/template/binding.gyp | 8 ++ Examples/javascript/template/example.h | 32 ++++++++ Examples/javascript/template/example.i | 17 ++++ Examples/javascript/template/runme.js | 30 +++++++ Examples/javascript/variables/Makefile | 21 +++++ Examples/javascript/variables/binding.gyp | 8 ++ Examples/javascript/variables/example.cxx | 96 ++++++++++++++++++++++ Examples/javascript/variables/example.h | 6 ++ Examples/javascript/variables/example.i | 49 +++++++++++ Examples/javascript/variables/runme.js | 68 +++++++++++++++ Examples/javascript/variables/swig_gdb.log | 9 ++ 76 files changed, 1685 insertions(+) create mode 100644 Examples/javascript/check.list create mode 100755 Examples/javascript/class/Makefile create mode 100644 Examples/javascript/class/binding.gyp create mode 100755 Examples/javascript/class/example.cxx create mode 100755 Examples/javascript/class/example.h create mode 100755 Examples/javascript/class/example.i create mode 100755 Examples/javascript/class/runme.js create mode 100755 Examples/javascript/constant/Makefile create mode 100644 Examples/javascript/constant/binding.gyp create mode 100644 Examples/javascript/constant/example.h create mode 100755 Examples/javascript/constant/example.i create mode 100755 Examples/javascript/constant/runme.js create mode 100755 Examples/javascript/enum/Makefile create mode 100644 Examples/javascript/enum/binding.gyp create mode 100755 Examples/javascript/enum/example.cxx create mode 100755 Examples/javascript/enum/example.h create mode 100755 Examples/javascript/enum/example.i create mode 100755 Examples/javascript/enum/runme.js create mode 100755 Examples/javascript/exception/Makefile create mode 100644 Examples/javascript/exception/binding.gyp create mode 100644 Examples/javascript/exception/example.cxx create mode 100644 Examples/javascript/exception/example.h create mode 100644 Examples/javascript/exception/example.i create mode 100644 Examples/javascript/exception/runme.js create mode 100755 Examples/javascript/functor/Makefile create mode 100644 Examples/javascript/functor/binding.gyp create mode 100644 Examples/javascript/functor/example.cxx create mode 100644 Examples/javascript/functor/example.i create mode 100644 Examples/javascript/functor/runme.js create mode 100755 Examples/javascript/namespace/Makefile create mode 100644 Examples/javascript/namespace/binding.gyp create mode 100644 Examples/javascript/namespace/example.cxx create mode 100644 Examples/javascript/namespace/example.h create mode 100644 Examples/javascript/namespace/example.i create mode 100644 Examples/javascript/namespace/runme.js create mode 100755 Examples/javascript/operator/Makefile create mode 100644 Examples/javascript/operator/binding.gyp create mode 100644 Examples/javascript/operator/example.h create mode 100644 Examples/javascript/operator/example.i create mode 100644 Examples/javascript/operator/runme.js create mode 100755 Examples/javascript/overload/Makefile create mode 100644 Examples/javascript/overload/binding.gyp create mode 100644 Examples/javascript/overload/example.h create mode 100644 Examples/javascript/overload/example.i create mode 100644 Examples/javascript/overload/runme.js create mode 100644 Examples/javascript/overload/swig_gdb.log create mode 100755 Examples/javascript/pointer/Makefile create mode 100644 Examples/javascript/pointer/binding.gyp create mode 100755 Examples/javascript/pointer/example.cxx create mode 100755 Examples/javascript/pointer/example.i create mode 100755 Examples/javascript/pointer/runme.js create mode 100644 Examples/javascript/pointer/typemaps.i create mode 100755 Examples/javascript/reference/Makefile create mode 100644 Examples/javascript/reference/binding.gyp create mode 100755 Examples/javascript/reference/example.cxx create mode 100755 Examples/javascript/reference/example.h create mode 100755 Examples/javascript/reference/example.i create mode 100755 Examples/javascript/reference/runme.js create mode 100644 Examples/javascript/reference/swig_gdb.log create mode 100755 Examples/javascript/simple/Makefile create mode 100644 Examples/javascript/simple/binding.gyp create mode 100644 Examples/javascript/simple/example.cxx create mode 100644 Examples/javascript/simple/example.i create mode 100755 Examples/javascript/simple/runme.js create mode 100755 Examples/javascript/template/Makefile create mode 100644 Examples/javascript/template/binding.gyp create mode 100644 Examples/javascript/template/example.h create mode 100644 Examples/javascript/template/example.i create mode 100644 Examples/javascript/template/runme.js create mode 100755 Examples/javascript/variables/Makefile create mode 100644 Examples/javascript/variables/binding.gyp create mode 100755 Examples/javascript/variables/example.cxx create mode 100755 Examples/javascript/variables/example.h create mode 100755 Examples/javascript/variables/example.i create mode 100755 Examples/javascript/variables/runme.js create mode 100644 Examples/javascript/variables/swig_gdb.log diff --git a/Examples/javascript/check.list b/Examples/javascript/check.list new file mode 100644 index 000000000..146f1800f --- /dev/null +++ b/Examples/javascript/check.list @@ -0,0 +1,13 @@ +class +constant +enum +exception +functor +namespace +operator +overload +pointer +reference +simple +template +variables diff --git a/Examples/javascript/class/Makefile b/Examples/javascript/class/Makefile new file mode 100755 index 000000000..99a9e9e86 --- /dev/null +++ b/Examples/javascript/class/Makefile @@ -0,0 +1,21 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +CXXSRCS = example.cxx +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i + +wrapper:: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: build + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/class/binding.gyp b/Examples/javascript/class/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/class/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/class/example.cxx b/Examples/javascript/class/example.cxx new file mode 100755 index 000000000..e23fa6f73 --- /dev/null +++ b/Examples/javascript/class/example.cxx @@ -0,0 +1,28 @@ +/* File : example.c */ +#include +#include "example.h" +#define M_PI 3.14159265358979323846 + +/* Move the shape to a new location */ +void Shape::move(double dx, double dy) { + x += dx; + y += dy; +} + +int Shape::nshapes = 0; + +double Circle::area(void) { + return M_PI*radius*radius; +} + +double Circle::perimeter(void) { + return 2*M_PI*radius; +} + +double Square::area(void) { + return width*width; +} + +double Square::perimeter(void) { + return 4*width; +} diff --git a/Examples/javascript/class/example.h b/Examples/javascript/class/example.h new file mode 100755 index 000000000..64b7684fa --- /dev/null +++ b/Examples/javascript/class/example.h @@ -0,0 +1,34 @@ +/* File : example.h */ + +class Shape { +public: + Shape() { + nshapes++; + } + virtual ~Shape() { + nshapes--; + }; + double x, y; + void move(double dx, double dy); + virtual double area(void) = 0; + virtual double perimeter(void) = 0; + static int nshapes; +}; + +class Circle : public Shape { +private: + double radius; +public: + Circle(double r) : radius(r) { }; + virtual double area(void); + virtual double perimeter(void); +}; + +class Square : public Shape { +private: + double width; +public: + Square(double w) : width(w) { }; + virtual double area(void); + virtual double perimeter(void); +}; diff --git a/Examples/javascript/class/example.i b/Examples/javascript/class/example.i new file mode 100755 index 000000000..75700b305 --- /dev/null +++ b/Examples/javascript/class/example.i @@ -0,0 +1,10 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +/* Let's just grab the original header file here */ +%include "example.h" + diff --git a/Examples/javascript/class/runme.js b/Examples/javascript/class/runme.js new file mode 100755 index 000000000..5bb62ecd4 --- /dev/null +++ b/Examples/javascript/class/runme.js @@ -0,0 +1,46 @@ +var example = require("./build/Release/example"); + +// ----- Object creation ----- + +console.log("Creating some objects:"); +c = new example.Circle(10); +console.log("Created circle " + c); +s = new example.Square(10); +console.log("Created square " + s); + +// ----- Access a static member ----- +console.log("\nA total of " + example.Shape.nshapes + " shapes were created"); // access static member as properties of the class object + +// ----- Member data access ----- +// Set the location of the object. +// Note: methods in the base class Shape are used since +// x and y are defined there. + +c.x = 20; +c.y = 30; +s.x = -10; +s.y = 5; + +console.log("\nHere is their new position:"); +console.log("Circle = (" + c.x + "," + c.y + ")"); +console.log("Square = (" + s.x + "," + s.y + ")"); + +// ----- Call some methods ----- +console.log("\nHere are some properties of the shapes:"); +console.log("Circle:"); +console.log("area = " + c.area() + ""); +console.log("perimeter = " + c.perimeter() + ""); +console.log("\n"); +console.log("Square:"); +console.log("area = " + s.area() + ""); +console.log("perimeter = " + s.perimeter() + ""); + +// ----- Delete everything ----- +console.log("\nGuess I'll clean up now"); +// Note: this invokes the virtual destructor +delete c; +delete s; + +console.log(example.Shape.nshapes + " shapes remain"); + +console.log("Goodbye"); diff --git a/Examples/javascript/constant/Makefile b/Examples/javascript/constant/Makefile new file mode 100755 index 000000000..99a9e9e86 --- /dev/null +++ b/Examples/javascript/constant/Makefile @@ -0,0 +1,21 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +CXXSRCS = example.cxx +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i + +wrapper:: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: build + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/constant/binding.gyp b/Examples/javascript/constant/binding.gyp new file mode 100644 index 000000000..69af46b22 --- /dev/null +++ b/Examples/javascript/constant/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/constant/example.h b/Examples/javascript/constant/example.h new file mode 100644 index 000000000..2c88ebd1e --- /dev/null +++ b/Examples/javascript/constant/example.h @@ -0,0 +1,8 @@ +#define ICONST 42 +#define FCONST 2.1828 +#define CCONST 'x' +#define CCONST2 '\n' +#define SCONST "Hello World" +#define SCONST2 "\"Hello World\"" +#define EXTERN extern +#define FOO (ICONST + BAR) diff --git a/Examples/javascript/constant/example.i b/Examples/javascript/constant/example.i new file mode 100755 index 000000000..a6d28e7c9 --- /dev/null +++ b/Examples/javascript/constant/example.i @@ -0,0 +1,24 @@ +/* File : example.i */ +%module example + +/* A few preprocessor macros */ + +#define ICONST 42 +#define FCONST 2.1828 +#define CCONST 'x' +#define CCONST2 '\n' +#define SCONST "Hello World" +#define SCONST2 "\"Hello World\"" + +/* This should work just fine */ +#define EXPR ICONST + 3*(FCONST) + +/* This shouldn't do anything */ +#define EXTERN extern + +/* Neither should this (BAR isn't defined) */ +#define FOO (ICONST + BAR) + +/* The following directives also produce constants */ +%constant int iconst = 37; +%constant double fconst = 3.14; diff --git a/Examples/javascript/constant/runme.js b/Examples/javascript/constant/runme.js new file mode 100755 index 000000000..b11c08c98 --- /dev/null +++ b/Examples/javascript/constant/runme.js @@ -0,0 +1,14 @@ +var example = require("./build/Release/example"); + +console.log("ICONST = " + example.ICONST + " (should be 42)\n"); +console.log("FCONST = " + example.FCONST + " (should be 2.1828)\n"); +console.log("CCONST = " + example.CCONST + " (should be 'x')\n"); +console.log("CCONST2 = " + example.CCONST2 + " (this should be on a new line)\n"); +console.log("SCONST = " + example.SCONST + " (should be 'Hello World')\n"); +console.log("SCONST2 = " + example.SCONST2 + " (should be '\"Hello World\"')\n"); +console.log("EXPR = " + example.EXPR + " (should be 48.5484)\n"); +console.log("iconst = " + example.iconst + " (should be 37)\n"); +console.log("fconst = " + example.fconst + " (should be 3.14)\n"); + +console.log("EXTERN = " + example.EXTERN + " (should be undefined)\n"); +console.log("FOO = " + example.FOO + " (should be undefined)\n"); diff --git a/Examples/javascript/enum/Makefile b/Examples/javascript/enum/Makefile new file mode 100755 index 000000000..99a9e9e86 --- /dev/null +++ b/Examples/javascript/enum/Makefile @@ -0,0 +1,21 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +CXXSRCS = example.cxx +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i + +wrapper:: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: build + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/enum/binding.gyp b/Examples/javascript/enum/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/enum/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/enum/example.cxx b/Examples/javascript/enum/example.cxx new file mode 100755 index 000000000..6785e57ac --- /dev/null +++ b/Examples/javascript/enum/example.cxx @@ -0,0 +1,37 @@ +/* File : example.c */ + +#include "example.h" +#include + +void Foo::enum_test(speed s) { + if (s == IMPULSE) { + printf("IMPULSE speed\n"); + } else if (s == WARP) { + printf("WARP speed\n"); + } else if (s == LUDICROUS) { + printf("LUDICROUS speed\n"); + } else { + printf("Unknown speed\n"); + } +} + +void enum_test(color c, Foo::speed s) { + if (c == RED) { + printf("color = RED, "); + } else if (c == BLUE) { + printf("color = BLUE, "); + } else if (c == GREEN) { + printf("color = GREEN, "); + } else { + printf("color = Unknown color!, "); + } + if (s == Foo::IMPULSE) { + printf("speed = IMPULSE speed\n"); + } else if (s == Foo::WARP) { + printf("speed = WARP speed\n"); + } else if (s == Foo::LUDICROUS) { + printf("speed = LUDICROUS speed\n"); + } else { + printf("speed = Unknown speed!\n"); + } +} diff --git a/Examples/javascript/enum/example.h b/Examples/javascript/enum/example.h new file mode 100755 index 000000000..9119cd9fc --- /dev/null +++ b/Examples/javascript/enum/example.h @@ -0,0 +1,13 @@ +/* File : example.h */ + +enum color { RED, BLUE, GREEN }; + +class Foo { + public: + Foo() { } + enum speed { IMPULSE=10, WARP=20, LUDICROUS=30 }; + void enum_test(speed s); +}; + +void enum_test(color c, Foo::speed s); + diff --git a/Examples/javascript/enum/example.i b/Examples/javascript/enum/example.i new file mode 100755 index 000000000..23ee8a822 --- /dev/null +++ b/Examples/javascript/enum/example.i @@ -0,0 +1,11 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +/* Let's just grab the original header file here */ + +%include "example.h" + diff --git a/Examples/javascript/enum/runme.js b/Examples/javascript/enum/runme.js new file mode 100755 index 000000000..9d3accd1d --- /dev/null +++ b/Examples/javascript/enum/runme.js @@ -0,0 +1,34 @@ +var example = require("./build/Release/example"); + +// ----- Object creation ----- + +// Print out the value of some enums +console.log("*** color ***"); +console.log(" RED =" + example.RED); +console.log(" BLUE =" + example.BLUE); +console.log(" GREEN =" + example.GREEN); + +console.log("\n*** Foo::speed ***"); +console.log(" Foo_IMPULSE =" + example.Foo.IMPULSE); +console.log(" Foo_WARP =" + example.Foo.WARP); +console.log(" Foo_LUDICROUS =" + example.Foo.LUDICROUS); + +console.log("\nTesting use of enums with functions\n"); + +example.enum_test(example.RED, example.Foo.IMPULSE); +example.enum_test(example.BLUE, example.Foo.WARP); +example.enum_test(example.GREEN, example.Foo.LUDICROUS); +example.enum_test(1234,5678); + +console.log("\nTesting use of enum with class method"); +f = new example.Foo(); + +f.enum_test(example.Foo.IMPULSE); +f.enum_test(example.Foo.WARP); +f.enum_test(example.Foo.LUDICROUS); + +// enum value BLUE of enum color is accessed as property of cconst +console.log("example.BLUE= " + example.BLUE); + +// enum value LUDICROUS of enum Foo::speed is accessed as as property of cconst +console.log("example.speed.LUDICROUS= " + example.Foo.LUDICROUS); diff --git a/Examples/javascript/exception/Makefile b/Examples/javascript/exception/Makefile new file mode 100755 index 000000000..99a9e9e86 --- /dev/null +++ b/Examples/javascript/exception/Makefile @@ -0,0 +1,21 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +CXXSRCS = example.cxx +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i + +wrapper:: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: build + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/exception/binding.gyp b/Examples/javascript/exception/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/exception/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/exception/example.cxx b/Examples/javascript/exception/example.cxx new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/Examples/javascript/exception/example.cxx @@ -0,0 +1 @@ + diff --git a/Examples/javascript/exception/example.h b/Examples/javascript/exception/example.h new file mode 100644 index 000000000..7cf917d01 --- /dev/null +++ b/Examples/javascript/exception/example.h @@ -0,0 +1,53 @@ +/* File : example.h */ + +#include +#ifndef SWIG +struct A { +}; +#endif + +class Exc { +public: + Exc(int c, const char *m) { + code = c; + strncpy(msg,m,256); + } + int code; + char msg[256]; +}; + +#if defined(_MSC_VER) + #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow) +#endif + +class Test { +public: + int simple() throw(int) { + throw(37); + return 1; + } + int message() throw(const char *) { + throw("I died."); + return 1; + } + int hosed() throw(Exc) { + throw(Exc(42,"Hosed")); + return 1; + } + int unknown() throw(A*) { + static A a; + throw &a; + return 1; + } + int multi(int x) throw(int, const char *, Exc) { + if (x == 1) throw(37); + if (x == 2) throw("Bleah!"); + if (x == 3) throw(Exc(42,"No-go-diggy-die")); + return 1; + } +}; + +#if defined(_MSC_VER) + #pragma warning(default: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow) +#endif + diff --git a/Examples/javascript/exception/example.i b/Examples/javascript/exception/example.i new file mode 100644 index 000000000..08672c3a8 --- /dev/null +++ b/Examples/javascript/exception/example.i @@ -0,0 +1,12 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +%include "std_string.i" + +/* Let's just grab the original header file here */ +%include "example.h" + diff --git a/Examples/javascript/exception/runme.js b/Examples/javascript/exception/runme.js new file mode 100644 index 000000000..f7041f028 --- /dev/null +++ b/Examples/javascript/exception/runme.js @@ -0,0 +1,64 @@ +var example = require("./build/Release/example"); + +console.log("Trying to catch some exceptions."); +t = new example.Test(); +try{ + t.unknown(); + throw -1; +} catch(error) +{ + if(error == -1) { + console.log("t.unknown() didn't throw"); + } else { + console.log("successfully catched throw in Test::unknown()."); + } +} + +try{ + t.simple(); + throw -1; +} +catch(error){ + if(error == -1) { + console.log("t.simple() did not throw"); + } else { + console.log("successfully catched throw in Test::simple()."); + } +} + +try{ + t.message(); + throw -1; +} catch(error){ + if(error == -1) { + console.log("t.message() did not throw"); + } else { + console.log("successfully catched throw in Test::message()."); + } +} + +try{ + t.hosed(); + throw -1; +} +catch(error){ + if(error == -1) { + console.log("t.hosed() did not throw"); + } else { + console.log("successfully catched throw in Test::hosed()."); + } +} + +for (var i=1; i<4; i++) { + try{ + t.multi(i); + throw -1; + } + catch(error){ + if(error == -1) { + console.log("t.multi(" + i + ") did not throw"); + } else { + console.log("successfully catched throw in Test::multi()."); + } + } +} diff --git a/Examples/javascript/functor/Makefile b/Examples/javascript/functor/Makefile new file mode 100755 index 000000000..99a9e9e86 --- /dev/null +++ b/Examples/javascript/functor/Makefile @@ -0,0 +1,21 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +CXXSRCS = example.cxx +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i + +wrapper:: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: build + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/functor/binding.gyp b/Examples/javascript/functor/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/functor/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/functor/example.cxx b/Examples/javascript/functor/example.cxx new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/javascript/functor/example.i b/Examples/javascript/functor/example.i new file mode 100644 index 000000000..0450c2124 --- /dev/null +++ b/Examples/javascript/functor/example.i @@ -0,0 +1,25 @@ +/* File : example.i */ +%module example + + +%inline %{ +// From B. Strousjoup, "The C++ Programming Language, Third Edition", p. 514 +template class Sum { + T res; +public: + Sum(T i = 0) : res(i) { } + void operator() (T x) { res += x; } + T result() const { return res; } +}; + +%} + +%rename(call) *::operator(); // the fn call operator + +// Instantiate a few versions +%template(intSum) Sum; +%template(doubleSum) Sum; + + + + diff --git a/Examples/javascript/functor/runme.js b/Examples/javascript/functor/runme.js new file mode 100644 index 000000000..f7be78286 --- /dev/null +++ b/Examples/javascript/functor/runme.js @@ -0,0 +1,15 @@ +var example = require("./build/Release/example"); + +a = new example.intSum(0); +b = new example.doubleSum(100.0); + +// Use the objects. They should be callable just like a normal +// javascript function. + +for (i=1;i<=100;i++) + a.call(i); // Note: function call + b.call(Math.sqrt(i)); // Note: function call + +console.log(a.result()); +console.log(b.result()); + diff --git a/Examples/javascript/namespace/Makefile b/Examples/javascript/namespace/Makefile new file mode 100755 index 000000000..99a9e9e86 --- /dev/null +++ b/Examples/javascript/namespace/Makefile @@ -0,0 +1,21 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +CXXSRCS = example.cxx +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i + +wrapper:: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: build + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/namespace/binding.gyp b/Examples/javascript/namespace/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/namespace/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/namespace/example.cxx b/Examples/javascript/namespace/example.cxx new file mode 100644 index 000000000..5beeb09fe --- /dev/null +++ b/Examples/javascript/namespace/example.cxx @@ -0,0 +1,36 @@ +/* File : example.c */ + +#include +#include "example.h" + +#define M_PI 3.14159 + + +/* A global variable */ +namespace nspace +{ +double Foo = 3.0; + +/* Compute the greatest common divisor of positive integers */ +int gcd(int x, int y) { + int g; + g = y; + while (x > 0) { + g = x; + x = y % x; + y = g; + } + return g; +} + +Circle::Circle(): radius(1.0) {} + +Circle::Circle(double r): radius(r) { + std::cout << "created Circle with r=" << radius << std::endl; +} + +double Circle::area() { + std::cout << "Circle::area called, r=" << radius << std::endl; + return M_PI*radius*radius; +} +} diff --git a/Examples/javascript/namespace/example.h b/Examples/javascript/namespace/example.h new file mode 100644 index 000000000..7f76c2f07 --- /dev/null +++ b/Examples/javascript/namespace/example.h @@ -0,0 +1,20 @@ + +namespace nspace { + +extern int gcd(int x, int y); +extern double Foo; + +class Circle +{ +public: + Circle(); + + Circle(double r); + + double area(); + + double radius; + +}; + +} diff --git a/Examples/javascript/namespace/example.i b/Examples/javascript/namespace/example.i new file mode 100644 index 000000000..e14b10b44 --- /dev/null +++ b/Examples/javascript/namespace/example.i @@ -0,0 +1,10 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +%feature("nspace", 1); + +%include "example.h" diff --git a/Examples/javascript/namespace/runme.js b/Examples/javascript/namespace/runme.js new file mode 100644 index 000000000..9a9d6744d --- /dev/null +++ b/Examples/javascript/namespace/runme.js @@ -0,0 +1,10 @@ +var example = require("./build/Release/example"); + +console.log("Global variable Foo=" + example.nspace.Foo); +example.nspace.Foo = 5; +console.log("Variable Foo changed to " + example.nspace.Foo); +console.log("GCD of number 6,18 is " + example.nspace.gcd(6,18)); + +console.log("Creating some objects:"); +c = new example.nspace.Circle(10); +console.log("area = " + c.area()); diff --git a/Examples/javascript/operator/Makefile b/Examples/javascript/operator/Makefile new file mode 100755 index 000000000..99a9e9e86 --- /dev/null +++ b/Examples/javascript/operator/Makefile @@ -0,0 +1,21 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +CXXSRCS = example.cxx +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i + +wrapper:: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: build + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/operator/binding.gyp b/Examples/javascript/operator/binding.gyp new file mode 100644 index 000000000..69af46b22 --- /dev/null +++ b/Examples/javascript/operator/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/operator/example.h b/Examples/javascript/operator/example.h new file mode 100644 index 000000000..4da6a2307 --- /dev/null +++ b/Examples/javascript/operator/example.h @@ -0,0 +1,36 @@ +/* File : example.h */ +#include + +class Complex { +private: + double rpart, ipart; +public: + Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { } + Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { } + Complex &operator=(const Complex &c) { + rpart = c.rpart; + ipart = c.ipart; + return *this; + } + Complex operator+(const Complex &c) const { + return Complex(rpart+c.rpart, ipart+c.ipart); + } + Complex operator-(const Complex &c) const { + return Complex(rpart-c.rpart, ipart-c.ipart); + } + Complex operator*(const Complex &c) const { + return Complex(rpart*c.rpart - ipart*c.ipart, + rpart*c.ipart + c.rpart*ipart); + } + Complex operator-() const { + return Complex(-rpart, -ipart); + } + + double re() const { return rpart; } + double im() const { return ipart; } +}; + + + + + diff --git a/Examples/javascript/operator/example.i b/Examples/javascript/operator/example.i new file mode 100644 index 000000000..7a1bd45e1 --- /dev/null +++ b/Examples/javascript/operator/example.i @@ -0,0 +1,34 @@ +/* File : example.i */ +%module example +#pragma SWIG nowarn=SWIGWARN_IGNORE_OPERATOR_EQ +%{ +#include "example.h" +%} + +/* This header file is a little tough to handle because it has overloaded + operators and constructors. We're going to try and deal with that here */ + +/* This turns the copy constructor in a function ComplexCopy() that can + be called */ + +%rename(assign) Complex::operator=; +%rename(plus) Complex::operator+; +%rename(minus) Complex::operator-(const Complex &) const; +%rename(uminus) Complex::operator-() const; +%rename(times) Complex::operator*; + +/* Now grab the original header file */ +%include "example.h" + +/* An output method that turns a complex into a short string */ +%extend Complex { + char *toString() { + static char temp[512]; + sprintf(temp,"(%g,%g)", $self->re(), $self->im()); + return temp; + } + static Complex* copy(const Complex& c) { + return new Complex(c); + } +}; + diff --git a/Examples/javascript/operator/runme.js b/Examples/javascript/operator/runme.js new file mode 100644 index 000000000..9dba4b7f9 --- /dev/null +++ b/Examples/javascript/operator/runme.js @@ -0,0 +1,25 @@ +var example = require("./build/Release/example"); + +a = new example.Complex(2,3); +b = new example.Complex(-5,10); + +console.log ("a =" + a); +console.log ("b =" + b); + +c = a.plus(b); + +console.log("c =" + c); +console.log("a*b =" + a.times(b)); +console.log("a-c =" + a.minus(c)); + +e = example.Complex.copy(a.minus(c)); +console.log("e =" + e); + +// Big expression +f = a.plus(b).times(c.plus(b.times(e))).plus(a.uminus()); +console.log("f =" + f); + + + + + diff --git a/Examples/javascript/overload/Makefile b/Examples/javascript/overload/Makefile new file mode 100755 index 000000000..99a9e9e86 --- /dev/null +++ b/Examples/javascript/overload/Makefile @@ -0,0 +1,21 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +CXXSRCS = example.cxx +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i + +wrapper:: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: build + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/overload/binding.gyp b/Examples/javascript/overload/binding.gyp new file mode 100644 index 000000000..69af46b22 --- /dev/null +++ b/Examples/javascript/overload/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/overload/example.h b/Examples/javascript/overload/example.h new file mode 100644 index 000000000..2f112f1e1 --- /dev/null +++ b/Examples/javascript/overload/example.h @@ -0,0 +1,28 @@ +#include + +void f() { + std::cout << "Called f()." << std::endl; +} + +void f(int val) { + std::cout << "Called f(int)." << std::endl; +} +void f(int val1, int val2) { + std::cout << "Called f(int, int)." << std::endl; +} + +void f(const char* s) { + std::cout << "Called f(const char*)." << std::endl; +} + +void f(bool val) { + std::cout << "Called f(bool)." << std::endl; +} + +void f(long val) { + std::cout << "Called f(long)." << std::endl; +} + +void f(double val) { + std::cout << "Called f(double)." << std::endl; +} diff --git a/Examples/javascript/overload/example.i b/Examples/javascript/overload/example.i new file mode 100644 index 000000000..b86689f8a --- /dev/null +++ b/Examples/javascript/overload/example.i @@ -0,0 +1,16 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +/* + Note: overloading is implemented in a sloppy way currently + i.e., only the number of arguments is taken into conideration + for dispatching. + To solve the problem one has to rename such conflicting methods. +*/ +%rename(f_double) f(double val); + +%include "example.h" diff --git a/Examples/javascript/overload/runme.js b/Examples/javascript/overload/runme.js new file mode 100644 index 000000000..5ff5d01be --- /dev/null +++ b/Examples/javascript/overload/runme.js @@ -0,0 +1,9 @@ +var example = require("./build/Release/example"); + +example.f(); +example.f(1); +example.f(1, 2); +example.f("bla"); +example.f(false); +example.f(11111111111); +example.f_double(1.0); diff --git a/Examples/javascript/overload/swig_gdb.log b/Examples/javascript/overload/swig_gdb.log new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/javascript/pointer/Makefile b/Examples/javascript/pointer/Makefile new file mode 100755 index 000000000..99a9e9e86 --- /dev/null +++ b/Examples/javascript/pointer/Makefile @@ -0,0 +1,21 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +CXXSRCS = example.cxx +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i + +wrapper:: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: build + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/pointer/binding.gyp b/Examples/javascript/pointer/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/pointer/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/pointer/example.cxx b/Examples/javascript/pointer/example.cxx new file mode 100755 index 000000000..8762329fe --- /dev/null +++ b/Examples/javascript/pointer/example.cxx @@ -0,0 +1,16 @@ +/* File : example.c */ + +void add(int *x, int *y, int *result) { + *result = *x + *y; +} + +void subtract(int *x, int *y, int *result) { + *result = *x - *y; +} + +int divide(int n, int d, int *r) { + int q; + q = n/d; + *r = n - q*d; + return q; +} diff --git a/Examples/javascript/pointer/example.i b/Examples/javascript/pointer/example.i new file mode 100755 index 000000000..38c67d7d2 --- /dev/null +++ b/Examples/javascript/pointer/example.i @@ -0,0 +1,30 @@ +/* File : example.i */ +%module example + +%{ +extern void add(int *, int *, int *); +extern void subtract(int *, int *, int *); +extern int divide(int, int, int *); +%} + +/* This example illustrates a couple of different techniques + for manipulating C pointers */ + +/* First we'll use the pointer library */ +extern void add(int *x, int *y, int *result); +%include cpointer.i +%pointer_functions(int, intp); + +/* Next we'll use some typemaps */ + +%include typemaps.i +extern void subtract(int *INPUT, int *INPUT, int *OUTPUT); + +/* Next we'll use typemaps and the %apply directive */ + +%apply int *OUTPUT { int *r }; +extern int divide(int n, int d, int *r); + + + + diff --git a/Examples/javascript/pointer/runme.js b/Examples/javascript/pointer/runme.js new file mode 100755 index 000000000..00778dfbc --- /dev/null +++ b/Examples/javascript/pointer/runme.js @@ -0,0 +1,35 @@ +var example = require("./build/Release/example"); + +// First create some objects using the pointer library. +console.log("Testing the pointer library\n"); +a = example.new_intp(); +b = example.new_intp(); +c = example.new_intp(); + +example.intp_assign(a,37); +example.intp_assign(b,42); + +console.log(" a = " + example.intp_value(a) + "\n"); +console.log(" b = " + example.intp_value(b) + "\n"); +console.log(" c = " + example.intp_value(c) + "\n"); + +//// Call the add() function with some pointers +example.add(a, b, c); + +// +//// Now get the result +r = example.intp_value(c); +console.log(" 37 + 42 = " + r + "\n"); + +// Clean up the pointers +example.delete_intp(a); +example.delete_intp(b); +example.delete_intp(c); + +//// Now try the typemap library +//// This should be much easier. Now how it is no longer +//// necessary to manufacture pointers. +//"OUTPUT" Mapping is not supported +//console.log("Trying the typemap library"); +//r = example.subtract(37,42); +//console.log("37 - 42 =" + r); diff --git a/Examples/javascript/pointer/typemaps.i b/Examples/javascript/pointer/typemaps.i new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/javascript/reference/Makefile b/Examples/javascript/reference/Makefile new file mode 100755 index 000000000..99a9e9e86 --- /dev/null +++ b/Examples/javascript/reference/Makefile @@ -0,0 +1,21 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +CXXSRCS = example.cxx +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i + +wrapper:: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: build + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/reference/binding.gyp b/Examples/javascript/reference/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/reference/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/reference/example.cxx b/Examples/javascript/reference/example.cxx new file mode 100755 index 000000000..8a513bf49 --- /dev/null +++ b/Examples/javascript/reference/example.cxx @@ -0,0 +1,46 @@ +/* File : example.cxx */ + +/* Deal with Microsoft's attempt at deprecating C standard runtime functions */ +#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +# define _CRT_SECURE_NO_DEPRECATE +#endif + +#include "example.h" +#include +#include + +Vector operator+(const Vector &a, const Vector &b) { + Vector r; + r.x = a.x + b.x; + r.y = a.y + b.y; + r.z = a.z + b.z; + return r; +} + +char *Vector::print() { + static char temp[512]; + sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z); + return temp; +} + +VectorArray::VectorArray(int size) { + items = new Vector[size]; + maxsize = size; +} + +VectorArray::~VectorArray() { + delete [] items; +} + +Vector &VectorArray::operator[](int index) { + if ((index < 0) || (index >= maxsize)) { + printf("Panic! Array index out of bounds.\n"); + exit(1); + } + return items[index]; +} + +int VectorArray::size() { + return maxsize; +} + diff --git a/Examples/javascript/reference/example.h b/Examples/javascript/reference/example.h new file mode 100755 index 000000000..4915adb1b --- /dev/null +++ b/Examples/javascript/reference/example.h @@ -0,0 +1,26 @@ +/* File : example.h */ + +class Vector { +private: + double x,y,z; +public: + Vector() : x(0), y(0), z(0) { }; + Vector(double x, double y, double z) : x(x), y(y), z(z) { }; + friend Vector operator+(const Vector &a, const Vector &b); + char *print(); +}; + +class VectorArray { +private: + Vector *items; + int maxsize; +public: + VectorArray(int maxsize); + ~VectorArray(); + Vector &operator[](int); + int size(); +}; + + + + diff --git a/Examples/javascript/reference/example.i b/Examples/javascript/reference/example.i new file mode 100755 index 000000000..1cf19c82c --- /dev/null +++ b/Examples/javascript/reference/example.i @@ -0,0 +1,42 @@ +/* File : example.i */ + +/* This file has a few "typical" uses of C++ references. */ + +%module example + +%{ +#include "example.h" +%} + +class Vector { +public: + Vector(double x, double y, double z); + ~Vector(); + char *print(); +}; + +/* This helper function calls an overloaded operator */ +%inline %{ +Vector addv(Vector &a, Vector &b) { + return a+b; +} +%} + +/* Wrapper around an array of vectors class */ + +class VectorArray { +public: + VectorArray(int maxsize); + ~VectorArray(); + int size(); + + /* This wrapper provides an alternative to the [] operator */ + %extend { + Vector &get(int index) { + return (*$self)[index]; + } + void set(int index, Vector &a) { + (*$self)[index] = a; + } + } +}; diff --git a/Examples/javascript/reference/runme.js b/Examples/javascript/reference/runme.js new file mode 100755 index 000000000..ee5737076 --- /dev/null +++ b/Examples/javascript/reference/runme.js @@ -0,0 +1,67 @@ +// This file illustrates the manipulation of C++ references in Javascript. +var example = require("./build/Release/example"); + +// ----- Object creation ----- + +console.log("Creating some objects:\n"); +a = new example.Vector(3,4,5); +b = new example.Vector(10,11,12); + +console.log(" created" + a.print()); +console.log(" created" + b.print()); + +// ----- Call an overloaded operator ----- + +// This calls the wrapper we placed around operator+(const Vector &a, const Vector &) +// It returns a new allocated object. + +console.log("Adding a+b\n"); +c = example.addv(a, b); +console.log("a+b = " + c.print()); + + +// TODO: Note: Unless we free the result, a memory leak will occur +//delete_Vector(c); + +// ----- Create a vector array ----- + +// Note: Using the high-level interface here +console.log("Creating an array of vectors\n"); +va = new example.VectorArray(10); +console.log("va = " + va + "\n"); + +// ----- Set some values in the array ----- + +// These operators copy the value of a and b to the vector array +va.set(0,a); +va.set(1,b); + +// This will work, but it will cause a memory leak! +va.set(2,example.addv(a,b)); + +// The non-leaky way to do it +//c = addv(a,b); +//va.set(3,c); +//delete_Vector(c); + +// Get some values from the array + +console.log("Getting some array values\n"); +for (i = 0; i < 5; i++) { + temp = va.get(i); + console.log(i,temp.print()); +} + +// Watch under resource meter to check on this +console.log("Making sure we don't leak memory.\n"); +for (i = 0; i < 1000000; i++) { + c = va.get(i % 10); +} +//---------TODO--------- +//----- Clean up ----- +//console.log("Cleaning up\n"); + +//example.delete_VectorArray(va); +//example.delete_Vector(a); +//example.delete_Vector(b); + diff --git a/Examples/javascript/reference/swig_gdb.log b/Examples/javascript/reference/swig_gdb.log new file mode 100644 index 000000000..57bca0306 --- /dev/null +++ b/Examples/javascript/reference/swig_gdb.log @@ -0,0 +1,22 @@ +Loaded swig printers +SwigStringPrinter: Could not convert const char* to string +SwigListIterator: Construction failed. + Cannot access memory at address 0x7d894828ec834853. +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigListIterator: Construction failed. + Cannot access memory at address 0x7d894828ec834853. +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not dereference struct String* +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not dereference struct String* +SwigStringPrinter: Could not dereference struct String* +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not dereference struct String* +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not dereference struct String* +SwigStringPrinter: Could not dereference struct String* diff --git a/Examples/javascript/simple/Makefile b/Examples/javascript/simple/Makefile new file mode 100755 index 000000000..99a9e9e86 --- /dev/null +++ b/Examples/javascript/simple/Makefile @@ -0,0 +1,21 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +CXXSRCS = example.cxx +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i + +wrapper:: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: build + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/simple/binding.gyp b/Examples/javascript/simple/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/simple/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/simple/example.cxx b/Examples/javascript/simple/example.cxx new file mode 100644 index 000000000..1c2af789c --- /dev/null +++ b/Examples/javascript/simple/example.cxx @@ -0,0 +1,18 @@ +/* File : example.c */ + +/* A global variable */ +double Foo = 3.0; + +/* Compute the greatest common divisor of positive integers */ +int gcd(int x, int y) { + int g; + g = y; + while (x > 0) { + g = x; + x = y % x; + y = g; + } + return g; +} + + diff --git a/Examples/javascript/simple/example.i b/Examples/javascript/simple/example.i new file mode 100644 index 000000000..24093b9bf --- /dev/null +++ b/Examples/javascript/simple/example.i @@ -0,0 +1,7 @@ +/* File : example.i */ +%module example + +%inline %{ +extern int gcd(int x, int y); +extern double Foo; +%} diff --git a/Examples/javascript/simple/runme.js b/Examples/javascript/simple/runme.js new file mode 100755 index 000000000..d970dcb7c --- /dev/null +++ b/Examples/javascript/simple/runme.js @@ -0,0 +1,26 @@ +var example = require("./build/Release/example"); + +/* Call our gcd() function */ + +x = 42; +y = 105; +g = example.gcd(x,y); +console.log("GCD of x and y is=" + g); + +/* Manipulate the Foo global variable */ + +/* Output its current value */ +console.log("Global variable Foo=" + example.Foo); + +/* Change its value */ +example.Foo = 3.1415926; + +/* See if the change took effect */ +console.log("Variable Foo changed to=" + example.Foo); + + + + + + + diff --git a/Examples/javascript/template/Makefile b/Examples/javascript/template/Makefile new file mode 100755 index 000000000..99a9e9e86 --- /dev/null +++ b/Examples/javascript/template/Makefile @@ -0,0 +1,21 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +CXXSRCS = example.cxx +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i + +wrapper:: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: build + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/template/binding.gyp b/Examples/javascript/template/binding.gyp new file mode 100644 index 000000000..69af46b22 --- /dev/null +++ b/Examples/javascript/template/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/template/example.h b/Examples/javascript/template/example.h new file mode 100644 index 000000000..7401df650 --- /dev/null +++ b/Examples/javascript/template/example.h @@ -0,0 +1,32 @@ +/* File : example.h */ + +// Some template definitions + +template T max(T a, T b) { return a>b ? a : b; } + +template class vector { + T *v; + int sz; + public: + vector(int _sz) { + v = new T[_sz]; + sz = _sz; + } + T &get(int index) { + return v[index]; + } + void set(int index, T &val) { + v[index] = val; + } +#ifdef SWIG + %extend { + T getitem(int index) { + return $self->get(index); + } + void setitem(int index, T val) { + $self->set(index,val); + } + } +#endif +}; + diff --git a/Examples/javascript/template/example.i b/Examples/javascript/template/example.i new file mode 100644 index 000000000..8f94c4da1 --- /dev/null +++ b/Examples/javascript/template/example.i @@ -0,0 +1,17 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +/* Let's just grab the original header file here */ +%include "example.h" + +/* Now instantiate some specific template declarations */ + +%template(maxint) max; +%template(maxdouble) max; +%template(vecint) vector; +%template(vecdouble) vector; + diff --git a/Examples/javascript/template/runme.js b/Examples/javascript/template/runme.js new file mode 100644 index 000000000..551475c72 --- /dev/null +++ b/Examples/javascript/template/runme.js @@ -0,0 +1,30 @@ +var example = require("./build/Release/example"); + +//Call some templated functions +console.log(example.maxint(3,7)); +console.log(example.maxdouble(3.14,2.18)); + +// Create some class + +iv = new example.vecint(100); +dv = new example.vecdouble(1000); + +for(i=0;i<=100;i++) + iv.setitem(i,2*i); + +for(i=0;i<=1000;i++) + dv.setitem(i, 1.0/(i+1)); + +sum = 0; +for(i=0;i<=100;i++) + sum = sum + iv.getitem(i); + +console.log(sum); + +sum = 0.0; +for(i=0;i<=1000;i++) + sum = sum + dv.getitem(i); +console.log(sum); + +delete iv; +delete dv; diff --git a/Examples/javascript/variables/Makefile b/Examples/javascript/variables/Makefile new file mode 100755 index 000000000..99a9e9e86 --- /dev/null +++ b/Examples/javascript/variables/Makefile @@ -0,0 +1,21 @@ +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +CXXSRCS = example.cxx +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i + +wrapper:: + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +build:: wrapper + $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build + +clean:: + $(MAKE) -f $(TOP)/Makefile javascript_clean + +check:: build + $(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \ + TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run diff --git a/Examples/javascript/variables/binding.gyp b/Examples/javascript/variables/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/variables/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/variables/example.cxx b/Examples/javascript/variables/example.cxx new file mode 100755 index 000000000..3ad4c2323 --- /dev/null +++ b/Examples/javascript/variables/example.cxx @@ -0,0 +1,96 @@ +/* File : example.c */ + +/* I'm a file containing some C global variables */ + +/* Deal with Microsoft's attempt at deprecating C standard runtime functions */ +#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +# define _CRT_SECURE_NO_DEPRECATE +#endif + +#include +#include +#include "example.h" + +int ivar = 0; +short svar = 0; +long lvar = 0; +unsigned int uivar = 0; +unsigned short usvar = 0; +unsigned long ulvar = 0; +signed char scvar = 0; +unsigned char ucvar = 0; +char cvar = 0; +float fvar = 0; +double dvar = 0; +char *strvar = 0; +#ifdef __cplusplus // Note: for v8 this must be linkable with g++, without extern cstrvar is mangled +extern const char cstrvar[] = "Goodbye"; +#else +const char cstrvar[] = "Goodbye"; +#endif +const +int *iptrvar = 0; +char name[256] = "Dave"; +char path[256] = "/home/beazley"; + + +/* Global variables involving a structure */ +Point *ptptr = 0; +Point pt = { 10, 20 }; + +/* A variable that we will make read-only in the interface */ +int status = 1; + +/* A debugging function to print out their values */ + +void print_vars() { + printf("ivar = %d\n", ivar); + printf("svar = %d\n", svar); + printf("lvar = %ld\n", lvar); + printf("uivar = %u\n", uivar); + printf("usvar = %u\n", usvar); + printf("ulvar = %lu\n", ulvar); + printf("scvar = %d\n", scvar); + printf("ucvar = %u\n", ucvar); + printf("fvar = %g\n", fvar); + 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("iptrvar = %p\n", iptrvar); + printf("name = %s\n", name); + printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); + printf("pt = (%d, %d)\n", pt.x, pt.y); + printf("status = %d\n", status); +} + +/* A function to create an integer (to test iptrvar) */ + +int *new_int(int value) { + int *ip = (int *) malloc(sizeof(int)); + *ip = value; + return ip; +} + +/* A function to create a point */ + +Point *new_Point(int x, int y) { + Point *p = (Point *) malloc(sizeof(Point)); + p->x = x; + p->y = y; + return p; +} + +char * Point_print(Point *p) { + static char buffer[256]; + if (p) { + sprintf(buffer,"(%d,%d)", p->x,p->y); + } else { + sprintf(buffer,"null"); + } + return buffer; +} + +void pt_print() { + printf("(%d, %d)\n", pt.x, pt.y); +} diff --git a/Examples/javascript/variables/example.h b/Examples/javascript/variables/example.h new file mode 100755 index 000000000..0f7e89594 --- /dev/null +++ b/Examples/javascript/variables/example.h @@ -0,0 +1,6 @@ +/* File: example.h */ + +typedef struct { + int x,y; +} Point; + diff --git a/Examples/javascript/variables/example.i b/Examples/javascript/variables/example.i new file mode 100755 index 000000000..591b871ed --- /dev/null +++ b/Examples/javascript/variables/example.i @@ -0,0 +1,49 @@ +/* File : example.i */ +%module example +%{ +#include "example.h" +%} + +/* Some global variable declarations */ +%inline %{ +extern int ivar; +extern short svar; +extern long lvar; +extern unsigned int uivar; +extern unsigned short usvar; +extern unsigned long ulvar; +extern signed char scvar; +extern unsigned char ucvar; +extern char cvar; +extern float fvar; +extern double dvar; +extern char *strvar; +extern const char cstrvar[]; +extern int *iptrvar; +extern char name[256]; + +extern Point *ptptr; +extern Point pt; +%} + + +/* Some read-only variables */ + +%immutable; + +%inline %{ +extern int status; +extern char path[256]; +%} + +%mutable; + +/* Some helper functions to make it easier to test */ +%inline %{ +extern void print_vars(); +extern int *new_int(int value); +extern Point *new_Point(int x, int y); +extern char *Point_print(Point *p); +extern void pt_print(); +%} + diff --git a/Examples/javascript/variables/runme.js b/Examples/javascript/variables/runme.js new file mode 100755 index 000000000..22d208480 --- /dev/null +++ b/Examples/javascript/variables/runme.js @@ -0,0 +1,68 @@ +var example = require("./build/Release/example"); + +// Try to set the values of some global variables +example.ivar = 42; +example.svar = -31000; +example.lvar = 65537; +example.uivar = 123456; +example.usvar = 61000; +example.ulvar = 654321; +example.scvar = -13; +example.ucvar = 251; +example.cvar = "S"; +example.fvar = 3.14159; +example.dvar = 2.1828; +example.strvar = "Hello World"; +example.iptrvar= example.new_int(37); +example.ptptr = example.new_Point(37,42); +example.name = "Bill"; + +// Now console.log out the values of the variables +console.log("Variables (values console.loged from Python)" + "\n"); +console.log("ivar = " + example.ivar + "\n"); +console.log("svar = " + example.svar + "\n"); +console.log("lvar = " + example.lvar + "\n"); +console.log("uivar = " + example.uivar + "\n"); +console.log("usvar = " + example.usvar + "\n"); +console.log("ulvar = " + example.ulvar + "\n"); +console.log("scvar = " + example.scvar + "\n"); +console.log("ucvar = " + example.ucvar + "\n"); +console.log("fvar = " + example.fvar + "\n"); +console.log("dvar = " + example.dvar + "\n"); +console.log("cvar = " + example.cvar + "\n"); +console.log("strvar = " + example.strvar+ "\n"); +console.log("cstrvar = " + example.cstrvar+ "\n"); +console.log("iptrvar = " + example.iptrvar+ "\n"); +console.log("name = " + example.name + "\n"); +console.log("ptptr = " + example.ptptr + ": " + example.Point_print(example.ptptr) + "\n"); +console.log("pt = " + example.pt + ": " + example.Point_print(example.pt) + "\n"); + + +console.log("\nVariables (values console.loged from C)"); + +example.print_vars(); + +console.log("\nNow I'm going to try and modify some read only variables"); + +console.log("Tring to set 'path'"); +try{ + example.path = "Whoa!"; + console.log("Hey, what's going on?!?! This shouldn't work"); +} +catch(e){ + console.log("Good."); +} + +console.log("Trying to set 'status'"); +try{ + example.status = 0; + console.log("Hey, what's going on?!?! This shouldn't work"); +} catch(e){ + console.log("Good."); +} + +console.log("\nI'm going to try and update a structure variable.\n"); +example.pt = example.ptptr; +console.log("The new value is: "); +example.pt_print(); +console.log("You should see the value: " + example.Point_print(example.ptptr)); diff --git a/Examples/javascript/variables/swig_gdb.log b/Examples/javascript/variables/swig_gdb.log new file mode 100644 index 000000000..2fe437110 --- /dev/null +++ b/Examples/javascript/variables/swig_gdb.log @@ -0,0 +1,9 @@ +Loaded swig printers +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string From 41ec3fb67e65f3448e52c0eb7372d0331bc7b6ca Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 27 Sep 2013 02:54:42 +0200 Subject: [PATCH 0348/1048] Travis configuration for Javascript branch. --- .travis.yml | 70 ++++++++++++----------------------------------------- 1 file changed, 15 insertions(+), 55 deletions(-) diff --git a/.travis.yml b/.travis.yml index 26758304f..3b8500aee 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,58 +1,18 @@ -language: cpp +language: c 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 +node_js: + -0.10.12 +before_script: + - "sudo apt-get install rlwrap" + - "wget https://launchpad.net/~chris-lea/+archive/node.js/+build/4936691/+files/nodejs_0.10.18-1chl1~precise1_amd64.deb" + - "sudo dpkg -i nodejs_0.10.18-1chl1~precise1_amd64.deb" + - "sudo npm install -g node-gyp" + - "sudo apt-get install libv8-3.7.12.22 libv8-dev" + - "sudo apt-get install libwebkitgtk-dev" + - "./autogen.sh && ./configure && make" + - "cd Examples && make javascript_exe && cd .." 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 + - "make SMOKE=1 check-javascript-test-suite" + - "make SMOKE=1 ENGINE=jsc check-javascript-test-suite" + - "make SMOKE=1 ENGINE=v8 check-javascript-test-suite" From 738cc36aabb80c8a0abbc22147f39cbe3cb13915 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 7 Oct 2013 20:37:00 +0100 Subject: [PATCH 0349/1048] 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 0350/1048] 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 0351/1048] 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 0352/1048] 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 0353/1048] 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 0354/1048] 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 0355/1048] 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 0356/1048] 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 0357/1048] 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 0358/1048] 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 0359/1048] 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 0360/1048] 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 0361/1048] 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 0362/1048] 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 0363/1048] 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 0364/1048] 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 0365/1048] 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 0366/1048] 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 0367/1048] 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 0368/1048] 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 0369/1048] 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 0370/1048] 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 0371/1048] 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 0372/1048] 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 0373/1048] 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 0374/1048] 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 0375/1048] 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 0376/1048] 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 0377/1048] 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 0378/1048] 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 0379/1048] 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 0380/1048] 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 0381/1048] 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 0382/1048] 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 0383/1048] 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 0384/1048] 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 0385/1048] 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 0386/1048] 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 0387/1048] 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 0388/1048] 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 0389/1048] 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 0390/1048] 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 0391/1048] 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 0392/1048] 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 0393/1048] 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 0394/1048] 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 0395/1048] 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 0396/1048] 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 0397/1048] 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 0398/1048] 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 0399/1048] 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 0400/1048] 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 0401/1048] 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 0402/1048] 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 0403/1048] 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 0404/1048] 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 0405/1048] 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 0406/1048] 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 0407/1048] 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 0408/1048] 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 0409/1048] 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 0410/1048] 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 0411/1048] 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 0412/1048] 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 0413/1048] 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 0414/1048] 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 0415/1048] 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 0416/1048] 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 0417/1048] 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 0418/1048] 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 0419/1048] 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 0420/1048] 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 0421/1048] 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 0422/1048] 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 0423/1048] 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 0424/1048] 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 0425/1048] 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 0426/1048] 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
  • Modules can be unloaded from the type system.
  • -

    10.12.1 Implementation

    +

    11.12.1 Implementation

    @@ -4151,7 +4151,7 @@ structures rather than creating new ones. These swig_module_info structures are chained together in a circularly linked list.

    -

    10.12.2 Usage

    +

    11.12.2 Usage

    This section covers how to use these functions from typemaps. To learn how to @@ -4245,7 +4245,7 @@ probably just look at the output of SWIG to get a better sense for how types are managed.

    -

    10.13 Typemaps and overloading

    +

    11.13 Typemaps and overloading

    @@ -4556,7 +4556,7 @@ Subsequent "in" typemaps would then perform more extensive type-checking. -

    10.14 More about %apply and %clear

    +

    11.14 More about %apply and %clear

    @@ -4642,7 +4642,7 @@ example: -

    10.15 Passing data between typemaps

    +

    11.15 Passing data between typemaps

    @@ -4679,7 +4679,7 @@ sure that the typemaps sharing information have exactly the same types and names

    -

    10.16 C++ "this" pointer

    +

    11.16 C++ "this" pointer

    @@ -4739,7 +4739,7 @@ will also match the typemap. One work around is to create an interface file tha the method, but gives the argument a name other than self.

    -

    10.17 Where to go for more information?

    +

    11.17 Where to go for more information?

    diff --git a/Doc/Manual/Varargs.html b/Doc/Manual/Varargs.html index 9564fe00b..dac1ad7bc 100644 --- a/Doc/Manual/Varargs.html +++ b/Doc/Manual/Varargs.html @@ -6,7 +6,7 @@ -

    13 Variable Length Arguments

    +

    14 Variable Length Arguments

      @@ -42,7 +42,7 @@ added in SWIG-1.3.12. Most other wrapper generation tools have wisely chosen to avoid this issue.

      -

      13.1 Introduction

      +

      14.1 Introduction

      @@ -139,7 +139,7 @@ List make_list(const char *s, ...) {

    -

    13.2 The Problem

    +

    14.2 The Problem

    @@ -232,7 +232,7 @@ can also support real varargs wrapping (with stack-frame manipulation) if you are willing to get hands dirty. Keep reading.

    -

    13.3 Default varargs support

    +

    14.3 Default varargs support

    @@ -301,7 +301,7 @@ Read on for further solutions.

    -

    13.4 Argument replacement using %varargs

    +

    14.4 Argument replacement using %varargs

    @@ -412,7 +412,7 @@ mixed argument types such as printf(). Providing general purpose wrappers to such functions presents special problems (covered shortly).

    -

    13.5 Varargs and typemaps

    +

    14.5 Varargs and typemaps

    @@ -589,7 +589,7 @@ really want to elevate your guru status and increase your job security, continue to the next section.

    -

    13.6 Varargs wrapping with libffi

    +

    14.6 Varargs wrapping with libffi

    @@ -841,7 +841,7 @@ provide an argument number for the first extra argument. This can be used to in values. Please consult the chapter on each language module for more details.

    -

    13.7 Wrapping of va_list

    +

    14.7 Wrapping of va_list

    @@ -895,7 +895,7 @@ int my_vprintf(const char *fmt, ...) { -

    13.8 C++ Issues

    +

    14.8 C++ Issues

    @@ -964,7 +964,7 @@ design or to provide an alternative interface using a helper function than it is fully general wrapper to a varargs C++ member function.

    -

    13.9 Discussion

    +

    14.9 Discussion

    diff --git a/Doc/Manual/Warnings.html b/Doc/Manual/Warnings.html index b4d27872c..99b89c425 100644 --- a/Doc/Manual/Warnings.html +++ b/Doc/Manual/Warnings.html @@ -6,7 +6,7 @@ -

    14 Warning Messages

    +

    15 Warning Messages

      @@ -35,7 +35,7 @@ -

      14.1 Introduction

      +

      15.1 Introduction

      @@ -55,7 +55,7 @@ where the generated wrapper code will probably compile, but it may not work like you expect.

      -

      14.2 Warning message suppression

      +

      15.2 Warning message suppression

      @@ -147,7 +147,7 @@ your interface. Ignore the warning messages at your own peril.

      -

      14.3 Enabling extra warnings

      +

      15.3 Enabling extra warnings

      @@ -220,7 +220,7 @@ that is, any warnings suppressed or added in %warnfilter, #pragma S or the -w option.

      -

      14.4 Issuing a warning message

      +

      15.4 Issuing a warning message

      @@ -274,7 +274,7 @@ example.i:24: Warning 901: You are really going to regret this usage of blah * s

    -

    14.5 Symbolic symbols

    +

    15.5 Symbolic symbols

    @@ -309,7 +309,7 @@ or -

    14.6 Commentary

    +

    15.6 Commentary

    @@ -326,7 +326,7 @@ no obvious recovery. There is no mechanism for suppressing error messages.

    -

    14.7 Warnings as errors

    +

    15.7 Warnings as errors

    @@ -335,7 +335,7 @@ option. This will cause SWIG to exit with a non successful exit code if a warning is encountered.

    -

    14.8 Message output format

    +

    15.8 Message output format

    @@ -354,10 +354,10 @@ $ swig -python -Fmicrosoft example.i example.i(4) : Syntax error in input. -

    14.9 Warning number reference

    +

    15.9 Warning number reference

    -

    14.9.1 Deprecated features (100-199)

    +

    15.9.1 Deprecated features (100-199)

      @@ -385,7 +385,7 @@ example.i(4) : Syntax error in input.
    • 126. The 'nestedworkaround' feature is deprecated.
    -

    14.9.2 Preprocessor (200-299)

    +

    15.9.2 Preprocessor (200-299)

      @@ -397,7 +397,7 @@ example.i(4) : Syntax error in input.
    • 206. Unexpected tokens after #directive directive.
    -

    14.9.3 C/C++ Parser (300-399)

    +

    15.9.3 C/C++ Parser (300-399)

      @@ -474,7 +474,7 @@ example.i(4) : Syntax error in input.
    • 395. operator delete[] ignored.
    -

    14.9.4 Types and typemaps (400-499)

    +

    15.9.4 Types and typemaps (400-499)

    -

    No other lua metafunction is inherited. For example, __gc is not inherited and must be redefined in every class. __tostring is subject to a special handling. If absent in class and in class bases, a default one will be provided by SWIG

    +

    No other lua metafunction is inherited. For example, __gc is not inherited and must be redefined in every class. __tostring is subject to a special handling. If absent in class and in class bases, a default one will be provided by SWIG.

    -

    27.3.12 Class extension with %extend

    +

    28.3.12 Class extension with %extend

    @@ -1116,7 +1116,7 @@ true Extend works with both C and C++ code, on classes and structs. It does not modify the underlying object in any way---the extensions only show up in the Lua interface. The only item to take note of is the code has to use the '$self' instead of 'this', and that you cannot access protected/private members of the code (as you are not officially part of the class).

    -

    27.3.13 Using %newobject to release memory

    +

    28.3.13 Using %newobject to release memory

    If you have a function that allocates memory like this,

    @@ -1140,7 +1140,7 @@ char *foo();

    This will release the allocated memory.

    -

    27.3.14 C++ templates

    +

    28.3.14 C++ templates

    @@ -1175,7 +1175,7 @@ In Lua:

    Obviously, there is more to template wrapping than shown in this example. More details can be found in the SWIG and C++ chapter. Some more complicated examples will appear later.

    -

    27.3.15 C++ Smart Pointers

    +

    28.3.15 C++ Smart Pointers

    @@ -1227,7 +1227,7 @@ If you ever need to access the underlying pointer returned by operator->( > f = p:__deref__() -- Returns underlying Foo * -

    27.3.16 C++ Exceptions

    +

    28.3.16 C++ Exceptions

    @@ -1370,7 +1370,7 @@ and the "Exception handling add exception specification to functions or globally (respectively).

    -

    27.3.17 Namespaces

    +

    28.3.17 Namespaces

    @@ -1421,7 +1421,7 @@ Now, from Lua usage is as follows: 19 > -

    27.3.17.1 Compatibility Note

    +

    28.3.17.1 Compatibility Note

    @@ -1437,7 +1437,7 @@ If SWIG is running in a backwards compatible way, i.e. without the -no-old-m -

    27.3.17.2 Names

    +

    28.3.17.2 Names

    If SWIG is launched without -no-old-metatable-bindings option, then it enters backward-compatible mode. While in this mode, it tries @@ -1481,7 +1481,7 @@ surrounding scope without any prefixing. Pretending that Test2 is a struct, not > -

    27.3.17.3 Inheritance

    +

    28.3.17.3 Inheritance

    The internal organization of inheritance has changed. @@ -1522,12 +1522,12 @@ function > -

    27.4 Typemaps

    +

    28.4 Typemaps

    This section explains what typemaps are and how to use them. The default wrapping behaviour of SWIG is enough in most cases. However sometimes SWIG may need a little additional assistance to know which typemap to apply to provide the best wrapping. This section will be explaining how to use typemaps to best effect

    -

    27.4.1 What is a typemap?

    +

    28.4.1 What is a typemap?

    A typemap is nothing more than a code generation rule that is attached to a specific C datatype. For example, to convert integers from Lua to C, you might define a typemap like this:

    @@ -1555,7 +1555,7 @@ Received an integer : 6 720 -

    27.4.2 Using typemaps

    +

    28.4.2 Using typemaps

    There are many ready written typemaps built into SWIG for all common types (int, float, short, long, char*, enum and more), which SWIG uses automatically, with no effort required on your part.

    @@ -1608,7 +1608,7 @@ void swap(int *sx, int *sy);

    Note: C++ references must be handled exactly the same way. However SWIG will automatically wrap a const int& as an input parameter (since that it obviously input).

    -

    27.4.3 Typemaps and arrays

    +

    28.4.3 Typemaps and arrays

    Arrays present a challenge for SWIG, because like pointers SWIG does not know whether these are input or output values, nor @@ -1672,7 +1672,7 @@ and Lua tables to be 1..N, (the indexing follows the norm for the language). In

    Note: SWIG also can support arrays of pointers in a similar manner.

    -

    27.4.4 Typemaps and pointer-pointer functions

    +

    28.4.4 Typemaps and pointer-pointer functions

    Several C++ libraries use a pointer-pointer functions to create its objects. These functions require a pointer to a pointer which is then filled with the pointer to the new object. Microsoft's COM and DirectX as well as many other libraries have this kind of function. An example is given below:

    @@ -1706,7 +1706,7 @@ int Create_Math(iMath** pptr); // its creator (assume it mallocs) ptr=nil -- the iMath* will be GC'ed as normal -

    27.5 Writing typemaps

    +

    28.5 Writing typemaps

    This section describes how you can modify SWIG's default wrapping behavior for various C/C++ datatypes using the %typemap directive. This is an advanced topic that assumes familiarity with the Lua C API as well as the material in the "Typemaps" chapter.

    @@ -1715,7 +1715,7 @@ ptr=nil -- the iMath* will be GC'ed as normal

    Before proceeding, you should read the previous section on using typemaps, and look at the existing typemaps found in luatypemaps.swg and typemaps.i. These are both well documented and fairly easy to read. You should not attempt to write your own typemaps until you have read and can understand both of these files (they may well also give you an idea to base your work on).

    -

    27.5.1 Typemaps you can write

    +

    28.5.1 Typemaps you can write

    There are many different types of typemap that can be written, the full list can be found in the "Typemaps" chapter. However the following are the most commonly used ones.

    @@ -1728,7 +1728,7 @@ ptr=nil -- the iMath* will be GC'ed as normal (the syntax for the typecheck is different from the typemap, see typemaps for details). -

    27.5.2 SWIG's Lua-C API

    +

    28.5.2 SWIG's Lua-C API

    This section explains the SWIG specific Lua-C API. It does not cover the main Lua-C api, as this is well documented and not worth covering.

    @@ -1777,7 +1777,7 @@ This macro, when called within the context of a SWIG wrapped function, will disp
    Similar to SWIG_fail_arg, except that it will display the swig_type_info information instead.
    -

    27.6 Customization of your Bindings

    +

    28.6 Customization of your Bindings

    @@ -1786,7 +1786,7 @@ This section covers adding of some small extra bits to your module to add the la -

    27.6.1 Writing your own custom wrappers

    +

    28.6.1 Writing your own custom wrappers

    @@ -1805,7 +1805,7 @@ int native_function(lua_State*L) // my native code The %native directive in the above example, tells SWIG that there is a function int native_function(lua_State*L); which is to be added into the module under the name 'my_func'. SWIG will not add any wrapper for this function, beyond adding it into the function table. How you write your code is entirely up to you.

    -

    27.6.2 Adding additional Lua code

    +

    28.6.2 Adding additional Lua code

    @@ -1843,7 +1843,7 @@ Good uses for this feature is adding of new code, or writing helper functions to See Examples/lua/arrays for an example of this code.

    -

    27.7 Details on the Lua binding

    +

    28.7 Details on the Lua binding

    @@ -1854,7 +1854,7 @@ See Examples/lua/arrays for an example of this code.

    -

    27.7.1 Binding global data into the module.

    +

    28.7.1 Binding global data into the module.

    @@ -1914,7 +1914,7 @@ end

    That way when you call 'a=example.Foo', the interpreter looks at the table 'example' sees that there is no field 'Foo' and calls __index. This will in turn check in '.get' table and find the existence of 'Foo' and then return the value of the C function call 'Foo_get()'. Similarly for the code 'example.Foo=10', the interpreter will check the table, then call the __newindex which will then check the '.set' table and call the C function 'Foo_set(10)'.

    -

    27.7.2 Userdata and Metatables

    +

    28.7.2 Userdata and Metatables

    @@ -1994,7 +1994,7 @@ Note: Both the opaque structures (like the FILE*) and normal wrapped classes/str

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

    -

    27.7.3 Memory management

    +

    28.7.3 Memory management

    From 4a680e5545af57bd866a8211679b3d953e286545 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 9 May 2014 23:26:59 +0100 Subject: [PATCH 0915/1048] html doc chapter numbering update since adding Javascript --- Doc/Manual/Contents.html | 69 +++++++++++--- Doc/Manual/Extending.html | 100 +++++++++---------- Doc/Manual/Lisp.html | 22 ++--- Doc/Manual/Modula3.html | 40 ++++---- Doc/Manual/Mzscheme.html | 8 +- Doc/Manual/Ocaml.html | 62 ++++++------ Doc/Manual/Octave.html | 48 +++++----- Doc/Manual/Perl5.html | 108 ++++++++++----------- Doc/Manual/Php.html | 48 +++++----- Doc/Manual/Pike.html | 24 ++--- Doc/Manual/Python.html | 164 +++++++++++++++---------------- Doc/Manual/R.html | 16 ++-- Doc/Manual/Ruby.html | 196 +++++++++++++++++++------------------- Doc/Manual/Tcl.html | 92 +++++++++--------- 14 files changed, 519 insertions(+), 478 deletions(-) diff --git a/Doc/Manual/Contents.html b/Doc/Manual/Contents.html index 7cf40b95d..37a5aacff 100644 --- a/Doc/Manual/Contents.html +++ b/Doc/Manual/Contents.html @@ -1046,7 +1046,48 @@ -

    26 SWIG and Common Lisp

    +

    26 SWIG and Javascript

    + + + + + +

    27 SWIG and Common Lisp

    @@ -1069,7 +1110,7 @@
    -

    27 SWIG and Lua

    +

    28 SWIG and Lua

    @@ -1137,7 +1178,7 @@
    -

    28 SWIG and Modula-3

    +

    29 SWIG and Modula-3

    @@ -1175,7 +1216,7 @@
    -

    29 SWIG and MzScheme/Racket

    +

    30 SWIG and MzScheme/Racket

    @@ -1187,7 +1228,7 @@
    -

    30 SWIG and Ocaml

    +

    31 SWIG and Ocaml

    @@ -1238,7 +1279,7 @@
    -

    31 SWIG and Octave

    +

    32 SWIG and Octave

    @@ -1274,7 +1315,7 @@
    -

    32 SWIG and Perl5

    +

    33 SWIG and Perl5

    @@ -1350,7 +1391,7 @@
    -

    33 SWIG and PHP

    +

    34 SWIG and PHP

    @@ -1390,7 +1431,7 @@
    -

    34 SWIG and Pike

    +

    35 SWIG and Pike

    @@ -1414,7 +1455,7 @@
    -

    35 SWIG and Python

    +

    36 SWIG and Python

    @@ -1530,7 +1571,7 @@
    -

    36 SWIG and R

    +

    37 SWIG and R

    @@ -1546,7 +1587,7 @@
    -

    37 SWIG and Ruby

    +

    38 SWIG and Ruby

    @@ -1680,7 +1721,7 @@
    -

    38 SWIG and Tcl

    +

    39 SWIG and Tcl

    @@ -1746,7 +1787,7 @@
    -

    39 Extending SWIG to support new languages

    +

    40 Extending SWIG to support new languages

    diff --git a/Doc/Manual/Extending.html b/Doc/Manual/Extending.html index 5c209bbb5..00302d7b5 100644 --- a/Doc/Manual/Extending.html +++ b/Doc/Manual/Extending.html @@ -6,7 +6,7 @@ -

    39 Extending SWIG to support new languages

    +

    40 Extending SWIG to support new languages

      @@ -75,7 +75,7 @@ -

      39.1 Introduction

      +

      40.1 Introduction

      @@ -91,7 +91,7 @@ Also, this chapter is not meant to be a hand-holding tutorial. As a starting po you should probably look at one of SWIG's existing modules.

      -

      39.2 Prerequisites

      +

      40.2 Prerequisites

      @@ -121,7 +121,7 @@ obvious, but almost all SWIG directives as well as the low-level generation of wrapper code are driven by C++ datatypes.

      -

      39.3 The Big Picture

      +

      40.3 The Big Picture

      @@ -158,7 +158,7 @@ role in making the system work. For example, both typemaps and declaration anno based on pattern matching and interact heavily with the underlying type system.

      -

      39.4 Execution Model

      +

      40.4 Execution Model

      @@ -203,7 +203,7 @@ latter stage of compilation. The next few sections briefly describe some of these stages.

      -

      39.4.1 Preprocessing

      +

      40.4.1 Preprocessing

      @@ -284,7 +284,7 @@ been expanded as well as everything else that goes into the low-level construction of the wrapper code.

      -

      39.4.2 Parsing

      +

      40.4.2 Parsing

      @@ -385,7 +385,7 @@ returning a foo and taking types a and b as arguments).

      -

      39.4.3 Parse Trees

      +

      40.4.3 Parse Trees

      @@ -640,7 +640,7 @@ $ swig -c++ -python -debug-module 4 example.i

    -

    39.4.4 Attribute namespaces

    +

    40.4.4 Attribute namespaces

    @@ -659,7 +659,7 @@ that matches the name of the target language. For example, python:foo perl:foo.

    -

    39.4.5 Symbol Tables

    +

    40.4.5 Symbol Tables

    @@ -750,7 +750,7 @@ example.i:5. Previous declaration is foo_i(int )

    -

    39.4.6 The %feature directive

    +

    40.4.6 The %feature directive

    @@ -806,7 +806,7 @@ For example, the exception code above is simply stored without any modifications.

    -

    39.4.7 Code Generation

    +

    40.4.7 Code Generation

    @@ -928,7 +928,7 @@ public : The role of these functions is described shortly.

    -

    39.4.8 SWIG and XML

    +

    40.4.8 SWIG and XML

    @@ -941,7 +941,7 @@ internal data structures, it may be useful to keep XML in the back of your mind as a model.

    -

    39.5 Primitive Data Structures

    +

    40.5 Primitive Data Structures

    @@ -987,7 +987,7 @@ typedef Hash Typetab; -

    39.5.1 Strings

    +

    40.5.1 Strings

    @@ -1128,7 +1128,7 @@ Returns the number of replacements made (if any). -

    39.5.2 Hashes

    +

    40.5.2 Hashes

    @@ -1205,7 +1205,7 @@ Returns the list of hash table keys. -

    39.5.3 Lists

    +

    40.5.3 Lists

    @@ -1294,7 +1294,7 @@ If t is not a standard object, it is assumed to be a char * and is used to create a String object. -

    39.5.4 Common operations

    +

    40.5.4 Common operations

    The following operations are applicable to all datatypes. @@ -1349,7 +1349,7 @@ objects and report errors. Gets the line number associated with x. -

    39.5.5 Iterating over Lists and Hashes

    +

    40.5.5 Iterating over Lists and Hashes

    To iterate over the elements of a list or a hash table, the following functions are used: @@ -1394,7 +1394,7 @@ for (j = First(j); j.item; j= Next(j)) { -

    39.5.6 I/O

    +

    40.5.6 I/O

    Special I/O functions are used for all internal I/O. These operations @@ -1528,7 +1528,7 @@ Printf(f, "%s\n", s); Similarly, the preprocessor and parser all operate on string-files.

    -

    39.6 Navigating and manipulating parse trees

    +

    40.6 Navigating and manipulating parse trees

    Parse trees are built as collections of hash tables. Each node is a hash table in which @@ -1662,7 +1662,7 @@ Deletes a node from the parse tree. Deletion reconnects siblings and properly u the parent so that sibling nodes are unaffected. -

    39.7 Working with attributes

    +

    40.7 Working with attributes

    @@ -1779,7 +1779,7 @@ the attribute is optional. Swig_restore() must always be called after function. -

    39.8 Type system

    +

    40.8 Type system

    @@ -1788,7 +1788,7 @@ pointers, references, and pointers to members. A detailed discussion of type theory is impossible here. However, let's cover the highlights.

    -

    39.8.1 String encoding of types

    +

    40.8.1 String encoding of types

    @@ -1889,7 +1889,7 @@ make the final type, the two parts are just joined together using string concatenation.

    -

    39.8.2 Type construction

    +

    40.8.2 Type construction

    @@ -2058,7 +2058,7 @@ Returns the prefix of a type. For example, if ty is ty is unmodified. -

    39.8.3 Type tests

    +

    40.8.3 Type tests

    @@ -2145,7 +2145,7 @@ Checks if ty is a varargs type. Checks if ty is a templatized type. -

    39.8.4 Typedef and inheritance

    +

    40.8.4 Typedef and inheritance

    @@ -2247,7 +2247,7 @@ Fully reduces ty according to typedef rules. Resulting datatype will consist only of primitive typenames. -

    39.8.5 Lvalues

    +

    40.8.5 Lvalues

    @@ -2284,7 +2284,7 @@ Literal y; // type = 'Literal', ltype='p.char' -

    39.8.6 Output functions

    +

    40.8.6 Output functions

    @@ -2346,7 +2346,7 @@ SWIG, but is most commonly associated with type-descriptor objects that appear in wrappers (e.g., SWIGTYPE_p_double). -

    39.9 Parameters

    +

    40.9 Parameters

    @@ -2445,7 +2445,7 @@ included. Used to emit prototypes. Returns the number of required (non-optional) arguments in p. -

    39.10 Writing a Language Module

    +

    40.10 Writing a Language Module

    @@ -2460,7 +2460,7 @@ describes the creation of a minimal Python module. You should be able to extra this to other languages.

    -

    39.10.1 Execution model

    +

    40.10.1 Execution model

    @@ -2470,7 +2470,7 @@ the parsing of command line options, all aspects of code generation are controll different methods of the Language that must be defined by your module.

    -

    39.10.2 Starting out

    +

    40.10.2 Starting out

    @@ -2578,7 +2578,7 @@ that activates your module. For example, swig -python foo.i. The messages from your new module should appear.

    -

    39.10.3 Command line options

    +

    40.10.3 Command line options

    @@ -2637,7 +2637,7 @@ to mark the option as valid. If you forget to do this, SWIG will terminate wit unrecognized command line option error.

    -

    39.10.4 Configuration and preprocessing

    +

    40.10.4 Configuration and preprocessing

    @@ -2686,7 +2686,7 @@ an implementation file python.cxx and a configuration file python.swg.

    -

    39.10.5 Entry point to code generation

    +

    40.10.5 Entry point to code generation

    @@ -2744,7 +2744,7 @@ int Python::top(Node *n) { -

    39.10.6 Module I/O and wrapper skeleton

    +

    40.10.6 Module I/O and wrapper skeleton

    @@ -2892,7 +2892,7 @@ functionWrapper : void Shape_y_set(Shape *self,double y) -

    39.10.7 Low-level code generators

    +

    40.10.7 Low-level code generators

    @@ -3046,7 +3046,7 @@ but without the typemaps, there is still work to do.

    -

    39.10.8 Configuration files

    +

    40.10.8 Configuration files

    @@ -3190,7 +3190,7 @@ politely displays the ignoring language message. -

    39.10.9 Runtime support

    +

    40.10.9 Runtime support

    @@ -3199,7 +3199,7 @@ Discuss the kinds of functions typically needed for SWIG runtime support (e.g. the SWIG files that implement those functions.

    -

    39.10.10 Standard library files

    +

    40.10.10 Standard library files

    @@ -3218,7 +3218,7 @@ The following are the minimum that are usually supported: Please copy these and modify for any new language.

    -

    39.10.11 User examples

    +

    40.10.11 User examples

    @@ -3247,7 +3247,7 @@ during this process, see the section on .

    -

    39.10.12 Test driven development and the test-suite

    +

    40.10.12 Test driven development and the test-suite

    @@ -3306,7 +3306,7 @@ It is therefore essential that the runtime tests are written in a manner that di but error/exception out with an error message on stderr on failure.

    -

    39.10.12.1 Running the test-suite

    +

    40.10.12.1 Running the test-suite

    @@ -3498,7 +3498,7 @@ It can be run in the same way as the other language test-suites, replacing [lang The test cases used and the way it works is described in Examples/test-suite/errors/Makefile.in.

    -

    39.10.13 Documentation

    +

    40.10.13 Documentation

    @@ -3530,7 +3530,7 @@ Some topics that you'll want to be sure to address include: if available. -

    39.10.14 Prerequisites for adding a new language module to the SWIG distribution

    +

    40.10.14 Prerequisites for adding a new language module to the SWIG distribution

    @@ -3587,7 +3587,7 @@ should be added should there be an area not already covered by the existing tests.

    -

    39.10.15 Coding style guidelines

    +

    40.10.15 Coding style guidelines

    @@ -3611,7 +3611,7 @@ The generated C/C++ code should also follow this style as close as possible. How should be avoided as unlike the SWIG developers, users will never have consistent tab settings.

    -

    39.11 Debugging Options

    +

    40.11 Debugging Options

    @@ -3638,7 +3638,7 @@ There are various command line options which can aid debugging a SWIG interface The complete list of command line options for SWIG are available by running swig -help.

    -

    39.12 Guide to parse tree nodes

    +

    40.12 Guide to parse tree nodes

    @@ -4046,7 +4046,7 @@ extern "X" { ... } declaration. -

    39.13 Further Development Information

    +

    40.13 Further Development Information

    diff --git a/Doc/Manual/Lisp.html b/Doc/Manual/Lisp.html index 7ea9139ac..0b8d47846 100644 --- a/Doc/Manual/Lisp.html +++ b/Doc/Manual/Lisp.html @@ -6,7 +6,7 @@ -

    26 SWIG and Common Lisp

    +

    27 SWIG and Common Lisp

      @@ -41,7 +41,7 @@ Lisp, Common Foreign Function Interface(CFFI), CLisp and UFFI foreign function interfaces.

      -

      26.1 Allegro Common Lisp

      +

      27.1 Allegro Common Lisp

      @@ -50,7 +50,7 @@ here

      -

      26.2 Common Foreign Function Interface(CFFI)

      +

      27.2 Common Foreign Function Interface(CFFI)

      @@ -77,7 +77,7 @@ swig -cffi -module module-name file-name files and the various things which you can do with them.

      -

      26.2.1 Additional Commandline Options

      +

      27.2.1 Additional Commandline Options

      @@ -118,7 +118,7 @@ swig -cffi -help -

      26.2.2 Generating CFFI bindings

      +

      27.2.2 Generating CFFI bindings

      As we mentioned earlier the ideal way to use SWIG is to use interface @@ -392,7 +392,7 @@ The feature intern_function ensures that all C names are
    -

    26.2.3 Generating CFFI bindings for C++ code

    +

    27.2.3 Generating CFFI bindings for C++ code

    This feature to SWIG (for CFFI) is very new and still far from @@ -568,7 +568,7 @@ If you have any questions, suggestions, patches, etc., related to CFFI module feel free to contact us on the SWIG mailing list, and also please add a "[CFFI]" tag in the subject line. -

    26.2.4 Inserting user code into generated files

    +

    27.2.4 Inserting user code into generated files

    @@ -608,7 +608,7 @@ Note that the block %{ ... %} is effectively a shortcut for

    -

    26.3 CLISP

    +

    27.3 CLISP

    @@ -638,7 +638,7 @@ swig -clisp -module module-name file-name interface file for the CLISP module. The CLISP module tries to produce code which is both human readable and easily modifyable.

    -

    26.3.1 Additional Commandline Options

    +

    27.3.1 Additional Commandline Options

    @@ -671,7 +671,7 @@ and global variables will be created otherwise only definitions for
    -

    26.3.2 Details on CLISP bindings

    +

    27.3.2 Details on CLISP bindings

    @@ -795,7 +795,7 @@ struct bar { -

    26.4 UFFI

    +

    27.4 UFFI

    diff --git a/Doc/Manual/Modula3.html b/Doc/Manual/Modula3.html index 0bf9f2995..ffbf6132d 100644 --- a/Doc/Manual/Modula3.html +++ b/Doc/Manual/Modula3.html @@ -5,7 +5,7 @@ -

    28 SWIG and Modula-3

    +

    29 SWIG and Modula-3

      @@ -54,7 +54,7 @@ especially typemaps.

      -

      28.1 Overview

      +

      29.1 Overview

      @@ -84,7 +84,7 @@ FFTW -

      28.1.1 Motivation

      +

      29.1.1 Motivation

      @@ -131,10 +131,10 @@ functions), but it doesn't allow you to easily integrate a Modula-3 module into a C/C++ project.

      -

      28.2 Conception

      +

      29.2 Conception

      -

      28.2.1 Interfaces to C libraries

      +

      29.2.1 Interfaces to C libraries

      @@ -283,7 +283,7 @@ and the principal type must be renamed (%typemap).

      -

      28.2.2 Interfaces to C++ libraries

      +

      29.2.2 Interfaces to C++ libraries

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

      -

      28.3 Preliminaries

      +

      29.3 Preliminaries

      -

      28.3.1 Compilers

      +

      29.3.1 Compilers

      @@ -400,7 +400,7 @@ For testing examples I use Critical Mass cm3.

      -

      28.3.2 Additional Commandline Options

      +

      29.3.2 Additional Commandline Options

      @@ -477,10 +477,10 @@ Instead generate templates for some basic typemaps. -

      28.4 Modula-3 typemaps

      +

      29.4 Modula-3 typemaps

      -

      28.4.1 Inputs and outputs

      +

      29.4.1 Inputs and outputs

      @@ -694,7 +694,7 @@ consist of the following parts: -

      28.4.2 Subranges, Enumerations, Sets

      +

      29.4.2 Subranges, Enumerations, Sets

      @@ -746,7 +746,7 @@ that I'd like to automate.

      -

      28.4.3 Objects

      +

      29.4.3 Objects

      @@ -759,7 +759,7 @@ is not really useful, yet.

      -

      28.4.4 Imports

      +

      29.4.4 Imports

      @@ -792,7 +792,7 @@ IMPORT M3toC;

    -

    28.4.5 Exceptions

    +

    29.4.5 Exceptions

    @@ -816,7 +816,7 @@ you should declare %typemap("m3wrapinconv:throws") blah * %{OSError.E%}.

    -

    28.4.6 Example

    +

    29.4.6 Example

    @@ -863,10 +863,10 @@ where almost everything is generated by a typemap: -

    28.5 More hints to the generator

    +

    29.5 More hints to the generator

    -

    28.5.1 Features

    +

    29.5.1 Features

    @@ -903,7 +903,7 @@ where almost everything is generated by a typemap:
    -

    28.5.2 Pragmas

    +

    29.5.2 Pragmas

    @@ -926,7 +926,7 @@ where almost everything is generated by a typemap:
    -

    28.6 Remarks

    +

    29.6 Remarks

      diff --git a/Doc/Manual/Mzscheme.html b/Doc/Manual/Mzscheme.html index 40173d720..fadda5fc9 100644 --- a/Doc/Manual/Mzscheme.html +++ b/Doc/Manual/Mzscheme.html @@ -8,7 +8,7 @@ -

      29 SWIG and MzScheme/Racket

      +

      30 SWIG and MzScheme/Racket

        @@ -24,7 +24,7 @@

        This section contains information on SWIG's support of Racket, formally known as MzScheme. -

        29.1 Creating native structures

        +

        30.1 Creating native structures

        @@ -65,7 +65,7 @@ Then in scheme, you can use regular struct access procedures like

      -

      29.2 Simple example

      +

      30.2 Simple example

      @@ -166,7 +166,7 @@ Some points of interest:

    • The above requests mzc to create an extension using the CGC garbage-collector. The alternative -- the 3m collector -- has generally better performance, but work is still required for SWIG to emit code which is compatible with it.
    -

    29.3 External documentation

    +

    30.3 External documentation

    diff --git a/Doc/Manual/Ocaml.html b/Doc/Manual/Ocaml.html index ec46d6e50..aa6679f9a 100644 --- a/Doc/Manual/Ocaml.html +++ b/Doc/Manual/Ocaml.html @@ -6,7 +6,7 @@ -

    30 SWIG and Ocaml

    +

    31 SWIG and Ocaml

      @@ -80,7 +80,7 @@ If you're not familiar with the Objective Caml language, you can visit The Ocaml Website.

      -

      30.1 Preliminaries

      +

      31.1 Preliminaries

      @@ -99,7 +99,7 @@ file Examples/Makefile illustrate how to compile and link SWIG modules that will be loaded dynamically. This has only been tested on Linux so far.

      -

      30.1.1 Running SWIG

      +

      31.1.1 Running SWIG

      @@ -122,7 +122,7 @@ you will compile the file example_wrap.c with ocamlc or the resulting .ml and .mli files as well, and do the final link with -custom (not needed for native link).

      -

      30.1.2 Compiling the code

      +

      31.1.2 Compiling the code

      @@ -158,7 +158,7 @@ the user more freedom with respect to custom typing.

    -

    30.1.3 The camlp4 module

    +

    31.1.3 The camlp4 module

    @@ -234,7 +234,7 @@ let b = C_string (getenv "PATH") -

    30.1.4 Using your module

    +

    31.1.4 Using your module

    @@ -248,7 +248,7 @@ When linking any ocaml bytecode with your module, use the -custom option is not needed when you build native code.

    -

    30.1.5 Compilation problems and compiling with C++

    +

    31.1.5 Compilation problems and compiling with C++

    @@ -259,7 +259,7 @@ liberal with pointer types may not compile under the C++ compiler. Most code meant to be compiled as C++ will not have problems.

    -

    30.2 The low-level Ocaml/C interface

    +

    31.2 The low-level Ocaml/C interface

    @@ -360,7 +360,7 @@ is that you must append them to the return list with swig_result = caml_list_a signature for a function that uses value in this way.

    -

    30.2.1 The generated module

    +

    31.2.1 The generated module

    @@ -394,7 +394,7 @@ it describes the output SWIG will generate for class definitions. -

    30.2.2 Enums

    +

    31.2.2 Enums

    @@ -457,7 +457,7 @@ val x : Enum_test.c_obj = C_enum `a -

    30.2.2.1 Enum typing in Ocaml

    +

    31.2.2.1 Enum typing in Ocaml

    @@ -470,10 +470,10 @@ functions imported from different modules. You must convert values to master values using the swig_val function before sharing them with another module.

    -

    30.2.3 Arrays

    +

    31.2.3 Arrays

    -

    30.2.3.1 Simple types of bounded arrays

    +

    31.2.3.1 Simple types of bounded arrays

    @@ -494,7 +494,7 @@ arrays of simple types with known bounds in your code, but this only works for arrays whose bounds are completely specified.

    -

    30.2.3.2 Complex and unbounded arrays

    +

    31.2.3.2 Complex and unbounded arrays

    @@ -507,7 +507,7 @@ SWIG can't predict which of these methods will be used in the array, so you have to specify it for yourself in the form of a typemap.

    -

    30.2.3.3 Using an object

    +

    31.2.3.3 Using an object

    @@ -521,7 +521,7 @@ Consider writing an object when the ending condition of your array is complex, such as using a required sentinel, etc.

    -

    30.2.3.4 Example typemap for a function taking float * and int

    +

    31.2.3.4 Example typemap for a function taking float * and int

    @@ -572,7 +572,7 @@ void printfloats( float *tab, int len ); -

    30.2.4 C++ Classes

    +

    31.2.4 C++ Classes

    @@ -615,7 +615,7 @@ the underlying pointer, so using create_[x]_from_ptr alters the returned value for the same object.

    -

    30.2.4.1 STL vector and string Example

    +

    31.2.4.1 STL vector and string Example

    @@ -695,7 +695,7 @@ baz # -

    30.2.4.2 C++ Class Example

    +

    31.2.4.2 C++ Class Example

    @@ -725,7 +725,7 @@ public: }; -

    30.2.4.3 Compiling the example

    +

    31.2.4.3 Compiling the example

    @@ -743,7 +743,7 @@ bash-2.05a$ ocamlmktop -custom swig.cmo -I `camlp4 -where` \
       -L$QTPATH/lib -cclib -lqt
     
    -

    30.2.4.4 Sample Session

    +

    31.2.4.4 Sample Session

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

    -

    30.2.5 Director Classes

    +

    31.2.5 Director Classes

    -

    30.2.5.1 Director Introduction

    +

    31.2.5.1 Director Introduction

    @@ -800,7 +800,7 @@ class foo { };

    -

    30.2.5.2 Overriding Methods in Ocaml

    +

    31.2.5.2 Overriding Methods in Ocaml

    @@ -828,7 +828,7 @@ In this example, I'll examine the objective caml code involved in providing an overloaded class. This example is contained in Examples/ocaml/shapes.

    -

    30.2.5.3 Director Usage Example

    +

    31.2.5.3 Director Usage Example

    @@ -887,7 +887,7 @@ in a more effortless style in ocaml, while leaving the "engine" part of the program in C++.

    -

    30.2.5.4 Creating director objects

    +

    31.2.5.4 Creating director objects

    @@ -928,7 +928,7 @@ object from causing a core dump, as long as the object is destroyed properly.

    -

    30.2.5.5 Typemaps for directors, directorin, directorout, directorargout

    +

    31.2.5.5 Typemaps for directors, directorin, directorout, directorargout

    @@ -939,7 +939,7 @@ well as a function return value in the same way you provide function arguments, and to receive arguments the same way you normally receive function returns.

    -

    30.2.5.6 directorin typemap

    +

    31.2.5.6 directorin typemap

    @@ -950,7 +950,7 @@ code receives when you are called. In general, a simple directorin typ can use the same body as a simple out typemap.

    -

    30.2.5.7 directorout typemap

    +

    31.2.5.7 directorout typemap

    @@ -961,7 +961,7 @@ for the same type, except when there are special requirements for object ownership, etc.

    -

    30.2.5.8 directorargout typemap

    +

    31.2.5.8 directorargout typemap

    @@ -978,7 +978,7 @@ In the event that you don't specify all of the necessary values, integral values will read zero, and struct or object returns have undefined results.

    -

    30.2.6 Exceptions

    +

    31.2.6 Exceptions

    diff --git a/Doc/Manual/Octave.html b/Doc/Manual/Octave.html index bc6873c4b..9c3489fb8 100644 --- a/Doc/Manual/Octave.html +++ b/Doc/Manual/Octave.html @@ -8,7 +8,7 @@ -

    31 SWIG and Octave

    +

    32 SWIG and Octave

      @@ -55,7 +55,7 @@ More information can be found at O Also, there are a dozen or so examples in the Examples/octave directory, and hundreds in the test suite (Examples/test-suite and Examples/test-suite/octave).

      -

      31.1 Preliminaries

      +

      32.1 Preliminaries

      @@ -63,7 +63,7 @@ As of SWIG 3.0.0, the Octave module has been tested with Octave versions 3.0.5, Use of Octave versions older than 3.x.x is not recommended, as these versions are no longer tested with SWIG.

      -

      31.2 Running SWIG

      +

      32.2 Running SWIG

      @@ -95,7 +95,7 @@ The -c++ option is also required when wrapping C++ code: This creates a C++ source file "example_wrap.cpp". A C++ file is generated even when wrapping C code as Octave is itself written in C++ and requires wrapper code to be in the same language. The generated C++ source file contains the low-level wrappers that need to be compiled and linked with the rest of your C/C++ application (in this case, the gcd implementation) to create an extension module.

      -

      31.2.1 Command-line options

      +

      32.2.1 Command-line options

      @@ -118,7 +118,7 @@ The special name "." loads C global variables into the module namespace, i.e. al The -opprefix options sets the prefix of the names of global/friend operator functions.

      -

      31.2.2 Compiling a dynamic module

      +

      32.2.2 Compiling a dynamic module

      @@ -145,7 +145,7 @@ $ mkoctfile example_wrap.cpp example.c

      octave:1> swigexample
      -

      31.2.3 Using your module

      +

      32.2.3 Using your module

      @@ -163,10 +163,10 @@ octave:4> swigexample.cvar.Foo=4; octave:5> swigexample.cvar.Foo ans = 4

    -

    31.3 A tour of basic C/C++ wrapping

    +

    32.3 A tour of basic C/C++ wrapping

    -

    31.3.1 Modules

    +

    32.3.1 Modules

    @@ -211,7 +211,7 @@ octave:4> swigexample.gcd(4,6) ans = 2 -

    31.3.2 Functions

    +

    32.3.2 Functions

    @@ -228,7 +228,7 @@ int fact(int n);

    octave:1> swigexample.fact(4)
     24 
    -

    31.3.3 Global variables

    +

    32.3.3 Global variables

    @@ -281,7 +281,7 @@ octave:2> swigexample.PI=3.142; octave:3> swigexample.PI ans = 3.1420 -

    31.3.4 Constants and enums

    +

    32.3.4 Constants and enums

    @@ -303,7 +303,7 @@ swigexample.SCONST="Hello World" swigexample.SUNDAY=0 .... -

    31.3.5 Pointers

    +

    32.3.5 Pointers

    @@ -350,7 +350,7 @@ octave:2> f=swigexample.fopen("not there","r"); error: value on right hand side of assignment is undefined error: evaluating assignment expression near line 2, column 2 -

    31.3.6 Structures and C++ classes

    +

    32.3.6 Structures and C++ classes

    @@ -485,7 +485,7 @@ ans = 1 Depending on the ownership setting of a swig_ref, it may call C++ destructors when its reference count goes to zero. See the section on memory management below for details.

    -

    31.3.7 C++ inheritance

    +

    32.3.7 C++ inheritance

    @@ -494,7 +494,7 @@ This information contains the full class hierarchy. When an indexing operation ( the tree is walked to find a match in the current class as well as any of its bases. The lookup is then cached in the swig_ref.

    -

    31.3.8 C++ overloaded functions

    +

    32.3.8 C++ overloaded functions

    @@ -504,7 +504,7 @@ The dispatch function selects which overload to call (if any) based on the passe typecheck typemaps are used to analyze each argument, as well as assign precedence. See the chapter on typemaps for details.

    -

    31.3.9 C++ operators

    +

    32.3.9 C++ operators

    @@ -608,7 +608,7 @@ On the C++ side, the default mappings are as follows: Octave can also utilise friend (i.e. non-member) operators with a simple %rename: see the example in the Examples/octave/operator directory.

    -

    31.3.10 Class extension with %extend

    +

    32.3.10 Class extension with %extend

    @@ -638,7 +638,7 @@ octave:3> printf("%s\n",a); octave:4> a.__str() 4 -

    31.3.11 C++ templates

    +

    32.3.11 C++ templates

    @@ -715,14 +715,14 @@ ans = -

    31.3.12 C++ Smart Pointers

    +

    32.3.12 C++ Smart Pointers

    C++ smart pointers are fully supported as in other modules.

    -

    31.3.13 Directors (calling Octave from C++ code)

    +

    32.3.13 Directors (calling Octave from C++ code)

    @@ -803,14 +803,14 @@ c-side routine called octave-side routine called -

    31.3.14 Threads

    +

    32.3.14 Threads

    The use of threads in wrapped Director code is not supported; i.e., an Octave-side implementation of a C++ class must be called from the Octave interpreter's thread. Anything fancier (apartment/queue model, whatever) is left to the user. Without anything fancier, this amounts to the limitation that Octave must drive the module... like, for example, an optimization package that calls Octave to evaluate an objective function.

    -

    31.3.15 Memory management

    +

    32.3.15 Memory management

    @@ -844,14 +844,14 @@ The %newobject directive may be used to control this behavior for pointers retur In the case where one wishes for the C++ side to own an object that was created in Octave (especially a Director object), one can use the __disown() method to invert this logic. Then letting the Octave reference count go to zero will not destroy the object, but destroying the object will invalidate the Octave-side object if it still exists (and call destructors of other C++ bases in the case of multiple inheritance/subclass()'ing).

    -

    31.3.16 STL support

    +

    32.3.16 STL support

    Various STL library files are provided for wrapping STL containers.

    -

    31.3.17 Matrix typemaps

    +

    32.3.17 Matrix typemaps

    diff --git a/Doc/Manual/Perl5.html b/Doc/Manual/Perl5.html index 010eb48df..8bc7cbfd3 100644 --- a/Doc/Manual/Perl5.html +++ b/Doc/Manual/Perl5.html @@ -6,7 +6,7 @@ -

    32 SWIG and Perl5

    +

    33 SWIG and Perl5

      @@ -96,7 +96,7 @@ later. We're no longer testing regularly with older versions, but Perl 5.6 seems to mostly work, while older versions don't.

      -

      32.1 Overview

      +

      33.1 Overview

      @@ -117,7 +117,7 @@ described. Advanced customization features, typemaps, and other options are found near the end of the chapter.

      -

      32.2 Preliminaries

      +

      33.2 Preliminaries

      @@ -142,7 +142,7 @@ To build the module, you will need to compile the file example_wrap.c and link it with the rest of your program.

      -

      32.2.1 Getting the right header files

      +

      33.2.1 Getting the right header files

      @@ -174,7 +174,7 @@ $ perl -e 'use Config; print "$Config{archlib}\n";'

    -

    32.2.2 Compiling a dynamic module

    +

    33.2.2 Compiling a dynamic module

    @@ -207,7 +207,7 @@ the target should be named `example.so', `example.sl', or the appropriate dynamic module name on your system.

    -

    32.2.3 Building a dynamic module with MakeMaker

    +

    33.2.3 Building a dynamic module with MakeMaker

    @@ -241,7 +241,7 @@ the preferred approach to compilation. More information about MakeMaker can be found in "Programming Perl, 2nd ed." by Larry Wall, Tom Christiansen, and Randal Schwartz.

    -

    32.2.4 Building a static version of Perl

    +

    33.2.4 Building a static version of Perl

    @@ -310,7 +310,7 @@ added to it. Depending on your machine, you may need to link with additional libraries such as -lsocket, -lnsl, -ldl, etc.

    -

    32.2.5 Using the module

    +

    33.2.5 Using the module

    @@ -463,7 +463,7 @@ system configuration (this requires root access and you will need to read the man pages).

    -

    32.2.6 Compilation problems and compiling with C++

    +

    33.2.6 Compilation problems and compiling with C++

    @@ -606,7 +606,7 @@ have to find the macro that conflicts and add an #undef into the .i file. Pleas any conflicting macros you find to swig-user mailing list.

    -

    32.2.7 Compiling for 64-bit platforms

    +

    33.2.7 Compiling for 64-bit platforms

    @@ -633,7 +633,7 @@ also introduce problems on platforms that support more than one linking standard (e.g., -o32 and -n32 on Irix).

    -

    32.3 Building Perl Extensions under Windows

    +

    33.3 Building Perl Extensions under Windows

    @@ -644,7 +644,7 @@ section assumes you are using SWIG with Microsoft Visual C++ although the procedure may be similar with other compilers.

    -

    32.3.1 Running SWIG from Developer Studio

    +

    33.3.1 Running SWIG from Developer Studio

    @@ -707,7 +707,7 @@ print "$a\n"; -

    32.3.2 Using other compilers

    +

    33.3.2 Using other compilers

    @@ -715,7 +715,7 @@ SWIG is known to work with Cygwin and may work with other compilers on Windows. For general hints and suggestions refer to the Windows chapter.

    -

    32.4 The low-level interface

    +

    33.4 The low-level interface

    @@ -725,7 +725,7 @@ can be used to control your application. However, it is also used to construct more user-friendly proxy classes as described in the next section.

    -

    32.4.1 Functions

    +

    33.4.1 Functions

    @@ -748,7 +748,7 @@ use example; $a = &example::fact(2); -

    32.4.2 Global variables

    +

    33.4.2 Global variables

    @@ -818,7 +818,7 @@ extern char *path; // Declared later in the input -

    32.4.3 Constants

    +

    33.4.3 Constants

    @@ -858,7 +858,7 @@ print example::FOO,"\n"; -

    32.4.4 Pointers

    +

    33.4.4 Pointers

    @@ -967,7 +967,7 @@ as XS and xsubpp. Given the advancement of the SWIG typesystem and the SWIG and XS, this is no longer supported.

    -

    32.4.5 Structures

    +

    33.4.5 Structures

    @@ -1101,7 +1101,7 @@ void Bar_f_set(Bar *b, Foo *val) { -

    32.4.6 C++ classes

    +

    33.4.6 C++ classes

    @@ -1166,7 +1166,7 @@ provides direct access to C++ objects. A higher level interface using Perl prox can be built using these low-level accessors. This is described shortly.

    -

    32.4.7 C++ classes and type-checking

    +

    33.4.7 C++ classes and type-checking

    @@ -1202,7 +1202,7 @@ If necessary, the type-checker also adjusts the value of the pointer (as is nece multiple inheritance is used).

    -

    32.4.8 C++ overloaded functions

    +

    33.4.8 C++ overloaded functions

    @@ -1246,7 +1246,7 @@ example::Spam_foo_d($s,3.14); Please refer to the "SWIG Basics" chapter for more information.

    -

    32.4.9 Operators

    +

    33.4.9 Operators

    @@ -1273,7 +1273,7 @@ The following C++ operators are currently supported by the Perl module:

  • operator or
  • -

    32.4.10 Modules and packages

    +

    33.4.10 Modules and packages

    @@ -1368,7 +1368,7 @@ print Foo::fact(4),"\n"; # Call a function in package FooBar --> -

    32.5 Input and output parameters

    +

    33.5 Input and output parameters

    @@ -1587,7 +1587,7 @@ print "$c\n"; Note: The REFERENCE feature is only currently supported for numeric types (integers and floating point).

    -

    32.6 Exception handling

    +

    33.6 Exception handling

    @@ -1752,7 +1752,7 @@ This is still supported, but it is deprecated. The newer %exception di functionality, but it has additional capabilities that make it more powerful.

    -

    32.7 Remapping datatypes with typemaps

    +

    33.7 Remapping datatypes with typemaps

    @@ -1769,7 +1769,7 @@ Typemaps are only used if you want to change some aspect of the primitive C-Perl interface.

    -

    32.7.1 A simple typemap example

    +

    33.7.1 A simple typemap example

    @@ -1873,7 +1873,7 @@ example::count("e","Hello World"); -

    32.7.2 Perl5 typemaps

    +

    33.7.2 Perl5 typemaps

    @@ -1978,7 +1978,7 @@ Return of C++ member data (all languages). Check value of input parameter. -

    32.7.3 Typemap variables

    +

    33.7.3 Typemap variables

    @@ -2049,7 +2049,7 @@ properly assigned. The Perl name of the wrapper function being created. -

    32.7.4 Useful functions

    +

    33.7.4 Useful functions

    @@ -2118,7 +2118,7 @@ int sv_isa(SV *, char *0; -

    32.8 Typemap Examples

    +

    33.8 Typemap Examples

    @@ -2127,7 +2127,7 @@ might look at the files "perl5.swg" and "typemaps.i" in the SWIG library.

    -

    32.8.1 Converting a Perl5 array to a char **

    +

    33.8.1 Converting a Perl5 array to a char **

    @@ -2219,7 +2219,7 @@ print @$b,"\n"; # Print it out -

    32.8.2 Return values

    +

    33.8.2 Return values

    @@ -2248,7 +2248,7 @@ can be done using the EXTEND() macro as in: } -

    32.8.3 Returning values from arguments

    +

    33.8.3 Returning values from arguments

    @@ -2302,7 +2302,7 @@ print "multout(7,13) = @r\n"; ($x,$y) = multout(7,13); -

    32.8.4 Accessing array structure members

    +

    33.8.4 Accessing array structure members

    @@ -2365,7 +2365,7 @@ the "in" typemap in the previous section would be used to convert an to copy the converted array into a C data structure.

    -

    32.8.5 Turning Perl references into C pointers

    +

    33.8.5 Turning Perl references into C pointers

    @@ -2430,7 +2430,7 @@ print "$c\n"; -

    32.8.6 Pointer handling

    +

    33.8.6 Pointer handling

    @@ -2509,7 +2509,7 @@ For example: -

    32.9 Proxy classes

    +

    33.9 Proxy classes

    @@ -2525,7 +2525,7 @@ to the underlying code. This section describes the implementation details of the proxy interface.

    -

    32.9.1 Preliminaries

    +

    33.9.1 Preliminaries

    @@ -2547,7 +2547,7 @@ SWIG creates a collection of high-level Perl wrappers. In your scripts, you wil high level wrappers. The wrappers, in turn, interact with the low-level procedural module.

    -

    32.9.2 Structure and class wrappers

    +

    33.9.2 Structure and class wrappers

    @@ -2673,7 +2673,7 @@ $v->DESTROY(); -

    32.9.3 Object Ownership

    +

    33.9.3 Object Ownership

    @@ -2760,7 +2760,7 @@ counting, garbage collection, or advanced features one might find in sophisticated languages.

    -

    32.9.4 Nested Objects

    +

    33.9.4 Nested Objects

    @@ -2813,7 +2813,7 @@ $p->{f}->{x} = 0.0; %${$p->{v}} = ( x=>0, y=>0, z=>0); -

    32.9.5 Proxy Functions

    +

    33.9.5 Proxy Functions

    @@ -2847,7 +2847,7 @@ This function replaces the original function, but operates in an identical manner.

    -

    32.9.6 Inheritance

    +

    33.9.6 Inheritance

    @@ -2923,7 +2923,7 @@ particular, inheritance of data members is extremely tricky (and I'm not even sure if it really works).

    -

    32.9.7 Modifying the proxy methods

    +

    33.9.7 Modifying the proxy methods

    @@ -2951,7 +2951,7 @@ public: }; -

    32.10 Adding additional Perl code

    +

    33.10 Adding additional Perl code

    @@ -3002,7 +3002,7 @@ set_transform($im, $a); -

    32.11 Cross language polymorphism

    +

    33.11 Cross language polymorphism

    @@ -3036,7 +3036,7 @@ proxy classes, director classes, and C wrapper functions takes care of all the cross-language method routing transparently.

    -

    32.11.1 Enabling directors

    +

    33.11.1 Enabling directors

    @@ -3126,7 +3126,7 @@ sub one { -

    32.11.2 Director classes

    +

    33.11.2 Director classes

    @@ -3206,7 +3206,7 @@ so there is no need for the extra overhead involved with routing the calls through Perl.

    -

    32.11.3 Ownership and object destruction

    +

    33.11.3 Ownership and object destruction

    @@ -3255,7 +3255,7 @@ sub DESTROY { -

    32.11.4 Exception unrolling

    +

    33.11.4 Exception unrolling

    @@ -3311,7 +3311,7 @@ Swig::DirectorMethodException is thrown, Perl will register the exception as soon as the C wrapper function returns.

    -

    32.11.5 Overhead and code bloat

    +

    33.11.5 Overhead and code bloat

    @@ -3345,7 +3345,7 @@ directive) for only those methods that are likely to be extended in Perl.

    -

    32.11.6 Typemaps

    +

    33.11.6 Typemaps

    diff --git a/Doc/Manual/Php.html b/Doc/Manual/Php.html index 493c861f8..7e5cccf6a 100644 --- a/Doc/Manual/Php.html +++ b/Doc/Manual/Php.html @@ -7,7 +7,7 @@ -

    33 SWIG and PHP

    +

    34 SWIG and PHP

      @@ -79,7 +79,7 @@ your extension into php directly, you will need the complete PHP source tree available.

      -

      33.1 Generating PHP Extensions

      +

      34.1 Generating PHP Extensions

      @@ -126,7 +126,7 @@ and it doesn't play nicely with package system. We don't recommend this approach, or provide explicit support for it.

      -

      33.1.1 Building a loadable extension

      +

      34.1.1 Building a loadable extension

      @@ -141,7 +141,7 @@ least work for Linux though): gcc -shared example_wrap.o -o example.so

    -

    33.1.2 Using PHP Extensions

    +

    34.1.2 Using PHP Extensions

    @@ -172,7 +172,7 @@ attempts to do the dl() call for you: include("example.php"); -

    33.2 Basic PHP interface

    +

    34.2 Basic PHP interface

    @@ -183,7 +183,7 @@ other symbols unless care is taken to %rename them. At present SWIG doesn't have support for the namespace feature added in PHP 5.3.

    -

    33.2.1 Constants

    +

    34.2.1 Constants

    @@ -260,7 +260,7 @@ is treated as true by the if test, when the value of the intended constant would be treated as false!

    -

    33.2.2 Global Variables

    +

    34.2.2 Global Variables

    @@ -309,7 +309,7 @@ undefined. At this time SWIG does not support custom accessor methods.

    -

    33.2.3 Functions

    +

    34.2.3 Functions

    @@ -362,7 +362,7 @@ print $s; # The value of $s was not changed. --> -

    33.2.4 Overloading

    +

    34.2.4 Overloading

    @@ -418,7 +418,7 @@ taking the integer argument.

    --> -

    33.2.5 Pointers and References

    +

    34.2.5 Pointers and References

    @@ -563,7 +563,7 @@ PHP in a number of ways: by using unset on an existing variable, or assigning NULL to a variable.

    -

    33.2.6 Structures and C++ classes

    +

    34.2.6 Structures and C++ classes

    @@ -624,7 +624,7 @@ Would be used in the following way from PHP5: Member variables and methods are accessed using the -> operator.

    -

    33.2.6.1 Using -noproxy

    +

    34.2.6.1 Using -noproxy

    @@ -650,7 +650,7 @@ Complex_im_set($obj,$d); Complex_im_get($obj); -

    33.2.6.2 Constructors and Destructors

    +

    34.2.6.2 Constructors and Destructors

    @@ -691,7 +691,7 @@ the programmer can either reassign the variable or call unset($v)

    -

    33.2.6.3 Static Member Variables

    +

    34.2.6.3 Static Member Variables

    @@ -734,7 +734,7 @@ Ko::threats(10); echo "There have now been " . Ko::threats() . " threats\n"; -

    33.2.6.4 Static Member Functions

    +

    34.2.6.4 Static Member Functions

    @@ -756,7 +756,7 @@ Ko::threats(); -

    33.2.7 PHP Pragmas, Startup and Shutdown code

    +

    34.2.7 PHP Pragmas, Startup and Shutdown code

    @@ -844,7 +844,7 @@ The %rinit and %rshutdown statements are very similar but inse into the request init (PHP_RINIT_FUNCTION) and request shutdown (PHP_RSHUTDOWN_FUNCTION) code respectively.

    -

    33.3 Cross language polymorphism

    +

    34.3 Cross language polymorphism

    @@ -879,7 +879,7 @@ wrapper functions takes care of all the cross-language method routing transparently.

    -

    33.3.1 Enabling directors

    +

    34.3.1 Enabling directors

    @@ -968,7 +968,7 @@ class MyFoo extends Foo { -

    33.3.2 Director classes

    +

    34.3.2 Director classes

    @@ -1048,7 +1048,7 @@ so there is no need for the extra overhead involved with routing the calls through PHP.

    -

    33.3.3 Ownership and object destruction

    +

    34.3.3 Ownership and object destruction

    @@ -1104,7 +1104,7 @@ In this example, we are assuming that FooContainer will take care of deleting all the Foo pointers it contains at some point.

    -

    33.3.4 Exception unrolling

    +

    34.3.4 Exception unrolling

    @@ -1163,7 +1163,7 @@ Swig::DirectorMethodException is thrown, PHP will register the exception as soon as the C wrapper function returns.

    -

    33.3.5 Overhead and code bloat

    +

    34.3.5 Overhead and code bloat

    @@ -1196,7 +1196,7 @@ optimized by selectively enabling director methods (using the %feature directive) for only those methods that are likely to be extended in PHP.

    -

    33.3.6 Typemaps

    +

    34.3.6 Typemaps

    @@ -1210,7 +1210,7 @@ need to be supported.

    -

    33.3.7 Miscellaneous

    +

    34.3.7 Miscellaneous

    Director typemaps for STL classes are mostly in place, and hence you diff --git a/Doc/Manual/Pike.html b/Doc/Manual/Pike.html index 3ede1a992..44c6930f8 100644 --- a/Doc/Manual/Pike.html +++ b/Doc/Manual/Pike.html @@ -6,7 +6,7 @@ -

    34 SWIG and Pike

    +

    35 SWIG and Pike

      @@ -46,10 +46,10 @@ least, make sure you read the "SWIG Basics" chapter.

      -

      34.1 Preliminaries

      +

      35.1 Preliminaries

      -

      34.1.1 Running SWIG

      +

      35.1.1 Running SWIG

      @@ -94,7 +94,7 @@ can use the -o option:

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

      34.1.2 Getting the right header files

      +

      35.1.2 Getting the right header files

      @@ -114,7 +114,7 @@ You're looking for files with the names global.h, program.h and so on.

      -

      34.1.3 Using your module

      +

      35.1.3 Using your module

      @@ -129,10 +129,10 @@ Pike v7.4 release 10 running Hilfe v3.5 (Incremental Pike Frontend) (1) Result: 24

    -

    34.2 Basic C/C++ Mapping

    +

    35.2 Basic C/C++ Mapping

    -

    34.2.1 Modules

    +

    35.2.1 Modules

    @@ -143,7 +143,7 @@ concerned), SWIG's %module directive doesn't really have any significance.

    -

    34.2.2 Functions

    +

    35.2.2 Functions

    @@ -168,7 +168,7 @@ exactly as you'd expect it to: (1) Result: 24 -

    34.2.3 Global variables

    +

    35.2.3 Global variables

    @@ -197,7 +197,7 @@ will result in two functions, Foo_get() and Foo_set(): (3) Result: 3.141590 -

    34.2.4 Constants and enumerated types

    +

    35.2.4 Constants and enumerated types

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

    -

    34.2.5 Constructors and Destructors

    +

    35.2.5 Constructors and Destructors

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

    -

    34.2.6 Static Members

    +

    35.2.6 Static Members

    diff --git a/Doc/Manual/Python.html b/Doc/Manual/Python.html index 9b86652f4..bdb1ada30 100644 --- a/Doc/Manual/Python.html +++ b/Doc/Manual/Python.html @@ -6,7 +6,7 @@ -

    35 SWIG and Python

    +

    36 SWIG and Python

      @@ -141,7 +141,7 @@ very least, make sure you read the "SWIG Basics" chapter.

      -

      35.1 Overview

      +

      36.1 Overview

      @@ -168,10 +168,10 @@ described followed by a discussion of low-level implementation details.

      -

      35.2 Preliminaries

      +

      36.2 Preliminaries

      -

      35.2.1 Running SWIG

      +

      36.2.1 Running SWIG

      @@ -269,7 +269,7 @@ The following sections have further practical examples and details on how you might go about compiling and using the generated files.

      -

      35.2.2 Using distutils

      +

      36.2.2 Using distutils

      @@ -361,7 +361,7 @@ This same approach works on all platforms if the appropriate compiler is install can even build extensions to the standard Windows Python using MingGW)

      -

      35.2.3 Hand compiling a dynamic module

      +

      36.2.3 Hand compiling a dynamic module

      @@ -409,7 +409,7 @@ module actually consists of two files; socket.py and

      -

      35.2.4 Static linking

      +

      36.2.4 Static linking

      @@ -488,7 +488,7 @@ If using static linking, you might want to rely on a different approach (perhaps using distutils).

      -

      35.2.5 Using your module

      +

      36.2.5 Using your module

      @@ -645,7 +645,7 @@ system configuration (this requires root access and you will need to read the man pages).

      -

      35.2.6 Compilation of C++ extensions

      +

      36.2.6 Compilation of C++ extensions

      @@ -737,7 +737,7 @@ erratic program behavior. If working with lots of software components, you might want to investigate using a more formal standard such as COM.

      -

      35.2.7 Compiling for 64-bit platforms

      +

      36.2.7 Compiling for 64-bit platforms

      @@ -774,7 +774,7 @@ and -m64 allow you to choose the desired binary format for your python extension.

      -

      35.2.8 Building Python Extensions under Windows

      +

      36.2.8 Building Python Extensions under Windows

      @@ -903,7 +903,7 @@ SWIG Wiki.

      -

      35.3 A tour of basic C/C++ wrapping

      +

      36.3 A tour of basic C/C++ wrapping

      @@ -912,7 +912,7 @@ to your C/C++ code. Functions are wrapped as functions, classes are wrapped as This section briefly covers the essential aspects of this wrapping.

      -

      35.3.1 Modules

      +

      36.3.1 Modules

      @@ -925,7 +925,7 @@ module name, make sure you don't use the same name as a built-in Python command or standard module name.

      -

      35.3.2 Functions

      +

      36.3.2 Functions

      @@ -949,7 +949,7 @@ like you think it does: >>>

    -

    35.3.3 Global variables

    +

    36.3.3 Global variables

    @@ -1087,7 +1087,7 @@ that starts with a leading underscore. SWIG does not create cvar if there are no global variables in a module.

    -

    35.3.4 Constants and enums

    +

    36.3.4 Constants and enums

    @@ -1127,7 +1127,7 @@ other object. Unfortunately, there is no easy way for SWIG to generate code that prevents this. You will just have to be careful.

    -

    35.3.5 Pointers

    +

    36.3.5 Pointers

    @@ -1268,7 +1268,7 @@ C-style cast may return a bogus result whereas as the C++-style cast will return None if the conversion can't be performed.

    -

    35.3.6 Structures

    +

    36.3.6 Structures

    @@ -1457,7 +1457,7 @@ everything works just like you would expect. For example: -

    35.3.7 C++ classes

    +

    36.3.7 C++ classes

    @@ -1546,7 +1546,7 @@ they are accessed through cvar like this: -

    35.3.8 C++ inheritance

    +

    36.3.8 C++ inheritance

    @@ -1601,7 +1601,7 @@ then the function spam() accepts Foo * or a pointer to any cla It is safe to use multiple inheritance with SWIG.

    -

    35.3.9 Pointers, references, values, and arrays

    +

    36.3.9 Pointers, references, values, and arrays

    @@ -1662,7 +1662,7 @@ treated as a returning value, and it will follow the same allocation/deallocation process.

    -

    35.3.10 C++ overloaded functions

    +

    36.3.10 C++ overloaded functions

    @@ -1785,7 +1785,7 @@ first declaration takes precedence. Please refer to the "SWIG and C++" chapter for more information about overloading.

    -

    35.3.11 C++ operators

    +

    36.3.11 C++ operators

    @@ -1874,7 +1874,7 @@ Also, be aware that certain operators don't map cleanly to Python. For instance overloaded assignment operators don't map to Python semantics and will be ignored.

    -

    35.3.12 C++ namespaces

    +

    36.3.12 C++ namespaces

    @@ -1941,7 +1941,7 @@ utilizes thousands of small deeply nested namespaces each with identical symbol names, well, then you get what you deserve.

    -

    35.3.13 C++ templates

    +

    36.3.13 C++ templates

    @@ -1995,7 +1995,7 @@ Some more complicated examples will appear later.

    -

    35.3.14 C++ Smart Pointers

    +

    36.3.14 C++ Smart Pointers

    @@ -2079,7 +2079,7 @@ simply use the __deref__() method. For example: -

    35.3.15 C++ reference counted objects

    +

    36.3.15 C++ reference counted objects

    @@ -2088,7 +2088,7 @@ Python examples of memory management using referencing counting.

    -

    35.4 Further details on the Python class interface

    +

    36.4 Further details on the Python class interface

    @@ -2111,7 +2111,7 @@ the -builtin option are in the Built-in section.

    -

    35.4.1 Proxy classes

    +

    36.4.1 Proxy classes

    @@ -2200,7 +2200,7 @@ you can attach new Python methods to the class and you can even inherit from it by Python built-in types until Python 2.2).

    -

    35.4.2 Built-in Types

    +

    36.4.2 Built-in Types

    @@ -2244,7 +2244,7 @@ please refer to the python documentation:

    http://docs.python.org/extending/newtypes.html

    -

    35.4.2.1 Limitations

    +

    36.4.2.1 Limitations

    Use of the -builtin option implies a couple of limitations: @@ -2412,7 +2412,7 @@ assert(issubclass(B.Derived, A.Base)) -

    35.4.2.2 Operator overloads -- use them!

    +

    36.4.2.2 Operator overloads -- use them!

    The entire justification for the -builtin option is improved @@ -2513,7 +2513,7 @@ structs.

    -

    35.4.3 Memory management

    +

    36.4.3 Memory management

    NOTE: Although this section refers to proxy objects, everything here also applies @@ -2708,7 +2708,7 @@ It is also possible to deal with situations like this using typemaps--an advanced topic discussed later.

    -

    35.4.4 Python 2.2 and classic classes

    +

    36.4.4 Python 2.2 and classic classes

    @@ -2745,7 +2745,7 @@ class itself. In Python-2.1 and earlier, they have to be accessed as a global function or through an instance (see the earlier section).

    -

    35.5 Cross language polymorphism

    +

    36.5 Cross language polymorphism

    @@ -2779,7 +2779,7 @@ proxy classes, director classes, and C wrapper functions takes care of all the cross-language method routing transparently.

    -

    35.5.1 Enabling directors

    +

    36.5.1 Enabling directors

    @@ -2869,7 +2869,7 @@ class MyFoo(mymodule.Foo): -

    35.5.2 Director classes

    +

    36.5.2 Director classes

    @@ -2951,7 +2951,7 @@ so there is no need for the extra overhead involved with routing the calls through Python.

    -

    35.5.3 Ownership and object destruction

    +

    36.5.3 Ownership and object destruction

    @@ -3018,7 +3018,7 @@ deleting all the Foo pointers it contains at some point. Note that no hard references to the Foo objects remain in Python.

    -

    35.5.4 Exception unrolling

    +

    36.5.4 Exception unrolling

    @@ -3077,7 +3077,7 @@ Swig::DirectorMethodException is thrown, Python will register the exception as soon as the C wrapper function returns.

    -

    35.5.5 Overhead and code bloat

    +

    36.5.5 Overhead and code bloat

    @@ -3111,7 +3111,7 @@ directive) for only those methods that are likely to be extended in Python.

    -

    35.5.6 Typemaps

    +

    36.5.6 Typemaps

    @@ -3125,7 +3125,7 @@ need to be supported.

    -

    35.5.7 Miscellaneous

    +

    36.5.7 Miscellaneous

    @@ -3172,7 +3172,7 @@ methods that return const references.

    -

    35.6 Common customization features

    +

    36.6 Common customization features

    @@ -3185,7 +3185,7 @@ This section describes some common SWIG features that are used to improve your the interface to an extension module.

    -

    35.6.1 C/C++ helper functions

    +

    36.6.1 C/C++ helper functions

    @@ -3266,7 +3266,7 @@ hard to implement. It is possible to clean this up using Python code, typemaps, customization features as covered in later sections.

    -

    35.6.2 Adding additional Python code

    +

    36.6.2 Adding additional Python code

    @@ -3494,7 +3494,7 @@ The same applies for overloaded constructors.

    -

    35.6.3 Class extension with %extend

    +

    36.6.3 Class extension with %extend

    @@ -3583,7 +3583,7 @@ Vector(12,14,16) in any way---the extensions only show up in the Python interface.

    -

    35.6.4 Exception handling with %exception

    +

    36.6.4 Exception handling with %exception

    @@ -3709,7 +3709,7 @@ The language-independent exception.i library file can also be used to raise exceptions. See the SWIG Library chapter.

    -

    35.7 Tips and techniques

    +

    36.7 Tips and techniques

    @@ -3719,7 +3719,7 @@ strings, binary data, and arrays. This chapter discusses the common techniques solving these problems.

    -

    35.7.1 Input and output parameters

    +

    36.7.1 Input and output parameters

    @@ -3932,7 +3932,7 @@ void foo(Bar *OUTPUT); may not have the intended effect since typemaps.i does not define an OUTPUT rule for Bar.

    -

    35.7.2 Simple pointers

    +

    36.7.2 Simple pointers

    @@ -4001,7 +4001,7 @@ If you replace %pointer_functions() by %pointer_class(type,name)SWIG Library chapter for further details.

    -

    35.7.3 Unbounded C Arrays

    +

    36.7.3 Unbounded C Arrays

    @@ -4063,7 +4063,7 @@ well suited for applications in which you need to create buffers, package binary data, etc.

    -

    35.7.4 String handling

    +

    36.7.4 String handling

    @@ -4132,7 +4132,7 @@ If you need to return binary data, you might use the also be used to extra binary data from arbitrary pointers.

    -

    35.8 Typemaps

    +

    36.8 Typemaps

    @@ -4149,7 +4149,7 @@ Typemaps are only used if you want to change some aspect of the primitive C-Python interface or if you want to elevate your guru status.

    -

    35.8.1 What is a typemap?

    +

    36.8.1 What is a typemap?

    @@ -4265,7 +4265,7 @@ parameter is omitted): -

    35.8.2 Python typemaps

    +

    36.8.2 Python typemaps

    @@ -4306,7 +4306,7 @@ a look at the SWIG library version 1.3.20 or so.

    -

    35.8.3 Typemap variables

    +

    36.8.3 Typemap variables

    @@ -4377,7 +4377,7 @@ properly assigned. The Python name of the wrapper function being created. -

    35.8.4 Useful Python Functions

    +

    36.8.4 Useful Python Functions

    @@ -4505,7 +4505,7 @@ write me -

    35.9 Typemap Examples

    +

    36.9 Typemap Examples

    @@ -4514,7 +4514,7 @@ might look at the files "python.swg" and "typemaps.i" in the SWIG library.

    -

    35.9.1 Converting Python list to a char **

    +

    36.9.1 Converting Python list to a char **

    @@ -4594,7 +4594,7 @@ memory allocation is used to allocate memory for the array, the the C function.

    -

    35.9.2 Expanding a Python object into multiple arguments

    +

    36.9.2 Expanding a Python object into multiple arguments

    @@ -4673,7 +4673,7 @@ to supply the argument count. This is automatically set by the typemap code. F -

    35.9.3 Using typemaps to return arguments

    +

    36.9.3 Using typemaps to return arguments

    @@ -4761,7 +4761,7 @@ function can now be used as follows: >>> -

    35.9.4 Mapping Python tuples into small arrays

    +

    36.9.4 Mapping Python tuples into small arrays

    @@ -4810,7 +4810,7 @@ array, such an approach would not be recommended for huge arrays, but for small structures, this approach works fine.

    -

    35.9.5 Mapping sequences to C arrays

    +

    36.9.5 Mapping sequences to C arrays

    @@ -4899,7 +4899,7 @@ static int convert_darray(PyObject *input, double *ptr, int size) { -

    35.9.6 Pointer handling

    +

    36.9.6 Pointer handling

    @@ -4996,7 +4996,7 @@ class object (if applicable). -

    35.10 Docstring Features

    +

    36.10 Docstring Features

    @@ -5024,7 +5024,7 @@ of your users much simpler.

    -

    35.10.1 Module docstring

    +

    36.10.1 Module docstring

    @@ -5058,7 +5058,7 @@ layout of controls on a panel, etc. to be loaded from an XML file." -

    35.10.2 %feature("autodoc")

    +

    36.10.2 %feature("autodoc")

    @@ -5086,7 +5086,7 @@ four levels for autodoc controlled by the value given to the feature, %feature("autodoc", "level"). The four values for level are covered in the following sub-sections. -

    35.10.2.1 %feature("autodoc", "0")

    +

    36.10.2.1 %feature("autodoc", "0")

    @@ -5115,7 +5115,7 @@ def function_name(*args, **kwargs): -

    35.10.2.2 %feature("autodoc", "1")

    +

    36.10.2.2 %feature("autodoc", "1")

    @@ -5140,7 +5140,7 @@ def function_name(*args, **kwargs): -

    35.10.2.3 %feature("autodoc", "2")

    +

    36.10.2.3 %feature("autodoc", "2")

    @@ -5200,7 +5200,7 @@ def function_name(*args, **kwargs): -

    35.10.2.4 %feature("autodoc", "3")

    +

    36.10.2.4 %feature("autodoc", "3")

    @@ -5225,7 +5225,7 @@ def function_name(*args, **kwargs): -

    35.10.2.5 %feature("autodoc", "docstring")

    +

    36.10.2.5 %feature("autodoc", "docstring")

    @@ -5244,7 +5244,7 @@ void GetPosition(int* OUTPUT, int* OUTPUT); -

    35.10.3 %feature("docstring")

    +

    36.10.3 %feature("docstring")

    @@ -5276,7 +5276,7 @@ with more than one line. -

    35.11 Python Packages

    +

    36.11 Python Packages

    Python has concepts of modules and packages. Modules are separate units of @@ -5334,7 +5334,7 @@ users may need to use special features such as the package option in th %module directive or import related command line options. These are explained in the following sections.

    -

    35.11.1 Setting the Python package

    +

    36.11.1 Setting the Python package

    @@ -5388,7 +5388,7 @@ pkg1/pkg2/_foo.so # (shared library built from C/C++ code generated by SWI -

    35.11.2 Absolute and relative imports

    +

    36.11.2 Absolute and relative imports

    Suppose, we have the following hierarchy of files:

    @@ -5527,7 +5527,7 @@ 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).

    -

    35.11.3 Enforcing absolute import semantics

    +

    36.11.3 Enforcing absolute import semantics

    As you may know, there is an incompatibility in import semantics (for the @@ -5564,7 +5564,7 @@ from __future__ import absolute_import -

    35.11.4 Importing from __init__.py

    +

    36.11.4 Importing from __init__.py

    Imports in __init__.py are handy when you want to populate a @@ -5675,7 +5675,7 @@ effect (note, that the Python 2 case also needs the -relativeimport workaround).

    -

    35.12 Python 3 Support

    +

    36.12 Python 3 Support

    @@ -5702,7 +5702,7 @@ The following are Python 3.0 new features that are currently supported by SWIG.

    -

    35.12.1 Function annotation

    +

    36.12.1 Function annotation

    @@ -5735,7 +5735,7 @@ For detailed usage of function annotation, see PEP 3107.

    -

    35.12.2 Buffer interface

    +

    36.12.2 Buffer interface

    @@ -5887,7 +5887,7 @@ modify the buffer. -

    35.12.3 Abstract base classes

    +

    36.12.3 Abstract base classes

    diff --git a/Doc/Manual/R.html b/Doc/Manual/R.html index ce9523ced..5de390eab 100644 --- a/Doc/Manual/R.html +++ b/Doc/Manual/R.html @@ -6,7 +6,7 @@ -

    36 SWIG and R

    +

    37 SWIG and R

      @@ -33,7 +33,7 @@ compile and run an R interface to QuantLib running on Mandriva Linux with gcc. The R bindings also work on Microsoft Windows using Visual C++.

      -

      36.1 Bugs

      +

      37.1 Bugs

      @@ -45,7 +45,7 @@ Currently the following features are not implemented or broken:

    • C Array wrappings
    -

    36.2 Using R and SWIG

    +

    37.2 Using R and SWIG

    @@ -119,7 +119,7 @@ Without it, inheritance of wrapped objects may fail. These two files can be loaded in any order

    -

    36.3 Precompiling large R files

    +

    37.3 Precompiling large R files

    In cases where the R file is large, one make save a lot of loading @@ -137,7 +137,7 @@ will save a large amount of loading time. -

    36.4 General policy

    +

    37.4 General policy

    @@ -146,7 +146,7 @@ wrapping over the underlying functions and rely on the R type system to provide R syntax.

    -

    36.5 Language conventions

    +

    37.5 Language conventions

    @@ -155,7 +155,7 @@ and [ are overloaded to allow for R syntax (one based indices and slices)

    -

    36.6 C++ classes

    +

    37.6 C++ classes

    @@ -167,7 +167,7 @@ keep track of the pointer object which removes the necessity for a lot of the proxy class baggage you see in other languages.

    -

    36.7 Enumerations

    +

    37.7 Enumerations

    diff --git a/Doc/Manual/Ruby.html b/Doc/Manual/Ruby.html index 9719239a9..cdebfe07b 100644 --- a/Doc/Manual/Ruby.html +++ b/Doc/Manual/Ruby.html @@ -7,7 +7,7 @@ -

    37 SWIG and Ruby

    +

    38 SWIG and Ruby

      @@ -144,7 +144,7 @@

      This chapter describes SWIG's support of Ruby.

      -

      37.1 Preliminaries

      +

      38.1 Preliminaries

      SWIG 1.3 is known to work with Ruby versions 1.6 and later. @@ -159,7 +159,7 @@ read the "SWIG Basics" chapter. It is also assumed that the reader has a basic understanding of Ruby.

      -

      37.1.1 Running SWIG

      +

      38.1.1 Running SWIG

      To build a Ruby module, run SWIG using the -ruby @@ -183,7 +183,7 @@ if compiling a C++ extension) that contains all of the code needed to build a Ruby extension module. To finish building the module, you need to compile this file and link it with the rest of your program.

      -

      37.1.2 Getting the right header files

      +

      38.1.2 Getting the right header files

      In order to compile the wrapper code, the compiler needs the ruby.h @@ -206,7 +206,7 @@ installed, you can run Ruby to find out. For example:

    -

    37.1.3 Compiling a dynamic module

    +

    38.1.3 Compiling a dynamic module

    Ruby extension modules are typically compiled into shared @@ -279,7 +279,7 @@ manual pages for your compiler and linker to determine the correct set of options. You might also check the SWIG Wiki for additional information.

    -

    37.1.4 Using your module

    +

    38.1.4 Using your module

    Ruby module names must be capitalized, @@ -309,7 +309,7 @@ begins with:

    will result in an extension module using the feature name "example" and Ruby module name "Example".

    -

    37.1.5 Static linking

    +

    38.1.5 Static linking

    An alternative approach to dynamic linking is to rebuild the @@ -324,7 +324,7 @@ finding the Ruby source, adding an entry to the ext/Setup file, adding your directory to the list of extensions in the file, and finally rebuilding Ruby.

    -

    37.1.6 Compilation of C++ extensions

    +

    38.1.6 Compilation of C++ extensions

    On most machines, C++ extension modules should be linked @@ -356,7 +356,7 @@ $libs = append_library($libs, "supc++") create_makefile('example')

    -

    37.2 Building Ruby Extensions under Windows 95/NT

    +

    38.2 Building Ruby Extensions under Windows 95/NT

    Building a SWIG extension to Ruby under Windows 95/NT is @@ -381,7 +381,7 @@ order to build extensions, you may need to download the source distribution to the Ruby package, as you will need the Ruby header files.

    -

    37.2.1 Running SWIG from Developer Studio

    +

    38.2.1 Running SWIG from Developer Studio

    If you are developing your application within Microsoft @@ -445,13 +445,13 @@ Foo = 3.0 -

    37.3 The Ruby-to-C/C++ Mapping

    +

    38.3 The Ruby-to-C/C++ Mapping

    This section describes the basics of how SWIG maps C or C++ declarations in your SWIG interface files to Ruby constructs.

    -

    37.3.1 Modules

    +

    38.3.1 Modules

    The SWIG %module directive specifies @@ -523,7 +523,7 @@ option to wrap everything into the global module, take care that the names of your constants, classes and methods don't conflict with any of Ruby's built-in names.

    -

    37.3.2 Functions

    +

    38.3.2 Functions

    Global functions are wrapped as Ruby module methods. For @@ -557,7 +557,7 @@ irb(main):002:0> Example.fact(4) 24 -

    37.3.3 Variable Linking

    +

    38.3.3 Variable Linking

    C/C++ global variables are wrapped as a pair of singleton @@ -619,7 +619,7 @@ directive. For example:

    effect until it is explicitly disabled using %mutable.

    -

    37.3.4 Constants

    +

    38.3.4 Constants

    C/C++ constants are wrapped as module constants initialized @@ -647,7 +647,7 @@ irb(main):002:0> Example::PI 3.14159 -

    37.3.5 Pointers

    +

    38.3.5 Pointers

    "Opaque" pointers to arbitrary C/C++ types (i.e. types that @@ -671,7 +671,7 @@ returns an instance of an internally generated Ruby class:

    A NULL pointer is always represented by the Ruby nil object.

    -

    37.3.6 Structures

    +

    38.3.6 Structures

    C/C++ structs are wrapped as Ruby classes, with accessor @@ -776,7 +776,7 @@ void Bar_f_set(Bar *b, Foo *val) { } -

    37.3.7 C++ classes

    +

    38.3.7 C++ classes

    Like structs, C++ classes are wrapped by creating a new Ruby @@ -831,7 +831,7 @@ Ale 3 -

    37.3.8 C++ Inheritance

    +

    38.3.8 C++ Inheritance

    The SWIG type-checker is fully aware of C++ inheritance. @@ -984,7 +984,7 @@ inherit from both Base1 and Base2 (i.e. they exhibit "Duck Typing").

    -

    37.3.9 C++ Overloaded Functions

    +

    38.3.9 C++ Overloaded Functions

    C++ overloaded functions, methods, and constructors are @@ -1074,7 +1074,7 @@ arises--in this case, the first declaration takes precedence.

    Please refer to the "SWIG and C++" chapter for more information about overloading.

    -

    37.3.10 C++ Operators

    +

    38.3.10 C++ Operators

    For the most part, overloaded operators are handled @@ -1116,7 +1116,7 @@ c = Example.add_complex(a, b) is discussed in the section on operator overloading.

    -

    37.3.11 C++ namespaces

    +

    38.3.11 C++ namespaces

    SWIG is aware of C++ namespaces, but namespace names do not @@ -1173,7 +1173,7 @@ and create extension modules for each namespace separately. If your program utilizes thousands of small deeply nested namespaces each with identical symbol names, well, then you get what you deserve.

    -

    37.3.12 C++ templates

    +

    38.3.12 C++ templates

    C++ templates don't present a huge problem for SWIG. However, @@ -1215,7 +1215,7 @@ irb(main):004:0> p.second 4 -

    37.3.13 C++ Standard Template Library (STL)

    +

    38.3.13 C++ Standard Template Library (STL)

    On a related note, the standard SWIG library contains a @@ -1308,7 +1308,7 @@ puts v shown in these examples. More details can be found in the SWIG and C++ chapter.

    -

    37.3.14 C++ STL Functors

    +

    38.3.14 C++ STL Functors

    Some containers in the STL allow you to modify their default @@ -1369,7 +1369,7 @@ b -

    37.3.15 C++ STL Iterators

    +

    38.3.15 C++ STL Iterators

    The STL is well known for the use of iterators. There @@ -1452,7 +1452,7 @@ i

    If you'd rather have STL classes without any iterators, you should define -DSWIG_NO_EXPORT_ITERATOR_METHODS when running swig.

    -

    37.3.16 C++ Smart Pointers

    +

    38.3.16 C++ Smart Pointers

    In certain C++ programs, it is common to use classes that @@ -1517,7 +1517,7 @@ method. For example:

    irb(main):004:0> f = p.__deref__() # Returns underlying Foo *
    -

    37.3.17 Cross-Language Polymorphism

    +

    38.3.17 Cross-Language Polymorphism

    SWIG's Ruby module supports cross-language polymorphism @@ -1526,7 +1526,7 @@ module. Rather than duplicate the information presented in the 37.3.17.1 Exception Unrolling +

    38.3.17.1 Exception Unrolling

    Whenever a C++ director class routes one of its virtual @@ -1549,7 +1549,7 @@ method is "wrapped" using the rb_rescue2() function from Ruby's C API. If any Ruby exception is raised, it will be caught here and a C++ exception is raised in its place.

    -

    37.4 Naming

    +

    38.4 Naming

    Ruby has several common naming conventions. Constants are @@ -1587,7 +1587,7 @@ generated by SWIG, it is turned off by default in SWIG 1.3.28. However, it is planned to become the default option in future releases.

    -

    37.4.1 Defining Aliases

    +

    38.4.1 Defining Aliases

    It's a fairly common practice in the Ruby built-ins and @@ -1657,7 +1657,7 @@ matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

    -

    37.4.2 Predicate Methods

    +

    38.4.2 Predicate Methods

    Ruby methods that return a boolean value and end in a @@ -1706,7 +1706,7 @@ using SWIG's "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

    -

    37.4.3 Bang Methods

    +

    38.4.3 Bang Methods

    Ruby methods that modify an object in-place and end in an @@ -1738,7 +1738,7 @@ using SWIG's "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

    -

    37.4.4 Getters and Setters

    +

    38.4.4 Getters and Setters

    Often times a C++ library will expose properties through @@ -1773,7 +1773,7 @@ irb(main):003:0> puts foo.value %rename("value=") Foo::setValue(int value); -

    37.5 Input and output parameters

    +

    38.5 Input and output parameters

    A common problem in some C programs is handling parameters @@ -1912,10 +1912,10 @@ void get_dimensions(Matrix *m, int *rows, int*columns);

    r, c = Example.get_dimensions(m)
    -

    37.6 Exception handling

    +

    38.6 Exception handling

    -

    37.6.1 Using the %exception directive

    +

    38.6.1 Using the %exception directive

    The SWIG %exception directive can be @@ -2024,7 +2024,7 @@ methods and functions named getitem and setitem. limited to C++ exception handling. See the chapter on Customization Features for more examples.

    -

    37.6.2 Handling Ruby Blocks

    +

    38.6.2 Handling Ruby Blocks

    One of the highlights of Ruby and most of its standard library @@ -2091,7 +2091,7 @@ a special in typemap, like:

    For more information on typemaps, see Typemaps.

    -

    37.6.3 Raising exceptions

    +

    38.6.3 Raising exceptions

    There are three ways to raise exceptions from C++ code to @@ -2248,7 +2248,7 @@ function. The first argument passed to rb_raise() is the exception type. You can raise a custom exception type or one of the built-in Ruby exception types.

    -

    37.6.4 Exception classes

    +

    38.6.4 Exception classes

    Starting with SWIG 1.3.28, the Ruby module supports the %exceptionclass @@ -2285,7 +2285,7 @@ end

    For another example look at swig/Examples/ruby/exception_class.

    -

    37.7 Typemaps

    +

    38.7 Typemaps

    This section describes how you can modify SWIG's default @@ -2300,7 +2300,7 @@ a required part of using SWIG---the default wrapping behavior is enough in most cases. Typemaps are only used if you want to change some aspect of the primitive C-Ruby interface.

    -

    37.7.1 What is a typemap?

    +

    38.7.1 What is a typemap?

    A typemap is nothing more than a code generation rule that is @@ -2457,7 +2457,7 @@ to be used as follows (notice how the length parameter is omitted):

    2 -

    37.7.2 Typemap scope

    +

    38.7.2 Typemap scope

    Once defined, a typemap remains in effect for all of the @@ -2503,7 +2503,7 @@ where the class itself is defined. For example:

    }; -

    37.7.3 Copying a typemap

    +

    38.7.3 Copying a typemap

    A typemap is copied by using assignment. For example:

    @@ -2545,7 +2545,7 @@ rules as for %apply (char *buf, int len) { (char *buffer, int size) }; // Multiple arguments -

    37.7.4 Deleting a typemap

    +

    38.7.4 Deleting a typemap

    A typemap can be deleted by simply defining no code. For @@ -2570,7 +2570,7 @@ defined by typemaps, clearing a fundamental type like int will make that type unusable unless you also define a new set of typemaps immediately after the clear operation.

    -

    37.7.5 Placement of typemaps

    +

    38.7.5 Placement of typemaps

    Typemap declarations can be declared in the global scope, @@ -2641,13 +2641,13 @@ In this example, this is done using the class declaration class string .

    -

    37.7.6 Ruby typemaps

    +

    38.7.6 Ruby typemaps

    The following list details all of the typemap methods that can be used by the Ruby module:

    -

    37.7.6.1 "in" typemap

    +

    38.7.6.1 "in" typemap

    Converts Ruby objects to input @@ -2714,7 +2714,7 @@ arguments to be specified. For example:

    At this time, only zero or one arguments may be converted.

    -

    37.7.6.2 "typecheck" typemap

    +

    38.7.6.2 "typecheck" typemap

    The "typecheck" typemap is used to support overloaded @@ -2736,7 +2736,7 @@ program uses overloaded methods, you should also define a collection of "typecheck" typemaps. More details about this follow in a later section on "Typemaps and Overloading."

    -

    37.7.6.3 "out" typemap

    +

    38.7.6.3 "out" typemap

    Converts return value of a C function @@ -2787,7 +2787,7 @@ version of the C datatype matched by the typemap.

    -

    37.7.6.4 "arginit" typemap

    +

    38.7.6.4 "arginit" typemap

    The "arginit" typemap is used to set the initial value of a @@ -2802,7 +2802,7 @@ applications. For example:

    } -

    37.7.6.5 "default" typemap

    +

    38.7.6.5 "default" typemap

    The "default" typemap is used to turn an argument into a @@ -2827,7 +2827,7 @@ arguments that follow must have default values. See the 37.7.6.6 "check" typemap +

    38.7.6.6 "check" typemap

    The "check" typemap is used to supply value checking code @@ -2842,7 +2842,7 @@ arguments have been converted. For example:

    } -

    37.7.6.7 "argout" typemap

    +

    38.7.6.7 "argout" typemap

    The "argout" typemap is used to return values from arguments. @@ -2896,7 +2896,7 @@ some function like SWIG_Ruby_AppendOutput.

    See the typemaps.i library for examples.

    -

    37.7.6.8 "freearg" typemap

    +

    38.7.6.8 "freearg" typemap

    The "freearg" typemap is used to cleanup argument data. It is @@ -2923,7 +2923,7 @@ This code is also placed into a special variable $cleanup that may be used in other typemaps whenever a wrapper function needs to abort prematurely.

    -

    37.7.6.9 "newfree" typemap

    +

    38.7.6.9 "newfree" typemap

    The "newfree" typemap is used in conjunction with the %newobject @@ -2947,7 +2947,7 @@ string *foo();

    See Object ownership and %newobject for further details.

    -

    37.7.6.10 "memberin" typemap

    +

    38.7.6.10 "memberin" typemap

    The "memberin" typemap is used to copy data from an @@ -2965,21 +2965,21 @@ example:

    already provides a default implementation for arrays, strings, and other objects.

    -

    37.7.6.11 "varin" typemap

    +

    38.7.6.11 "varin" typemap

    The "varin" typemap is used to convert objects in the target language to C for the purposes of assigning to a C/C++ global variable. This is implementation specific.

    -

    37.7.6.12 "varout" typemap

    +

    38.7.6.12 "varout" typemap

    The "varout" typemap is used to convert a C/C++ object to an object in the target language when reading a C/C++ global variable. This is implementation specific.

    -

    37.7.6.13 "throws" typemap

    +

    38.7.6.13 "throws" typemap

    The "throws" typemap is only used when SWIG parses a C++ @@ -3020,7 +3020,7 @@ specification yet they do throw exceptions, SWIG cannot know how to deal with them. For a neat way to handle these, see the Exception handling with %exception section.

    -

    37.7.6.14 directorin typemap

    +

    38.7.6.14 directorin typemap

    Converts C++ objects in director @@ -3079,7 +3079,7 @@ referring to the class itself. -

    37.7.6.15 directorout typemap

    +

    38.7.6.15 directorout typemap

    Converts Ruby objects in director @@ -3152,7 +3152,7 @@ exception.

    -

    37.7.6.16 directorargout typemap

    +

    38.7.6.16 directorargout typemap

    Output argument processing in director @@ -3210,19 +3210,19 @@ referring to the instance of the class itself -

    37.7.6.17 ret typemap

    +

    38.7.6.17 ret typemap

    Cleanup of function return values

    -

    37.7.6.18 globalin typemap

    +

    38.7.6.18 globalin typemap

    Setting of C global variables

    -

    37.7.7 Typemap variables

    +

    38.7.7 Typemap variables

    @@ -3272,7 +3272,7 @@ so that their values can be properly assigned.

    The Ruby name of the wrapper function being created.
    -

    37.7.8 Useful Functions

    +

    38.7.8 Useful Functions

    When you write a typemap, you usually have to work directly @@ -3287,7 +3287,7 @@ stick to the swig functions instead of the native Ruby functions. That should help you avoid having to rewrite a lot of typemaps across multiple languages.

    -

    37.7.8.1 C Datatypes to Ruby Objects

    +

    38.7.8.1 C Datatypes to Ruby Objects

    @@ -3329,7 +3329,7 @@ SWIG_From_float(float)
    -

    37.7.8.2 Ruby Objects to C Datatypes

    +

    38.7.8.2 Ruby Objects to C Datatypes

    Here, while the Ruby versions return the value directly, the SWIG @@ -3397,7 +3397,7 @@ versions do not, but return a status value to indicate success (SWIG_OK -

    37.7.8.3 Macros for VALUE

    +

    38.7.8.3 Macros for VALUE

    RSTRING_LEN(str)

    @@ -3420,7 +3420,7 @@ versions do not, but return a status value to indicate success (SWIG_OK
    pointer to array storage
    -

    37.7.8.4 Exceptions

    +

    38.7.8.4 Exceptions

    void rb_raise(VALUE exception, const char *fmt, @@ -3499,7 +3499,7 @@ message to standard error if Ruby was invoked with the -w flag. The given format string fmt and remaining arguments are interpreted as with printf(). -

    37.7.8.5 Iterators

    +

    38.7.8.5 Iterators

    void rb_iter_break()

    @@ -3545,14 +3545,14 @@ VALUE), VALUE value)

    Equivalent to Ruby's throw.
    -

    37.7.9 Typemap Examples

    +

    38.7.9 Typemap Examples

    This section includes a few examples of typemaps. For more examples, you might look at the examples in the Example/ruby directory.

    -

    37.7.10 Converting a Ruby array to a char **

    +

    38.7.10 Converting a Ruby array to a char **

    A common problem in many C programs is the processing of @@ -3617,7 +3617,7 @@ array. Since dynamic memory allocation is used to allocate memory for the array, the "freearg" typemap is used to later release this memory after the execution of the C function.

    -

    37.7.11 Collecting arguments in a hash

    +

    38.7.11 Collecting arguments in a hash

    Ruby's solution to the "keyword arguments" capability of some @@ -3831,7 +3831,7 @@ memory leak. Fortunately, this typemap is a lot easier to write:

    program that uses the extension, can be found in the Examples/ruby/hashargs directory of the SWIG distribution.

    -

    37.7.12 Pointer handling

    +

    38.7.12 Pointer handling

    Occasionally, it might be necessary to convert pointer values @@ -3890,7 +3890,7 @@ For example:

    } -

    37.7.12.1 Ruby Datatype Wrapping

    +

    38.7.12.1 Ruby Datatype Wrapping

    VALUE Data_Wrap_Struct(VALUE class, void @@ -3917,7 +3917,7 @@ as above. type c-type from the data object obj and assigns that pointer to ptr. -

    37.7.13 Example: STL Vector to Ruby Array

    +

    38.7.13 Example: STL Vector to Ruby Array

    Another use for macros and type maps is to create a Ruby array @@ -4009,7 +4009,7 @@ STL with ruby, you are advised to use the standard swig STL library, which does much more than this. Refer to the section called the C++ Standard Template Library. -

    37.8 Docstring Features

    +

    38.8 Docstring Features

    @@ -4043,7 +4043,7 @@ generate ri documentation from a c wrap file, you could do:

    $ rdoc -r file_wrap.c -

    37.8.1 Module docstring

    +

    38.8.1 Module docstring

    @@ -4073,7 +4073,7 @@ layout of controls on a panel, etc. to be loaded from an XML file." %module(docstring=DOCSTRING) xrc -

    37.8.2 %feature("autodoc")

    +

    38.8.2 %feature("autodoc")

    Since SWIG does know everything about the function it wraps, @@ -4094,7 +4094,7 @@ several options for autodoc controlled by the value given to the feature, described below.

    -

    37.8.2.1 %feature("autodoc", "0")

    +

    38.8.2.1 %feature("autodoc", "0")

    @@ -4118,7 +4118,7 @@ Then Ruby code like this will be generated: ... -

    37.8.2.2 %feature("autodoc", "1")

    +

    38.8.2.2 %feature("autodoc", "1")

    @@ -4138,7 +4138,7 @@ this: ... -

    37.8.2.3 %feature("autodoc", "2")

    +

    38.8.2.3 %feature("autodoc", "2")

    @@ -4150,7 +4150,7 @@ parameter types with the "2" option will result in Ruby code like this:

    -

    37.8.2.4 %feature("autodoc", "3")

    +

    38.8.2.4 %feature("autodoc", "3")

    @@ -4171,7 +4171,7 @@ Parameters: bar - Bar -

    37.8.2.5 %feature("autodoc", "docstring")

    +

    38.8.2.5 %feature("autodoc", "docstring")

    @@ -4187,7 +4187,7 @@ generated string. For example: void GetPosition(int* OUTPUT, int* OUTPUT); -

    37.8.3 %feature("docstring")

    +

    38.8.3 %feature("docstring")

    @@ -4198,10 +4198,10 @@ docstring associated with classes, function or methods are output. If an item already has an autodoc string then it is combined with the docstring and they are output together.

    -

    37.9 Advanced Topics

    +

    38.9 Advanced Topics

    -

    37.9.1 Operator overloading

    +

    38.9.1 Operator overloading

    SWIG allows operator overloading with, by using the %extend @@ -4382,7 +4382,7 @@ separate method for handling inequality since Ruby parses the expression a != b as !(a == b).

    -

    37.9.2 Creating Multi-Module Packages

    +

    38.9.2 Creating Multi-Module Packages

    The chapter on Working @@ -4508,7 +4508,7 @@ irb(main):005:0> c.getX() 5.0 -

    37.9.3 Specifying Mixin Modules

    +

    38.9.3 Specifying Mixin Modules

    The Ruby language doesn't support multiple inheritance, but @@ -4575,7 +4575,7 @@ matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

    -

    37.10 Memory Management

    +

    38.10 Memory Management

    One of the most common issues in generating SWIG bindings for @@ -4598,7 +4598,7 @@ to C++ (or vice versa) depending on what function or methods are invoked. Clearly, developing a SWIG wrapper requires a thorough understanding of how the underlying library manages memory.

    -

    37.10.1 Mark and Sweep Garbage Collector

    +

    38.10.1 Mark and Sweep Garbage Collector

    Ruby uses a mark and sweep garbage collector. When the garbage @@ -4630,7 +4630,7 @@ any memory has been allocated in creating the underlying C struct or C++ struct, then a "free" function must be defined that deallocates this memory.

    -

    37.10.2 Object Ownership

    +

    38.10.2 Object Ownership

    As described above, memory management depends on clearly @@ -4775,7 +4775,7 @@ public:

    This code can be seen in swig/examples/ruby/tracking.

    -

    37.10.3 Object Tracking

    +

    38.10.3 Object Tracking

    The remaining parts of this section will use the class library @@ -5000,7 +5000,7 @@ However, if you implement your own free functions (see below) you may also have to call the SWIG_RubyRemoveTracking and RubyUnlinkObjects methods.

    -

    37.10.4 Mark Functions

    +

    38.10.4 Mark Functions

    With a bit more testing, we see that our class library still @@ -5129,7 +5129,7 @@ irb(main):016:0>

    This code can be seen in swig/examples/ruby/mark_function.

    -

    37.10.5 Free Functions

    +

    38.10.5 Free Functions

    By default, SWIG creates a "free" function that is called when @@ -5296,7 +5296,7 @@ been freed, and thus raises a runtime exception.

    This code can be seen in swig/examples/ruby/free_function.

    -

    37.10.6 Embedded Ruby and the C++ Stack

    +

    38.10.6 Embedded Ruby and the C++ Stack

    As has been said, the Ruby GC runs and marks objects before diff --git a/Doc/Manual/Tcl.html b/Doc/Manual/Tcl.html index 45eebbf5e..c12701ac9 100644 --- a/Doc/Manual/Tcl.html +++ b/Doc/Manual/Tcl.html @@ -6,7 +6,7 @@ -

    38 SWIG and Tcl

    +

    39 SWIG and Tcl

      @@ -83,7 +83,7 @@ Tcl 8.0 or a later release. Earlier releases of SWIG supported Tcl 7.x, but this is no longer supported.

      -

      38.1 Preliminaries

      +

      39.1 Preliminaries

      @@ -109,7 +109,7 @@ build a Tcl extension module. To finish building the module, you need to compile this file and link it with the rest of your program.

      -

      38.1.1 Getting the right header files

      +

      39.1.1 Getting the right header files

      @@ -127,7 +127,7 @@ this is the case, you should probably make a symbolic link so that tcl.h -

      38.1.2 Compiling a dynamic module

      +

      39.1.2 Compiling a dynamic module

      @@ -163,7 +163,7 @@ The name of the module is specified using the %module directive or the -module command line option.

      -

      38.1.3 Static linking

      +

      39.1.3 Static linking

      @@ -229,7 +229,7 @@ minimal in most situations (and quite frankly not worth the extra hassle in the opinion of this author).

      -

      38.1.4 Using your module

      +

      39.1.4 Using your module

      @@ -357,7 +357,7 @@ to the default system configuration (this requires root access and you will need the man pages).

      -

      38.1.5 Compilation of C++ extensions

      +

      39.1.5 Compilation of C++ extensions

      @@ -440,7 +440,7 @@ erratic program behavior. If working with lots of software components, you might want to investigate using a more formal standard such as COM.

      -

      38.1.6 Compiling for 64-bit platforms

      +

      39.1.6 Compiling for 64-bit platforms

      @@ -467,7 +467,7 @@ also introduce problems on platforms that support more than one linking standard (e.g., -o32 and -n32 on Irix).

      -

      38.1.7 Setting a package prefix

      +

      39.1.7 Setting a package prefix

      @@ -486,7 +486,7 @@ option will append the prefix to the name when creating a command and call it "Foo_bar".

      -

      38.1.8 Using namespaces

      +

      39.1.8 Using namespaces

      @@ -508,7 +508,7 @@ When the -namespace option is used, objects in the module are always accessed with the namespace name such as Foo::bar.

      -

      38.2 Building Tcl/Tk Extensions under Windows 95/NT

      +

      39.2 Building Tcl/Tk Extensions under Windows 95/NT

      @@ -519,7 +519,7 @@ covers the process of using SWIG with Microsoft Visual C++. although the procedure may be similar with other compilers.

      -

      38.2.1 Running SWIG from Developer Studio

      +

      39.2.1 Running SWIG from Developer Studio

      @@ -577,7 +577,7 @@ MSDOS > tclsh80 %

    -

    38.2.2 Using NMAKE

    +

    39.2.2 Using NMAKE

    @@ -640,7 +640,7 @@ to get you started. With a little practice, you'll be making lots of Tcl extensions.

    -

    38.3 A tour of basic C/C++ wrapping

    +

    39.3 A tour of basic C/C++ wrapping

    @@ -651,7 +651,7 @@ classes. This section briefly covers the essential aspects of this wrapping.

    -

    38.3.1 Modules

    +

    39.3.1 Modules

    @@ -685,7 +685,7 @@ To fix this, supply an extra argument to load like this: -

    38.3.2 Functions

    +

    39.3.2 Functions

    @@ -710,7 +710,7 @@ like you think it does: % -

    38.3.3 Global variables

    +

    39.3.3 Global variables

    @@ -790,7 +790,7 @@ extern char *path; // Read-only (due to %immutable) -

    38.3.4 Constants and enums

    +

    39.3.4 Constants and enums

    @@ -874,7 +874,7 @@ When an identifier name is given, it is used to perform an implicit hash-table l conversion. This allows the global statement to be omitted.

    -

    38.3.5 Pointers

    +

    39.3.5 Pointers

    @@ -970,7 +970,7 @@ C-style cast may return a bogus result whereas as the C++-style cast will return None if the conversion can't be performed.

    -

    38.3.6 Structures

    +

    39.3.6 Structures

    @@ -1252,7 +1252,7 @@ Note: Tcl only destroys the underlying object if it has ownership. See the memory management section that appears shortly.

    -

    38.3.7 C++ classes

    +

    39.3.7 C++ classes

    @@ -1319,7 +1319,7 @@ In Tcl, the static member is accessed as follows: -

    38.3.8 C++ inheritance

    +

    39.3.8 C++ inheritance

    @@ -1368,7 +1368,7 @@ For instance: It is safe to use multiple inheritance with SWIG.

    -

    38.3.9 Pointers, references, values, and arrays

    +

    39.3.9 Pointers, references, values, and arrays

    @@ -1422,7 +1422,7 @@ to hold the result and a pointer is returned (Tcl will release this memory when the return value is garbage collected).

    -

    38.3.10 C++ overloaded functions

    +

    39.3.10 C++ overloaded functions

    @@ -1545,7 +1545,7 @@ first declaration takes precedence. Please refer to the "SWIG and C++" chapter for more information about overloading.

    -

    38.3.11 C++ operators

    +

    39.3.11 C++ operators

    @@ -1647,7 +1647,7 @@ There are ways to make this operator appear as part of the class using the % Keep reading.

    -

    38.3.12 C++ namespaces

    +

    39.3.12 C++ namespaces

    @@ -1711,7 +1711,7 @@ utilizes thousands of small deeply nested namespaces each with identical symbol names, well, then you get what you deserve.

    -

    38.3.13 C++ templates

    +

    39.3.13 C++ templates

    @@ -1763,7 +1763,7 @@ More details can be found in the SWIG and C++ -

    38.3.14 C++ Smart Pointers

    +

    39.3.14 C++ Smart Pointers

    @@ -1847,7 +1847,7 @@ simply use the __deref__() method. For example: -

    38.4 Further details on the Tcl class interface

    +

    39.4 Further details on the Tcl class interface

    @@ -1860,7 +1860,7 @@ of low-level details were omitted. This section provides a brief overview of how the proxy classes work.

    -

    38.4.1 Proxy classes

    +

    39.4.1 Proxy classes

    @@ -1925,7 +1925,7 @@ function. This allows objects to be encapsulated objects that look a lot like as shown in the last section.

    -

    38.4.2 Memory management

    +

    39.4.2 Memory management

    @@ -2113,7 +2113,7 @@ typemaps--an advanced topic discussed later.

    -

    38.5 Input and output parameters

    +

    39.5 Input and output parameters

    @@ -2301,7 +2301,7 @@ set c [lindex $dim 1] -

    38.6 Exception handling

    +

    39.6 Exception handling

    @@ -2435,7 +2435,7 @@ Since SWIG's exception handling is user-definable, you are not limited to C++ ex See the chapter on "Customization Features" for more examples.

    -

    38.7 Typemaps

    +

    39.7 Typemaps

    @@ -2452,7 +2452,7 @@ Typemaps are only used if you want to change some aspect of the primitive C-Tcl interface.

    -

    38.7.1 What is a typemap?

    +

    39.7.1 What is a typemap?

    @@ -2569,7 +2569,7 @@ parameter is omitted): -

    38.7.2 Tcl typemaps

    +

    39.7.2 Tcl typemaps

    @@ -2707,7 +2707,7 @@ Initialize an argument to a value before any conversions occur. Examples of these methods will appear shortly.

    -

    38.7.3 Typemap variables

    +

    39.7.3 Typemap variables

    @@ -2778,7 +2778,7 @@ properly assigned. The Tcl name of the wrapper function being created. -

    38.7.4 Converting a Tcl list to a char **

    +

    39.7.4 Converting a Tcl list to a char **

    @@ -2840,7 +2840,7 @@ argv[2] = Larry 3 -

    38.7.5 Returning values in arguments

    +

    39.7.5 Returning values in arguments

    @@ -2882,7 +2882,7 @@ result, a Tcl function using these typemaps will work like this : % -

    38.7.6 Useful functions

    +

    39.7.6 Useful functions

    @@ -2959,7 +2959,7 @@ int Tcl_IsShared(Tcl_Obj *obj); -

    38.7.7 Standard typemaps

    +

    39.7.7 Standard typemaps

    @@ -3043,7 +3043,7 @@ work) -

    38.7.8 Pointer handling

    +

    39.7.8 Pointer handling

    @@ -3119,7 +3119,7 @@ For example: -

    38.8 Turning a SWIG module into a Tcl Package.

    +

    39.8 Turning a SWIG module into a Tcl Package.

    @@ -3191,7 +3191,7 @@ As a final note, most SWIG examples do not yet use the to use the load command instead.

    -

    38.9 Building new kinds of Tcl interfaces (in Tcl)

    +

    39.9 Building new kinds of Tcl interfaces (in Tcl)

    @@ -3290,7 +3290,7 @@ danger of blowing something up (although it is easily accomplished with an out of bounds array access).

    -

    38.9.1 Proxy classes

    +

    39.9.1 Proxy classes

    @@ -3411,7 +3411,7 @@ short, but clever Tcl script can be combined with SWIG to do many interesting things.

    -

    38.10 Tcl/Tk Stubs

    +

    39.10 Tcl/Tk Stubs

    From a6d71e6c57dedcdf520f1d62026fe35a43fbb549 Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Fri, 2 May 2014 00:04:23 +0200 Subject: [PATCH 0916/1048] configure.ac: fix to Javascript configuration - setting SKIP_JAVASCRIPT assumes that JSCENABLED/JSV8ENABLED are empty when jsc/v8 are not available --- configure.ac | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/configure.ac b/configure.ac index 6d70f1da8..46c7479d0 100644 --- a/configure.ac +++ b/configure.ac @@ -1203,7 +1203,7 @@ else if test -z "$JSCORELIB"; then AC_MSG_RESULT(not found) - JSCENABLED=0 + JSCENABLED= else JSCOREDYNAMICLINKING="$JSCORELIB" JSCENABLED=1 @@ -1270,7 +1270,7 @@ else if test "$JSV8LIB" = "" ; then AC_MSG_RESULT(not found) - JSV8ENABLED=0 + JSV8ENABLED= else AC_MSG_RESULT($JSV8LIBDIR) JSV8ENABLED=1 From 00a02a3d9c84c531087a072979681e00f93e3f2a Mon Sep 17 00:00:00 2001 From: xantares Date: Sat, 10 May 2014 12:09:52 +0200 Subject: [PATCH 0917/1048] Fix duplicate entry --- Examples/test-suite/common.mk | 1 - 1 file changed, 1 deletion(-) diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 2a4591524..c8789cb99 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -409,7 +409,6 @@ CPP_TEST_CASES += \ template_partial_specialization \ template_partial_specialization_typedef \ template_qualifier \ - template_qualifier \ template_ref_type \ template_rename \ template_retvalue \ From 55bda53145d2898bd4642926b25209c12738e558 Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Sat, 10 May 2014 22:16:26 +0400 Subject: [PATCH 0918/1048] C nested classes symbol table should be in global space --- Source/CParse/parser.y | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 7e7e5633f..26af7be2d 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -3515,6 +3515,9 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { } else { cplus_mode = CPLUS_PUBLIC; } + if (!cparse_cplusplus) { + set_scope_to_global(); + } Swig_symbol_newscope(); Swig_symbol_setscopename($3); Swig_inherit_base_symbols(bases); From 4fe6622f64fe05eb14ff397c903970898b78c87a Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Fri, 2 May 2014 00:41:43 +0200 Subject: [PATCH 0919/1048] configure.ac: print configured languages at end of configuration --- configure.ac | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/configure.ac b/configure.ac index 46c7479d0..eeabd11b4 100644 --- a/configure.ac +++ b/configure.ac @@ -2678,4 +2678,40 @@ AC_CONFIG_FILES([preinst-swig], [chmod +x preinst-swig]) AC_CONFIG_FILES([CCache/ccache_swig_config.h]) AC_OUTPUT + +langs="" +test -n "$SKIP_ALLEGROCL" || langs="$langs allegrocl" +test -n "$SKIP_CFFI" || langs="$langs cffi" +test -n "$SKIP_CHICKEN" || langs="$langs chicken" +test -n "$SKIP_CLISP" || langs="$langs clisp" +test -n "$SKIP_CSHARP" || langs="$langs csharp" +test -n "$SKIP_D" || langs="$langs d" +test -n "$SKIP_GO" || langs="$langs go" +test -n "$SKIP_GUILE" || langs="$langs guile" +test -n "$SKIP_JAVA" || langs="$langs java" +test -n "$SKIP_JAVASCRIPT" || langs="$langs javascript" +test -n "$SKIP_LUA" || langs="$langs lua" +test -n "$SKIP_MODULA3" || langs="$langs modula3" +test -n "$SKIP_MZSCHEME" || langs="$langs mzscheme" +test -n "$SKIP_OCAML" || langs="$langs ocaml" +test -n "$SKIP_OCTAVE" || langs="$langs octave" +test -n "$SKIP_PERL5" || langs="$langs perl5" +test -n "$SKIP_PHP" || langs="$langs php" +test -n "$SKIP_PIKE" || langs="$langs pike" +test -n "$SKIP_PYTHON" || langs="$langs python" +test -n "$SKIP_R" || langs="$langs r" +test -n "$SKIP_RUBY" || langs="$langs ruby" +test -n "$SKIP_TCL" || langs="$langs tcl" +test -n "$SKIP_UFFI" || langs="$langs uffi" + +echo " +======================================================== + +SWIG is configured for use with the following languages: + +$langs + +======================================================== +" + dnl configure.ac ends here From 6fc07c5dc9a05669174b2c03881619bcb492ec5b Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Fri, 2 May 2014 01:28:15 +0200 Subject: [PATCH 0920/1048] Fix segmentation fault in some Javascript examples - memory allocated with malloc() was then being freed with delete[], which is overridden by Javascript libraries (jsc), leading to segfault - replacing malloc with %new_array seems to work though --- Lib/javascript/jsc/javascriptstrings.swg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/javascript/jsc/javascriptstrings.swg b/Lib/javascript/jsc/javascriptstrings.swg index 0581c1920..10a0e252a 100644 --- a/Lib/javascript/jsc/javascriptstrings.swg +++ b/Lib/javascript/jsc/javascriptstrings.swg @@ -8,7 +8,7 @@ SWIG_JSC_AsCharPtrAndSize(JSContextRef context, JSValueRef valRef, char** cptr, if(JSValueIsString(context, valRef)) { JSStringRef js_str = JSValueToStringCopy(context, valRef, NULL); size_t len = JSStringGetMaximumUTF8CStringSize(js_str); - char* cstr = (char*) malloc(len * sizeof(char)); + char* cstr = (char*) %new_array(len, char); /* JSStringGetUTF8CString returns the length including 0-terminator */ len = JSStringGetUTF8CString(js_str, cstr, len); From 96153c7c0a9200f39d0dc66ffbea2426cd2a4d95 Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Fri, 25 Apr 2014 17:01:14 +0200 Subject: [PATCH 0921/1048] Regenerate configured Makefile if Makefile.in or config.status have changed --- CCache/Makefile.in | 4 ++++ Examples/Makefile.in | 4 ++++ Examples/test-suite/common.mk | 7 +++++++ Examples/test-suite/errors/Makefile.in | 3 +++ Makefile.in | 5 +++++ Tools/javascript/Makefile.in | 16 ++++++++++++---- 6 files changed, 35 insertions(+), 4 deletions(-) diff --git a/CCache/Makefile.in b/CCache/Makefile.in index abe78c277..3513222ca 100644 --- a/CCache/Makefile.in +++ b/CCache/Makefile.in @@ -27,6 +27,10 @@ HEADERS = ccache.h mdfour.h all: $(PACKAGE_NAME)$(EXEEXT) +# Regenerate Makefile if Makefile.in or config.status have changed. +Makefile: $(srcdir)/Makefile.in ./config.status + $(SHELL) ./config.status + # Note that HTML documentation is actually generated and used from the main SWIG documentation Makefile docs: $(PACKAGE_NAME).1 web/ccache-man.html diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 326f678c7..a0acd0fb8 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -21,6 +21,10 @@ # 'method' describes what is being built. #--------------------------------------------------------------- +# Regenerate Makefile if Makefile.in or config.status have changed. +Makefile: @srcdir@/Makefile.in ../config.status + cd .. && $(SHELL) ./config.status Examples/Makefile + TARGET = CC = @CC@ CXX = @CXX@ diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index c8789cb99..bdd1cd471 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -71,6 +71,13 @@ LIBPREFIX = lib ACTION = check INTERFACEDIR = $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/ +# Regenerate Makefile if Makefile.in or config.status have changed. +ifeq (,$(TEST_SUITE_SUBDIR)) +TEST_SUITE_SUBDIR = $(LANGUAGE) +endif +Makefile: $(srcdir)/Makefile.in ../../../config.status + cd ../../../ && $(SHELL) ./config.status $(EXAMPLES)/$(TEST_SUITE)/$(TEST_SUITE_SUBDIR)/Makefile + # # Please keep test cases in alphabetical order. # Note that any whitespace after the last entry in each list will break make diff --git a/Examples/test-suite/errors/Makefile.in b/Examples/test-suite/errors/Makefile.in index e4ba7b751..843283e7c 100644 --- a/Examples/test-suite/errors/Makefile.in +++ b/Examples/test-suite/errors/Makefile.in @@ -31,6 +31,9 @@ C_ERROR_TEST_CASES := $(filter-out $(CPP_ERROR_TEST_CASES), $(ALL_ERROR_TEST_CAS ERROR_TEST_CASES := $(CPP_ERROR_TEST_CASES:=.cpptest) \ $(C_ERROR_TEST_CASES:=.ctest) +# For rebuilding Makefile from Makefile.in in common.mk +TEST_SUITE_SUBDIR = errors + include $(srcdir)/../common.mk diff --git a/Makefile.in b/Makefile.in index 06e4724c7..53ac47de5 100644 --- a/Makefile.in +++ b/Makefile.in @@ -243,11 +243,13 @@ check-%-examples : # individual example %.actionexample: + @cd Examples && $(MAKE) Makefile @echo $(ACTION)ing Examples/$(LANGUAGE)/$* @(cd Examples/$(LANGUAGE)/$* && $(MAKE) $(FLAGS) $(chk-set-env) $(ACTION) RUNPIPE=$(RUNPIPE)) # gcj individual example java.actionexample: + @cd Examples && $(MAKE) Makefile @if $(skip-gcj); then \ echo "skipping Examples/$(LANGUAGE)/java $(ACTION) (gcj test)"; \ else \ @@ -283,6 +285,9 @@ check-test-suite: \ check-javascript-test-suite check-%-test-suite: + @if test -d Examples/test-suite/$*; then \ + cd Examples/test-suite/$* && $(MAKE) Makefile; \ + fi @if test -z "$(skip-$*)"; then \ echo $* unknown; \ exit 1; \ diff --git a/Tools/javascript/Makefile.in b/Tools/javascript/Makefile.in index 373c5d952..6fbca2384 100644 --- a/Tools/javascript/Makefile.in +++ b/Tools/javascript/Makefile.in @@ -11,6 +11,8 @@ # interpreter (see 'Tools/javascript'). # # ---------------------------------------------------------------- +all: javascript + CC = @CC@ # HACK: under OSX a g++ compiled interpreter is seg-faulting when loading module libraries # with 'c++' it works... probably some missing flags? @@ -29,15 +31,21 @@ JSCXXSHARED = @JSCXXSHARED@ JSV8ENABLED = @JSV8ENABLED@ JSCENABLED = @JSCENABLED@ +srcdir = @srcdir@ + +# Regenerate Makefile if Makefile.in or config.status have changed. +Makefile: $(srcdir)/Makefile.in ../../config.status + cd ../.. && $(SHELL) ./config.status Tools/javascript/Makefile + # These settings are provided by 'configure' (see '/configure.in') ifeq (1, $(JSV8ENABLED)) - JS_INTERPRETER_SRC_V8 = v8_shell.cxx - JS_INTERPRETER_ENABLE_V8 = -DENABLE_V8 +JS_INTERPRETER_SRC_V8 = v8_shell.cxx +JS_INTERPRETER_ENABLE_V8 = -DENABLE_V8 endif ifeq (1, $(JSCENABLED)) - JS_INTERPRETER_SRC_JSC = jsc_shell.cxx - JS_INTERPRETER_ENABLE_JSC = -DENABLE_JSC +JS_INTERPRETER_SRC_JSC = jsc_shell.cxx +JS_INTERPRETER_ENABLE_JSC = -DENABLE_JSC endif JS_INTERPRETER_DEFINES = $(JS_INTERPRETER_ENABLE_JSC) $(JS_INTERPRETER_ENABLE_V8) From e0b987b32faf68075890f7b6579661245247fd01 Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Sat, 29 Mar 2014 16:31:32 +0100 Subject: [PATCH 0922/1048] CCache/Makefile.in: fix to allow out of source tree check/install --- CCache/Makefile.in | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/CCache/Makefile.in b/CCache/Makefile.in index 3513222ca..ae77ae745 100644 --- a/CCache/Makefile.in +++ b/CCache/Makefile.in @@ -14,7 +14,7 @@ NOSOFTLINKSTEST= CC=@CC@ CFLAGS=@CFLAGS@ -I. SWIG=swig -SWIG_LIB=../../Lib +SWIG_LIB=../$(srcdir)/../Lib EXEEXT=@EXEEXT@ # Use standard autoconf approach to transform executable name using --program-prefix and --program-suffix @@ -38,7 +38,7 @@ $(PACKAGE_NAME)$(EXEEXT): $(OBJS) $(HEADERS) $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJS) $(LIBS) $(PACKAGE_NAME).1: ccache.yo - -yodl2man -o $(PACKAGE_NAME).1 ccache.yo + -yodl2man -o $(PACKAGE_NAME).1 $(srcdir)/ccache.yo web/ccache-man.html: ccache.yo yodl2html -o web/ccache-man.html ccache.yo @@ -50,7 +50,7 @@ install: $(PACKAGE_NAME)$(EXEEXT) $(PACKAGE_NAME).1 ${INSTALLCMD} -m 755 $(PACKAGE_NAME)$(EXEEXT) $(DESTDIR)${bindir}/`echo $(PACKAGE_NAME) | sed '$(transform)'`$(EXEEXT) @echo "Installing $(DESTDIR)${mandir}/man1/`echo $(PACKAGE_NAME) | sed '$(transform)'`.1" ${INSTALLCMD} -d $(DESTDIR)${mandir}/man1 - ${INSTALLCMD} -m 644 ${srcdir}/$(PACKAGE_NAME).1 $(DESTDIR)${mandir}/man1/`echo $(PACKAGE_NAME) | sed '$(transform)'`.1 + ${INSTALLCMD} -m 644 $(PACKAGE_NAME).1 $(DESTDIR)${mandir}/man1/`echo $(PACKAGE_NAME) | sed '$(transform)'`.1 uninstall: $(PACKAGE_NAME)$(EXEEXT) $(PACKAGE_NAME).1 rm -f $(DESTDIR)${bindir}/`echo $(PACKAGE_NAME) | sed '$(transform)'`$(EXEEXT) @@ -62,7 +62,7 @@ clean: check : test test: test.sh - SWIG_LIB='$(SWIG_LIB)' PATH=../..:$$PATH SWIG='$(SWIG)' CC='$(CC)' NOSOFTLINKSTEST='$(NOSOFTLINKSTEST)' ./test.sh + SWIG_LIB='$(SWIG_LIB)' PATH=../..:$$PATH SWIG='$(SWIG)' CC='$(CC)' NOSOFTLINKSTEST='$(NOSOFTLINKSTEST)' $(srcdir)/test.sh check: test From 72e6b5349e62c44b42de448fab6c9b005811d025 Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Fri, 2 May 2014 17:43:06 +0200 Subject: [PATCH 0923/1048] Add "make maintainer-clean" to Travis CI build --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 890382c40..26cb18910 100644 --- a/.travis.yml +++ b/.travis.yml @@ -77,6 +77,7 @@ script: - 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 + - make maintainer-clean branches: only: - master From f574a34155e4ede49b1b023494e0a1637ab89f8f Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Sun, 11 May 2014 23:21:10 +0200 Subject: [PATCH 0924/1048] Allow examples and test-suite to be built out of source tree - Examples/Makefile.in rules use SRCDIR as the relative source directory - ./config.status replicates Examples/ source directory tree in build directory, and copies each Makefile to build directory, prefixed with a header which sets SRCDIR to source directory - Examples/test-suite/.../Makefile.in set SRCDIR from Autoconf-set srcdir - Examples/test-suite/errors/Makefile.in needs to filter out source directory from SWIG error messages - Lua: embedded interpreters are passed location of run-time test - Python: copy run-time scripts to build directory because of 2to3 conversion; import_packages example copies __init__.py from source directory; test-suite sets SCRIPTDIR to location of run-time tests - Javascript: binding.gyp renamed to binding.gyp.in so that $srcdir can be substituted with SRCDIR; removed './' from require() statements so that NODE_PATH can be used to point Node.js to build directory --- .gitignore | 3 + Examples/Makefile.in | 524 ++++++++++-------- Examples/android/class/Makefile | 6 +- Examples/android/extend/Makefile | 6 +- Examples/android/simple/Makefile | 6 +- Examples/chicken/class/Makefile | 10 +- Examples/chicken/constants/Makefile | 6 +- Examples/chicken/multimap/Makefile | 6 +- Examples/chicken/overload/Makefile | 6 +- Examples/chicken/simple/Makefile | 6 +- Examples/csharp/arrays/Makefile | 8 +- Examples/csharp/callback/Makefile | 8 +- Examples/csharp/class/Makefile | 8 +- Examples/csharp/enum/Makefile | 8 +- Examples/csharp/extend/Makefile | 8 +- Examples/csharp/funcptr/Makefile | 8 +- Examples/csharp/nested/Makefile | 8 +- Examples/csharp/reference/Makefile | 8 +- Examples/csharp/simple/Makefile | 8 +- Examples/csharp/template/Makefile | 8 +- Examples/csharp/variables/Makefile | 8 +- Examples/d/callback/Makefile | 8 +- Examples/d/class/Makefile | 8 +- Examples/d/constants/Makefile | 8 +- Examples/d/enum/Makefile | 8 +- Examples/d/extend/Makefile | 8 +- Examples/d/funcptr/Makefile | 8 +- Examples/d/simple/Makefile | 8 +- Examples/d/variables/Makefile | 8 +- Examples/go/callback/Makefile | 6 +- Examples/go/class/Makefile | 6 +- Examples/go/constants/Makefile | 6 +- Examples/go/enum/Makefile | 6 +- Examples/go/extend/Makefile | 6 +- Examples/go/funcptr/Makefile | 6 +- Examples/go/multimap/Makefile | 6 +- Examples/go/pointer/Makefile | 6 +- Examples/go/reference/Makefile | 6 +- Examples/go/simple/Makefile | 6 +- Examples/go/template/Makefile | 6 +- Examples/go/variables/Makefile | 6 +- Examples/guile/class/Makefile | 8 +- Examples/guile/constants/Makefile | 6 +- Examples/guile/matrix/Makefile | 6 +- Examples/guile/multimap/Makefile | 8 +- Examples/guile/multivalue/Makefile | 8 +- Examples/guile/port/Makefile | 6 +- Examples/guile/simple/Makefile | 6 +- Examples/guile/std_vector/Makefile | 8 +- Examples/java/callback/Makefile | 8 +- Examples/java/class/Makefile | 8 +- Examples/java/constants/Makefile | 8 +- Examples/java/enum/Makefile | 8 +- Examples/java/extend/Makefile | 8 +- Examples/java/funcptr/Makefile | 8 +- Examples/java/multimap/Makefile | 8 +- Examples/java/native/Makefile | 8 +- Examples/java/nested/Makefile | 8 +- Examples/java/pointer/Makefile | 8 +- Examples/java/reference/Makefile | 8 +- Examples/java/simple/Makefile | 8 +- Examples/java/template/Makefile | 8 +- Examples/java/typemap/Makefile | 8 +- Examples/java/variables/Makefile | 8 +- Examples/javascript/class/Makefile | 2 +- Examples/javascript/class/binding.gyp | 8 - Examples/javascript/class/binding.gyp.in | 9 + Examples/javascript/class/example.js | 2 +- Examples/javascript/class/runme.js | 2 +- Examples/javascript/constant/Makefile | 2 +- Examples/javascript/constant/binding.gyp | 8 - Examples/javascript/constant/binding.gyp.in | 9 + Examples/javascript/constant/example.js | 2 +- Examples/javascript/constant/runme.js | 2 +- Examples/javascript/enum/Makefile | 2 +- Examples/javascript/enum/binding.gyp | 8 - Examples/javascript/enum/binding.gyp.in | 9 + Examples/javascript/enum/example.js | 2 +- Examples/javascript/enum/runme.js | 2 +- Examples/javascript/example.mk | 8 +- Examples/javascript/exception/Makefile | 2 +- .../exception/{binding.gyp => binding.gyp.in} | 3 +- Examples/javascript/exception/example.js | 2 +- Examples/javascript/exception/runme.js | 2 +- Examples/javascript/functor/Makefile | 2 +- Examples/javascript/functor/binding.gyp | 8 - Examples/javascript/functor/binding.gyp.in | 9 + Examples/javascript/functor/example.js | 2 +- Examples/javascript/functor/runme.js | 2 +- Examples/javascript/nspace/Makefile | 2 +- Examples/javascript/nspace/binding.gyp | 8 - Examples/javascript/nspace/binding.gyp.in | 9 + Examples/javascript/nspace/example.js | 2 +- Examples/javascript/nspace/runme.js | 2 +- Examples/javascript/operator/Makefile | 2 +- Examples/javascript/operator/binding.gyp | 8 - Examples/javascript/operator/binding.gyp.in | 9 + Examples/javascript/operator/example.js | 2 +- Examples/javascript/operator/runme.js | 2 +- Examples/javascript/overload/Makefile | 2 +- Examples/javascript/overload/binding.gyp | 8 - Examples/javascript/overload/binding.gyp.in | 9 + Examples/javascript/overload/example.js | 2 +- Examples/javascript/overload/runme.js | 2 +- Examples/javascript/pointer/Makefile | 2 +- Examples/javascript/pointer/binding.gyp | 8 - Examples/javascript/pointer/binding.gyp.in | 9 + Examples/javascript/pointer/example.js | 2 +- Examples/javascript/pointer/runme.js | 2 +- Examples/javascript/reference/Makefile | 2 +- Examples/javascript/reference/binding.gyp | 8 - Examples/javascript/reference/binding.gyp.in | 9 + Examples/javascript/reference/example.js | 2 +- Examples/javascript/reference/runme.js | 2 +- Examples/javascript/simple/Makefile | 2 +- Examples/javascript/simple/binding.gyp | 8 - Examples/javascript/simple/binding.gyp.in | 9 + Examples/javascript/simple/example.js | 2 +- Examples/javascript/simple/runme.js | 2 +- Examples/javascript/template/Makefile | 2 +- Examples/javascript/template/binding.gyp | 8 - Examples/javascript/template/binding.gyp.in | 9 + Examples/javascript/template/example.js | 2 +- Examples/javascript/template/runme.js | 2 +- Examples/javascript/variables/Makefile | 2 +- Examples/javascript/variables/binding.gyp | 8 - Examples/javascript/variables/binding.gyp.in | 9 + Examples/javascript/variables/example.js | 2 +- Examples/javascript/variables/runme.js | 2 +- Examples/lua/arrays/Makefile | 8 +- Examples/lua/class/Makefile | 8 +- Examples/lua/constants/Makefile | 8 +- Examples/lua/dual/Makefile | 10 +- Examples/lua/embed/Makefile | 6 +- Examples/lua/embed/embed.c | 9 +- Examples/lua/embed2/Makefile | 6 +- Examples/lua/embed2/embed2.c | 9 +- Examples/lua/embed3/Makefile | 6 +- Examples/lua/embed3/embed3.cpp | 10 +- Examples/lua/exception/Makefile | 8 +- Examples/lua/funcptr3/Makefile | 8 +- Examples/lua/functest/Makefile | 8 +- Examples/lua/functor/Makefile | 8 +- Examples/lua/import/Makefile | 12 +- Examples/lua/nspace/Makefile | 8 +- Examples/lua/owner/Makefile | 8 +- Examples/lua/pointer/Makefile | 8 +- Examples/lua/simple/Makefile | 8 +- Examples/lua/variables/Makefile | 8 +- Examples/modula3/class/Makefile | 6 +- Examples/modula3/enum/Makefile | 6 +- Examples/modula3/exception/Makefile | 8 +- Examples/modula3/reference/Makefile | 6 +- Examples/modula3/simple/Makefile | 6 +- Examples/modula3/typemap/Makefile | 6 +- Examples/mzscheme/multimap/Makefile | 6 +- Examples/mzscheme/simple/Makefile | 6 +- Examples/mzscheme/std_vector/Makefile | 4 +- Examples/ocaml/argout_ref/Makefile | 8 +- Examples/ocaml/contract/Makefile | 10 +- Examples/ocaml/scoped_enum/Makefile | 10 +- Examples/ocaml/shapes/Makefile | 10 +- Examples/ocaml/simple/Makefile | 10 +- Examples/ocaml/std_string/Makefile | 8 +- Examples/ocaml/std_vector/Makefile | 8 +- Examples/ocaml/stl/Makefile | 12 +- Examples/ocaml/string_from_ptr/Makefile | 10 +- Examples/ocaml/strings_test/Makefile | 10 +- Examples/octave/callback/Makefile | 6 +- Examples/octave/class/Makefile | 6 +- Examples/octave/constants/Makefile | 6 +- Examples/octave/contract/Makefile | 6 +- Examples/octave/enum/Makefile | 6 +- Examples/octave/extend/Makefile | 6 +- Examples/octave/funcptr/Makefile | 6 +- Examples/octave/funcptr2/Makefile | 6 +- Examples/octave/functor/Makefile | 6 +- Examples/octave/module_load/Makefile | 8 +- Examples/octave/operator/Makefile | 6 +- Examples/octave/pointer/Makefile | 6 +- Examples/octave/reference/Makefile | 6 +- Examples/octave/simple/Makefile | 6 +- Examples/octave/template/Makefile | 6 +- Examples/octave/variables/Makefile | 6 +- Examples/perl5/callback/Makefile | 8 +- Examples/perl5/class/Makefile | 8 +- Examples/perl5/constants/Makefile | 8 +- Examples/perl5/constants2/Makefile | 8 +- Examples/perl5/extend/Makefile | 8 +- Examples/perl5/funcptr/Makefile | 8 +- Examples/perl5/import/Makefile | 12 +- Examples/perl5/inline/Makefile | 4 +- Examples/perl5/java/Makefile | 10 +- Examples/perl5/multimap/Makefile | 8 +- Examples/perl5/multiple_inheritance/Makefile | 8 +- Examples/perl5/pointer/Makefile | 8 +- Examples/perl5/reference/Makefile | 8 +- Examples/perl5/simple/Makefile | 8 +- Examples/perl5/value/Makefile | 8 +- Examples/perl5/variables/Makefile | 8 +- Examples/perl5/xmlstring/Makefile | 8 +- Examples/php/callback/Makefile | 8 +- Examples/php/class/Makefile | 8 +- Examples/php/constants/Makefile | 8 +- Examples/php/cpointer/Makefile | 8 +- Examples/php/disown/Makefile | 8 +- Examples/php/enum/Makefile | 8 +- Examples/php/extend/Makefile | 8 +- Examples/php/funcptr/Makefile | 8 +- Examples/php/overloading/Makefile | 8 +- Examples/php/pointer/Makefile | 8 +- Examples/php/pragmas/Makefile | 8 +- Examples/php/proxy/Makefile | 8 +- Examples/php/reference/Makefile | 8 +- Examples/php/simple/Makefile | 8 +- Examples/php/sync/Makefile | 8 +- Examples/php/value/Makefile | 8 +- Examples/php/variables/Makefile | 8 +- Examples/pike/class/Makefile | 8 +- Examples/pike/constants/Makefile | 8 +- Examples/pike/enum/Makefile | 8 +- Examples/pike/overload/Makefile | 8 +- Examples/pike/simple/Makefile | 8 +- Examples/pike/template/Makefile | 8 +- Examples/python/callback/Makefile | 8 +- Examples/python/class/Makefile | 8 +- Examples/python/constants/Makefile | 8 +- Examples/python/contract/Makefile | 8 +- Examples/python/docstrings/Makefile | 8 +- Examples/python/enum/Makefile | 8 +- Examples/python/exception/Makefile | 8 +- Examples/python/exceptproxy/Makefile | 8 +- Examples/python/extend/Makefile | 8 +- Examples/python/funcptr/Makefile | 8 +- Examples/python/funcptr2/Makefile | 8 +- Examples/python/functor/Makefile | 8 +- Examples/python/import/Makefile | 12 +- Examples/python/import_packages/Makefile | 11 +- .../import_packages/from_init1/Makefile | 4 +- .../import_packages/from_init1/py2/Makefile | 2 +- .../from_init1/py2/pkg2/Makefile | 12 +- .../import_packages/from_init1/py3/Makefile | 2 +- .../from_init1/py3/pkg2/Makefile | 12 +- .../import_packages/from_init2/Makefile | 4 +- .../import_packages/from_init2/py2/Makefile | 2 +- .../from_init2/py2/pkg2/Makefile | 6 +- .../from_init2/py2/pkg2/pkg3/Makefile | 6 +- .../import_packages/from_init2/py3/Makefile | 2 +- .../from_init2/py3/pkg2/Makefile | 6 +- .../from_init2/py3/pkg2/pkg3/Makefile | 6 +- .../import_packages/from_init3/Makefile | 4 +- .../import_packages/from_init3/py2/Makefile | 2 +- .../from_init3/py2/pkg2/Makefile | 6 +- .../from_init3/py2/pkg2/pkg3/Makefile | 2 +- .../from_init3/py2/pkg2/pkg3/pkg4/Makefile | 6 +- .../import_packages/from_init3/py3/Makefile | 2 +- .../from_init3/py3/pkg2/Makefile | 6 +- .../from_init3/py3/pkg2/pkg3/Makefile | 2 +- .../from_init3/py3/pkg2/pkg3/pkg4/Makefile | 6 +- .../import_packages/relativeimport1/Makefile | 4 +- .../relativeimport1/py2/Makefile | 2 +- .../relativeimport1/py2/pkg2/Makefile | 6 +- .../relativeimport1/py2/pkg2/pkg3/Makefile | 6 +- .../relativeimport1/py3/Makefile | 2 +- .../relativeimport1/py3/pkg2/Makefile | 6 +- .../relativeimport1/py3/pkg2/pkg3/Makefile | 6 +- .../import_packages/relativeimport2/Makefile | 4 +- .../relativeimport2/py2/Makefile | 2 +- .../relativeimport2/py2/pkg2/Makefile | 6 +- .../relativeimport2/py2/pkg2/pkg3/Makefile | 2 +- .../py2/pkg2/pkg3/pkg4/Makefile | 6 +- .../relativeimport2/py3/Makefile | 2 +- .../relativeimport2/py3/pkg2/Makefile | 6 +- .../relativeimport2/py3/pkg2/pkg3/Makefile | 2 +- .../py3/pkg2/pkg3/pkg4/Makefile | 6 +- .../import_packages/same_modnames1/Makefile | 4 +- .../same_modnames1/pkg1/Makefile | 6 +- .../same_modnames1/pkg2/Makefile | 6 +- .../import_packages/same_modnames2/Makefile | 4 +- .../same_modnames2/pkg1/Makefile | 6 +- .../same_modnames2/pkg1/pkg2/Makefile | 6 +- Examples/python/import_template/Makefile | 12 +- Examples/python/java/Makefile | 10 +- Examples/python/libffi/Makefile | 8 +- Examples/python/multimap/Makefile | 8 +- Examples/python/operator/Makefile | 8 +- .../python/performance/constructor/Makefile | 10 +- Examples/python/performance/func/Makefile | 10 +- .../python/performance/hierarchy/Makefile | 10 +- .../performance/hierarchy_operator/Makefile | 10 +- Examples/python/performance/operator/Makefile | 10 +- Examples/python/pointer/Makefile | 8 +- Examples/python/reference/Makefile | 8 +- Examples/python/simple/Makefile | 8 +- Examples/python/smartptr/Makefile | 8 +- Examples/python/std_map/Makefile | 8 +- Examples/python/std_vector/Makefile | 8 +- Examples/python/swigrun/Makefile | 8 +- Examples/python/template/Makefile | 8 +- Examples/python/varargs/Makefile | 8 +- Examples/python/variables/Makefile | 8 +- Examples/r/class/Makefile | 6 +- Examples/r/simple/Makefile | 6 +- Examples/ruby/class/Makefile | 8 +- Examples/ruby/constants/Makefile | 8 +- Examples/ruby/enum/Makefile | 8 +- Examples/ruby/exception_class/Makefile | 8 +- Examples/ruby/free_function/Makefile | 8 +- Examples/ruby/funcptr/Makefile | 8 +- Examples/ruby/funcptr2/Makefile | 8 +- Examples/ruby/functor/Makefile | 8 +- Examples/ruby/hashargs/Makefile | 8 +- Examples/ruby/import/Makefile | 12 +- Examples/ruby/import_template/Makefile | 12 +- Examples/ruby/java/Makefile | 10 +- Examples/ruby/mark_function/Makefile | 8 +- Examples/ruby/multimap/Makefile | 8 +- Examples/ruby/operator/Makefile | 8 +- Examples/ruby/overloading/Makefile | 8 +- Examples/ruby/pointer/Makefile | 8 +- Examples/ruby/reference/Makefile | 8 +- Examples/ruby/simple/Makefile | 8 +- Examples/ruby/std_vector/Makefile | 8 +- Examples/ruby/template/Makefile | 8 +- Examples/ruby/value/Makefile | 8 +- Examples/ruby/variables/Makefile | 8 +- Examples/tcl/class/Makefile | 8 +- Examples/tcl/constants/Makefile | 8 +- Examples/tcl/contract/Makefile | 8 +- Examples/tcl/enum/Makefile | 8 +- Examples/tcl/funcptr/Makefile | 8 +- Examples/tcl/import/Makefile | 12 +- Examples/tcl/java/Makefile | 10 +- Examples/tcl/multimap/Makefile | 8 +- Examples/tcl/operator/Makefile | 8 +- Examples/tcl/pointer/Makefile | 8 +- Examples/tcl/reference/Makefile | 8 +- Examples/tcl/simple/Makefile | 8 +- Examples/tcl/std_vector/Makefile | 8 +- Examples/tcl/value/Makefile | 8 +- Examples/tcl/variables/Makefile | 8 +- Examples/test-suite/allegrocl/Makefile.in | 6 + Examples/test-suite/cffi/Makefile.in | 6 + Examples/test-suite/chicken/Makefile.in | 7 + Examples/test-suite/clisp/Makefile.in | 6 + Examples/test-suite/common.mk | 14 +- Examples/test-suite/csharp/Makefile.in | 13 +- Examples/test-suite/d/Makefile.in | 10 +- Examples/test-suite/errors/Makefile.in | 19 +- Examples/test-suite/go/Makefile.in | 20 +- Examples/test-suite/guile/Makefile.in | 12 +- Examples/test-suite/java/Makefile.in | 13 +- Examples/test-suite/javascript/Makefile.in | 27 +- .../javascript/abstract_access_runme.js | 2 +- .../javascript/abstract_inherit_runme.js | 2 +- .../javascript/abstract_typedef2_runme.js | 2 +- .../javascript/abstract_typedef_runme.js | 2 +- .../javascript/abstract_virtual_runme.js | 2 +- .../javascript/array_member_runme.js | 2 +- .../javascript/arrays_global_runme.js | 2 +- .../test-suite/javascript/callback_runme.js | 2 +- .../javascript/char_binary_runme.js | 2 +- .../javascript/char_strings_runme.js | 2 +- .../javascript/class_ignore_runme.js | 2 +- .../javascript/class_scope_weird_runme.js | 2 +- .../javascript/complextest_runme.js | 2 +- .../test-suite/javascript/constover_runme.js | 2 +- .../javascript/constructor_copy_runme.js | 2 +- .../test-suite/javascript/cpp_enum_runme.js | 2 +- .../javascript/cpp_namespace_runme.js | 2 +- .../test-suite/javascript/cpp_static_runme.js | 2 +- .../javascript/director_alternating_runme.js | 2 +- .../test-suite/javascript/disown_runme.js | 2 +- .../javascript/dynamic_cast_runme.js | 2 +- Examples/test-suite/javascript/empty_runme.js | 2 +- .../javascript/enum_template_runme.js | 2 +- .../test-suite/javascript/infinity_runme.js | 2 +- .../namespace_virtual_method_runme.js | 2 +- .../javascript/node_template/binding.gyp.in | 2 +- .../javascript/nspace_extend_runme.js | 2 +- .../test-suite/javascript/nspace_runme.js | 2 +- .../javascript/overload_copy_runme.js | 2 +- .../javascript/preproc_include_runme.js | 2 +- .../test-suite/javascript/preproc_runme.js | 2 +- .../test-suite/javascript/rename1_runme.js | 2 +- .../test-suite/javascript/rename2_runme.js | 2 +- .../test-suite/javascript/rename3_runme.js | 2 +- .../test-suite/javascript/rename4_runme.js | 2 +- .../javascript/rename_scope_runme.js | 2 +- .../javascript/rename_simple_runme.js | 2 +- .../javascript/ret_by_value_runme.js | 2 +- Examples/test-suite/javascript/setup_test.sh | 6 - .../javascript/string_simple_runme.js | 2 +- .../javascript/struct_value_runme.js | 2 +- .../javascript/template_static_runme.js | 2 +- .../javascript/typedef_class_runme.js | 2 +- .../javascript/typedef_inherit_runme.js | 2 +- .../javascript/typedef_scope_runme.js | 2 +- .../javascript/typemap_arrays_runme.js | 2 +- .../javascript/typemap_delete_runme.js | 2 +- .../javascript/typemap_namespace_runme.js | 2 +- .../javascript/typemap_ns_using_runme.js | 2 +- .../test-suite/javascript/using1_runme.js | 2 +- .../test-suite/javascript/using2_runme.js | 2 +- .../test-suite/javascript/varargs_runme.js | 2 +- Examples/test-suite/lua/Makefile.in | 11 +- Examples/test-suite/mzscheme/Makefile.in | 6 + Examples/test-suite/ocaml/Makefile.in | 6 + Examples/test-suite/octave/Makefile.in | 13 +- Examples/test-suite/perl5/Makefile.in | 13 +- Examples/test-suite/php/Makefile.in | 15 +- Examples/test-suite/pike/Makefile.in | 6 + Examples/test-suite/python/Makefile.in | 43 +- Examples/test-suite/r/Makefile.in | 6 + Examples/test-suite/ruby/Makefile.in | 11 +- Examples/test-suite/tcl/Makefile.in | 11 +- Examples/test-suite/uffi/Makefile.in | 6 + Makefile.in | 4 +- Tools/javascript/Makefile.in | 2 +- configure.ac | 35 ++ 420 files changed, 1772 insertions(+), 1510 deletions(-) delete mode 100644 Examples/javascript/class/binding.gyp create mode 100644 Examples/javascript/class/binding.gyp.in delete mode 100644 Examples/javascript/constant/binding.gyp create mode 100644 Examples/javascript/constant/binding.gyp.in delete mode 100644 Examples/javascript/enum/binding.gyp create mode 100644 Examples/javascript/enum/binding.gyp.in rename Examples/javascript/exception/{binding.gyp => binding.gyp.in} (89%) delete mode 100644 Examples/javascript/functor/binding.gyp create mode 100644 Examples/javascript/functor/binding.gyp.in delete mode 100644 Examples/javascript/nspace/binding.gyp create mode 100644 Examples/javascript/nspace/binding.gyp.in delete mode 100644 Examples/javascript/operator/binding.gyp create mode 100644 Examples/javascript/operator/binding.gyp.in delete mode 100644 Examples/javascript/overload/binding.gyp create mode 100644 Examples/javascript/overload/binding.gyp.in delete mode 100644 Examples/javascript/pointer/binding.gyp create mode 100644 Examples/javascript/pointer/binding.gyp.in delete mode 100644 Examples/javascript/reference/binding.gyp create mode 100644 Examples/javascript/reference/binding.gyp.in delete mode 100644 Examples/javascript/simple/binding.gyp create mode 100644 Examples/javascript/simple/binding.gyp.in delete mode 100644 Examples/javascript/template/binding.gyp create mode 100644 Examples/javascript/template/binding.gyp.in delete mode 100644 Examples/javascript/variables/binding.gyp create mode 100644 Examples/javascript/variables/binding.gyp.in delete mode 100644 Examples/test-suite/javascript/setup_test.sh diff --git a/.gitignore b/.gitignore index d4d70b010..ce6a3c4b7 100644 --- a/.gitignore +++ b/.gitignore @@ -136,3 +136,6 @@ Examples/test-suite/uffi/*/ # Scratch directories Examples/scratch + +# Out of source tree build directories +_build*/ diff --git a/Examples/Makefile.in b/Examples/Makefile.in index a0acd0fb8..dcfbd83b9 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -25,11 +25,28 @@ Makefile: @srcdir@/Makefile.in ../config.status cd .. && $(SHELL) ./config.status Examples/Makefile +# SRCDIR is the relative path to the current source directory +# - For in-source-tree builds, SRCDIR with be either '', +# or '../' for some of the test suites (e.g. C#, Java) +# - For out-of-source-tree builds, SRCDIR will be a relative +# path ending with a '/' + +# SRCDIR_SRCS, etc. are $(SRCS), etc. with $(SRCDIR) prepended +SRCDIR_SRCS = $(addprefix $(SRCDIR),$(SRCS)) +SRCDIR_CSRCS = $(addprefix $(SRCDIR),$(CSRCS)) +SRCDIR_CXXSRCS = $(addprefix $(SRCDIR),$(CXXSRCS)) + +ifeq (,$(SRCDIR)) +SRCDIR_INCLUDE = -I. +else +SRCDIR_INCLUDE = -I. -I$(SRCDIR) +endif + TARGET = CC = @CC@ CXX = @CXX@ -CFLAGS = @PLATCFLAGS@ -CXXFLAGS = @BOOST_CPPFLAGS@ @PLATCXXFLAGS@ +CFLAGS = $(SRCDIR_INCLUDE) @PLATCFLAGS@ +CXXFLAGS = $(SRCDIR_INCLUDE) @BOOST_CPPFLAGS@ @PLATCXXFLAGS@ prefix = @prefix@ exec_prefix= @exec_prefix@ SRCS = @@ -37,7 +54,7 @@ INCLUDES = LIBS = INTERFACE = INTERFACEDIR = -INTERFACEPATH = $(INTERFACEDIR)$(INTERFACE) +INTERFACEPATH = $(SRCDIR)$(INTERFACEDIR)$(INTERFACE) SWIGOPT = SWIG = swig @@ -130,38 +147,38 @@ TCL_DLNK = @TCLDYNAMICLINKING@ TCL_SO = @TCL_SO@ TCLLDSHARED = @TCLLDSHARED@ TCLCXXSHARED = @TCLCXXSHARED@ -TCL_SCRIPT = $(RUNME).tcl +TCL_SCRIPT = $(SRCDIR)$(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) \ +tclsh: $(SRCDIR_SRCS) + $(SWIG) -tcl8 $(SWIGOPT) $(TCL_SWIGOPTS) -ltclsh.i -o $(ISRCS) $(INTERFACEPATH) + $(CC) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(TCL_INCLUDE) \ $(TCL_LIB) $(TCL_OPTS) $(LIBS) $(SYSLIBS) -o $(TARGET) -tclsh_cpp: $(SRCS) - $(SWIG) -tcl8 -c++ $(SWIGOPT) $(TCL_SWIGOPTS) -ltclsh.i $(INTERFACEPATH) - $(CXX) $(CXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) \ +tclsh_cpp: $(SRCDIR_SRCS) + $(SWIG) -tcl8 -c++ $(SWIGOPT) $(TCL_SWIGOPTS) -ltclsh.i -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) \ $(TCL_LIB) $(TCL_OPTS) $(LIBS) $(SYSLIBS) -o $(TARGET) # ----------------------------------------------------------- # Build a Tcl dynamic loadable module (you might need to tweak this) # ----------------------------------------------------------- -tcl: $(SRCS) - $(SWIG) -tcl8 $(SWIGOPT) $(TCL_SWIGOPTS) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(TCL_INCLUDE) +tcl: $(SRCDIR_SRCS) + $(SWIG) -tcl8 $(SWIGOPT) $(TCL_SWIGOPTS) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(TCL_INCLUDE) $(TCLLDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(TCL_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(TCL_SO) # ----------------------------------------------------------- # Build a Tcl7.5 dynamic loadable module for C++ # ----------------------------------------------------------- -tcl_cpp: $(SRCS) - $(SWIG) -tcl8 -c++ $(SWIGOPT) $(TCL_SWIGOPTS) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) +tcl_cpp: $(SRCDIR_SRCS) + $(SWIG) -tcl8 -c++ $(SWIGOPT) $(TCL_SWIGOPTS) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) $(TCLCXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(TCL_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(TCL_SO) # ----------------------------------------------------------------- @@ -205,44 +222,44 @@ PERL5_CCCDLFLAGS = @PERL5CCCDLFLAGS@ PERL5_LDFLAGS = @PERL5LDFLAGS@ PERL = @PERL@ PERL5_LIB = -L$(PERL5_INCLUDE) -l@PERL5LIB@ @LIBS@ $(SYSLIBS) -PERL5_SCRIPT = $(RUNME).pl +PERL5_SCRIPT = $(SRCDIR)$(RUNME).pl # ---------------------------------------------------------------- # Build a Perl5 dynamically loadable module (C) # ---------------------------------------------------------------- -perl5: $(SRCS) - $(SWIG) -perl5 $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c -Dbool=char $(CCSHARED) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(PERL5_CCFLAGS) $(PERL5_CCCDLFLAGS) -I$(PERL5_INCLUDE) +perl5: $(SRCDIR_SRCS) + $(SWIG) -perl5 $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c -Dbool=char $(CCSHARED) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(PERL5_CCFLAGS) $(PERL5_CCCDLFLAGS) -I$(PERL5_INCLUDE) $(LDSHARED) $(CFLAGS) $(PERL5_CCDLFLAGS) $(OBJS) $(IOBJS) $(PERL5_LDFLAGS) $(PERL5_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ---------------------------------------------------------------- # Build a Perl5 dynamically loadable module (C++) # ---------------------------------------------------------------- -perl5_cpp: $(SRCS) - $(SWIG) -perl5 -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(PERL5_CCFLAGS) $(PERL5_CCCDLFLAGS) -I$(PERL5_INCLUDE) +perl5_cpp: $(SRCDIR_SRCS) + $(SWIG) -perl5 -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(PERL5_CCFLAGS) $(PERL5_CCCDLFLAGS) -I$(PERL5_INCLUDE) $(CXXSHARED) $(CXXFLAGS) $(PERL5_CCDLFLAGS) $(OBJS) $(IOBJS) $(PERL5_LDFLAGS) $(PERL5_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ---------------------------------------------------------------- # Build a module from existing XS C source code. (ie. from xsubpp). # ---------------------------------------------------------------- -perl5_xs: $(SRCS) - $(CC) -c $(CCSHARED) $(CFLAGS) $(SRCS) $(INCLUDES) -I$(PERL5_INCLUDE) +perl5_xs: $(SRCDIR_SRCS) + $(CC) -c $(CCSHARED) $(CFLAGS) $(SRCDIR_SRCS) $(INCLUDES) -I$(PERL5_INCLUDE) $(LDSHARED) $(CFLAGS) $(OBJS) $(LIBS) -o $(TARGET)$(SO) # ---------------------------------------------------------------- # Build a statically linked Perl5 executable # ---------------------------------------------------------------- -perl5_static: $(SRCS) - $(SWIG) -perl5 -static -lperlmain.i $(SWIGOPT) $(INTERFACEPATH) - $(CC) $(CFLAGS) -Dbool=char $(SRCS) $(ISRCS) $(INCLUDES) -I$(PERL5_INCLUDE) $(PERL5_LIB) $(LIBS) -o $(TARGET) +perl5_static: $(SRCDIR_SRCS) + $(SWIG) -perl5 -static -lperlmain.i $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) $(CFLAGS) -Dbool=char $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) -I$(PERL5_INCLUDE) $(PERL5_LIB) $(LIBS) -o $(TARGET) -perl5_static_cpp: $(SRCS) - $(SWIG) -perl5 -c++ -static -lperlmain.i $(SWIGOPT) $(INTERFACEPATH) - $(CXX) $(CXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) -I$(PERL5_INCLUDE) $(PERL5_LIB) $(LIBS) -o $(TARGET) +perl5_static_cpp: $(SRCDIR_SRCS) + $(SWIG) -perl5 -c++ -static -lperlmain.i $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) -I$(PERL5_INCLUDE) $(PERL5_LIB) $(LIBS) -o $(TARGET) # ----------------------------------------------------------------- # Running a Perl5 example @@ -271,15 +288,17 @@ perl5_clean: ##### PYTHON ###### ################################################################## +PYTHON_FLAGS = + # Make sure these locate your Python installation ifeq (,$(PY3)) PYTHON_INCLUDE= $(DEFS) @PYINCLUDE@ PYTHON_LIB = @PYLIB@ - PYTHON = @PYTHON@ + PYTHON = @PYTHON@ $(PYTHON_FLAGS) else PYTHON_INCLUDE= $(DEFS) @PY3INCLUDE@ PYTHON_LIB = @PY3LIB@ - PYTHON = @PYTHON3@ + PYTHON = @PYTHON3@ $(PYTHON_FLAGS) endif # Extra Python specific linking options @@ -303,18 +322,18 @@ endif # Build a C dynamically loadable module # ---------------------------------------------------------------- -python: $(SRCS) - $(SWIGPYTHON) $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) $(PYTHON_INCLUDE) +python: $(SRCDIR_SRCS) + $(SWIGPYTHON) $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(PYTHON_INCLUDE) $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(PYTHON_DLNK) $(LIBS) -o $(LIBPREFIX)_$(TARGET)$(PYTHON_SO) # ----------------------------------------------------------------- # Build a C++ dynamically loadable module # ----------------------------------------------------------------- -python_cpp: $(SRCS) - $(SWIGPYTHON) -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(PYTHON_INCLUDE) +python_cpp: $(SRCDIR_SRCS) + $(SWIGPYTHON) -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(PYTHON_INCLUDE) $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(PYTHON_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)_$(TARGET)$(PYTHON_SO) # ----------------------------------------------------------------- @@ -328,14 +347,14 @@ python_cpp: $(SRCS) TKINTER = PYTHON_LIBOPTS = $(PYTHON_LINK) @LIBS@ $(TKINTER) $(SYSLIBS) -python_static: $(SRCS) - $(SWIGPYTHON) -lembed.i $(SWIGOPT) $(INTERFACEPATH) - $(CC) $(CFLAGS) @LINKFORSHARED@ $(ISRCS) $(SRCS) $(INCLUDES) \ +python_static: $(SRCDIR_SRCS) + $(SWIGPYTHON) -lembed.i $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) $(CFLAGS) @LINKFORSHARED@ $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) \ $(PYTHON_INCLUDE) $(LIBS) -L$(PYTHON_LIB) $(PYTHON_LIBOPTS) -o $(TARGET) -python_static_cpp: $(SRCS) - $(SWIGPYTHON) -c++ -lembed.i $(SWIGOPT) $(INTERFACEPATH) - $(CXX) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \ +python_static_cpp: $(SRCDIR_SRCS) + $(SWIGPYTHON) -c++ -lembed.i $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) \ $(PYTHON_INCLUDE) $(LIBS) -L$(PYTHON_LIB) $(PYTHON_LIBOPTS) -o $(TARGET) # ----------------------------------------------------------------- @@ -351,9 +370,15 @@ endif PY2TO3 = 2to3 `2to3 -l | grep -v -E "Available|import$$" | awk '{print "-f "$$0}'` python_run: $(PYSCRIPT) + export PYTHONPATH=".:$$PYTHONPATH"; \ $(RUNTOOL) $(PYTHON) $(PYSCRIPT) $(RUNPIPE) -$(RUNME)3.py: $(RUNME).py +ifneq (,$(SRCDIR)) +$(RUNME).py: $(SRCDIR)$(RUNME).py + cp $< $@ +endif + +$(RUNME)3.py: $(SRCDIR)$(RUNME).py cp $< $@ $(PY2TO3) -w $@ >/dev/null 2>&1 @@ -389,26 +414,26 @@ OCTAVE_CXX = $(DEFS) @OCTAVE_CPPFLAGS@ @OCTAVE_CXXFLAGS@ OCTAVE_DLNK = @OCTAVE_LDFLAGS@ OCTAVE_SO = @OCTAVE_SO@ -OCTAVE_SCRIPT = $(RUNME).m +OCTAVE_SCRIPT = $(SRCDIR)$(RUNME).m # ---------------------------------------------------------------- # Build a C dynamically loadable module # Note: Octave requires C++ compiler when compiling C wrappers # ---------------------------------------------------------------- -octave: $(SRCS) - $(SWIG) -octave $(SWIGOPT) $(INTERFACEPATH) +octave: $(SRCDIR_SRCS) + $(SWIG) -octave $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) $(CXX) -g -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(INCLUDES) $(OCTAVE_CXX) - $(CC) -g -c $(CCSHARED) $(CFLAGS) $(SRCS) $(CSRCS) $(INCLUDES) + $(CC) -g -c $(CCSHARED) $(CFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CSRCS) $(INCLUDES) $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(OCTAVE_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(OCTAVE_SO) # ----------------------------------------------------------------- # Build a C++ dynamically loadable module # ----------------------------------------------------------------- -octave_cpp: $(SRCS) - $(SWIG) -c++ -octave $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -g -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(OCTAVE_CXX) +octave_cpp: $(SRCDIR_SRCS) + $(SWIG) -c++ -octave $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -g -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(OCTAVE_CXX) $(CXXSHARED) -g $(CXXFLAGS) $(OBJS) $(IOBJS) $(OCTAVE_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(OCTAVE_SO) # ----------------------------------------------------------------- @@ -446,20 +471,20 @@ GUILE_SO = @GUILE_SO@ GUILE_LIBS = @GUILE_LIBS@ GUILE_LIBOPTS = @LIBS@ $(SYSLIBS) GUILE_LIBPREFIX = lib -GUILE_SCRIPT = $(RUNME).scm +GUILE_SCRIPT = $(SRCDIR)$(RUNME).scm #------------------------------------------------------------------ # Build a dynamically loaded module with passive linkage #------------------------------------------------------------------ -guile: $(SRCS) - $(SWIG) -guile -Linkage passive $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(INCLUDES) $(GUILE_CFLAGS) $(ISRCS) $(SRCS) +guile: $(SRCDIR_SRCS) + $(SWIG) -guile -Linkage passive $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CFLAGS) $(INCLUDES) $(GUILE_CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(GUILE_LIBS) $(LIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO) guile_cpp: $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO) -$(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO): $(SRCS) - $(SWIG) -c++ -guile -Linkage passive $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(INCLUDES) $(GUILE_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) +$(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO): $(SRCDIR_SRCS) + $(SWIG) -c++ -guile -Linkage passive $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(INCLUDES) $(GUILE_CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(GUILE_LIBS) $(LIBS) $(CPP_DLLIBS) -o $@ guile_externalhdr: @@ -469,34 +494,34 @@ guile_externalhdr: # Build Guile interpreter augmented with extra functions # ----------------------------------------------------------------- -guile_augmented: - $(SWIG) -guile $(SWIGOPT) $(INTERFACE) - $(CC) $(CXXFLAGS) $(SRCS) $(ISRCS) $(GUILE_CFLAGS) $(GUILE_LIBS) $(LIBS) -o $(TARGET) +guile_augmented: $(SRCDIR_SRCS) + $(SWIG) -guile $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) $(CXXFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(GUILE_CFLAGS) $(GUILE_LIBS) $(LIBS) -o $(TARGET) # ----------------------------------------------------------------- # Build statically linked Guile interpreter # ----------------------------------------------------------------- -guile_static: $(SRCS) - $(SWIG) -guile -lguilemain.i -Linkage ltdlmod $(SWIGOPT) $(INTERFACEPATH) - $(CC) $(CFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) \ +guile_static: $(SRCDIR_SRCS) + $(SWIG) -guile -lguilemain.i -Linkage ltdlmod $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) \ -DSWIGINIT="SCM scm_init_$(TARGET)_module(void); scm_init_$(TARGET)_module();" \ $(GUILE_CFLAGS) $(GUILE_LIBS) $(LIBS) $(GUILE_LIBOPTS) -o $(TARGET)-guile -guile_static_cpp: $(SRCS) - $(SWIG) -c++ -guile -lguilemain.i -Linkage ltdlmod $(SWIGOPT) $(INTERFACEPATH) - $(CXX) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \ +guile_static_cpp: $(SRCDIR_SRCS) + $(SWIG) -c++ -guile -lguilemain.i -Linkage ltdlmod $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) \ -DSWIGINIT="SCM scm_init_$(TARGET)_module(void); scm_init_$(TARGET)_module();" \ $(GUILE_CFLAGS) $(GUILE_LIBS) $(LIBS) $(GUILE_LIBOPTS) -o $(TARGET)-guile -guile_simple: $(SRCS) - $(SWIG) -guile -lguilemain.i -Linkage simple $(SWIGOPT) $(INTERFACEPATH) - $(CC) $(CFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) \ +guile_simple: $(SRCDIR_SRCS) + $(SWIG) -guile -lguilemain.i -Linkage simple $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) \ $(GUILE_CFLAGS) $(GUILE_LIBS) $(LIBS) $(GUILE_LIBOPTS) -o $(TARGET)-guile -guile_simple_cpp: $(SRCS) - $(SWIG) -c++ -guile -lguilemain.i -Linkage simple $(SWIGOPT) $(INTERFACEPATH) - $(CXX) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \ +guile_simple_cpp: $(SRCDIR_SRCS) + $(SWIG) -c++ -guile -lguilemain.i -Linkage simple $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) \ $(GUILE_CFLAGS) $(GUILE_LIBS) $(LIBS) $(GUILE_LIBOPTS) -o $(TARGET)-guile # ----------------------------------------------------------------- @@ -542,39 +567,39 @@ JAVALDSHARED = @JAVALDSHARED@ JAVACXXSHARED = @JAVACXXSHARED@ JAVACFLAGS = @JAVACFLAGS@ JAVA = @JAVA@ -JAVAC = @JAVAC@ +JAVAC = @JAVAC@ -d . # ---------------------------------------------------------------- # Build a java dynamically loadable module (C) # ---------------------------------------------------------------- -java: $(SRCS) - $(SWIG) -java $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(JAVACFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(JAVA_INCLUDE) +java: $(SRCDIR_SRCS) + $(SWIG) -java $(SWIGOPT) -o $(ISRCS) $(realpath $(INTERFACEPATH)) + $(CC) -c $(CCSHARED) $(CFLAGS) $(JAVACFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(JAVA_INCLUDE) $(JAVALDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JAVA_DLNK) $(LIBS) -o $(JAVA_LIBPREFIX)$(TARGET)$(JAVASO) # ---------------------------------------------------------------- # Build a java dynamically loadable module (C++) # ---------------------------------------------------------------- -java_cpp: $(SRCS) - $(SWIG) -java -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(JAVACFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(JAVA_INCLUDE) +java_cpp: $(SRCDIR_SRCS) + $(SWIG) -java -c++ $(SWIGOPT) -o $(ICXXSRCS) $(realpath $(INTERFACEPATH)) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(JAVACFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(JAVA_INCLUDE) $(JAVACXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(JAVA_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(JAVA_LIBPREFIX)$(TARGET)$(JAVASO) # ---------------------------------------------------------------- # Compile java files # ---------------------------------------------------------------- -java_compile: $(SRCS) - $(COMPILETOOL) $(JAVAC) $(JAVACFLAGS) $(JAVASRCS) +java_compile: $(SRCDIR_SRCS) + $(COMPILETOOL) $(JAVAC) $(JAVACFLAGS) $(addprefix $(SRCDIR),$(JAVASRCS)) # ----------------------------------------------------------------- # Run java example # ----------------------------------------------------------------- java_run: - env LD_LIBRARY_PATH=. $(RUNTOOL) $(JAVA) $(RUNME) $(RUNPIPE) + env LD_LIBRARY_PATH=$$PWD $(RUNTOOL) $(JAVA) $(RUNME) $(RUNPIPE) # ----------------------------------------------------------------- # Version display @@ -617,37 +642,38 @@ NODEGYP = @NODEGYP@ javascript_wrapper: $(SWIG) -javascript $(SWIGOPT) -o $(INTERFACEDIR)$(TARGET)_wrap.c $(INTERFACEPATH) -javascript_wrapper_cpp: $(SRCS) +javascript_wrapper_cpp: $(SRCDIR_SRCS) $(SWIG) -javascript -c++ $(SWIGOPT) -o $(INTERFACEDIR)$(TARGET)_wrap.cxx $(INTERFACEPATH) -javascript_build: $(SRCS) - $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) $(JSINCLUDES) +javascript_build: $(SRCDIR_SRCS) + $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(JSINCLUDES) $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) -javascript_build_cpp: $(SRCS) +javascript_build_cpp: $(SRCDIR_SRCS) ifeq (node,$(JSENGINE)) + sed -e 's|$$srcdir|./$(SRCDIR)|g' $(SRCDIR)binding.gyp.in > binding.gyp $(NODEGYP) --loglevel=silent configure build 1>>/dev/null else - $(CXX) -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(JSINCLUDES) + $(CXX) -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(JSINCLUDES) $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) endif # These targets are used by the test-suite: -javascript: $(SRCS) javascript_custom_interpreter +javascript: $(SRCDIR_SRCS) javascript_custom_interpreter $(SWIG) -javascript $(SWIGOPT) $(INTERFACEPATH) ifeq (jsc, $(ENGINE)) - $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) $(JSINCLUDES) + $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(JSINCLUDES) $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) else # (v8 | node) # v8 and node must be compiled as c++ - $(CXX) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(JSINCLUDES) + $(CXX) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(JSINCLUDES) $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) endif -javascript_cpp: $(SRCS) javascript_custom_interpreter +javascript_cpp: $(SRCDIR_SRCS) javascript_custom_interpreter $(SWIG) -javascript -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(JSINCLUDES) + $(CXX) -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(JSINCLUDES) $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- @@ -659,10 +685,10 @@ javascript_custom_interpreter: ifeq (node,$(JSENGINE)) javascript_run: - $(RUNTOOL) $(NODEJS) $(RUNME).js $(RUNPIPE) + env NODE_PATH=$$PWD:$(SRCDIR) $(RUNTOOL) $(NODEJS) $(SRCDIR)$(RUNME).js $(RUNPIPE) else javascript_run: javascript_custom_interpreter - $(RUNTOOL) $(ROOT_DIR)/Tools/javascript/javascript -$(JSENGINE) -L $(TARGET) $(RUNME).js $(RUNPIPE) + $(RUNTOOL) $(ROOT_DIR)/Tools/javascript/javascript -$(JSENGINE) -L $(TARGET) $(SRCDIR)$(RUNME).js $(RUNPIPE) endif # ----------------------------------------------------------------- @@ -718,7 +744,7 @@ TARGETID = 1 # Build an Android dynamically loadable module (C) # ---------------------------------------------------------------- -android: $(SRCS) +android: $(SRCDIR_SRCS) $(ANDROID) $(SILENT_OPTION) update project --target $(TARGETID) --name $(PROJECTNAME) --path . $(SWIG) -java $(SWIGOPT) -o $(INTERFACEDIR)$(TARGET)_wrap.c $(INTERFACEPATH) +$(ANDROID_NDK_BUILD) $(SILENT_PIPE) @@ -728,7 +754,7 @@ android: $(SRCS) # Build an Android dynamically loadable module (C++) # ---------------------------------------------------------------- -android_cpp: $(SRCS) +android_cpp: $(SRCDIR_SRCS) $(ANDROID) $(SILENT_OPTION) update project --target $(TARGETID) --name $(PROJECTNAME) --path . $(SWIG) -java -c++ $(SWIGOPT) -o $(INTERFACEDIR)$(TARGET)_wrap.cpp $(INTERFACEPATH) +$(ANDROID_NDK_BUILD) $(SILENT_PIPE) @@ -769,13 +795,13 @@ MODULA3_INCLUDE= @MODULA3INC@ # Build a modula3 dynamically loadable module (C) # ---------------------------------------------------------------- -modula3: $(SRCS) - $(SWIG) -modula3 $(SWIGOPT) $(INTERFACEPATH) -# $(CC) -c $(CCSHARED) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) \ +modula3: $(SRCDIR_SRCS) + $(SWIG) -modula3 $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) +# $(CC) -c $(CCSHARED) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) \ # $(OBJS) $(IOBJS) $(LIBS) -modula3_cpp: $(SRCS) - $(SWIG) -modula3 -c++ $(SWIGOPT) $(INTERFACEPATH) +modula3_cpp: $(SRCDIR_SRCS) + $(SWIG) -modula3 -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) # ----------------------------------------------------------------- # Run modula3 example @@ -814,14 +840,14 @@ MZSCHEME_SCRIPT = $(RUNME).scm # Build a C/C++ dynamically loadable module # ---------------------------------------------------------------- -mzscheme: $(SRCS) - $(SWIG) -mzscheme $(SWIGOPT) $(INTERFACEPATH) - $(COMPILETOOL) $(MZC) `echo $(INCLUDES) | sed 's/-I/++ccf -I/g'` --cc $(ISRCS) $(SRCS) +mzscheme: $(SRCDIR_SRCS) + $(SWIG) -mzscheme $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(COMPILETOOL) $(MZC) `echo $(INCLUDES) | sed 's/-I/++ccf -I/g'` --cc $(ISRCS) $(SRCDIR_SRCS) $(COMPILETOOL) $(MZC) --ld $(TARGET)$(MZSCHEME_SO) $(OBJS) $(IOBJS) -mzscheme_cpp: $(SRCS) - $(SWIG) -mzscheme -c++ $(SWIGOPT) $(INTERFACEPATH) - $(COMPILETOOL) $(MZC) `echo $(INCLUDES) | sed 's/-I/++ccf -I/g'` --cc $(ICXXSRCS) $(SRCS) $(CXXSRCS) +mzscheme_cpp: $(SRCDIR_SRCS) + $(SWIG) -mzscheme -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(COMPILETOOL) $(MZC) `echo $(INCLUDES) | sed 's/-I/++ccf -I/g'` --cc $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(CXXSHARED) $(CXXFLAGS) -o $(LIBPREFIX)$(TARGET)$(MZSCHEME_SO) $(OBJS) $(IOBJS) $(MZDYNOBJ) $(CPP_DLLIBS) # ----------------------------------------------------------------- @@ -829,7 +855,7 @@ mzscheme_cpp: $(SRCS) # ----------------------------------------------------------------- mzscheme_run: - env LD_LIBRARY_PATH=. $(RUNTOOL) $(MZSCHEME) -r $(MZSCHEME_SCRIPT) $(RUNPIPE) + env LD_LIBRARY_PATH=$$PWD $(RUNTOOL) $(MZSCHEME) -r $(MZSCHEME_SCRIPT) $(RUNPIPE) # ----------------------------------------------------------------- # Version display @@ -869,10 +895,10 @@ OCAMLCORE=\ $(OCC) -I $(OCAMLP4WHERE) -pp "camlp4o pa_extend.cmo q_MLast.cmo" \ -c swigp4.ml -ocaml_static: $(SRCS) +ocaml_static: $(SRCDIR_SRCS) $(OCAMLCORE) - $(SWIG) -ocaml $(SWIGOPT) $(INTERFACEPATH) - $(OCC) -g -c -ccopt -g -ccopt "$(INCLUDES)" $(ISRCS) $(SRCS) + $(SWIG) -ocaml $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(OCC) -g -c -ccopt -g -ccopt "$(INCLUDES)" $(ISRCS) $(SRCDIR_SRCS) $(OCC) -g -c $(INTERFACE:%.i=%.mli) $(OCC) -g -c $(INTERFACE:%.i=%.ml) test -z "$(PROGFILE)" || test -f "$(PROGFILE)" && \ @@ -883,10 +909,10 @@ ocaml_static: $(SRCS) $(PROGFILE:%.ml=%.cmo) \ $(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) -cclib "$(LIBS)" -ocaml_dynamic: $(SRCS) +ocaml_dynamic: $(SRCDIR_SRCS) $(OCAMLCORE) - $(SWIG) -ocaml $(SWIGOPT) $(INTERFACEPATH) - $(OCC) -g -c -ccopt -g -ccopt "$(INCLUDES)" $(ISRCS) $(SRCS) + $(SWIG) -ocaml $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(OCC) -g -c -ccopt -g -ccopt "$(INCLUDES)" $(ISRCS) $(SRCDIR_SRCS) $(CXXSHARED) $(CXXFLAGS) $(CCSHARED) $(CFLAGS) -o $(INTERFACE:%.i=%@SO@) \ $(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) $(LIBS) $(OCAMLDLGEN) $(INTERFACE:%.i=%.ml) $(INTERFACE:%.i=%@SO@) > \ @@ -902,10 +928,10 @@ ocaml_dynamic: $(SRCS) -package dl -linkpkg \ $(INTERFACE:%.i=%.cmo) $(PROGFILE:%.ml=%.cmo) -ocaml_static_toplevel: $(SRCS) +ocaml_static_toplevel: $(SRCDIR_SRCS) $(OCAMLCORE) - $(SWIG) -ocaml $(SWIGOPT) $(INTERFACEPATH) - $(OCC) -g -c -ccopt -g -ccopt "$(INCLUDES)" $(ISRCS) $(SRCS) + $(SWIG) -ocaml $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(OCC) -g -c -ccopt -g -ccopt "$(INCLUDES)" $(ISRCS) $(SRCDIR_SRCS) $(OCC) -g -c $(INTERFACE:%.i=%.mli) $(OCC) -g -c $(INTERFACE:%.i=%.ml) test -z "$(PROGFILE)" || test -f "$(PROGFILE)" && \ @@ -917,12 +943,12 @@ ocaml_static_toplevel: $(SRCS) $(INTERFACE:%.i=%.cmo) \ $(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) -cclib "$(LIBS)" -ocaml_static_cpp: $(SRCS) +ocaml_static_cpp: $(SRCDIR_SRCS) $(OCAMLCORE) - $(SWIG) -ocaml -c++ $(SWIGOPT) $(INTERFACEPATH) + $(SWIG) -ocaml -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) cp $(ICXXSRCS) $(ICXXSRCS:%.cxx=%.c) $(OCC) -cc '$(CXX) -Wno-write-strings' -g -c -ccopt -g -ccopt "-xc++ $(INCLUDES)" \ - $(ICXXSRCS:%.cxx=%.c) $(SRCS) $(CXXSRCS) + $(ICXXSRCS:%.cxx=%.c) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(OCC) -g -c $(INTERFACE:%.i=%.mli) $(OCC) -g -c $(INTERFACE:%.i=%.ml) test -z "$(PROGFILE)" || test -f "$(PROGFILE)" && \ @@ -934,12 +960,12 @@ ocaml_static_cpp: $(SRCS) $(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) \ -cclib "$(LIBS)" -cc '$(CXX) -Wno-write-strings' -ocaml_static_cpp_toplevel: $(SRCS) +ocaml_static_cpp_toplevel: $(SRCDIR_SRCS) $(OCAMLCORE) - $(SWIG) -ocaml -c++ $(SWIGOPT) $(INTERFACEPATH) + $(SWIG) -ocaml -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) cp $(ICXXSRCS) $(ICXXSRCS:%.cxx=%.c) $(OCC) -cc '$(CXX) -Wno-write-strings' -g -c -ccopt -g -ccopt "-xc++ $(INCLUDES)" \ - $(ICXXSRCS:%.cxx=%.c) $(SRCS) $(CXXSRCS) + $(ICXXSRCS:%.cxx=%.c) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(OCC) -g -c $(INTERFACE:%.i=%.mli) $(OCC) -g -c $(INTERFACE:%.i=%.ml) test -z "$(PROGFILE)" || test -f "$(PROGFILE)" && \ @@ -952,12 +978,12 @@ ocaml_static_cpp_toplevel: $(SRCS) $(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) \ -cclib "$(LIBS)" -cc '$(CXX) -Wno-write-strings' -ocaml_dynamic_cpp: $(SRCS) +ocaml_dynamic_cpp: $(SRCDIR_SRCS) $(OCAMLCORE) - $(SWIG) -ocaml -c++ $(SWIGOPT) $(INTERFACEPATH) + $(SWIG) -ocaml -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) cp $(ICXXSRCS) $(ICXXSRCS:%.cxx=%.c) $(OCC) -cc '$(CXX) -Wno-write-strings' -g -c -ccopt -g -ccopt "-xc++ $(INCLUDES)" \ - $(ICXXSRCS:%.cxx=%.c) $(SRCS) $(CXXSRCS) -ccopt -fPIC + $(ICXXSRCS:%.cxx=%.c) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) -ccopt -fPIC $(CXXSHARED) $(CXXFLAGS) -o $(INTERFACE:%.i=%@SO@) \ $(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) \ $(CPP_DLLIBS) $(LIBS) @@ -1010,25 +1036,25 @@ RUBY_DLNK = @RUBYDYNAMICLINKING@ RUBY_LIBOPTS = @RUBYLINK@ @LIBS@ $(SYSLIBS) RUBY_SO = @RUBYSO@ RUBY = @RUBY@ -RUBY_SCRIPT = $(RUNME).rb +RUBY_SCRIPT = $(SRCDIR)$(RUNME).rb # ---------------------------------------------------------------- # Build a C dynamically loadable module # ---------------------------------------------------------------- -ruby: $(SRCS) - $(SWIG) -ruby $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(RUBY_CFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) $(RUBY_INCLUDE) +ruby: $(SRCDIR_SRCS) + $(SWIG) -ruby $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CFLAGS) $(RUBY_CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(RUBY_INCLUDE) $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(RUBY_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(RUBY_SO) # ----------------------------------------------------------------- # Build a C++ dynamically loadable module # ----------------------------------------------------------------- -ruby_cpp: $(SRCS) - $(SWIG) -c++ -ruby $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(RUBY_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(RUBY_INCLUDE) +ruby_cpp: $(SRCDIR_SRCS) + $(SWIG) -c++ -ruby $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(RUBY_CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(RUBY_INCLUDE) $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(RUBY_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(RUBY_SO) # ----------------------------------------------------------------- @@ -1038,14 +1064,14 @@ ruby_cpp: $(SRCS) # library file # ----------------------------------------------------------------- -ruby_static: $(SRCS) - $(SWIG) -ruby -lembed.i $(SWIGOPT) $(INTERFACEPATH) - $(CC) $(CFLAGS) $(RUBY_CFLAGS) @LINKFORSHARED@ $(ISRCS) $(SRCS) $(INCLUDES) \ +ruby_static: $(SRCDIR_SRCS) + $(SWIG) -ruby -lembed.i $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) $(CFLAGS) $(RUBY_CFLAGS) @LINKFORSHARED@ $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) \ $(RUBY_INCLUDE) $(LIBS) -L$(RUBY_LIB) $(RUBY_LIBOPTS) -o $(TARGET) -ruby_cpp_static: $(SRCS) - $(SWIG) -c++ -ruby -lembed.i $(SWIGOPT) $(INTERFACEPATH) - $(CXX) $(CXXFLAGS) $(RUBY_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \ +ruby_cpp_static: $(SRCDIR_SRCS) + $(SWIG) -c++ -ruby -lembed.i $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) $(CXXFLAGS) $(RUBY_CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) \ $(RUBY_INCLUDE) $(LIBS) -L$(RUBY_LIB) $(RUBY_LIBOPTS) -o $(TARGET) # ----------------------------------------------------------------- @@ -1078,24 +1104,24 @@ ruby_clean: PHP = @PHP@ PHP_INCLUDE = @PHPINC@ PHP_SO = @PHP_SO@ -PHP_SCRIPT = $(RUNME).php +PHP_SCRIPT = $(SRCDIR)$(RUNME).php # ------------------------------------------------------------------- # Build a PHP dynamically loadable module (C) # ------------------------------------------------------------------- -php: $(SRCS) - $(SWIG) -php $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) $(PHP_INCLUDE) +php: $(SRCDIR_SRCS) + $(SWIG) -php $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(PHP_INCLUDE) $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(PHP_SO) # -------------------------------------------------------------------- # Build a PHP dynamically loadable module (C++) # -------------------------------------------------------------------- -php_cpp: $(SRCS) - $(SWIG) -php -cppext cxx -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(PHP_INCLUDE) +php_cpp: $(SRCDIR_SRCS) + $(SWIG) -php -cppext cxx -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(PHP_INCLUDE) $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(PHP_SO) # ----------------------------------------------------------------- @@ -1138,18 +1164,18 @@ PIKE_SCRIPT = $(RUNME).pike # Build a C dynamically loadable module # ---------------------------------------------------------------- -pike: $(SRCS) - $(SWIG) -pike $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(PIKE_CFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) $(PIKE_INCLUDE) +pike: $(SRCDIR_SRCS) + $(SWIG) -pike $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CFLAGS) $(PIKE_CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(PIKE_INCLUDE) $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(PIKE_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- # Build a C++ dynamically loadable module # ----------------------------------------------------------------- -pike_cpp: $(SRCS) - $(SWIG) -c++ -pike $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(PIKE_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(PIKE_INCLUDE) +pike_cpp: $(SRCDIR_SRCS) + $(SWIG) -c++ -pike $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(PIKE_CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(PIKE_INCLUDE) $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(PIKE_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- @@ -1159,14 +1185,14 @@ pike_cpp: $(SRCS) # library file # ----------------------------------------------------------------- -pike_static: $(SRCS) - $(SWIG) -pike -lembed.i $(SWIGOPT) $(INTERFACEPATH) - $(CC) $(CFLAGS) $(PIKE_CFLAGS) @LINKFORSHARED@ $(ISRCS) $(SRCS) $(INCLUDES) \ +pike_static: $(SRCDIR_SRCS) + $(SWIG) -pike -lembed.i $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) $(CFLAGS) $(PIKE_CFLAGS) @LINKFORSHARED@ $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) \ $(PIKE_INCLUDE) $(LIBS) -L$(PIKE_LIB) $(PIKE_LIBOPTS) -o $(TARGET) -pike_cpp_static: $(SRCS) - $(SWIG) -c++ -pike -lembed.i $(SWIGOPT) $(INTERFACEPATH) - $(CXX) $(CXXFLAGS) $(PIKE_CFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) \ +pike_cpp_static: $(SRCDIR_SRCS) + $(SWIG) -c++ -pike -lembed.i $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) $(CXXFLAGS) $(PIKE_CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) \ $(PIKE_INCLUDE) $(LIBS) -L$(PIKE_LIB) $(PIKE_LIBOPTS) -o $(TARGET) # ----------------------------------------------------------------- @@ -1222,23 +1248,23 @@ CHICKEN_COMPILED_MAIN_OBJECT = $(CHICKEN_COMPILED_MAIN:.c=.@OBJEXT@) # ----------------------------------------------------------------- # This is the old way to build chicken, but it does not work correctly with exceptions -chicken_direct: $(SRCS) +chicken_direct: $(SRCDIR_SRCS) $(SWIG) -chicken $(SWIGOPT) $(INCLUDE) $(INTERFACEPATH) $(CHICKEN) $(CHICKEN_GENERATED_SCHEME) $(CHICKENOPTS) \ -dynamic -feature chicken-compile-shared \ -output-file $(CHICKEN_COMPILED_SCHEME) $(CC) -c $(CCSHARED) $(CFLAGS) $(CHICKEN_CFLAGS) \ - $(INCLUDES) $(CHICKEN_INCLUDE) $(ISRCS) $(SRCS) $(CHICKEN_COMPILED_SCHEME) + $(INCLUDES) $(CHICKEN_INCLUDE) $(ISRCS) $(SRCDIR_SRCS) $(CHICKEN_COMPILED_SCHEME) $(LDSHARED) $(CFLAGS) $(CHICKEN_COMPILED_OBJECT) $(OBJS) $(IOBJS) \ $(LIBS) $(CHICKEN_SHAREDLIBOPTS) -o $(LIBPREFIX)$(TARGET)$(SO) -chicken_direct_cpp: $(CXXSRCS) $(CHICKSRCS) +chicken_direct_cpp: $(SRCDIR_CXXSRCS) $(CHICKSRCS) $(SWIG) -c++ -chicken $(SWIGOPT) $(INCLUDE) $(INTERFACEPATH) $(CHICKEN) $(CHICKEN_GENERATED_SCHEME) $(CHICKENOPTS) \ -dynamic -feature chicken-compile-shared \ -output-file $(CHICKEN_COMPILED_SCHEME) $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(CHICKEN_CFLAGS) \ - $(INCLUDES) $(CHICKEN_INCLUDE) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(CHICKEN_COMPILED_SCHEME) + $(INCLUDES) $(CHICKEN_INCLUDE) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(CHICKEN_COMPILED_SCHEME) $(CXXSHARED) $(CXXFLAGS) $(CHICKEN_COMPILED_OBJECT) $(OBJS) $(IOBJS) \ $(LIBS) $(CPP_DLLIBS) $(CHICKEN_SHAREDLIBOPTS) -o $(LIBPREFIX)$(TARGET)$(SO) @@ -1247,26 +1273,26 @@ chicken_direct_cpp: $(CXXSRCS) $(CHICKSRCS) # ----------------------------------------------------------------- # The following two targets are also used by the test suite -chicken_static: $(SRCS) $(CHICKSRCS) +chicken_static: $(SRCDIR_SRCS) $(CHICKSRCS) $(SWIG) -chicken $(SWIGOPT) $(INCLUDE) $(INTERFACEPATH) $(CHICKEN) $(CHICKEN_GENERATED_SCHEME) $(CHICKENOPTS) \ -output-file $(CHICKEN_COMPILED_SCHEME) $(CHICKEN) $(CHICKEN_MAIN) $(CHICKENOPTS) \ -output-file $(CHICKEN_MAIN:.scm=_chicken.c) $(CC) -c $(CCSHARED) $(CFLAGS) $(CHICKEN_CFLAGS) \ - $(INCLUDES) $(CHICKEN_INCLUDE) $(ISRCS) $(SRCS) \ + $(INCLUDES) $(CHICKEN_INCLUDE) $(ISRCS) $(SRCDIR_SRCS) \ $(CHICKEN_COMPILED_SCHEME) $(CHICKEN_COMPILED_MAIN) $(CC) $(CHICKEN_COMPILED_OBJECT) $(CHICKEN_COMPILED_MAIN_OBJECT) \ $(OBJS) $(IOBJS) $(LIBS) $(CHICKEN_SHAREDLIBOPTS) -o $(TARGET) -chicken_static_cpp: $(CXXSRCS) $(CHICKSRCS) +chicken_static_cpp: $(SRCDIR_CXXSRCS) $(CHICKSRCS) $(SWIG) -c++ -chicken $(SWIGOPT) $(INCLUDE) $(INTERFACEPATH) $(CHICKEN) $(CHICKEN_GENERATED_SCHEME) $(CHICKENOPTS) \ -output-file $(CHICKEN_COMPILED_SCHEME) $(CHICKEN) $(CHICKEN_MAIN) $(CHICKENOPTS) \ -output-file $(CHICKEN_MAIN:.scm=_chicken.c) $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(CHICKEN_CFLAGS) \ - $(INCLUDES) $(CHICKEN_INCLUDE) $(ICXXSRCS) $(SRCS) $(CXXSRCS) \ + $(INCLUDES) $(CHICKEN_INCLUDE) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) \ $(CHICKEN_COMPILED_SCHEME) $(CHICKEN_COMPILED_MAIN) $(CXX) $(CHICKEN_COMPILED_OBJECT) $(CHICKEN_COMPILED_MAIN_OBJECT) \ $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) $(CHICKEN_SHAREDLIBOPTS) -o $(TARGET) @@ -1277,11 +1303,11 @@ chicken_static_cpp: $(CXXSRCS) $(CHICKSRCS) chicken: $(SWIG) -chicken $(SWIGOPT) $(INCLUDE) $(INTERFACEPATH) - $(COMPILETOOL) $(CHICKEN_CSC) -s `echo $(INCLUDES) | sed 's/-I/-C -I/g'` $(CHICKEN_GENERATED_SCHEME) $(SRCS) $(ISRCS) -o $(TARGET)$(SO) + $(COMPILETOOL) $(CHICKEN_CSC) -s `echo $(INCLUDES) | sed 's/-I/-C -I/g'` $(CHICKEN_GENERATED_SCHEME) $(SRCDIR_SRCS) $(ISRCS) -o $(TARGET)$(SO) chicken_cpp: $(SWIG) -c++ -chicken $(SWIGOPT) $(INCLUDE) $(INTERFACEPATH) - $(COMPILETOOL) $(CHICKEN_CSC) -s `echo $(INCLUDES) | sed 's/-I/-C -I/g'` $(CHICKEN_GENERATED_SCHEME) $(SRCS) $(ICXXSRCS) $(CXXSRCS) -o $(TARGET)$(SO) + $(COMPILETOOL) $(CHICKEN_CSC) -s `echo $(INCLUDES) | sed 's/-I/-C -I/g'` $(CHICKEN_GENERATED_SCHEME) $(SRCDIR_SRCS) $(ICXXSRCS) $(SRCDIR_CXXSRCS) -o $(TARGET)$(SO) chicken_externalhdr: $(SWIG) -chicken -external-runtime $(TARGET) @@ -1291,7 +1317,7 @@ chicken_externalhdr: # ----------------------------------------------------------------- chicken_run: - env LD_LIBRARY_PATH=. $(RUNTOOL) $(CHICKEN_CSI) $(CHICKEN_SCRIPT) $(RUNPIPE) + env LD_LIBRARY_PATH=$$PWD $(RUNTOOL) $(CHICKEN_CSI) $(CHICKEN_SCRIPT) $(RUNPIPE) # ----------------------------------------------------------------- # Version display @@ -1327,33 +1353,39 @@ CSHARP_RUNME = $(CSHARPCILINTERPRETER) $(CSHARPCILINTERPRETER_FLAGS) ./$(RUNME). # Build a CSharp dynamically loadable module (C) # ---------------------------------------------------------------- -csharp: $(SRCS) - $(SWIG) -csharp $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(CSHARPCFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) +csharp: $(SRCDIR_SRCS) + $(SWIG) -csharp $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CFLAGS) $(CSHARPCFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(CSHARP_DLNK) $(LIBS) -o $(CSHARP_LIBPREFIX)$(TARGET)$(CSHARPSO) # ---------------------------------------------------------------- # Build a CSharp dynamically loadable module (C++) # ---------------------------------------------------------------- -csharp_cpp: $(SRCS) - $(SWIG) -csharp -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(CSHARPCFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) +csharp_cpp: $(SRCDIR_SRCS) + $(SWIG) -csharp -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(CSHARPCFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(CSHARP_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(CSHARP_LIBPREFIX)$(TARGET)$(CSHARPSO) # ---------------------------------------------------------------- # Compile CSharp files # ---------------------------------------------------------------- -csharp_compile: $(SRCS) - $(COMPILETOOL) $(CSHARPCOMPILER) $(CSHARPFLAGS) $(CSHARPSRCS) +ifneq (,$(SRCDIR)) +SRCDIR_CSHARPSRCS = $(wildcard $(addprefix $(SRCDIR),$(CSHARPSRCS))) +else +SRCDIR_CSHARPSRCS = +endif + +csharp_compile: $(SRCDIR_SRCS) + $(COMPILETOOL) $(CSHARPCOMPILER) $(CSHARPFLAGS) $(CSHARPSRCS) $(SRCDIR_CSHARPSRCS) # ----------------------------------------------------------------- # Run CSharp example # ----------------------------------------------------------------- csharp_run: - env LD_LIBRARY_PATH=. $(RUNTOOL) $(CSHARP_RUNME) $(RUNPIPE) + env LD_LIBRARY_PATH=$$PWD $(RUNTOOL) $(CSHARP_RUNME) $(RUNPIPE) # ----------------------------------------------------------------- # Version display @@ -1385,7 +1417,7 @@ LUA_DLNK = @LUADYNAMICLINKING@ LUA_SO = @LUA_SO@ LUA = @LUABIN@ -LUA_SCRIPT = $(RUNME).lua +LUA_SCRIPT = $(SRCDIR)$(RUNME).lua # Extra code for lua static link LUA_INTERP = ../lua.c @@ -1394,32 +1426,32 @@ LUA_INTERP = ../lua.c # Build a C dynamically loadable module # ---------------------------------------------------------------- -lua: $(SRCS) - $(SWIG) -lua $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) $(LUA_INCLUDE) +lua: $(SRCDIR_SRCS) + $(SWIG) -lua $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(LUA_INCLUDE) $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(LUA_LIB) -o $(LIBPREFIX)$(TARGET)$(LUA_SO) # ----------------------------------------------------------------- # Build a C++ dynamically loadable module # ----------------------------------------------------------------- -lua_cpp: $(SRCS) - $(SWIG) -c++ -lua $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(LUA_INCLUDE) +lua_cpp: $(SRCDIR_SRCS) $(GENCXXSRCS) + $(SWIG) -c++ -lua $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(GENCXXSRCS) $(INCLUDES) $(LUA_INCLUDE) $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(LUA_LIB) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(LUA_SO) # ----------------------------------------------------------------- # Build statically linked Lua interpreter # ----------------------------------------------------------------- -lua_static: $(SRCS) - $(SWIG) -lua -module example $(SWIGOPT) $(INTERFACEPATH) - $(CC) $(CFLAGS) $(ISRCS) $(SRCS) $(LUA_INTERP) $(INCLUDES) \ +lua_static: $(SRCDIR_SRCS) + $(SWIG) -lua -module example $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(SRCDIR)$(LUA_INTERP) $(INCLUDES) \ $(LUA_INCLUDE) $(LIBS) $(LUA_LIB) -o $(TARGET) -lua_static_cpp: $(SRCS) - $(SWIG) -c++ -lua -module example $(SWIGOPT) $(INTERFACEPATH) - $(CXX) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(LUA_INTERP) $(INCLUDES) \ +lua_static_cpp: $(SRCDIR_SRCS) $(GENCXXSRCS) + $(SWIG) -c++ -lua -module example $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(GENCXXSRCS) $(SRCDIR)$(LUA_INTERP) $(INCLUDES) \ $(LUA_INCLUDE) $(LIBS) $(LUA_LIB) -o $(TARGET) # ----------------------------------------------------------------- @@ -1430,7 +1462,7 @@ lua_run: $(RUNTOOL) $(LUA) $(LUA_SCRIPT) $(RUNPIPE) lua_embed_run: - $(RUNTOOL) ./$(TARGET) $(RUNPIPE) + $(RUNTOOL) ./$(TARGET) $(LUA_SCRIPT) $(RUNPIPE) # ----------------------------------------------------------------- # Version display @@ -1455,14 +1487,14 @@ lua_clean: ALLEGROCL = @ALLEGROCLBIN@ ALLEGROCL_SCRIPT=$(RUNME).lisp -allegrocl: $(SRCS) - $(SWIG) -allegrocl -cwrap $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCS) +allegrocl: $(SRCDIR_SRCS) + $(SWIG) -allegrocl -cwrap $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCDIR_SRCS) $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) -allegrocl_cpp: $(SRCS) - $(SWIG) -c++ -allegrocl $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) +allegrocl_cpp: $(SRCDIR_SRCS) + $(SWIG) -c++ -allegrocl $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- @@ -1495,11 +1527,11 @@ allegrocl_clean: CLISP = @CLISPBIN@ CLISP_SCRIPT=$(RUNME).lisp -clisp: $(SRCS) - $(SWIG) -clisp $(SWIGOPT) $(INTERFACEPATH) +clisp: $(SRCDIR_SRCS) + $(SWIG) -clisp $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) -clisp_cpp: $(SRCS) - $(SWIG) -c++ -clisp $(SWIGOPT) $(INTERFACEPATH) +clisp_cpp: $(SRCDIR_SRCS) + $(SWIG) -c++ -clisp $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) # ----------------------------------------------------------------- # Run CLISP example @@ -1531,14 +1563,14 @@ clisp_clean: CFFI = @CFFIBIN@ CFFI_SCRIPT=$(RUNME).lisp -cffi: $(SRCS) - $(SWIG) -cffi $(SWIGOPT) $(INTERFACEPATH) -# $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCS) +cffi: $(SRCDIR_SRCS) + $(SWIG) -cffi $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) +# $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCDIR_SRCS) # $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) -cffi_cpp: $(SRCS) - $(SWIG) -c++ -cffi $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) +cffi_cpp: $(SRCDIR_SRCS) + $(SWIG) -c++ -cffi $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- @@ -1571,14 +1603,14 @@ cffi_clean: UFFI = @UFFIBIN@ UFFI_SCRIPT=$(RUNME).lisp -uffi: $(SRCS) - $(SWIG) -uffi $(SWIGOPT) $(INTERFACEPATH) -# $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCS) +uffi: $(SRCDIR_SRCS) + $(SWIG) -uffi $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) +# $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCDIR_SRCS) # $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) -uffi_cpp: $(SRCS) - $(SWIG) -c++ -uffi $(SWIGOPT) $(INTERFACEPATH) -# $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) +uffi_cpp: $(SRCDIR_SRCS) + $(SWIG) -c++ -uffi $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) +# $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) # $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- @@ -1622,10 +1654,10 @@ R_SCRIPT=$(RUNME).R # Build a R dynamically loadable module (C) # ---------------------------------------------------------------- -r: $(SRCS) - $(SWIG) -r $(SWIGOPT) $(INTERFACEPATH) -ifneq ($(SRCS),) - $(CC) -g -c $(CFLAGS) $(R_CFLAGS) $(SRCS) $(INCLUDES) +r: $(SRCDIR_SRCS) + $(SWIG) -r $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) +ifneq ($(SRCDIR_SRCS),) + $(CC) -g -c $(CFLAGS) $(R_CFLAGS) $(SRCDIR_SRCS) $(INCLUDES) endif +( PKG_CPPFLAGS="$(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(ISRCS) $(OBJS) > /dev/null ) @@ -1633,10 +1665,10 @@ endif # Build a R dynamically loadable module (C++) # ---------------------------------------------------------------- -r_cpp: $(CXXSRCS) +r_cpp: $(SRCDIR_CXXSRCS) $(SWIG) -c++ -r $(SWIGOPT) -o $(RCXXSRCS) $(INTERFACEPATH) -ifneq ($(CXXSRCS),) - $(CXX) -g -c $(CXXFLAGS) $(R_CFLAGS) $(CXXSRCS) $(INCLUDES) +ifneq ($(SRCDIR_CXXSRCS),) + $(CXX) -g -c $(CXXFLAGS) $(R_CFLAGS) $(SRCDIR_CXXSRCS) $(INCLUDES) endif +( PKG_CPPFLAGS="$(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(RCXXSRCS) $(OBJS) > /dev/null ) @@ -1697,12 +1729,12 @@ GOGCCOBJS = $(GOSRCS:.go=.@OBJEXT@) # Build a Go module (C) # ---------------------------------------------------------------- -go: $(SRCS) - $(SWIG) -go $(GOOPT) $(GOSWIGARG) $(SWIGOPT) $(INTERFACEPATH) +go: $(SRCDIR_SRCS) + $(SWIG) -go $(GOOPT) $(GOSWIGARG) $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) if $(GO12) || $(GO13) || $(GOGCC); then \ - $(CC) -g -c $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES); \ + $(CC) -g -c $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES); \ else \ - $(CC) -g -c $(CCSHARED) $(CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES); \ + $(CC) -g -c $(CCSHARED) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES); \ $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO); \ fi $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(GOSRCS) @@ -1718,12 +1750,12 @@ go: $(SRCS) $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)); \ fi; \ fi - if test -f $(RUNME).go; then \ - $(GO) $(GOCOMPILEARG) $(RUNME).go; \ + if test -f $(SRCDIR)$(RUNME).go; then \ + $(GO) $(GOCOMPILEARG) $(SRCDIR)$(RUNME).go; \ if $(GOGCC) ; then \ $(COMPILETOOL) $(GO) -o $(RUNME) $(RUNME).@OBJEXT@ $(GOGCCOBJS) $(OBJS) $(IOBJS); \ elif $(GO12) || $(GO13); then \ - $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CC) -extldflags "$(CFLAGS)" -o $(RUNME) $(RUNME).$(GOOBJEXT); \ + $(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; \ @@ -1733,12 +1765,12 @@ go: $(SRCS) # Build a Go module (C++) # ---------------------------------------------------------------- -go_cpp: $(SRCS) - $(SWIG) -go -c++ $(GOOPT) $(GOSWIGARG) $(SWIGOPT) $(INTERFACEPATH) +go_cpp: $(SRCDIR_SRCS) + $(SWIG) -go -c++ $(GOOPT) $(GOSWIGARG) $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) if $(GO12) || $(GO13) || $(GOGCC); then \ - $(CXX) -g -c $(CXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES); \ + $(CXX) -g -c $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES); \ else \ - $(CXX) -g -c $(CCSHARED) $(CXXFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES); \ + $(CXX) -g -c $(CCSHARED) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES); \ $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO); \ fi $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(GOSRCS) @@ -1754,12 +1786,12 @@ go_cpp: $(SRCS) $(COMPILETOOL) $(GOPACK) grc $(GOPACKAGE) $(GOGCOBJS) $(GOCSRCS:.c=.$(GOOBJEXT)); \ fi; \ fi - if test -f $(RUNME).go; then \ - $(GO) $(GOCOMPILEARG) $(RUNME).go; \ + if test -f $(SRCDIR)$(RUNME).go; then \ + $(GO) $(GOCOMPILEARG) $(SRCDIR)$(RUNME).go; \ if $(GOGCC) ; then \ $(COMPILETOOL) $(GO) -o $(RUNME) $(RUNME).@OBJEXT@ $(GOGCCOBJS) $(OBJS) $(IOBJS) -lstdc++; \ elif $(GO12) || $(GO13); then \ - $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld $(CXX) -extldflags "$(CXXFLAGS)" -o $(RUNME) $(RUNME).$(GOOBJEXT); \ + $(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; \ @@ -1770,7 +1802,7 @@ go_cpp: $(SRCS) # ----------------------------------------------------------------- go_run: - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) ./$(RUNME) $(RUNPIPE) + env LD_LIBRARY_PATH=$$PWD $(RUNTOOL) ./$(RUNME) $(RUNPIPE) # ----------------------------------------------------------------- # Version display @@ -1812,18 +1844,18 @@ D_RUNME = ./$(RUNME) # Build a dynamically loadable D wrapper for a C module # ---------------------------------------------------------------- -d: $(SRCS) - $(SWIGD) $(SWIGOPT) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(DCFLAGS) $(EXTRA_CFLAGS) $(SRCS) $(ISRCS) $(INCLUDES) +d: $(SRCDIR_SRCS) + $(SWIGD) $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CFLAGS) $(DCFLAGS) $(EXTRA_CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(LDSHARED) $(CFLAGS) $(DCFLAGS) $(EXTRA_LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(DLIBPREFIX)$(TARGET)$(SO) # ---------------------------------------------------------------- # Build a dynamically loadable D wrapper for a C++ module # ---------------------------------------------------------------- -d_cpp: $(SRCS) - $(SWIGD) -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(DCFLAGS) $(EXTRA_CFLAGS) $(SRCS) $(CXXSRCS) $(ICXXSRCS) $(INCLUDES) +d_cpp: $(SRCDIR_SRCS) + $(SWIGD) -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(DCFLAGS) $(EXTRA_CFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(CXXSHARED) $(CXXFLAGS) $(DCFLAGS) $(EXTRA_LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(DLIBPREFIX)$(TARGET)$(SO) # ---------------------------------------------------------------- @@ -1832,7 +1864,7 @@ d_cpp: $(SRCS) # Clear the DFLAGS environment variable for the compiler call itself # to work around a discrepancy in argument handling between DMD and LDC. -d_compile: $(SRCS) +d_compile: $(SRCDIR_SRCS) DFLAGS="" $(COMPILETOOL) $(DCOMPILER) $(DFLAGS) $(DSRCS) # ----------------------------------------------------------------- diff --git a/Examples/android/class/Makefile b/Examples/android/class/Makefile index cef405ece..44d33de0a 100644 --- a/Examples/android/class/Makefile +++ b/Examples/android/class/Makefile @@ -13,14 +13,14 @@ TARGETID = 1 check: build build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' INTERFACEDIR='$(INTERFACEDIR)' \ PROJECTNAME='$(PROJECTNAME)' TARGETID='$(TARGETID)' android_cpp install: - $(MAKE) -f $(TOP)/Makefile INSTALLOPTIONS='$(INSTALLOPTIONS)' PROJECTNAME='$(PROJECTNAME)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INSTALLOPTIONS='$(INSTALLOPTIONS)' PROJECTNAME='$(PROJECTNAME)' \ PACKAGEDIR='$(PACKAGEDIR)' PACKAGENAME='$(PACKAGENAME)' android_install clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' PROJECTNAME='$(PROJECTNAME)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' PROJECTNAME='$(PROJECTNAME)' \ PACKAGEDIR='$(PACKAGEDIR)' INTERFACEDIR='$(INTERFACEDIR)' android_clean diff --git a/Examples/android/extend/Makefile b/Examples/android/extend/Makefile index 9b796494a..3d0609a08 100644 --- a/Examples/android/extend/Makefile +++ b/Examples/android/extend/Makefile @@ -13,14 +13,14 @@ TARGETID = 1 check: build build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' INTERFACEDIR='$(INTERFACEDIR)' \ PROJECTNAME='$(PROJECTNAME)' TARGETID='$(TARGETID)' android_cpp install: - $(MAKE) -f $(TOP)/Makefile INSTALLOPTIONS='$(INSTALLOPTIONS)' PROJECTNAME='$(PROJECTNAME)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INSTALLOPTIONS='$(INSTALLOPTIONS)' PROJECTNAME='$(PROJECTNAME)' \ PACKAGEDIR='$(PACKAGEDIR)' PACKAGENAME='$(PACKAGENAME)' android_install clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' PROJECTNAME='$(PROJECTNAME)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' PROJECTNAME='$(PROJECTNAME)' \ PACKAGEDIR='$(PACKAGEDIR)' INTERFACEDIR='$(INTERFACEDIR)' android_clean diff --git a/Examples/android/simple/Makefile b/Examples/android/simple/Makefile index 7e7ff40e1..d71b9880c 100644 --- a/Examples/android/simple/Makefile +++ b/Examples/android/simple/Makefile @@ -13,14 +13,14 @@ TARGETID = 1 check: build build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' INTERFACEDIR='$(INTERFACEDIR)' \ PROJECTNAME='$(PROJECTNAME)' TARGETID='$(TARGETID)' android install: - $(MAKE) -f $(TOP)/Makefile INSTALLOPTIONS='$(INSTALLOPTIONS)' PROJECTNAME='$(PROJECTNAME)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INSTALLOPTIONS='$(INSTALLOPTIONS)' PROJECTNAME='$(PROJECTNAME)' \ PACKAGEDIR='$(PACKAGEDIR)' PACKAGENAME='$(PACKAGENAME)' android_install clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' PROJECTNAME='$(PROJECTNAME)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' PROJECTNAME='$(PROJECTNAME)' \ PACKAGEDIR='$(PACKAGEDIR)' INTERFACEDIR='$(INTERFACEDIR)' android_clean diff --git a/Examples/chicken/class/Makefile b/Examples/chicken/class/Makefile index cd445c867..5fafa5c15 100644 --- a/Examples/chicken/class/Makefile +++ b/Examples/chicken/class/Makefile @@ -15,24 +15,24 @@ VARIANT = #VARIANT = _static check: build - $(MAKE) -f $(TOP)/Makefile CHICKEN_SCRIPT='runme-lowlevel.scm' chicken_run - $(MAKE) -f $(TOP)/Makefile CHICKEN_SCRIPT='runme-tinyclos.scm' chicken_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CHICKEN_SCRIPT='runme-lowlevel.scm' chicken_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CHICKEN_SCRIPT='runme-tinyclos.scm' chicken_run build: $(TARGET) $(TARGET)_proxy $(TARGET): $(INTERFACE) $(SRCS) - $(MAKE) -f $(TOP)/Makefile \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \ INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' \ SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT)_cpp $(TARGET)_proxy: $(INTERFACE) $(SRCS) - $(MAKE) -f $(TOP)/Makefile \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \ INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT) -proxy' TARGET='$(TARGET)_proxy' \ SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT)_cpp clean: - $(MAKE) -f $(TOP)/Makefile chicken_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_clean rm -f example.scm rm -f $(TARGET) diff --git a/Examples/chicken/constants/Makefile b/Examples/chicken/constants/Makefile index fe396733e..a6100f757 100644 --- a/Examples/chicken/constants/Makefile +++ b/Examples/chicken/constants/Makefile @@ -14,17 +14,17 @@ VARIANT = #VARIANT = _static check: build - $(MAKE) -f $(TOP)/Makefile chicken_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_run build: $(TARGET) $(TARGET): $(INTERFACE) $(SRCS) - $(MAKE) -f $(TOP)/Makefile \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \ INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' \ SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT) clean: - $(MAKE) -f $(TOP)/Makefile chicken_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_clean rm -f example.scm rm -f $(TARGET) diff --git a/Examples/chicken/multimap/Makefile b/Examples/chicken/multimap/Makefile index d92cfede0..79282be17 100644 --- a/Examples/chicken/multimap/Makefile +++ b/Examples/chicken/multimap/Makefile @@ -14,17 +14,17 @@ VARIANT = #VARIANT = _static check: build - $(MAKE) -f $(TOP)/Makefile chicken_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_run build: $(TARGET) $(TARGET): $(INTERFACE) $(SRCS) - $(MAKE) -f $(TOP)/Makefile \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \ INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' \ SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT) clean: - $(MAKE) -f $(TOP)/Makefile chicken_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_clean rm -f example.scm rm -f $(TARGET) diff --git a/Examples/chicken/overload/Makefile b/Examples/chicken/overload/Makefile index fb190e882..717abd335 100644 --- a/Examples/chicken/overload/Makefile +++ b/Examples/chicken/overload/Makefile @@ -14,17 +14,17 @@ VARIANT = #VARIANT = _static check: build - $(MAKE) -f $(TOP)/Makefile chicken_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_run build: $(TARGET) $(TARGET): $(INTERFACE) $(SRCS) - $(MAKE) -f $(TOP)/Makefile \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \ INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' \ SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT)_cpp clean: - $(MAKE) -f $(TOP)/Makefile chicken_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_clean rm -f example.scm rm -f $(TARGET) diff --git a/Examples/chicken/simple/Makefile b/Examples/chicken/simple/Makefile index d0d737484..9d1f34fa0 100644 --- a/Examples/chicken/simple/Makefile +++ b/Examples/chicken/simple/Makefile @@ -14,17 +14,17 @@ VARIANT = #VARIANT = _static check: build - $(MAKE) -f $(TOP)/Makefile chicken_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_run build: $(TARGET) $(TARGET): $(INTERFACE) $(SRCS) - $(MAKE) -f $(TOP)/Makefile \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' \ SRCS='$(SRCS)' CXXSRCS='$(CXXSRCS)' CHICKEN_MAIN='$(CHICKEN_MAIN)' \ INCLUDE='$(INCLUDE)' SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' \ SWIG='$(SWIG)' INTERFACE='$(INTERFACE)' CHICKENOPTS='$(CHICKENOPTS)' chicken$(VARIANT) clean: - $(MAKE) -f $(TOP)/Makefile chicken_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' chicken_clean rm -f example.scm example-generic.scm example-clos.scm rm -f $(TARGET) diff --git a/Examples/csharp/arrays/Makefile b/Examples/csharp/arrays/Makefile index 4be092d1c..e5d733d35 100644 --- a/Examples/csharp/arrays/Makefile +++ b/Examples/csharp/arrays/Makefile @@ -8,12 +8,12 @@ CSHARPSRCS = *.cs CSHARPFLAGS= -nologo -debug+ -unsafe -out:runme.exe check: build - $(MAKE) -f $(TOP)/Makefile csharp_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp - $(MAKE) -f $(TOP)/Makefile CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile clean: - $(MAKE) -f $(TOP)/Makefile csharp_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_clean diff --git a/Examples/csharp/callback/Makefile b/Examples/csharp/callback/Makefile index 6c58abd28..4f4c84b9a 100644 --- a/Examples/csharp/callback/Makefile +++ b/Examples/csharp/callback/Makefile @@ -8,12 +8,12 @@ CSHARPSRCS = *.cs CSHARPFLAGS= -nologo -debug+ -out:runme.exe check: build - $(MAKE) -f $(TOP)/Makefile csharp_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp_cpp - $(MAKE) -f $(TOP)/Makefile CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile clean: - $(MAKE) -f $(TOP)/Makefile csharp_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_clean diff --git a/Examples/csharp/class/Makefile b/Examples/csharp/class/Makefile index 6c58abd28..4f4c84b9a 100644 --- a/Examples/csharp/class/Makefile +++ b/Examples/csharp/class/Makefile @@ -8,12 +8,12 @@ CSHARPSRCS = *.cs CSHARPFLAGS= -nologo -debug+ -out:runme.exe check: build - $(MAKE) -f $(TOP)/Makefile csharp_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp_cpp - $(MAKE) -f $(TOP)/Makefile CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile clean: - $(MAKE) -f $(TOP)/Makefile csharp_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_clean diff --git a/Examples/csharp/enum/Makefile b/Examples/csharp/enum/Makefile index 6c58abd28..4f4c84b9a 100644 --- a/Examples/csharp/enum/Makefile +++ b/Examples/csharp/enum/Makefile @@ -8,12 +8,12 @@ CSHARPSRCS = *.cs CSHARPFLAGS= -nologo -debug+ -out:runme.exe check: build - $(MAKE) -f $(TOP)/Makefile csharp_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp_cpp - $(MAKE) -f $(TOP)/Makefile CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile clean: - $(MAKE) -f $(TOP)/Makefile csharp_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_clean diff --git a/Examples/csharp/extend/Makefile b/Examples/csharp/extend/Makefile index 6c58abd28..4f4c84b9a 100644 --- a/Examples/csharp/extend/Makefile +++ b/Examples/csharp/extend/Makefile @@ -8,12 +8,12 @@ CSHARPSRCS = *.cs CSHARPFLAGS= -nologo -debug+ -out:runme.exe check: build - $(MAKE) -f $(TOP)/Makefile csharp_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp_cpp - $(MAKE) -f $(TOP)/Makefile CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile clean: - $(MAKE) -f $(TOP)/Makefile csharp_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_clean diff --git a/Examples/csharp/funcptr/Makefile b/Examples/csharp/funcptr/Makefile index ed15cb28e..99cdfa38a 100644 --- a/Examples/csharp/funcptr/Makefile +++ b/Examples/csharp/funcptr/Makefile @@ -8,12 +8,12 @@ CSHARPSRCS = *.cs CSHARPFLAGS= -nologo -debug+ -out:runme.exe check: build - $(MAKE) -f $(TOP)/Makefile csharp_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp - $(MAKE) -f $(TOP)/Makefile CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile clean: - $(MAKE) -f $(TOP)/Makefile csharp_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_clean diff --git a/Examples/csharp/nested/Makefile b/Examples/csharp/nested/Makefile index 6c58abd28..4f4c84b9a 100644 --- a/Examples/csharp/nested/Makefile +++ b/Examples/csharp/nested/Makefile @@ -8,12 +8,12 @@ CSHARPSRCS = *.cs CSHARPFLAGS= -nologo -debug+ -out:runme.exe check: build - $(MAKE) -f $(TOP)/Makefile csharp_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp_cpp - $(MAKE) -f $(TOP)/Makefile CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile clean: - $(MAKE) -f $(TOP)/Makefile csharp_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_clean diff --git a/Examples/csharp/reference/Makefile b/Examples/csharp/reference/Makefile index 6c58abd28..4f4c84b9a 100644 --- a/Examples/csharp/reference/Makefile +++ b/Examples/csharp/reference/Makefile @@ -8,12 +8,12 @@ CSHARPSRCS = *.cs CSHARPFLAGS= -nologo -debug+ -out:runme.exe check: build - $(MAKE) -f $(TOP)/Makefile csharp_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp_cpp - $(MAKE) -f $(TOP)/Makefile CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile clean: - $(MAKE) -f $(TOP)/Makefile csharp_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_clean diff --git a/Examples/csharp/simple/Makefile b/Examples/csharp/simple/Makefile index ed15cb28e..99cdfa38a 100644 --- a/Examples/csharp/simple/Makefile +++ b/Examples/csharp/simple/Makefile @@ -8,12 +8,12 @@ CSHARPSRCS = *.cs CSHARPFLAGS= -nologo -debug+ -out:runme.exe check: build - $(MAKE) -f $(TOP)/Makefile csharp_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp - $(MAKE) -f $(TOP)/Makefile CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile clean: - $(MAKE) -f $(TOP)/Makefile csharp_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_clean diff --git a/Examples/csharp/template/Makefile b/Examples/csharp/template/Makefile index 23fe2eec9..2d0e07009 100644 --- a/Examples/csharp/template/Makefile +++ b/Examples/csharp/template/Makefile @@ -8,12 +8,12 @@ CSHARPSRCS = *.cs CSHARPFLAGS= -nologo -debug+ -out:runme.exe check: build - $(MAKE) -f $(TOP)/Makefile csharp_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp_cpp - $(MAKE) -f $(TOP)/Makefile CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile clean: - $(MAKE) -f $(TOP)/Makefile csharp_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_clean diff --git a/Examples/csharp/variables/Makefile b/Examples/csharp/variables/Makefile index ed15cb28e..99cdfa38a 100644 --- a/Examples/csharp/variables/Makefile +++ b/Examples/csharp/variables/Makefile @@ -8,12 +8,12 @@ CSHARPSRCS = *.cs CSHARPFLAGS= -nologo -debug+ -out:runme.exe check: build - $(MAKE) -f $(TOP)/Makefile csharp_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' csharp - $(MAKE) -f $(TOP)/Makefile CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CSHARPSRCS='$(CSHARPSRCS)' CSHARPFLAGS='$(CSHARPFLAGS)' csharp_compile clean: - $(MAKE) -f $(TOP)/Makefile csharp_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' csharp_clean diff --git a/Examples/d/callback/Makefile b/Examples/d/callback/Makefile index eda18f13c..72edc17a5 100644 --- a/Examples/d/callback/Makefile +++ b/Examples/d/callback/Makefile @@ -15,13 +15,13 @@ DFLAGS = -ofrunme check: build cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile d_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' d_run build: cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile EXTRA_CFLAGS='$(EXTRA_CFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -outcurrentdir ../example.i' TARGET='$(TARGET)' d_cpp; \ - $(MAKE) -f $(TOP)/Makefile DSRCS='$(DSRCS)' DFLAGS='$(DFLAGS)' d_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' EXTRA_CFLAGS='$(EXTRA_CFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -outcurrentdir ../example.i' TARGET='$(TARGET)' d_cpp; \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' DSRCS='$(DSRCS)' DFLAGS='$(DFLAGS)' d_compile clean: cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile d_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' d_clean diff --git a/Examples/d/class/Makefile b/Examples/d/class/Makefile index eda18f13c..72edc17a5 100644 --- a/Examples/d/class/Makefile +++ b/Examples/d/class/Makefile @@ -15,13 +15,13 @@ DFLAGS = -ofrunme check: build cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile d_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' d_run build: cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile EXTRA_CFLAGS='$(EXTRA_CFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -outcurrentdir ../example.i' TARGET='$(TARGET)' d_cpp; \ - $(MAKE) -f $(TOP)/Makefile DSRCS='$(DSRCS)' DFLAGS='$(DFLAGS)' d_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' EXTRA_CFLAGS='$(EXTRA_CFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -outcurrentdir ../example.i' TARGET='$(TARGET)' d_cpp; \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' DSRCS='$(DSRCS)' DFLAGS='$(DFLAGS)' d_compile clean: cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile d_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' d_clean diff --git a/Examples/d/constants/Makefile b/Examples/d/constants/Makefile index d537ce281..609c7f660 100644 --- a/Examples/d/constants/Makefile +++ b/Examples/d/constants/Makefile @@ -15,13 +15,13 @@ DFLAGS = -ofrunme check: build cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile d_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' d_run build: cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile EXTRA_CFLAGS='$(EXTRA_CFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -outcurrentdir ../example.i' TARGET='$(TARGET)' d; \ - $(MAKE) -f $(TOP)/Makefile DSRCS='$(DSRCS)' DFLAGS='$(DFLAGS)' d_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' EXTRA_CFLAGS='$(EXTRA_CFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -outcurrentdir ../example.i' TARGET='$(TARGET)' d; \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' DSRCS='$(DSRCS)' DFLAGS='$(DFLAGS)' d_compile clean: cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile d_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' d_clean diff --git a/Examples/d/enum/Makefile b/Examples/d/enum/Makefile index eda18f13c..72edc17a5 100644 --- a/Examples/d/enum/Makefile +++ b/Examples/d/enum/Makefile @@ -15,13 +15,13 @@ DFLAGS = -ofrunme check: build cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile d_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' d_run build: cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile EXTRA_CFLAGS='$(EXTRA_CFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -outcurrentdir ../example.i' TARGET='$(TARGET)' d_cpp; \ - $(MAKE) -f $(TOP)/Makefile DSRCS='$(DSRCS)' DFLAGS='$(DFLAGS)' d_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' EXTRA_CFLAGS='$(EXTRA_CFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -outcurrentdir ../example.i' TARGET='$(TARGET)' d_cpp; \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' DSRCS='$(DSRCS)' DFLAGS='$(DFLAGS)' d_compile clean: cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile d_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' d_clean diff --git a/Examples/d/extend/Makefile b/Examples/d/extend/Makefile index eda18f13c..72edc17a5 100644 --- a/Examples/d/extend/Makefile +++ b/Examples/d/extend/Makefile @@ -15,13 +15,13 @@ DFLAGS = -ofrunme check: build cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile d_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' d_run build: cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile EXTRA_CFLAGS='$(EXTRA_CFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -outcurrentdir ../example.i' TARGET='$(TARGET)' d_cpp; \ - $(MAKE) -f $(TOP)/Makefile DSRCS='$(DSRCS)' DFLAGS='$(DFLAGS)' d_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' EXTRA_CFLAGS='$(EXTRA_CFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -outcurrentdir ../example.i' TARGET='$(TARGET)' d_cpp; \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' DSRCS='$(DSRCS)' DFLAGS='$(DFLAGS)' d_compile clean: cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile d_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' d_clean diff --git a/Examples/d/funcptr/Makefile b/Examples/d/funcptr/Makefile index 2ba893ca7..6554c3c73 100644 --- a/Examples/d/funcptr/Makefile +++ b/Examples/d/funcptr/Makefile @@ -15,13 +15,13 @@ DFLAGS = -ofrunme check: build cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile d_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' d_run build: cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile EXTRA_CFLAGS='$(EXTRA_CFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -outcurrentdir ../example.i' TARGET='$(TARGET)' d; \ - $(MAKE) -f $(TOP)/Makefile DSRCS='$(DSRCS)' DFLAGS='$(DFLAGS)' d_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' EXTRA_CFLAGS='$(EXTRA_CFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -outcurrentdir ../example.i' TARGET='$(TARGET)' d; \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' DSRCS='$(DSRCS)' DFLAGS='$(DFLAGS)' d_compile clean: cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile d_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' d_clean diff --git a/Examples/d/simple/Makefile b/Examples/d/simple/Makefile index a8808c9c5..f5eed3210 100644 --- a/Examples/d/simple/Makefile +++ b/Examples/d/simple/Makefile @@ -15,13 +15,13 @@ DFLAGS = -ofrunme check: build cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile d_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' d_run build: cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile EXTRA_CFLAGS='$(EXTRA_CFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -outcurrentdir ../example.i' TARGET='$(TARGET)' d; \ - $(MAKE) -f $(TOP)/Makefile DSRCS='$(DSRCS)' DFLAGS='$(DFLAGS)' d_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' EXTRA_CFLAGS='$(EXTRA_CFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -outcurrentdir ../example.i' TARGET='$(TARGET)' d; \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' DSRCS='$(DSRCS)' DFLAGS='$(DFLAGS)' d_compile clean: cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile d_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' d_clean diff --git a/Examples/d/variables/Makefile b/Examples/d/variables/Makefile index a8808c9c5..f5eed3210 100644 --- a/Examples/d/variables/Makefile +++ b/Examples/d/variables/Makefile @@ -15,13 +15,13 @@ DFLAGS = -ofrunme check: build cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile d_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' d_run build: cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile EXTRA_CFLAGS='$(EXTRA_CFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -outcurrentdir ../example.i' TARGET='$(TARGET)' d; \ - $(MAKE) -f $(TOP)/Makefile DSRCS='$(DSRCS)' DFLAGS='$(DFLAGS)' d_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' EXTRA_CFLAGS='$(EXTRA_CFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -outcurrentdir ../example.i' TARGET='$(TARGET)' d; \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' DSRCS='$(DSRCS)' DFLAGS='$(DFLAGS)' d_compile clean: cd $(WORKING_DIR); \ - $(MAKE) -f $(TOP)/Makefile d_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' d_clean diff --git a/Examples/go/callback/Makefile b/Examples/go/callback/Makefile index 46a14b417..bf5275f14 100644 --- a/Examples/go/callback/Makefile +++ b/Examples/go/callback/Makefile @@ -6,11 +6,11 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_cpp clean: - $(MAKE) -f $(TOP)/Makefile INTERFACE='$(INTERFACE)' go_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' go_clean diff --git a/Examples/go/class/Makefile b/Examples/go/class/Makefile index 72605caa5..de067cdd8 100644 --- a/Examples/go/class/Makefile +++ b/Examples/go/class/Makefile @@ -6,11 +6,11 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_cpp clean: - $(MAKE) -f $(TOP)/Makefile INTERFACE='$(INTERFACE)' go_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' go_clean diff --git a/Examples/go/constants/Makefile b/Examples/go/constants/Makefile index 9fa967366..8fb07fd6b 100644 --- a/Examples/go/constants/Makefile +++ b/Examples/go/constants/Makefile @@ -6,11 +6,11 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go clean: - $(MAKE) -f $(TOP)/Makefile INTERFACE='$(INTERFACE)' go_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' go_clean diff --git a/Examples/go/enum/Makefile b/Examples/go/enum/Makefile index 1ceecc15c..2e2f1b2bd 100644 --- a/Examples/go/enum/Makefile +++ b/Examples/go/enum/Makefile @@ -6,11 +6,11 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_cpp clean: - $(MAKE) -f $(TOP)/Makefile INTERFACE='$(INTERFACE)' go_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' go_clean diff --git a/Examples/go/extend/Makefile b/Examples/go/extend/Makefile index 67da89286..290694210 100644 --- a/Examples/go/extend/Makefile +++ b/Examples/go/extend/Makefile @@ -6,11 +6,11 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_cpp clean: - $(MAKE) -f $(TOP)/Makefile INTERFACE='$(INTERFACE)' go_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' go_clean diff --git a/Examples/go/funcptr/Makefile b/Examples/go/funcptr/Makefile index 2c32c45fc..82031c9d5 100644 --- a/Examples/go/funcptr/Makefile +++ b/Examples/go/funcptr/Makefile @@ -6,11 +6,11 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go clean: - $(MAKE) -f $(TOP)/Makefile INTERFACE='$(INTERFACE)' go_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' go_clean diff --git a/Examples/go/multimap/Makefile b/Examples/go/multimap/Makefile index 0c5ec395f..4d739162b 100644 --- a/Examples/go/multimap/Makefile +++ b/Examples/go/multimap/Makefile @@ -6,11 +6,11 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go clean: - $(MAKE) -f $(TOP)/Makefile INTERFACE='$(INTERFACE)' go_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' go_clean diff --git a/Examples/go/pointer/Makefile b/Examples/go/pointer/Makefile index 12e94f939..9f1f3fda0 100644 --- a/Examples/go/pointer/Makefile +++ b/Examples/go/pointer/Makefile @@ -6,11 +6,11 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go clean: - $(MAKE) -f $(TOP)/Makefile INTERFACE='$(INTERFACE)' go_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' go_clean diff --git a/Examples/go/reference/Makefile b/Examples/go/reference/Makefile index 41a944239..e136f6fae 100644 --- a/Examples/go/reference/Makefile +++ b/Examples/go/reference/Makefile @@ -6,11 +6,11 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_cpp clean: - $(MAKE) -f $(TOP)/Makefile INTERFACE='$(INTERFACE)' go_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' go_clean diff --git a/Examples/go/simple/Makefile b/Examples/go/simple/Makefile index 907da8821..5bc16549d 100644 --- a/Examples/go/simple/Makefile +++ b/Examples/go/simple/Makefile @@ -5,11 +5,11 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go clean: - $(MAKE) -f $(TOP)/Makefile INTERFACE='$(INTERFACE)' go_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' go_clean diff --git a/Examples/go/template/Makefile b/Examples/go/template/Makefile index 51cd97a80..a1d674836 100644 --- a/Examples/go/template/Makefile +++ b/Examples/go/template/Makefile @@ -6,11 +6,11 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_cpp clean: - $(MAKE) -f $(TOP)/Makefile INTERFACE='$(INTERFACE)' go_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' go_clean diff --git a/Examples/go/variables/Makefile b/Examples/go/variables/Makefile index 1f144929c..d0da605e0 100644 --- a/Examples/go/variables/Makefile +++ b/Examples/go/variables/Makefile @@ -6,11 +6,11 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' go clean: - $(MAKE) -f $(TOP)/Makefile INTERFACE='$(INTERFACE)' go_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' go_clean diff --git a/Examples/guile/class/Makefile b/Examples/guile/class/Makefile index 8de4f292b..48426a8fb 100644 --- a/Examples/guile/class/Makefile +++ b/Examples/guile/class/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile guile_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' guile_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='my-guile' INTERFACE='$(INTERFACE)' guile_static_cpp clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' guile_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_clean diff --git a/Examples/guile/constants/Makefile b/Examples/guile/constants/Makefile index 2b6965e9e..d3f58ebdc 100644 --- a/Examples/guile/constants/Makefile +++ b/Examples/guile/constants/Makefile @@ -5,11 +5,11 @@ TARGET = my-guile INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' guile_augmented_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_augmented_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile_augmented clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' guile_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_clean diff --git a/Examples/guile/matrix/Makefile b/Examples/guile/matrix/Makefile index a32210e65..53638c867 100644 --- a/Examples/guile/matrix/Makefile +++ b/Examples/guile/matrix/Makefile @@ -5,11 +5,11 @@ TARGET = matrix INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' GUILE_RUNOPTIONS='-e do-test' guile_augmented_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' GUILE_RUNOPTIONS='-e do-test' guile_augmented_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' LIBS='-lm' guile_augmented clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' guile_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_clean diff --git a/Examples/guile/multimap/Makefile b/Examples/guile/multimap/Makefile index 4ca82a3d3..b8f5e9b5a 100644 --- a/Examples/guile/multimap/Makefile +++ b/Examples/guile/multimap/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile guile_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' guile_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='my-guile' INTERFACE='$(INTERFACE)' guile_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' guile_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_clean diff --git a/Examples/guile/multivalue/Makefile b/Examples/guile/multivalue/Makefile index 4ca82a3d3..b8f5e9b5a 100644 --- a/Examples/guile/multivalue/Makefile +++ b/Examples/guile/multivalue/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile guile_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' guile_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='my-guile' INTERFACE='$(INTERFACE)' guile_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' guile_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_clean diff --git a/Examples/guile/port/Makefile b/Examples/guile/port/Makefile index d6ec0ac24..95a3a479f 100644 --- a/Examples/guile/port/Makefile +++ b/Examples/guile/port/Makefile @@ -5,12 +5,12 @@ TARGET = port INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' guile_augmented_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_augmented_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile_augmented clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' guile_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_clean rm -f test.out diff --git a/Examples/guile/simple/Makefile b/Examples/guile/simple/Makefile index da4eb9015..517e41c64 100644 --- a/Examples/guile/simple/Makefile +++ b/Examples/guile/simple/Makefile @@ -5,11 +5,11 @@ TARGET = my-guile INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' guile_augmented_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_augmented_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile_augmented clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' guile_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_clean diff --git a/Examples/guile/std_vector/Makefile b/Examples/guile/std_vector/Makefile index fd7a8439a..d7f5de217 100644 --- a/Examples/guile/std_vector/Makefile +++ b/Examples/guile/std_vector/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile guile_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' guile_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' guile_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='my-guile' INTERFACE='$(INTERFACE)' guile_static_cpp clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' guile_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' guile_clean diff --git a/Examples/java/callback/Makefile b/Examples/java/callback/Makefile index 8f274e7cb..13cfd1708 100644 --- a/Examples/java/callback/Makefile +++ b/Examples/java/callback/Makefile @@ -7,12 +7,12 @@ SWIGOPT = JAVASRCS = *.java check: build - $(MAKE) -f $(TOP)/Makefile java_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp - $(MAKE) -f $(TOP)/Makefile JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile clean: - $(MAKE) -f $(TOP)/Makefile java_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/class/Makefile b/Examples/java/class/Makefile index 8f274e7cb..13cfd1708 100644 --- a/Examples/java/class/Makefile +++ b/Examples/java/class/Makefile @@ -7,12 +7,12 @@ SWIGOPT = JAVASRCS = *.java check: build - $(MAKE) -f $(TOP)/Makefile java_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp - $(MAKE) -f $(TOP)/Makefile JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile clean: - $(MAKE) -f $(TOP)/Makefile java_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/constants/Makefile b/Examples/java/constants/Makefile index 4e21fc4cd..637ce0ead 100644 --- a/Examples/java/constants/Makefile +++ b/Examples/java/constants/Makefile @@ -7,12 +7,12 @@ SWIGOPT = JAVASRCS = *.java check: build - $(MAKE) -f $(TOP)/Makefile java_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp - $(MAKE) -f $(TOP)/Makefile JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile clean: - $(MAKE) -f $(TOP)/Makefile java_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/enum/Makefile b/Examples/java/enum/Makefile index 8f274e7cb..13cfd1708 100644 --- a/Examples/java/enum/Makefile +++ b/Examples/java/enum/Makefile @@ -7,12 +7,12 @@ SWIGOPT = JAVASRCS = *.java check: build - $(MAKE) -f $(TOP)/Makefile java_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp - $(MAKE) -f $(TOP)/Makefile JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile clean: - $(MAKE) -f $(TOP)/Makefile java_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/extend/Makefile b/Examples/java/extend/Makefile index 8f274e7cb..13cfd1708 100644 --- a/Examples/java/extend/Makefile +++ b/Examples/java/extend/Makefile @@ -7,12 +7,12 @@ SWIGOPT = JAVASRCS = *.java check: build - $(MAKE) -f $(TOP)/Makefile java_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp - $(MAKE) -f $(TOP)/Makefile JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile clean: - $(MAKE) -f $(TOP)/Makefile java_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/funcptr/Makefile b/Examples/java/funcptr/Makefile index e9e29f3a3..c0b1927ca 100644 --- a/Examples/java/funcptr/Makefile +++ b/Examples/java/funcptr/Makefile @@ -7,12 +7,12 @@ SWIGOPT = JAVASRCS = *.java check: build - $(MAKE) -f $(TOP)/Makefile java_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java - $(MAKE) -f $(TOP)/Makefile JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile clean: - $(MAKE) -f $(TOP)/Makefile java_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/multimap/Makefile b/Examples/java/multimap/Makefile index e9e29f3a3..c0b1927ca 100644 --- a/Examples/java/multimap/Makefile +++ b/Examples/java/multimap/Makefile @@ -7,12 +7,12 @@ SWIGOPT = JAVASRCS = *.java check: build - $(MAKE) -f $(TOP)/Makefile java_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java - $(MAKE) -f $(TOP)/Makefile JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile clean: - $(MAKE) -f $(TOP)/Makefile java_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/native/Makefile b/Examples/java/native/Makefile index e858cbe77..fa67e48a4 100644 --- a/Examples/java/native/Makefile +++ b/Examples/java/native/Makefile @@ -7,12 +7,12 @@ SWIGOPT = JAVASRCS = *.java check: build - $(MAKE) -f $(TOP)/Makefile java_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java - $(MAKE) -f $(TOP)/Makefile JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile clean: - $(MAKE) -f $(TOP)/Makefile java_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/nested/Makefile b/Examples/java/nested/Makefile index 8f274e7cb..13cfd1708 100644 --- a/Examples/java/nested/Makefile +++ b/Examples/java/nested/Makefile @@ -7,12 +7,12 @@ SWIGOPT = JAVASRCS = *.java check: build - $(MAKE) -f $(TOP)/Makefile java_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp - $(MAKE) -f $(TOP)/Makefile JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile clean: - $(MAKE) -f $(TOP)/Makefile java_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/pointer/Makefile b/Examples/java/pointer/Makefile index e9e29f3a3..c0b1927ca 100644 --- a/Examples/java/pointer/Makefile +++ b/Examples/java/pointer/Makefile @@ -7,12 +7,12 @@ SWIGOPT = JAVASRCS = *.java check: build - $(MAKE) -f $(TOP)/Makefile java_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java - $(MAKE) -f $(TOP)/Makefile JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile clean: - $(MAKE) -f $(TOP)/Makefile java_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/reference/Makefile b/Examples/java/reference/Makefile index 8f274e7cb..13cfd1708 100644 --- a/Examples/java/reference/Makefile +++ b/Examples/java/reference/Makefile @@ -7,12 +7,12 @@ SWIGOPT = JAVASRCS = *.java check: build - $(MAKE) -f $(TOP)/Makefile java_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp - $(MAKE) -f $(TOP)/Makefile JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile clean: - $(MAKE) -f $(TOP)/Makefile java_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/simple/Makefile b/Examples/java/simple/Makefile index e9e29f3a3..c0b1927ca 100644 --- a/Examples/java/simple/Makefile +++ b/Examples/java/simple/Makefile @@ -7,12 +7,12 @@ SWIGOPT = JAVASRCS = *.java check: build - $(MAKE) -f $(TOP)/Makefile java_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java - $(MAKE) -f $(TOP)/Makefile JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile clean: - $(MAKE) -f $(TOP)/Makefile java_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/template/Makefile b/Examples/java/template/Makefile index 4e21fc4cd..637ce0ead 100644 --- a/Examples/java/template/Makefile +++ b/Examples/java/template/Makefile @@ -7,12 +7,12 @@ SWIGOPT = JAVASRCS = *.java check: build - $(MAKE) -f $(TOP)/Makefile java_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java_cpp - $(MAKE) -f $(TOP)/Makefile JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile clean: - $(MAKE) -f $(TOP)/Makefile java_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/typemap/Makefile b/Examples/java/typemap/Makefile index e858cbe77..fa67e48a4 100644 --- a/Examples/java/typemap/Makefile +++ b/Examples/java/typemap/Makefile @@ -7,12 +7,12 @@ SWIGOPT = JAVASRCS = *.java check: build - $(MAKE) -f $(TOP)/Makefile java_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java - $(MAKE) -f $(TOP)/Makefile JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile clean: - $(MAKE) -f $(TOP)/Makefile java_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/java/variables/Makefile b/Examples/java/variables/Makefile index e9e29f3a3..c0b1927ca 100644 --- a/Examples/java/variables/Makefile +++ b/Examples/java/variables/Makefile @@ -7,12 +7,12 @@ SWIGOPT = JAVASRCS = *.java check: build - $(MAKE) -f $(TOP)/Makefile java_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' java - $(MAKE) -f $(TOP)/Makefile JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' JAVASRCS='$(JAVASRCS)' JAVAFLAGS='$(JAVAFLAGS)' java_compile clean: - $(MAKE) -f $(TOP)/Makefile java_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' java_clean diff --git a/Examples/javascript/class/Makefile b/Examples/javascript/class/Makefile index 31846faae..54a8f7b03 100644 --- a/Examples/javascript/class/Makefile +++ b/Examples/javascript/class/Makefile @@ -1,3 +1,3 @@ SRCS = example.cxx -include ../example.mk +include $(SRCDIR)../example.mk diff --git a/Examples/javascript/class/binding.gyp b/Examples/javascript/class/binding.gyp deleted file mode 100644 index 54eebfaa0..000000000 --- a/Examples/javascript/class/binding.gyp +++ /dev/null @@ -1,8 +0,0 @@ -{ - "targets": [ - { - "target_name": "example", - "sources": [ "example.cxx", "example_wrap.cxx" ] - } - ] -} diff --git a/Examples/javascript/class/binding.gyp.in b/Examples/javascript/class/binding.gyp.in new file mode 100644 index 000000000..c56a650e9 --- /dev/null +++ b/Examples/javascript/class/binding.gyp.in @@ -0,0 +1,9 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "$srcdir/example.cxx", "example_wrap.cxx" ], + "include_dirs": ["$srcdir"] + } + ] +} diff --git a/Examples/javascript/class/example.js b/Examples/javascript/class/example.js index 79cd3913f..2e7f83a06 100644 --- a/Examples/javascript/class/example.js +++ b/Examples/javascript/class/example.js @@ -1 +1 @@ -module.exports = require("./build/Release/example"); +module.exports = require("build/Release/example"); diff --git a/Examples/javascript/class/runme.js b/Examples/javascript/class/runme.js index e1d5d9797..6a77b8d8e 100644 --- a/Examples/javascript/class/runme.js +++ b/Examples/javascript/class/runme.js @@ -1,4 +1,4 @@ -var example = require("./example"); +var example = require("example"); // ----- Object creation ----- diff --git a/Examples/javascript/constant/Makefile b/Examples/javascript/constant/Makefile index ea04c7df8..0402f8d09 100644 --- a/Examples/javascript/constant/Makefile +++ b/Examples/javascript/constant/Makefile @@ -1,3 +1,3 @@ SRCS = -include ../example.mk +include $(SRCDIR)../example.mk diff --git a/Examples/javascript/constant/binding.gyp b/Examples/javascript/constant/binding.gyp deleted file mode 100644 index 69af46b22..000000000 --- a/Examples/javascript/constant/binding.gyp +++ /dev/null @@ -1,8 +0,0 @@ -{ - "targets": [ - { - "target_name": "example", - "sources": [ "example_wrap.cxx" ] - } - ] -} diff --git a/Examples/javascript/constant/binding.gyp.in b/Examples/javascript/constant/binding.gyp.in new file mode 100644 index 000000000..59779aef4 --- /dev/null +++ b/Examples/javascript/constant/binding.gyp.in @@ -0,0 +1,9 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example_wrap.cxx" ], + "include_dirs": ["$srcdir"] + } + ] +} diff --git a/Examples/javascript/constant/example.js b/Examples/javascript/constant/example.js index 79cd3913f..2e7f83a06 100644 --- a/Examples/javascript/constant/example.js +++ b/Examples/javascript/constant/example.js @@ -1 +1 @@ -module.exports = require("./build/Release/example"); +module.exports = require("build/Release/example"); diff --git a/Examples/javascript/constant/runme.js b/Examples/javascript/constant/runme.js index f4b55881e..f29d1a850 100644 --- a/Examples/javascript/constant/runme.js +++ b/Examples/javascript/constant/runme.js @@ -1,4 +1,4 @@ -var example = require("./example"); +var example = require("example"); console.log("ICONST = " + example.ICONST + " (should be 42)"); console.log("FCONST = " + example.FCONST + " (should be 2.1828)"); diff --git a/Examples/javascript/enum/Makefile b/Examples/javascript/enum/Makefile index 31846faae..54a8f7b03 100644 --- a/Examples/javascript/enum/Makefile +++ b/Examples/javascript/enum/Makefile @@ -1,3 +1,3 @@ SRCS = example.cxx -include ../example.mk +include $(SRCDIR)../example.mk diff --git a/Examples/javascript/enum/binding.gyp b/Examples/javascript/enum/binding.gyp deleted file mode 100644 index 54eebfaa0..000000000 --- a/Examples/javascript/enum/binding.gyp +++ /dev/null @@ -1,8 +0,0 @@ -{ - "targets": [ - { - "target_name": "example", - "sources": [ "example.cxx", "example_wrap.cxx" ] - } - ] -} diff --git a/Examples/javascript/enum/binding.gyp.in b/Examples/javascript/enum/binding.gyp.in new file mode 100644 index 000000000..c56a650e9 --- /dev/null +++ b/Examples/javascript/enum/binding.gyp.in @@ -0,0 +1,9 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "$srcdir/example.cxx", "example_wrap.cxx" ], + "include_dirs": ["$srcdir"] + } + ] +} diff --git a/Examples/javascript/enum/example.js b/Examples/javascript/enum/example.js index 79cd3913f..2e7f83a06 100644 --- a/Examples/javascript/enum/example.js +++ b/Examples/javascript/enum/example.js @@ -1 +1 @@ -module.exports = require("./build/Release/example"); +module.exports = require("build/Release/example"); diff --git a/Examples/javascript/enum/runme.js b/Examples/javascript/enum/runme.js index d4e89e8c8..851d43c4b 100644 --- a/Examples/javascript/enum/runme.js +++ b/Examples/javascript/enum/runme.js @@ -1,4 +1,4 @@ -var example = require("./example"); +var example = require("example"); // ----- Object creation ----- diff --git a/Examples/javascript/example.mk b/Examples/javascript/example.mk index 274eff1a3..5a335bba4 100644 --- a/Examples/javascript/example.mk +++ b/Examples/javascript/example.mk @@ -15,13 +15,13 @@ INTERFACE = example.i SWIGOPT=-$(JSENGINE) check: build - $(MAKE) -f $(EXAMPLES_TOP)/Makefile JSENGINE='$(JSENGINE)' TARGET='$(TARGET)' javascript_run + $(MAKE) -f $(EXAMPLES_TOP)/Makefile SRCDIR='$(SRCDIR)' JSENGINE='$(JSENGINE)' TARGET='$(TARGET)' javascript_run build: - $(MAKE) -f $(EXAMPLES_TOP)/Makefile CXXSRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(EXAMPLES_TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp - $(MAKE) -f $(EXAMPLES_TOP)/Makefile CXXSRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(EXAMPLES_TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' JSENGINE='$(JSENGINE)' javascript_build_cpp clean: - $(MAKE) -f $(EXAMPLES_TOP)/Makefile javascript_clean + $(MAKE) -f $(EXAMPLES_TOP)/Makefile SRCDIR='$(SRCDIR)' javascript_clean diff --git a/Examples/javascript/exception/Makefile b/Examples/javascript/exception/Makefile index 31846faae..54a8f7b03 100644 --- a/Examples/javascript/exception/Makefile +++ b/Examples/javascript/exception/Makefile @@ -1,3 +1,3 @@ SRCS = example.cxx -include ../example.mk +include $(SRCDIR)../example.mk diff --git a/Examples/javascript/exception/binding.gyp b/Examples/javascript/exception/binding.gyp.in similarity index 89% rename from Examples/javascript/exception/binding.gyp rename to Examples/javascript/exception/binding.gyp.in index 2be0a17a2..577a5c2e3 100644 --- a/Examples/javascript/exception/binding.gyp +++ b/Examples/javascript/exception/binding.gyp.in @@ -2,7 +2,8 @@ "targets": [ { "target_name": "example", - "sources": [ "example.cxx", "example_wrap.cxx" ], + "sources": [ "$srcdir/example.cxx", "example_wrap.cxx" ], + "include_dirs": ["$srcdir"], 'defines': [ 'BUILDING_NODE_EXTENSION=1', ], diff --git a/Examples/javascript/exception/example.js b/Examples/javascript/exception/example.js index 79cd3913f..2e7f83a06 100644 --- a/Examples/javascript/exception/example.js +++ b/Examples/javascript/exception/example.js @@ -1 +1 @@ -module.exports = require("./build/Release/example"); +module.exports = require("build/Release/example"); diff --git a/Examples/javascript/exception/runme.js b/Examples/javascript/exception/runme.js index 977f51ebc..43ce66d6d 100644 --- a/Examples/javascript/exception/runme.js +++ b/Examples/javascript/exception/runme.js @@ -1,4 +1,4 @@ -var example = require("./example"); +var example = require("example"); console.log("Trying to catch some exceptions."); t = new example.Test(); diff --git a/Examples/javascript/functor/Makefile b/Examples/javascript/functor/Makefile index 31846faae..54a8f7b03 100644 --- a/Examples/javascript/functor/Makefile +++ b/Examples/javascript/functor/Makefile @@ -1,3 +1,3 @@ SRCS = example.cxx -include ../example.mk +include $(SRCDIR)../example.mk diff --git a/Examples/javascript/functor/binding.gyp b/Examples/javascript/functor/binding.gyp deleted file mode 100644 index 54eebfaa0..000000000 --- a/Examples/javascript/functor/binding.gyp +++ /dev/null @@ -1,8 +0,0 @@ -{ - "targets": [ - { - "target_name": "example", - "sources": [ "example.cxx", "example_wrap.cxx" ] - } - ] -} diff --git a/Examples/javascript/functor/binding.gyp.in b/Examples/javascript/functor/binding.gyp.in new file mode 100644 index 000000000..c56a650e9 --- /dev/null +++ b/Examples/javascript/functor/binding.gyp.in @@ -0,0 +1,9 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "$srcdir/example.cxx", "example_wrap.cxx" ], + "include_dirs": ["$srcdir"] + } + ] +} diff --git a/Examples/javascript/functor/example.js b/Examples/javascript/functor/example.js index 79cd3913f..2e7f83a06 100644 --- a/Examples/javascript/functor/example.js +++ b/Examples/javascript/functor/example.js @@ -1 +1 @@ -module.exports = require("./build/Release/example"); +module.exports = require("build/Release/example"); diff --git a/Examples/javascript/functor/runme.js b/Examples/javascript/functor/runme.js index dc12470f4..28dc64320 100644 --- a/Examples/javascript/functor/runme.js +++ b/Examples/javascript/functor/runme.js @@ -1,4 +1,4 @@ -var example = require("./example"); +var example = require("example"); a = new example.intSum(0); b = new example.doubleSum(100.0); diff --git a/Examples/javascript/nspace/Makefile b/Examples/javascript/nspace/Makefile index ea04c7df8..0402f8d09 100644 --- a/Examples/javascript/nspace/Makefile +++ b/Examples/javascript/nspace/Makefile @@ -1,3 +1,3 @@ SRCS = -include ../example.mk +include $(SRCDIR)../example.mk diff --git a/Examples/javascript/nspace/binding.gyp b/Examples/javascript/nspace/binding.gyp deleted file mode 100644 index 69af46b22..000000000 --- a/Examples/javascript/nspace/binding.gyp +++ /dev/null @@ -1,8 +0,0 @@ -{ - "targets": [ - { - "target_name": "example", - "sources": [ "example_wrap.cxx" ] - } - ] -} diff --git a/Examples/javascript/nspace/binding.gyp.in b/Examples/javascript/nspace/binding.gyp.in new file mode 100644 index 000000000..59779aef4 --- /dev/null +++ b/Examples/javascript/nspace/binding.gyp.in @@ -0,0 +1,9 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example_wrap.cxx" ], + "include_dirs": ["$srcdir"] + } + ] +} diff --git a/Examples/javascript/nspace/example.js b/Examples/javascript/nspace/example.js index 79cd3913f..2e7f83a06 100644 --- a/Examples/javascript/nspace/example.js +++ b/Examples/javascript/nspace/example.js @@ -1 +1 @@ -module.exports = require("./build/Release/example"); +module.exports = require("build/Release/example"); diff --git a/Examples/javascript/nspace/runme.js b/Examples/javascript/nspace/runme.js index d6a49d8d4..fad73477d 100644 --- a/Examples/javascript/nspace/runme.js +++ b/Examples/javascript/nspace/runme.js @@ -3,7 +3,7 @@ // This file illustrates class C++ interface generated // by SWIG. -var example = require("./example"); +var example = require("example"); // Calling a module function ( aka global function ) if (example.module_function() !== 7) { diff --git a/Examples/javascript/operator/Makefile b/Examples/javascript/operator/Makefile index ea04c7df8..0402f8d09 100644 --- a/Examples/javascript/operator/Makefile +++ b/Examples/javascript/operator/Makefile @@ -1,3 +1,3 @@ SRCS = -include ../example.mk +include $(SRCDIR)../example.mk diff --git a/Examples/javascript/operator/binding.gyp b/Examples/javascript/operator/binding.gyp deleted file mode 100644 index 69af46b22..000000000 --- a/Examples/javascript/operator/binding.gyp +++ /dev/null @@ -1,8 +0,0 @@ -{ - "targets": [ - { - "target_name": "example", - "sources": [ "example_wrap.cxx" ] - } - ] -} diff --git a/Examples/javascript/operator/binding.gyp.in b/Examples/javascript/operator/binding.gyp.in new file mode 100644 index 000000000..59779aef4 --- /dev/null +++ b/Examples/javascript/operator/binding.gyp.in @@ -0,0 +1,9 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example_wrap.cxx" ], + "include_dirs": ["$srcdir"] + } + ] +} diff --git a/Examples/javascript/operator/example.js b/Examples/javascript/operator/example.js index 79cd3913f..2e7f83a06 100644 --- a/Examples/javascript/operator/example.js +++ b/Examples/javascript/operator/example.js @@ -1 +1 @@ -module.exports = require("./build/Release/example"); +module.exports = require("build/Release/example"); diff --git a/Examples/javascript/operator/runme.js b/Examples/javascript/operator/runme.js index a700918d6..f72ca1c28 100644 --- a/Examples/javascript/operator/runme.js +++ b/Examples/javascript/operator/runme.js @@ -1,4 +1,4 @@ -var example = require("./example"); +var example = require("example"); a = new example.Complex(2,3); b = new example.Complex(-5,10); diff --git a/Examples/javascript/overload/Makefile b/Examples/javascript/overload/Makefile index ea04c7df8..0402f8d09 100644 --- a/Examples/javascript/overload/Makefile +++ b/Examples/javascript/overload/Makefile @@ -1,3 +1,3 @@ SRCS = -include ../example.mk +include $(SRCDIR)../example.mk diff --git a/Examples/javascript/overload/binding.gyp b/Examples/javascript/overload/binding.gyp deleted file mode 100644 index 69af46b22..000000000 --- a/Examples/javascript/overload/binding.gyp +++ /dev/null @@ -1,8 +0,0 @@ -{ - "targets": [ - { - "target_name": "example", - "sources": [ "example_wrap.cxx" ] - } - ] -} diff --git a/Examples/javascript/overload/binding.gyp.in b/Examples/javascript/overload/binding.gyp.in new file mode 100644 index 000000000..59779aef4 --- /dev/null +++ b/Examples/javascript/overload/binding.gyp.in @@ -0,0 +1,9 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example_wrap.cxx" ], + "include_dirs": ["$srcdir"] + } + ] +} diff --git a/Examples/javascript/overload/example.js b/Examples/javascript/overload/example.js index 79cd3913f..2e7f83a06 100644 --- a/Examples/javascript/overload/example.js +++ b/Examples/javascript/overload/example.js @@ -1 +1 @@ -module.exports = require("./build/Release/example"); +module.exports = require("build/Release/example"); diff --git a/Examples/javascript/overload/runme.js b/Examples/javascript/overload/runme.js index 1e6c861a6..1c23e3b6b 100644 --- a/Examples/javascript/overload/runme.js +++ b/Examples/javascript/overload/runme.js @@ -1,4 +1,4 @@ -var example = require("./example"); +var example = require("example"); example.f(); example.f(1); diff --git a/Examples/javascript/pointer/Makefile b/Examples/javascript/pointer/Makefile index 31846faae..54a8f7b03 100644 --- a/Examples/javascript/pointer/Makefile +++ b/Examples/javascript/pointer/Makefile @@ -1,3 +1,3 @@ SRCS = example.cxx -include ../example.mk +include $(SRCDIR)../example.mk diff --git a/Examples/javascript/pointer/binding.gyp b/Examples/javascript/pointer/binding.gyp deleted file mode 100644 index 54eebfaa0..000000000 --- a/Examples/javascript/pointer/binding.gyp +++ /dev/null @@ -1,8 +0,0 @@ -{ - "targets": [ - { - "target_name": "example", - "sources": [ "example.cxx", "example_wrap.cxx" ] - } - ] -} diff --git a/Examples/javascript/pointer/binding.gyp.in b/Examples/javascript/pointer/binding.gyp.in new file mode 100644 index 000000000..c56a650e9 --- /dev/null +++ b/Examples/javascript/pointer/binding.gyp.in @@ -0,0 +1,9 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "$srcdir/example.cxx", "example_wrap.cxx" ], + "include_dirs": ["$srcdir"] + } + ] +} diff --git a/Examples/javascript/pointer/example.js b/Examples/javascript/pointer/example.js index 79cd3913f..2e7f83a06 100644 --- a/Examples/javascript/pointer/example.js +++ b/Examples/javascript/pointer/example.js @@ -1 +1 @@ -module.exports = require("./build/Release/example"); +module.exports = require("build/Release/example"); diff --git a/Examples/javascript/pointer/runme.js b/Examples/javascript/pointer/runme.js index fb8cf0c74..e9fa9a0bc 100644 --- a/Examples/javascript/pointer/runme.js +++ b/Examples/javascript/pointer/runme.js @@ -1,4 +1,4 @@ -var example = require("./example"); +var example = require("example"); // First create some objects using the pointer library. console.log("Testing the pointer library"); diff --git a/Examples/javascript/reference/Makefile b/Examples/javascript/reference/Makefile index 31846faae..54a8f7b03 100644 --- a/Examples/javascript/reference/Makefile +++ b/Examples/javascript/reference/Makefile @@ -1,3 +1,3 @@ SRCS = example.cxx -include ../example.mk +include $(SRCDIR)../example.mk diff --git a/Examples/javascript/reference/binding.gyp b/Examples/javascript/reference/binding.gyp deleted file mode 100644 index 54eebfaa0..000000000 --- a/Examples/javascript/reference/binding.gyp +++ /dev/null @@ -1,8 +0,0 @@ -{ - "targets": [ - { - "target_name": "example", - "sources": [ "example.cxx", "example_wrap.cxx" ] - } - ] -} diff --git a/Examples/javascript/reference/binding.gyp.in b/Examples/javascript/reference/binding.gyp.in new file mode 100644 index 000000000..c56a650e9 --- /dev/null +++ b/Examples/javascript/reference/binding.gyp.in @@ -0,0 +1,9 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "$srcdir/example.cxx", "example_wrap.cxx" ], + "include_dirs": ["$srcdir"] + } + ] +} diff --git a/Examples/javascript/reference/example.js b/Examples/javascript/reference/example.js index 79cd3913f..2e7f83a06 100644 --- a/Examples/javascript/reference/example.js +++ b/Examples/javascript/reference/example.js @@ -1 +1 @@ -module.exports = require("./build/Release/example"); +module.exports = require("build/Release/example"); diff --git a/Examples/javascript/reference/runme.js b/Examples/javascript/reference/runme.js index 88c108314..04f732520 100644 --- a/Examples/javascript/reference/runme.js +++ b/Examples/javascript/reference/runme.js @@ -1,5 +1,5 @@ // This file illustrates the manipulation of C++ references in Javascript. -var example = require("./example"); +var example = require("example"); // ----- Object creation ----- diff --git a/Examples/javascript/simple/Makefile b/Examples/javascript/simple/Makefile index 31846faae..54a8f7b03 100644 --- a/Examples/javascript/simple/Makefile +++ b/Examples/javascript/simple/Makefile @@ -1,3 +1,3 @@ SRCS = example.cxx -include ../example.mk +include $(SRCDIR)../example.mk diff --git a/Examples/javascript/simple/binding.gyp b/Examples/javascript/simple/binding.gyp deleted file mode 100644 index 54eebfaa0..000000000 --- a/Examples/javascript/simple/binding.gyp +++ /dev/null @@ -1,8 +0,0 @@ -{ - "targets": [ - { - "target_name": "example", - "sources": [ "example.cxx", "example_wrap.cxx" ] - } - ] -} diff --git a/Examples/javascript/simple/binding.gyp.in b/Examples/javascript/simple/binding.gyp.in new file mode 100644 index 000000000..c56a650e9 --- /dev/null +++ b/Examples/javascript/simple/binding.gyp.in @@ -0,0 +1,9 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "$srcdir/example.cxx", "example_wrap.cxx" ], + "include_dirs": ["$srcdir"] + } + ] +} diff --git a/Examples/javascript/simple/example.js b/Examples/javascript/simple/example.js index 79cd3913f..2e7f83a06 100644 --- a/Examples/javascript/simple/example.js +++ b/Examples/javascript/simple/example.js @@ -1 +1 @@ -module.exports = require("./build/Release/example"); +module.exports = require("build/Release/example"); diff --git a/Examples/javascript/simple/runme.js b/Examples/javascript/simple/runme.js index be2c18669..4abff0e2a 100644 --- a/Examples/javascript/simple/runme.js +++ b/Examples/javascript/simple/runme.js @@ -1,4 +1,4 @@ -var example = require("./example"); +var example = require("example"); /* Call our gcd() function */ diff --git a/Examples/javascript/template/Makefile b/Examples/javascript/template/Makefile index ea04c7df8..0402f8d09 100644 --- a/Examples/javascript/template/Makefile +++ b/Examples/javascript/template/Makefile @@ -1,3 +1,3 @@ SRCS = -include ../example.mk +include $(SRCDIR)../example.mk diff --git a/Examples/javascript/template/binding.gyp b/Examples/javascript/template/binding.gyp deleted file mode 100644 index 69af46b22..000000000 --- a/Examples/javascript/template/binding.gyp +++ /dev/null @@ -1,8 +0,0 @@ -{ - "targets": [ - { - "target_name": "example", - "sources": [ "example_wrap.cxx" ] - } - ] -} diff --git a/Examples/javascript/template/binding.gyp.in b/Examples/javascript/template/binding.gyp.in new file mode 100644 index 000000000..59779aef4 --- /dev/null +++ b/Examples/javascript/template/binding.gyp.in @@ -0,0 +1,9 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example_wrap.cxx" ], + "include_dirs": ["$srcdir"] + } + ] +} diff --git a/Examples/javascript/template/example.js b/Examples/javascript/template/example.js index 79cd3913f..2e7f83a06 100644 --- a/Examples/javascript/template/example.js +++ b/Examples/javascript/template/example.js @@ -1 +1 @@ -module.exports = require("./build/Release/example"); +module.exports = require("build/Release/example"); diff --git a/Examples/javascript/template/runme.js b/Examples/javascript/template/runme.js index 55894dfd5..af96ac7f9 100644 --- a/Examples/javascript/template/runme.js +++ b/Examples/javascript/template/runme.js @@ -1,4 +1,4 @@ -var example = require("./example"); +var example = require("example"); //Call some templated functions console.log(example.maxint(3,7)); diff --git a/Examples/javascript/variables/Makefile b/Examples/javascript/variables/Makefile index 31846faae..54a8f7b03 100644 --- a/Examples/javascript/variables/Makefile +++ b/Examples/javascript/variables/Makefile @@ -1,3 +1,3 @@ SRCS = example.cxx -include ../example.mk +include $(SRCDIR)../example.mk diff --git a/Examples/javascript/variables/binding.gyp b/Examples/javascript/variables/binding.gyp deleted file mode 100644 index 54eebfaa0..000000000 --- a/Examples/javascript/variables/binding.gyp +++ /dev/null @@ -1,8 +0,0 @@ -{ - "targets": [ - { - "target_name": "example", - "sources": [ "example.cxx", "example_wrap.cxx" ] - } - ] -} diff --git a/Examples/javascript/variables/binding.gyp.in b/Examples/javascript/variables/binding.gyp.in new file mode 100644 index 000000000..c56a650e9 --- /dev/null +++ b/Examples/javascript/variables/binding.gyp.in @@ -0,0 +1,9 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "$srcdir/example.cxx", "example_wrap.cxx" ], + "include_dirs": ["$srcdir"] + } + ] +} diff --git a/Examples/javascript/variables/example.js b/Examples/javascript/variables/example.js index 79cd3913f..2e7f83a06 100644 --- a/Examples/javascript/variables/example.js +++ b/Examples/javascript/variables/example.js @@ -1 +1 @@ -module.exports = require("./build/Release/example"); +module.exports = require("build/Release/example"); diff --git a/Examples/javascript/variables/runme.js b/Examples/javascript/variables/runme.js index 537e17296..a2b5f791c 100644 --- a/Examples/javascript/variables/runme.js +++ b/Examples/javascript/variables/runme.js @@ -1,4 +1,4 @@ -var example = require("./example"); +var example = require("example"); // Try to set the values of some global variables example.ivar = 42; diff --git a/Examples/lua/arrays/Makefile b/Examples/lua/arrays/Makefile index d398dffea..4191f7ec3 100644 --- a/Examples/lua/arrays/Makefile +++ b/Examples/lua/arrays/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile lua_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static clean: - $(MAKE) -f $(TOP)/Makefile lua_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean diff --git a/Examples/lua/class/Makefile b/Examples/lua/class/Makefile index c39e8acdf..96308f0df 100644 --- a/Examples/lua/class/Makefile +++ b/Examples/lua/class/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile lua_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile lua_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean diff --git a/Examples/lua/constants/Makefile b/Examples/lua/constants/Makefile index 7e36e15a1..ae33cb182 100644 --- a/Examples/lua/constants/Makefile +++ b/Examples/lua/constants/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = check: build - $(MAKE) -f $(TOP)/Makefile lua_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static clean: - $(MAKE) -f $(TOP)/Makefile lua_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean diff --git a/Examples/lua/dual/Makefile b/Examples/lua/dual/Makefile index 12ee00a68..c86152a97 100644 --- a/Examples/lua/dual/Makefile +++ b/Examples/lua/dual/Makefile @@ -1,21 +1,21 @@ TOP = ../.. SWIG = $(TOP)/../preinst-swig TARGET = dual -CXXSRCS = example2_wrap.cxx +GENCXXSRCS = example2_wrap.cxx INTERFACE = dual.i LUA_INTERP = dual.cpp # This is a little different to normal as we need to static link two modules and a custom interpreter # We need the external runtime, then swig examples2, and build the module as normal check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' lua_embed_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' lua_embed_run build: $(SWIG) -lua -external-runtime - $(SWIG) -c++ -lua $(SWIGOPT) example2.i - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(SWIG) -c++ -lua $(SWIGOPT) -o $(GENCXXSRCS) $(SRCDIR)example2.i + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) GENCXXSRCS='$(GENCXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static_cpp clean: - $(MAKE) -f $(TOP)/Makefile lua_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean rm -f swigluarun.h $(TARGET) diff --git a/Examples/lua/embed/Makefile b/Examples/lua/embed/Makefile index 57979c061..5e3a91893 100644 --- a/Examples/lua/embed/Makefile +++ b/Examples/lua/embed/Makefile @@ -9,12 +9,12 @@ LIBS = -lm # this is a little different to normal as we have our own special interpreter # which we want to static link check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' lua_embed_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' lua_embed_run build: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' LIBS='$(LIBS)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static clean: - $(MAKE) -f $(TOP)/Makefile lua_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean rm -f $(TARGET) diff --git a/Examples/lua/embed/embed.c b/Examples/lua/embed/embed.c index 507567489..1f10cc8e8 100644 --- a/Examples/lua/embed/embed.c +++ b/Examples/lua/embed/embed.c @@ -13,6 +13,7 @@ We will be using the luaL_dostring()/lua_dostring() function to call into lua #include #include +#include #include #include @@ -62,9 +63,13 @@ int main(int argc,char* argv[]) { luaopen_example(L); printf("[C] all looks ok\n"); printf("\n"); - printf("[C] let's load the file 'runme.lua'\n"); + if (argc != 2 || argv[1] == NULL || strlen(argv[1]) == 0) { + printf("[C] ERROR: no lua file given on command line\n"); + exit(3); + } + printf("[C] let's load the file '%s'\n", argv[1]); printf("[C] any lua code in this file will be executed\n"); - if (luaL_loadfile(L, "runme.lua") || lua_pcall(L, 0, 0, 0)) { + if (luaL_loadfile(L, argv[1]) || lua_pcall(L, 0, 0, 0)) { printf("[C] ERROR: cannot run lua file: %s",lua_tostring(L, -1)); exit(3); } diff --git a/Examples/lua/embed2/Makefile b/Examples/lua/embed2/Makefile index ec22bdcae..d30ba0942 100644 --- a/Examples/lua/embed2/Makefile +++ b/Examples/lua/embed2/Makefile @@ -9,12 +9,12 @@ LIBS = -lm # this is a little different to normal as we have our own special interpreter # which we want to static link check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' lua_embed_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' lua_embed_run build: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' LIBS='$(LIBS)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static clean: - $(MAKE) -f $(TOP)/Makefile lua_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean rm -f $(TARGET) diff --git a/Examples/lua/embed2/embed2.c b/Examples/lua/embed2/embed2.c index 100a1fb33..7b2ca9b67 100644 --- a/Examples/lua/embed2/embed2.c +++ b/Examples/lua/embed2/embed2.c @@ -24,6 +24,7 @@ We will be using the luaL_dostring()/lua_dostring() function to call into lua #include #include +#include #include #include @@ -189,9 +190,13 @@ int main(int argc,char* argv[]) { luaopen_example(L); printf("[C] all looks ok\n"); printf("\n"); - printf("[C] let's load the file 'runme.lua'\n"); + if (argc != 2 || argv[1] == NULL || strlen(argv[1]) == 0) { + printf("[C] ERROR: no lua file given on command line\n"); + exit(3); + } + printf("[C] let's load the file '%s'\n", argv[1]); printf("[C] any lua code in this file will be executed\n"); - if (luaL_loadfile(L, "runme.lua") || lua_pcall(L, 0, 0, 0)) { + if (luaL_loadfile(L, argv[1]) || lua_pcall(L, 0, 0, 0)) { printf("[C] ERROR: cannot run lua file: %s",lua_tostring(L, -1)); exit(3); } diff --git a/Examples/lua/embed3/Makefile b/Examples/lua/embed3/Makefile index 8cfa97454..fc0026122 100644 --- a/Examples/lua/embed3/Makefile +++ b/Examples/lua/embed3/Makefile @@ -9,13 +9,13 @@ LUA_INTERP = embed3.cpp # which we want to static link # we also need the external runtime, so we can get access to certain internals of SWIG check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' lua_embed_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' lua_embed_run build: $(SWIG) -c++ -lua $(SWIGOPT) -external-runtime swigluarun.h - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='example.i' LUA_INTERP='$(LUA_INTERP)' lua_static_cpp clean: - $(MAKE) -f $(TOP)/Makefile lua_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean rm -f swigluarun.h $(TARGET) diff --git a/Examples/lua/embed3/embed3.cpp b/Examples/lua/embed3/embed3.cpp index d559167d1..9be49add3 100644 --- a/Examples/lua/embed3/embed3.cpp +++ b/Examples/lua/embed3/embed3.cpp @@ -113,10 +113,14 @@ int main(int argc, char* argv[]) { push_pointer(L,&engine,"Engine *",0); lua_setglobal(L, "pEngine"); // set as global variable - printf("[C++] now let's load the file 'runme.lua'\n"); + if (argc != 2 || argv[1] == NULL || strlen(argv[1]) == 0) { + printf("[C++] ERROR: no lua file given on command line\n"); + exit(3); + } + printf("[C++] now let's load the file '%s'\n", argv[1]); printf("[C++] any lua code in this file will be executed\n"); - if (luaL_loadfile(L, "runme.lua") || lua_pcall(L, 0, 0, 0)) { - printf("[C++] ERROR: cannot run lua file: %s", lua_tostring(L, -1)); + if (luaL_loadfile(L, argv[1]) || lua_pcall(L, 0, 0, 0)) { + printf("[C++] ERROR: cannot run lua file: %s",lua_tostring(L, -1)); exit(3); } printf("[C++] We are now back in C++, all looks ok\n"); diff --git a/Examples/lua/exception/Makefile b/Examples/lua/exception/Makefile index 3dbebb4e5..ac9c28b69 100644 --- a/Examples/lua/exception/Makefile +++ b/Examples/lua/exception/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile lua_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile lua_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean diff --git a/Examples/lua/funcptr3/Makefile b/Examples/lua/funcptr3/Makefile index 8b51e73e8..aeeaad469 100644 --- a/Examples/lua/funcptr3/Makefile +++ b/Examples/lua/funcptr3/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = check: build - $(MAKE) -f $(TOP)/Makefile lua_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static clean: - $(MAKE) -f $(TOP)/Makefile lua_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean diff --git a/Examples/lua/functest/Makefile b/Examples/lua/functest/Makefile index 8b51e73e8..aeeaad469 100644 --- a/Examples/lua/functest/Makefile +++ b/Examples/lua/functest/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = check: build - $(MAKE) -f $(TOP)/Makefile lua_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static clean: - $(MAKE) -f $(TOP)/Makefile lua_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean diff --git a/Examples/lua/functor/Makefile b/Examples/lua/functor/Makefile index 4e4edbfa5..e647fb2a8 100644 --- a/Examples/lua/functor/Makefile +++ b/Examples/lua/functor/Makefile @@ -7,15 +7,15 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile lua_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile lua_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean diff --git a/Examples/lua/import/Makefile b/Examples/lua/import/Makefile index 0a9aebd57..8d64a21c6 100644 --- a/Examples/lua/import/Makefile +++ b/Examples/lua/import/Makefile @@ -4,17 +4,17 @@ SWIGOPT = LIBS = check: build - $(MAKE) -f $(TOP)/Makefile lua_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' lua_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' lua_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' lua_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' lua_cpp clean: - $(MAKE) -f $(TOP)/Makefile lua_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean diff --git a/Examples/lua/nspace/Makefile b/Examples/lua/nspace/Makefile index 57875ec49..17757c2ec 100644 --- a/Examples/lua/nspace/Makefile +++ b/Examples/lua/nspace/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile lua_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile lua_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean diff --git a/Examples/lua/owner/Makefile b/Examples/lua/owner/Makefile index c39e8acdf..96308f0df 100644 --- a/Examples/lua/owner/Makefile +++ b/Examples/lua/owner/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile lua_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile lua_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean diff --git a/Examples/lua/pointer/Makefile b/Examples/lua/pointer/Makefile index 8b51e73e8..aeeaad469 100644 --- a/Examples/lua/pointer/Makefile +++ b/Examples/lua/pointer/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = check: build - $(MAKE) -f $(TOP)/Makefile lua_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static clean: - $(MAKE) -f $(TOP)/Makefile lua_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean diff --git a/Examples/lua/simple/Makefile b/Examples/lua/simple/Makefile index d398dffea..4191f7ec3 100644 --- a/Examples/lua/simple/Makefile +++ b/Examples/lua/simple/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile lua_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static clean: - $(MAKE) -f $(TOP)/Makefile lua_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean diff --git a/Examples/lua/variables/Makefile b/Examples/lua/variables/Makefile index d398dffea..4191f7ec3 100644 --- a/Examples/lua/variables/Makefile +++ b/Examples/lua/variables/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile lua_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' lua static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='mylua' INTERFACE='$(INTERFACE)' lua_static clean: - $(MAKE) -f $(TOP)/Makefile lua_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' lua_clean diff --git a/Examples/modula3/class/Makefile b/Examples/modula3/class/Makefile index af8e099cc..2e2f37526 100644 --- a/Examples/modula3/class/Makefile +++ b/Examples/modula3/class/Makefile @@ -8,10 +8,10 @@ SWIGOPT = -c++ MODULA3SRCS = *.[im]3 check: build - $(MAKE) -f $(TOP)/Makefile modula3_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' modula3 m3ppinplace $(MODULA3SRCS) # compilation of example_wrap.cxx is started by cm3 @@ -21,4 +21,4 @@ build: cm3 clean: - $(MAKE) -f $(TOP)/Makefile modula3_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_clean diff --git a/Examples/modula3/enum/Makefile b/Examples/modula3/enum/Makefile index a351cb1b9..3915e5405 100644 --- a/Examples/modula3/enum/Makefile +++ b/Examples/modula3/enum/Makefile @@ -8,18 +8,18 @@ SWIGOPT = -c++ MODULA3SRCS = *.[im]3 check: build - $(MAKE) -f $(TOP)/Makefile modula3_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_run build: $(SWIG) -modula3 $(SWIGOPT) -module Example -generateconst $(CONSTNUMERIC) $(TARGET).h $(CXX) -Wall $(CONSTNUMERIC).c -o $(CONSTNUMERIC) $(CONSTNUMERIC) >$(CONSTNUMERIC).i - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' modula3 m3ppinplace $(MODULA3SRCS) mv m3makefile $(MODULA3SRCS) src/ cm3 clean: - $(MAKE) -f $(TOP)/Makefile modula3_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_clean diff --git a/Examples/modula3/exception/Makefile b/Examples/modula3/exception/Makefile index 8d4525512..1dbf1a156 100644 --- a/Examples/modula3/exception/Makefile +++ b/Examples/modula3/exception/Makefile @@ -8,15 +8,15 @@ MODULA3SRCS = *.[im]3 MODULA3FLAGS= -o runme check: build - $(MAKE) -f $(TOP)/Makefile modula3_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' modula3_cpp -# $(MAKE) -f $(TOP)/Makefile MODULA3SRCS='$(MODULA3SRCS)' MODULA3FLAGS='$(MODULA3FLAGS)' modula3_compile +# $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' MODULA3SRCS='$(MODULA3SRCS)' MODULA3FLAGS='$(MODULA3FLAGS)' modula3_compile m3ppinplace $(MODULA3SRCS) mv m3makefile $(MODULA3SRCS) src/ cm3 clean: - $(MAKE) -f $(TOP)/Makefile modula3_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_clean diff --git a/Examples/modula3/reference/Makefile b/Examples/modula3/reference/Makefile index 1a5fdeb30..3b68fe822 100644 --- a/Examples/modula3/reference/Makefile +++ b/Examples/modula3/reference/Makefile @@ -7,14 +7,14 @@ SWIGOPT = -c++ MODULA3SRCS = *.[im]3 check: build - $(MAKE) -f $(TOP)/Makefile modula3_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' modula3 m3ppinplace $(MODULA3SRCS) mv m3makefile $(MODULA3SRCS) src/ cm3 clean: - $(MAKE) -f $(TOP)/Makefile modula3_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_clean diff --git a/Examples/modula3/simple/Makefile b/Examples/modula3/simple/Makefile index 6287dac20..2796b25f8 100644 --- a/Examples/modula3/simple/Makefile +++ b/Examples/modula3/simple/Makefile @@ -7,14 +7,14 @@ SWIGOPT = MODULA3SRCS = *.[im]3 check: build - $(MAKE) -f $(TOP)/Makefile modula3_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' modula3 m3ppinplace $(MODULA3SRCS) mv m3makefile $(MODULA3SRCS) src/ cm3 clean: - $(MAKE) -f $(TOP)/Makefile modula3_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_clean diff --git a/Examples/modula3/typemap/Makefile b/Examples/modula3/typemap/Makefile index 6287dac20..2796b25f8 100644 --- a/Examples/modula3/typemap/Makefile +++ b/Examples/modula3/typemap/Makefile @@ -7,14 +7,14 @@ SWIGOPT = MODULA3SRCS = *.[im]3 check: build - $(MAKE) -f $(TOP)/Makefile modula3_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' modula3 m3ppinplace $(MODULA3SRCS) mv m3makefile $(MODULA3SRCS) src/ cm3 clean: - $(MAKE) -f $(TOP)/Makefile modula3_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' modula3_clean diff --git a/Examples/mzscheme/multimap/Makefile b/Examples/mzscheme/multimap/Makefile index f8eeb72c3..ecf83fbeb 100644 --- a/Examples/mzscheme/multimap/Makefile +++ b/Examples/mzscheme/multimap/Makefile @@ -6,10 +6,10 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile mzscheme_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' mzscheme_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' mzscheme clean: - $(MAKE) -f $(TOP)/Makefile mzscheme_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' mzscheme_clean diff --git a/Examples/mzscheme/simple/Makefile b/Examples/mzscheme/simple/Makefile index f8eeb72c3..ecf83fbeb 100644 --- a/Examples/mzscheme/simple/Makefile +++ b/Examples/mzscheme/simple/Makefile @@ -6,10 +6,10 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile mzscheme_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' mzscheme_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' mzscheme clean: - $(MAKE) -f $(TOP)/Makefile mzscheme_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' mzscheme_clean diff --git a/Examples/mzscheme/std_vector/Makefile b/Examples/mzscheme/std_vector/Makefile index d2bf0a013..75918a61e 100644 --- a/Examples/mzscheme/std_vector/Makefile +++ b/Examples/mzscheme/std_vector/Makefile @@ -9,7 +9,7 @@ GPP = `which g++` MZC = test -n "/usr/bin/mzc" && /usr/bin/mzc check: build - $(MAKE) -f $(TOP)/Makefile mzscheme_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' mzscheme_run build: $(SWIG) -mzscheme -c++ $(SWIGOPT) $(INTERFACE) @@ -17,4 +17,4 @@ build: $(MZC) --linker $(GPP) --ld $(TARGET).so example_wrap.o clean: - $(MAKE) -f $(TOP)/Makefile mzscheme_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' mzscheme_clean diff --git a/Examples/ocaml/argout_ref/Makefile b/Examples/ocaml/argout_ref/Makefile index 4e12e3769..09893af65 100644 --- a/Examples/ocaml/argout_ref/Makefile +++ b/Examples/ocaml/argout_ref/Makefile @@ -8,21 +8,21 @@ PROGFILE = example_prog.ml OBJS = example.o check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_run build: static static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static_cpp dynamic: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_dynamic_cpp clean: - $(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' MLFILE='$(MLFILE)' ocaml_clean diff --git a/Examples/ocaml/contract/Makefile b/Examples/ocaml/contract/Makefile index 1db93e38a..df5d6a6f5 100644 --- a/Examples/ocaml/contract/Makefile +++ b/Examples/ocaml/contract/Makefile @@ -8,27 +8,27 @@ PROGFILE = example_prog.ml OBJS = check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_run build: static dynamic: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_dynamic static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static toplevel: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static_toplevel clean: - $(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' MLFILE='$(MLFILE)' ocaml_clean diff --git a/Examples/ocaml/scoped_enum/Makefile b/Examples/ocaml/scoped_enum/Makefile index e5de57ac2..794733971 100644 --- a/Examples/ocaml/scoped_enum/Makefile +++ b/Examples/ocaml/scoped_enum/Makefile @@ -8,27 +8,27 @@ PROGFILE = example_prog.ml OBJS = check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_run build: static dynamic: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_dynamic_cpp static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static_cpp toplevel: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static_cpp_toplevel clean: - $(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' MLFILE='$(MLFILE)' ocaml_clean diff --git a/Examples/ocaml/shapes/Makefile b/Examples/ocaml/shapes/Makefile index c1ab6507c..69102f3b1 100644 --- a/Examples/ocaml/shapes/Makefile +++ b/Examples/ocaml/shapes/Makefile @@ -9,27 +9,27 @@ PROGFILE = example_prog.ml OBJS = example.o check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_run build: static static_top static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ MLFILE='$(MLFILE)' PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static_cpp static_top: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ MLFILE='$(MLFILE)' PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static_cpp_toplevel dynamic: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_dynamic_cpp clean: - $(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' MLFILE='$(MLFILE)' ocaml_clean diff --git a/Examples/ocaml/simple/Makefile b/Examples/ocaml/simple/Makefile index 64c7256c1..49bf81c1e 100644 --- a/Examples/ocaml/simple/Makefile +++ b/Examples/ocaml/simple/Makefile @@ -8,27 +8,27 @@ PROGFILE = example_prog.ml OBJS = example.o check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_run build: static dynamic: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_dynamic static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static toplevel: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' \ PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static_toplevel clean: - $(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' MLFILE='$(MLFILE)' ocaml_clean diff --git a/Examples/ocaml/std_string/Makefile b/Examples/ocaml/std_string/Makefile index 89f997090..8f8b2f684 100644 --- a/Examples/ocaml/std_string/Makefile +++ b/Examples/ocaml/std_string/Makefile @@ -6,19 +6,19 @@ INTERFACE = example.i PROGFILE = runme.ml check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_run build: static static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_static_cpp dynamic: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_dynamic_cpp clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_clean diff --git a/Examples/ocaml/std_vector/Makefile b/Examples/ocaml/std_vector/Makefile index 89f997090..8f8b2f684 100644 --- a/Examples/ocaml/std_vector/Makefile +++ b/Examples/ocaml/std_vector/Makefile @@ -6,19 +6,19 @@ INTERFACE = example.i PROGFILE = runme.ml check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_run build: static static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_static_cpp dynamic: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_dynamic_cpp clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_clean diff --git a/Examples/ocaml/stl/Makefile b/Examples/ocaml/stl/Makefile index a913611fb..e4cce4883 100644 --- a/Examples/ocaml/stl/Makefile +++ b/Examples/ocaml/stl/Makefile @@ -6,29 +6,29 @@ INTERFACE = example.i PROGFILE = runme.ml check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_run build: static static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_static_cpp director: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_static_cpp_director dynamic: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_static_cpp toplevel: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_static_cpp_toplevel clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_clean diff --git a/Examples/ocaml/string_from_ptr/Makefile b/Examples/ocaml/string_from_ptr/Makefile index 6d344854a..294bdec83 100644 --- a/Examples/ocaml/string_from_ptr/Makefile +++ b/Examples/ocaml/string_from_ptr/Makefile @@ -9,27 +9,27 @@ PROGFILE = example_prog.ml OBJS = check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_run build: static static_top static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ MLFILE='$(MLFILE)' PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static_cpp static_top: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ MLFILE='$(MLFILE)' PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_static_cpp_toplevel dynamic: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' MLFILE='$(MLFILE)' PROGFILE='$(PROGFILE)' OBJS='$(OBJS)' \ ocaml_dynamic_cpp clean: - $(MAKE) -f $(TOP)/Makefile MLFILE='$(MLFILE)' ocaml_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' MLFILE='$(MLFILE)' ocaml_clean diff --git a/Examples/ocaml/strings_test/Makefile b/Examples/ocaml/strings_test/Makefile index 49cc544ed..b6b866669 100644 --- a/Examples/ocaml/strings_test/Makefile +++ b/Examples/ocaml/strings_test/Makefile @@ -6,24 +6,24 @@ INTERFACE = example.i PROGFILE = runme.ml check: build - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_run build: static top static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_static_cpp dynamic: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_static_cpp top: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ PROGFILE='$(PROGFILE)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ ocaml_static_cpp_toplevel clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' ocaml_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' ocaml_clean diff --git a/Examples/octave/callback/Makefile b/Examples/octave/callback/Makefile index d38d7f896..7855d0617 100644 --- a/Examples/octave/callback/Makefile +++ b/Examples/octave/callback/Makefile @@ -7,11 +7,11 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile octave_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run build: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp clean: - $(MAKE) -f $(TOP)/Makefile octave_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean diff --git a/Examples/octave/class/Makefile b/Examples/octave/class/Makefile index d38d7f896..7855d0617 100644 --- a/Examples/octave/class/Makefile +++ b/Examples/octave/class/Makefile @@ -7,11 +7,11 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile octave_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run build: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp clean: - $(MAKE) -f $(TOP)/Makefile octave_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean diff --git a/Examples/octave/constants/Makefile b/Examples/octave/constants/Makefile index 03501bd81..eb05d1e7e 100644 --- a/Examples/octave/constants/Makefile +++ b/Examples/octave/constants/Makefile @@ -7,11 +7,11 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile octave_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run build: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp clean: - $(MAKE) -f $(TOP)/Makefile octave_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean diff --git a/Examples/octave/contract/Makefile b/Examples/octave/contract/Makefile index 73e3962ed..2e0e82124 100644 --- a/Examples/octave/contract/Makefile +++ b/Examples/octave/contract/Makefile @@ -5,11 +5,11 @@ TARGET = swigexample INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile octave_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave clean: - $(MAKE) -f $(TOP)/Makefile octave_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean diff --git a/Examples/octave/enum/Makefile b/Examples/octave/enum/Makefile index d38d7f896..7855d0617 100644 --- a/Examples/octave/enum/Makefile +++ b/Examples/octave/enum/Makefile @@ -7,11 +7,11 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile octave_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run build: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp clean: - $(MAKE) -f $(TOP)/Makefile octave_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean diff --git a/Examples/octave/extend/Makefile b/Examples/octave/extend/Makefile index d38d7f896..7855d0617 100644 --- a/Examples/octave/extend/Makefile +++ b/Examples/octave/extend/Makefile @@ -7,11 +7,11 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile octave_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run build: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp clean: - $(MAKE) -f $(TOP)/Makefile octave_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean diff --git a/Examples/octave/funcptr/Makefile b/Examples/octave/funcptr/Makefile index 73e3962ed..2e0e82124 100644 --- a/Examples/octave/funcptr/Makefile +++ b/Examples/octave/funcptr/Makefile @@ -5,11 +5,11 @@ TARGET = swigexample INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile octave_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave clean: - $(MAKE) -f $(TOP)/Makefile octave_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean diff --git a/Examples/octave/funcptr2/Makefile b/Examples/octave/funcptr2/Makefile index 73e3962ed..2e0e82124 100644 --- a/Examples/octave/funcptr2/Makefile +++ b/Examples/octave/funcptr2/Makefile @@ -5,11 +5,11 @@ TARGET = swigexample INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile octave_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave clean: - $(MAKE) -f $(TOP)/Makefile octave_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean diff --git a/Examples/octave/functor/Makefile b/Examples/octave/functor/Makefile index 94fb96337..0fbc7586b 100644 --- a/Examples/octave/functor/Makefile +++ b/Examples/octave/functor/Makefile @@ -7,11 +7,11 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile octave_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp clean: - $(MAKE) -f $(TOP)/Makefile octave_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean diff --git a/Examples/octave/module_load/Makefile b/Examples/octave/module_load/Makefile index e388763bd..7b24a8530 100644 --- a/Examples/octave/module_load/Makefile +++ b/Examples/octave/module_load/Makefile @@ -5,14 +5,14 @@ TARGET = swigexample INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile octave_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' SWIGOPT='-module $$(TARGET)' INTERFACE='$(INTERFACE)' octave - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)2' SWIGOPT='-module $$(TARGET) -globals .' INTERFACE='$(INTERFACE)' octave clean: - $(MAKE) -f $(TOP)/Makefile octave_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean rm -f $(TARGET).m diff --git a/Examples/octave/operator/Makefile b/Examples/octave/operator/Makefile index 94fb96337..0fbc7586b 100644 --- a/Examples/octave/operator/Makefile +++ b/Examples/octave/operator/Makefile @@ -7,11 +7,11 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile octave_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp clean: - $(MAKE) -f $(TOP)/Makefile octave_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean diff --git a/Examples/octave/pointer/Makefile b/Examples/octave/pointer/Makefile index 73e3962ed..2e0e82124 100644 --- a/Examples/octave/pointer/Makefile +++ b/Examples/octave/pointer/Makefile @@ -5,11 +5,11 @@ TARGET = swigexample INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile octave_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave clean: - $(MAKE) -f $(TOP)/Makefile octave_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean diff --git a/Examples/octave/reference/Makefile b/Examples/octave/reference/Makefile index d38d7f896..7855d0617 100644 --- a/Examples/octave/reference/Makefile +++ b/Examples/octave/reference/Makefile @@ -7,11 +7,11 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile octave_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run build: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp clean: - $(MAKE) -f $(TOP)/Makefile octave_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean diff --git a/Examples/octave/simple/Makefile b/Examples/octave/simple/Makefile index 73e3962ed..2e0e82124 100644 --- a/Examples/octave/simple/Makefile +++ b/Examples/octave/simple/Makefile @@ -5,11 +5,11 @@ TARGET = swigexample INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile octave_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave clean: - $(MAKE) -f $(TOP)/Makefile octave_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean diff --git a/Examples/octave/template/Makefile b/Examples/octave/template/Makefile index 94fb96337..0fbc7586b 100644 --- a/Examples/octave/template/Makefile +++ b/Examples/octave/template/Makefile @@ -7,11 +7,11 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile octave_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp clean: - $(MAKE) -f $(TOP)/Makefile octave_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean diff --git a/Examples/octave/variables/Makefile b/Examples/octave/variables/Makefile index 73e3962ed..2e0e82124 100644 --- a/Examples/octave/variables/Makefile +++ b/Examples/octave/variables/Makefile @@ -5,11 +5,11 @@ TARGET = swigexample INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile octave_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave clean: - $(MAKE) -f $(TOP)/Makefile octave_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean diff --git a/Examples/perl5/callback/Makefile b/Examples/perl5/callback/Makefile index 544d13642..0d1cc574f 100644 --- a/Examples/perl5/callback/Makefile +++ b/Examples/perl5/callback/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile perl5_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile perl5_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/class/Makefile b/Examples/perl5/class/Makefile index 544d13642..0d1cc574f 100644 --- a/Examples/perl5/class/Makefile +++ b/Examples/perl5/class/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile perl5_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile perl5_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/constants/Makefile b/Examples/perl5/constants/Makefile index 899282913..b7b411534 100644 --- a/Examples/perl5/constants/Makefile +++ b/Examples/perl5/constants/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile perl5_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5 static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_static clean: - $(MAKE) -f $(TOP)/Makefile perl5_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/constants2/Makefile b/Examples/perl5/constants2/Makefile index 2ed10d733..85dd13741 100644 --- a/Examples/perl5/constants2/Makefile +++ b/Examples/perl5/constants2/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i SWIGOPT = -const check: build - $(MAKE) -f $(TOP)/Makefile perl5_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5 static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_static clean: - $(MAKE) -f $(TOP)/Makefile perl5_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/extend/Makefile b/Examples/perl5/extend/Makefile index 544d13642..0d1cc574f 100644 --- a/Examples/perl5/extend/Makefile +++ b/Examples/perl5/extend/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile perl5_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile perl5_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/funcptr/Makefile b/Examples/perl5/funcptr/Makefile index 366b5897c..3e1de1fc1 100644 --- a/Examples/perl5/funcptr/Makefile +++ b/Examples/perl5/funcptr/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile perl5_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5 static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_static clean: - $(MAKE) -f $(TOP)/Makefile perl5_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/import/Makefile b/Examples/perl5/import/Makefile index baa8277fd..b31ab7952 100644 --- a/Examples/perl5/import/Makefile +++ b/Examples/perl5/import/Makefile @@ -4,17 +4,17 @@ SWIGOPT = LIBS = check: build - $(MAKE) -f $(TOP)/Makefile perl5_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='baseclass' INTERFACE='base.i' perl5_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' perl5_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' perl5_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' perl5_cpp clean: - $(MAKE) -f $(TOP)/Makefile perl5_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/inline/Makefile b/Examples/perl5/inline/Makefile index d544a6532..5c98748c1 100644 --- a/Examples/perl5/inline/Makefile +++ b/Examples/perl5/inline/Makefile @@ -1,6 +1,6 @@ run: - $(MAKE) -f $(TOP)/Makefile perl5_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run clean: - $(MAKE) -f $(TOP)/Makefile perl5_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean rm -rf _Inline diff --git a/Examples/perl5/java/Makefile b/Examples/perl5/java/Makefile index 3a0bb215d..5eaea3212 100644 --- a/Examples/perl5/java/Makefile +++ b/Examples/perl5/java/Makefile @@ -6,17 +6,17 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile perl5_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: Example.class Example.h - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ CXXSHARED="gcj -fpic -shared Example.class" PERL5_CCFLAGS='' PERL5_EXP='' LIBS="-lstdc++" perl5_cpp clean: - $(MAKE) -f $(TOP)/Makefile perl5_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean rm -f *.class Example.h -Example.class Example.h: Example.java - gcj -fPIC -C -c -g Example.java +Example.class Example.h: $(SRCDIR)Example.java + gcj -d . -fPIC -C -c -g $(SRCDIR)Example.java gcjh Example.class diff --git a/Examples/perl5/multimap/Makefile b/Examples/perl5/multimap/Makefile index 366b5897c..3e1de1fc1 100644 --- a/Examples/perl5/multimap/Makefile +++ b/Examples/perl5/multimap/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile perl5_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5 static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_static clean: - $(MAKE) -f $(TOP)/Makefile perl5_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/multiple_inheritance/Makefile b/Examples/perl5/multiple_inheritance/Makefile index 62355a82c..1fe5a51bb 100644 --- a/Examples/perl5/multiple_inheritance/Makefile +++ b/Examples/perl5/multiple_inheritance/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = check: build - $(MAKE) -f $(TOP)/Makefile perl5_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile perl5_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/pointer/Makefile b/Examples/perl5/pointer/Makefile index 366b5897c..3e1de1fc1 100644 --- a/Examples/perl5/pointer/Makefile +++ b/Examples/perl5/pointer/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile perl5_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5 static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_static clean: - $(MAKE) -f $(TOP)/Makefile perl5_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/reference/Makefile b/Examples/perl5/reference/Makefile index 986fab86a..a22f5a68d 100644 --- a/Examples/perl5/reference/Makefile +++ b/Examples/perl5/reference/Makefile @@ -7,15 +7,15 @@ LIBS = -lm SWIGOPT = -noproxy check: build - $(MAKE) -f $(TOP)/Makefile perl5_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' SWIGOPT='$(SWIGOPT)' perl5_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='myperl' INTERFACE='$(INTERFACE)' SWIGOPT='$(SWIGOPT)' perl5_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile perl5_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/simple/Makefile b/Examples/perl5/simple/Makefile index 366b5897c..3e1de1fc1 100644 --- a/Examples/perl5/simple/Makefile +++ b/Examples/perl5/simple/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile perl5_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5 static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_static clean: - $(MAKE) -f $(TOP)/Makefile perl5_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/value/Makefile b/Examples/perl5/value/Makefile index 366b5897c..3e1de1fc1 100644 --- a/Examples/perl5/value/Makefile +++ b/Examples/perl5/value/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile perl5_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5 static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_static clean: - $(MAKE) -f $(TOP)/Makefile perl5_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/variables/Makefile b/Examples/perl5/variables/Makefile index 366b5897c..3e1de1fc1 100644 --- a/Examples/perl5/variables/Makefile +++ b/Examples/perl5/variables/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile perl5_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' perl5 static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_static clean: - $(MAKE) -f $(TOP)/Makefile perl5_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/perl5/xmlstring/Makefile b/Examples/perl5/xmlstring/Makefile index df9dabd11..4f02d3ee4 100644 --- a/Examples/perl5/xmlstring/Makefile +++ b/Examples/perl5/xmlstring/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lxerces-c -lxerces-depdom -lm check: build - $(MAKE) -f $(TOP)/Makefile perl5_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' LIBS=$(LIBS) CXX="g++ -g3" perl5_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='myperl' INTERFACE='$(INTERFACE)' perl5_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile perl5_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' perl5_clean diff --git a/Examples/php/callback/Makefile b/Examples/php/callback/Makefile index 6f7e4ad27..3ad3999a5 100644 --- a/Examples/php/callback/Makefile +++ b/Examples/php/callback/Makefile @@ -7,15 +7,15 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile php_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' php_cpp static: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' php_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile php_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/class/Makefile b/Examples/php/class/Makefile index cefd81f78..8b2b340e9 100644 --- a/Examples/php/class/Makefile +++ b/Examples/php/class/Makefile @@ -7,17 +7,17 @@ LIBS = SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile php_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile php_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/constants/Makefile b/Examples/php/constants/Makefile index 3f24a3921..e5b49571e 100644 --- a/Examples/php/constants/Makefile +++ b/Examples/php/constants/Makefile @@ -7,17 +7,17 @@ LIBS = SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile php_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_static clean: - $(MAKE) -f $(TOP)/Makefile php_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/cpointer/Makefile b/Examples/php/cpointer/Makefile index 57785acc7..f2c15c5c1 100644 --- a/Examples/php/cpointer/Makefile +++ b/Examples/php/cpointer/Makefile @@ -7,17 +7,17 @@ LIBS = SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile php_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_static clean: - $(MAKE) -f $(TOP)/Makefile php_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/disown/Makefile b/Examples/php/disown/Makefile index cefd81f78..8b2b340e9 100644 --- a/Examples/php/disown/Makefile +++ b/Examples/php/disown/Makefile @@ -7,17 +7,17 @@ LIBS = SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile php_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile php_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/enum/Makefile b/Examples/php/enum/Makefile index 22f979d2f..2028d03c7 100644 --- a/Examples/php/enum/Makefile +++ b/Examples/php/enum/Makefile @@ -7,17 +7,17 @@ LIBS = SWIGOPT = -noproxy check: build - $(MAKE) -f $(TOP)/Makefile php_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile php_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/extend/Makefile b/Examples/php/extend/Makefile index 6f7e4ad27..3ad3999a5 100644 --- a/Examples/php/extend/Makefile +++ b/Examples/php/extend/Makefile @@ -7,15 +7,15 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile php_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' php_cpp static: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' php_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile php_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/funcptr/Makefile b/Examples/php/funcptr/Makefile index 57785acc7..f2c15c5c1 100644 --- a/Examples/php/funcptr/Makefile +++ b/Examples/php/funcptr/Makefile @@ -7,17 +7,17 @@ LIBS = SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile php_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_static clean: - $(MAKE) -f $(TOP)/Makefile php_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/overloading/Makefile b/Examples/php/overloading/Makefile index cefd81f78..8b2b340e9 100644 --- a/Examples/php/overloading/Makefile +++ b/Examples/php/overloading/Makefile @@ -7,17 +7,17 @@ LIBS = SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile php_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile php_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/pointer/Makefile b/Examples/php/pointer/Makefile index 57785acc7..f2c15c5c1 100644 --- a/Examples/php/pointer/Makefile +++ b/Examples/php/pointer/Makefile @@ -7,17 +7,17 @@ LIBS = SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile php_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_static clean: - $(MAKE) -f $(TOP)/Makefile php_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/pragmas/Makefile b/Examples/php/pragmas/Makefile index 3f24a3921..e5b49571e 100644 --- a/Examples/php/pragmas/Makefile +++ b/Examples/php/pragmas/Makefile @@ -7,17 +7,17 @@ LIBS = SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile php_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_static clean: - $(MAKE) -f $(TOP)/Makefile php_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/proxy/Makefile b/Examples/php/proxy/Makefile index cefd81f78..8b2b340e9 100644 --- a/Examples/php/proxy/Makefile +++ b/Examples/php/proxy/Makefile @@ -7,17 +7,17 @@ LIBS = SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile php_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile php_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/reference/Makefile b/Examples/php/reference/Makefile index cefd81f78..8b2b340e9 100644 --- a/Examples/php/reference/Makefile +++ b/Examples/php/reference/Makefile @@ -7,17 +7,17 @@ LIBS = SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile php_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile php_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/simple/Makefile b/Examples/php/simple/Makefile index 57785acc7..f2c15c5c1 100644 --- a/Examples/php/simple/Makefile +++ b/Examples/php/simple/Makefile @@ -7,17 +7,17 @@ LIBS = SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile php_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_static clean: - $(MAKE) -f $(TOP)/Makefile php_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/sync/Makefile b/Examples/php/sync/Makefile index cefd81f78..8b2b340e9 100644 --- a/Examples/php/sync/Makefile +++ b/Examples/php/sync/Makefile @@ -7,17 +7,17 @@ LIBS = SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile php_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile php_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/value/Makefile b/Examples/php/value/Makefile index 449686784..3db7afec5 100644 --- a/Examples/php/value/Makefile +++ b/Examples/php/value/Makefile @@ -7,17 +7,17 @@ LIBS = SWIGOPT = -noproxy check: build - $(MAKE) -f $(TOP)/Makefile php_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_static clean: - $(MAKE) -f $(TOP)/Makefile php_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/php/variables/Makefile b/Examples/php/variables/Makefile index 57785acc7..f2c15c5c1 100644 --- a/Examples/php/variables/Makefile +++ b/Examples/php/variables/Makefile @@ -7,17 +7,17 @@ LIBS = SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile php_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ php static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myphp' INTERFACE='$(INTERFACE)' \ php_static clean: - $(MAKE) -f $(TOP)/Makefile php_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' php_clean diff --git a/Examples/pike/class/Makefile b/Examples/pike/class/Makefile index aadc47151..d8cf4ea7e 100644 --- a/Examples/pike/class/Makefile +++ b/Examples/pike/class/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile pike_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mypike' INTERFACE='$(INTERFACE)' pike_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile pike_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_clean diff --git a/Examples/pike/constants/Makefile b/Examples/pike/constants/Makefile index c9385ce3b..736d30f03 100644 --- a/Examples/pike/constants/Makefile +++ b/Examples/pike/constants/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile pike_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='mypike' INTERFACE='$(INTERFACE)' pike_static clean: - $(MAKE) -f $(TOP)/Makefile pike_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_clean diff --git a/Examples/pike/enum/Makefile b/Examples/pike/enum/Makefile index aadc47151..d8cf4ea7e 100644 --- a/Examples/pike/enum/Makefile +++ b/Examples/pike/enum/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile pike_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mypike' INTERFACE='$(INTERFACE)' pike_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile pike_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_clean diff --git a/Examples/pike/overload/Makefile b/Examples/pike/overload/Makefile index 8d799efe1..f111b1137 100644 --- a/Examples/pike/overload/Makefile +++ b/Examples/pike/overload/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lstdc++ -lm check: build - $(MAKE) -f $(TOP)/Makefile pike_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mypike' INTERFACE='$(INTERFACE)' pike_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile pike_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_clean diff --git a/Examples/pike/simple/Makefile b/Examples/pike/simple/Makefile index f58ed4e65..d7f6b209e 100644 --- a/Examples/pike/simple/Makefile +++ b/Examples/pike/simple/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile pike_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='mypike' INTERFACE='$(INTERFACE)' pike_static clean: - $(MAKE) -f $(TOP)/Makefile pike_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_clean diff --git a/Examples/pike/template/Makefile b/Examples/pike/template/Makefile index e4fc945f7..da115c1d5 100644 --- a/Examples/pike/template/Makefile +++ b/Examples/pike/template/Makefile @@ -7,15 +7,15 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile pike_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' pike_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='mypike' INTERFACE='$(INTERFACE)' pike_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile pike_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' pike_clean diff --git a/Examples/python/callback/Makefile b/Examples/python/callback/Makefile index 684995801..a4c4d2a69 100644 --- a/Examples/python/callback/Makefile +++ b/Examples/python/callback/Makefile @@ -7,15 +7,15 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/class/Makefile b/Examples/python/class/Makefile index e940c1f43..41cded284 100644 --- a/Examples/python/class/Makefile +++ b/Examples/python/class/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/constants/Makefile b/Examples/python/constants/Makefile index 15ffa24c9..8ec6e9cc9 100644 --- a/Examples/python/constants/Makefile +++ b/Examples/python/constants/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/contract/Makefile b/Examples/python/contract/Makefile index 999521ccc..fe1d9325e 100644 --- a/Examples/python/contract/Makefile +++ b/Examples/python/contract/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/docstrings/Makefile b/Examples/python/docstrings/Makefile index 51552f3cf..f471930dd 100644 --- a/Examples/python/docstrings/Makefile +++ b/Examples/python/docstrings/Makefile @@ -7,17 +7,17 @@ LIBS = -lm SWIGOPT = -O check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/enum/Makefile b/Examples/python/enum/Makefile index e940c1f43..41cded284 100644 --- a/Examples/python/enum/Makefile +++ b/Examples/python/enum/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/exception/Makefile b/Examples/python/exception/Makefile index fb200fbaf..ad3d49fe1 100644 --- a/Examples/python/exception/Makefile +++ b/Examples/python/exception/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/exceptproxy/Makefile b/Examples/python/exceptproxy/Makefile index 86a643415..f406dfaf4 100644 --- a/Examples/python/exceptproxy/Makefile +++ b/Examples/python/exceptproxy/Makefile @@ -7,15 +7,15 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/extend/Makefile b/Examples/python/extend/Makefile index 684995801..a4c4d2a69 100644 --- a/Examples/python/extend/Makefile +++ b/Examples/python/extend/Makefile @@ -7,15 +7,15 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/funcptr/Makefile b/Examples/python/funcptr/Makefile index df3bc86ff..222916fa1 100644 --- a/Examples/python/funcptr/Makefile +++ b/Examples/python/funcptr/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/funcptr2/Makefile b/Examples/python/funcptr2/Makefile index df3bc86ff..222916fa1 100644 --- a/Examples/python/funcptr2/Makefile +++ b/Examples/python/funcptr2/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/functor/Makefile b/Examples/python/functor/Makefile index dde0d0910..1234c310e 100644 --- a/Examples/python/functor/Makefile +++ b/Examples/python/functor/Makefile @@ -7,15 +7,15 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/import/Makefile b/Examples/python/import/Makefile index f63e12271..d83dfeaa8 100644 --- a/Examples/python/import/Makefile +++ b/Examples/python/import/Makefile @@ -4,19 +4,19 @@ SWIGOPT = LIBS = check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' python_cpp clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean rm -f foo.py bar.py spam.py base.py diff --git a/Examples/python/import_packages/Makefile b/Examples/python/import_packages/Makefile index fda2380b3..2df2be101 100644 --- a/Examples/python/import_packages/Makefile +++ b/Examples/python/import_packages/Makefile @@ -5,7 +5,7 @@ LIBS = PY3 = import_packages_subdirs = \ - same_modnames1 \ + same_modnames1 \ same_modnames2 \ from_init1 \ from_init2 \ @@ -14,8 +14,13 @@ import_packages_subdirs = \ relativeimport1 check: build + if test "x$(SRCDIR)" != x; then \ + for file in `cd $(SRCDIR) && find . -type f -name __init__.py`; do \ + cp "${SRCDIR}$$file" "$$file" || exit 1; \ + done; \ + fi; \ for s in $(import_packages_subdirs); do \ - (cd $$s && $(MAKE) check); \ + (cd $$s && $(MAKE) check); \ done build: @@ -29,7 +34,7 @@ static: done clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean for s in $(import_packages_subdirs); do \ (cd $$s && $(MAKE) clean); \ done diff --git a/Examples/python/import_packages/from_init1/Makefile b/Examples/python/import_packages/from_init1/Makefile index 8e35c6c61..b9d803a0e 100644 --- a/Examples/python/import_packages/from_init1/Makefile +++ b/Examples/python/import_packages/from_init1/Makefile @@ -11,7 +11,7 @@ else endif check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build @@ -20,6 +20,6 @@ static: cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean cd py2 && $(MAKE) clean cd py3 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init1/py2/Makefile b/Examples/python/import_packages/from_init1/py2/Makefile index 4c0dfab07..9595397d8 100644 --- a/Examples/python/import_packages/from_init1/py2/Makefile +++ b/Examples/python/import_packages/from_init1/py2/Makefile @@ -10,5 +10,5 @@ static: cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init1/py2/pkg2/Makefile b/Examples/python/import_packages/from_init1/py2/pkg2/Makefile index 0dd174659..1eb810e05 100644 --- a/Examples/python/import_packages/from_init1/py2/pkg2/Makefile +++ b/Examples/python/import_packages/from_init1/py2/pkg2/Makefile @@ -4,17 +4,17 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' 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 + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean diff --git a/Examples/python/import_packages/from_init1/py3/Makefile b/Examples/python/import_packages/from_init1/py3/Makefile index 4c0dfab07..9595397d8 100644 --- a/Examples/python/import_packages/from_init1/py3/Makefile +++ b/Examples/python/import_packages/from_init1/py3/Makefile @@ -10,5 +10,5 @@ static: cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init1/py3/pkg2/Makefile b/Examples/python/import_packages/from_init1/py3/pkg2/Makefile index 0dd174659..1eb810e05 100644 --- a/Examples/python/import_packages/from_init1/py3/pkg2/Makefile +++ b/Examples/python/import_packages/from_init1/py3/pkg2/Makefile @@ -4,17 +4,17 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' 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 + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean diff --git a/Examples/python/import_packages/from_init2/Makefile b/Examples/python/import_packages/from_init2/Makefile index 8e35c6c61..b9d803a0e 100644 --- a/Examples/python/import_packages/from_init2/Makefile +++ b/Examples/python/import_packages/from_init2/Makefile @@ -11,7 +11,7 @@ else endif check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build @@ -20,6 +20,6 @@ static: cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean cd py2 && $(MAKE) clean cd py3 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init2/py2/Makefile b/Examples/python/import_packages/from_init2/py2/Makefile index 4c0dfab07..9595397d8 100644 --- a/Examples/python/import_packages/from_init2/py2/Makefile +++ b/Examples/python/import_packages/from_init2/py2/Makefile @@ -10,5 +10,5 @@ static: cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init2/py2/pkg2/Makefile b/Examples/python/import_packages/from_init2/py2/pkg2/Makefile index 3fe56139d..36e099b78 100644 --- a/Examples/python/import_packages/from_init2/py2/pkg2/Makefile +++ b/Examples/python/import_packages/from_init2/py2/pkg2/Makefile @@ -4,15 +4,15 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' 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)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' 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 + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/Makefile b/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/Makefile index a417e2745..cb20bd25f 100644 --- a/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/Makefile +++ b/Examples/python/import_packages/from_init2/py2/pkg2/pkg3/Makefile @@ -4,12 +4,12 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/from_init2/py3/Makefile b/Examples/python/import_packages/from_init2/py3/Makefile index 4c0dfab07..9595397d8 100644 --- a/Examples/python/import_packages/from_init2/py3/Makefile +++ b/Examples/python/import_packages/from_init2/py3/Makefile @@ -10,5 +10,5 @@ static: cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init2/py3/pkg2/Makefile b/Examples/python/import_packages/from_init2/py3/pkg2/Makefile index 3fe56139d..36e099b78 100644 --- a/Examples/python/import_packages/from_init2/py3/pkg2/Makefile +++ b/Examples/python/import_packages/from_init2/py3/pkg2/Makefile @@ -4,15 +4,15 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' 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)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' 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 + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/Makefile b/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/Makefile index a417e2745..cb20bd25f 100644 --- a/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/Makefile +++ b/Examples/python/import_packages/from_init2/py3/pkg2/pkg3/Makefile @@ -4,12 +4,12 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/from_init3/Makefile b/Examples/python/import_packages/from_init3/Makefile index 8e35c6c61..b9d803a0e 100644 --- a/Examples/python/import_packages/from_init3/Makefile +++ b/Examples/python/import_packages/from_init3/Makefile @@ -11,7 +11,7 @@ else endif check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build @@ -20,6 +20,6 @@ static: cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean cd py2 && $(MAKE) clean cd py3 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init3/py2/Makefile b/Examples/python/import_packages/from_init3/py2/Makefile index 4c0dfab07..9595397d8 100644 --- a/Examples/python/import_packages/from_init3/py2/Makefile +++ b/Examples/python/import_packages/from_init3/py2/Makefile @@ -10,5 +10,5 @@ static: cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/Makefile b/Examples/python/import_packages/from_init3/py2/pkg2/Makefile index 3fe56139d..36e099b78 100644 --- a/Examples/python/import_packages/from_init3/py2/pkg2/Makefile +++ b/Examples/python/import_packages/from_init3/py2/pkg2/Makefile @@ -4,15 +4,15 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' 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)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' 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 + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/Makefile b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/Makefile index 470f9d561..d6ae1b2bc 100644 --- a/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/Makefile +++ b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/Makefile @@ -10,5 +10,5 @@ static: cd pkg4 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean cd pkg4 && $(MAKE) clean 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 index a98d31122..286d90070 100644 --- a/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/Makefile +++ b/Examples/python/import_packages/from_init3/py2/pkg2/pkg3/pkg4/Makefile @@ -4,12 +4,12 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/from_init3/py3/Makefile b/Examples/python/import_packages/from_init3/py3/Makefile index 4c0dfab07..9595397d8 100644 --- a/Examples/python/import_packages/from_init3/py3/Makefile +++ b/Examples/python/import_packages/from_init3/py3/Makefile @@ -10,5 +10,5 @@ static: cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/Makefile b/Examples/python/import_packages/from_init3/py3/pkg2/Makefile index 3fe56139d..36e099b78 100644 --- a/Examples/python/import_packages/from_init3/py3/pkg2/Makefile +++ b/Examples/python/import_packages/from_init3/py3/pkg2/Makefile @@ -4,15 +4,15 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' 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)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' 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 + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/Makefile b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/Makefile index 470f9d561..d6ae1b2bc 100644 --- a/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/Makefile +++ b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/Makefile @@ -10,5 +10,5 @@ static: cd pkg4 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean cd pkg4 && $(MAKE) clean 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 index a98d31122..286d90070 100644 --- a/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/Makefile +++ b/Examples/python/import_packages/from_init3/py3/pkg2/pkg3/pkg4/Makefile @@ -4,12 +4,12 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/relativeimport1/Makefile b/Examples/python/import_packages/relativeimport1/Makefile index 8e35c6c61..b9d803a0e 100644 --- a/Examples/python/import_packages/relativeimport1/Makefile +++ b/Examples/python/import_packages/relativeimport1/Makefile @@ -11,7 +11,7 @@ else endif check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build @@ -20,6 +20,6 @@ static: cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean cd py2 && $(MAKE) clean cd py3 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport1/py2/Makefile b/Examples/python/import_packages/relativeimport1/py2/Makefile index 4c0dfab07..9595397d8 100644 --- a/Examples/python/import_packages/relativeimport1/py2/Makefile +++ b/Examples/python/import_packages/relativeimport1/py2/Makefile @@ -10,5 +10,5 @@ static: cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport1/py2/pkg2/Makefile b/Examples/python/import_packages/relativeimport1/py2/pkg2/Makefile index 3fe56139d..36e099b78 100644 --- a/Examples/python/import_packages/relativeimport1/py2/pkg2/Makefile +++ b/Examples/python/import_packages/relativeimport1/py2/pkg2/Makefile @@ -4,15 +4,15 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' 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)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' 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 + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/Makefile b/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/Makefile index a417e2745..cb20bd25f 100644 --- a/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/Makefile +++ b/Examples/python/import_packages/relativeimport1/py2/pkg2/pkg3/Makefile @@ -4,12 +4,12 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/relativeimport1/py3/Makefile b/Examples/python/import_packages/relativeimport1/py3/Makefile index 4c0dfab07..9595397d8 100644 --- a/Examples/python/import_packages/relativeimport1/py3/Makefile +++ b/Examples/python/import_packages/relativeimport1/py3/Makefile @@ -10,5 +10,5 @@ static: cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport1/py3/pkg2/Makefile b/Examples/python/import_packages/relativeimport1/py3/pkg2/Makefile index 3fe56139d..36e099b78 100644 --- a/Examples/python/import_packages/relativeimport1/py3/pkg2/Makefile +++ b/Examples/python/import_packages/relativeimport1/py3/pkg2/Makefile @@ -4,15 +4,15 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' 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)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' 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 + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/Makefile b/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/Makefile index a417e2745..cb20bd25f 100644 --- a/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/Makefile +++ b/Examples/python/import_packages/relativeimport1/py3/pkg2/pkg3/Makefile @@ -4,12 +4,12 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/relativeimport2/Makefile b/Examples/python/import_packages/relativeimport2/Makefile index 8e35c6c61..b9d803a0e 100644 --- a/Examples/python/import_packages/relativeimport2/Makefile +++ b/Examples/python/import_packages/relativeimport2/Makefile @@ -11,7 +11,7 @@ else endif check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' build @@ -20,6 +20,6 @@ static: cd $(PKG1DIR) && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT) -relativeimport' LIBS='$(LIBS)' static clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean cd py2 && $(MAKE) clean cd py3 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport2/py2/Makefile b/Examples/python/import_packages/relativeimport2/py2/Makefile index 4c0dfab07..9595397d8 100644 --- a/Examples/python/import_packages/relativeimport2/py2/Makefile +++ b/Examples/python/import_packages/relativeimport2/py2/Makefile @@ -10,5 +10,5 @@ static: cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/Makefile b/Examples/python/import_packages/relativeimport2/py2/pkg2/Makefile index 3fe56139d..36e099b78 100644 --- a/Examples/python/import_packages/relativeimport2/py2/pkg2/Makefile +++ b/Examples/python/import_packages/relativeimport2/py2/pkg2/Makefile @@ -4,15 +4,15 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' 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)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' 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 + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/Makefile b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/Makefile index 470f9d561..d6ae1b2bc 100644 --- a/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/Makefile +++ b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/Makefile @@ -10,5 +10,5 @@ static: cd pkg4 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean cd pkg4 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/Makefile b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/Makefile index a98d31122..286d90070 100644 --- a/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/Makefile +++ b/Examples/python/import_packages/relativeimport2/py2/pkg2/pkg3/pkg4/Makefile @@ -4,12 +4,12 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/relativeimport2/py3/Makefile b/Examples/python/import_packages/relativeimport2/py3/Makefile index 4c0dfab07..9595397d8 100644 --- a/Examples/python/import_packages/relativeimport2/py3/Makefile +++ b/Examples/python/import_packages/relativeimport2/py3/Makefile @@ -10,5 +10,5 @@ static: cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/Makefile b/Examples/python/import_packages/relativeimport2/py3/pkg2/Makefile index 3fe56139d..36e099b78 100644 --- a/Examples/python/import_packages/relativeimport2/py3/pkg2/Makefile +++ b/Examples/python/import_packages/relativeimport2/py3/pkg2/Makefile @@ -4,15 +4,15 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' 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)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' 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 + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='bar' python_clean cd pkg3 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/Makefile b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/Makefile index 470f9d561..d6ae1b2bc 100644 --- a/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/Makefile +++ b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/Makefile @@ -10,5 +10,5 @@ static: cd pkg4 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean cd pkg4 && $(MAKE) clean diff --git a/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/Makefile b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/Makefile index a98d31122..286d90070 100644 --- a/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/Makefile +++ b/Examples/python/import_packages/relativeimport2/py3/pkg2/pkg3/pkg4/Makefile @@ -4,12 +4,12 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/same_modnames1/Makefile b/Examples/python/import_packages/same_modnames1/Makefile index 9dd5971dc..e05c13017 100644 --- a/Examples/python/import_packages/same_modnames1/Makefile +++ b/Examples/python/import_packages/same_modnames1/Makefile @@ -4,7 +4,7 @@ SWIGOPT = LIBS = check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: cd pkg1 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build @@ -15,6 +15,6 @@ static: cd pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean cd pkg1 && $(MAKE) clean cd pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/same_modnames1/pkg1/Makefile b/Examples/python/import_packages/same_modnames1/pkg1/Makefile index 9b51a76ed..df1b30321 100644 --- a/Examples/python/import_packages/same_modnames1/pkg1/Makefile +++ b/Examples/python/import_packages/same_modnames1/pkg1/Makefile @@ -4,12 +4,12 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/same_modnames1/pkg2/Makefile b/Examples/python/import_packages/same_modnames1/pkg2/Makefile index 9b51a76ed..df1b30321 100644 --- a/Examples/python/import_packages/same_modnames1/pkg2/Makefile +++ b/Examples/python/import_packages/same_modnames1/pkg2/Makefile @@ -4,12 +4,12 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/same_modnames2/Makefile b/Examples/python/import_packages/same_modnames2/Makefile index cfc327883..770343a80 100644 --- a/Examples/python/import_packages/same_modnames2/Makefile +++ b/Examples/python/import_packages/same_modnames2/Makefile @@ -4,7 +4,7 @@ SWIGOPT = LIBS = check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: cd pkg1 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' build @@ -15,6 +15,6 @@ static: cd pkg1/pkg2 && $(MAKE) SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' LIBS='$(LIBS)' static clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean cd pkg1 && $(MAKE) clean cd pkg1/pkg2 && $(MAKE) clean diff --git a/Examples/python/import_packages/same_modnames2/pkg1/Makefile b/Examples/python/import_packages/same_modnames2/pkg1/Makefile index 9b51a76ed..df1b30321 100644 --- a/Examples/python/import_packages/same_modnames2/pkg1/Makefile +++ b/Examples/python/import_packages/same_modnames2/pkg1/Makefile @@ -4,12 +4,12 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_packages/same_modnames2/pkg1/pkg2/Makefile b/Examples/python/import_packages/same_modnames2/pkg1/pkg2/Makefile index 053b911f5..11e8573ad 100644 --- a/Examples/python/import_packages/same_modnames2/pkg1/pkg2/Makefile +++ b/Examples/python/import_packages/same_modnames2/pkg1/pkg2/Makefile @@ -4,12 +4,12 @@ SWIGOPT = LIBS = build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp static: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='foo' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='foo' python_clean diff --git a/Examples/python/import_template/Makefile b/Examples/python/import_template/Makefile index f63e12271..d83dfeaa8 100644 --- a/Examples/python/import_template/Makefile +++ b/Examples/python/import_template/Makefile @@ -4,19 +4,19 @@ SWIGOPT = LIBS = check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' python_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' python_cpp clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean rm -f foo.py bar.py spam.py base.py diff --git a/Examples/python/java/Makefile b/Examples/python/java/Makefile index 2ce219969..4befa38ba 100644 --- a/Examples/python/java/Makefile +++ b/Examples/python/java/Makefile @@ -6,18 +6,18 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: Example.class Example.h - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ CXXSHARED="gcj -fpic -shared Example.class" DEFS='' LIBS="-lstdc++" python_cpp clean: - $(MAKE) -f $(TOP)/Makefile python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean rm -f $(TARGET).py rm -f *.class Example.h -Example.class Example.h: Example.java - gcj -fPIC -C -c -g Example.java +Example.class Example.h: $(SRCDIR)Example.java + gcj -d . -fPIC -C -c -g $(SRCDIR)Example.java gcjh Example.class diff --git a/Examples/python/libffi/Makefile b/Examples/python/libffi/Makefile index ae51b0a60..db5dfe138 100644 --- a/Examples/python/libffi/Makefile +++ b/Examples/python/libffi/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' LIBS='-L/usr/local/lib -lffi' python static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/multimap/Makefile b/Examples/python/multimap/Makefile index df3bc86ff..222916fa1 100644 --- a/Examples/python/multimap/Makefile +++ b/Examples/python/multimap/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/operator/Makefile b/Examples/python/operator/Makefile index dde0d0910..1234c310e 100644 --- a/Examples/python/operator/Makefile +++ b/Examples/python/operator/Makefile @@ -7,15 +7,15 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/performance/constructor/Makefile b/Examples/python/performance/constructor/Makefile index 98a50ec29..8e65123cf 100644 --- a/Examples/python/performance/constructor/Makefile +++ b/Examples/python/performance/constructor/Makefile @@ -5,17 +5,17 @@ TARGET = Simple INTERFACE = Simple.i build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -module Simple_baseline' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -module Simple_baseline' \ TARGET='$(TARGET)_baseline' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -O -module Simple_optimized' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -O -module Simple_optimized' \ TARGET='$(TARGET)_optimized' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -builtin -O -module Simple_builtin' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -builtin -O -module Simple_builtin' \ TARGET='$(TARGET)_builtin' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean rm -f $(TARGET)_*.py diff --git a/Examples/python/performance/func/Makefile b/Examples/python/performance/func/Makefile index 98a50ec29..8e65123cf 100644 --- a/Examples/python/performance/func/Makefile +++ b/Examples/python/performance/func/Makefile @@ -5,17 +5,17 @@ TARGET = Simple INTERFACE = Simple.i build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -module Simple_baseline' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -module Simple_baseline' \ TARGET='$(TARGET)_baseline' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -O -module Simple_optimized' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -O -module Simple_optimized' \ TARGET='$(TARGET)_optimized' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -builtin -O -module Simple_builtin' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -builtin -O -module Simple_builtin' \ TARGET='$(TARGET)_builtin' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean rm -f $(TARGET)_*.py diff --git a/Examples/python/performance/hierarchy/Makefile b/Examples/python/performance/hierarchy/Makefile index 98a50ec29..8e65123cf 100644 --- a/Examples/python/performance/hierarchy/Makefile +++ b/Examples/python/performance/hierarchy/Makefile @@ -5,17 +5,17 @@ TARGET = Simple INTERFACE = Simple.i build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -module Simple_baseline' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -module Simple_baseline' \ TARGET='$(TARGET)_baseline' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -O -module Simple_optimized' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -O -module Simple_optimized' \ TARGET='$(TARGET)_optimized' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -builtin -O -module Simple_builtin' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -builtin -O -module Simple_builtin' \ TARGET='$(TARGET)_builtin' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean rm -f $(TARGET)_*.py diff --git a/Examples/python/performance/hierarchy_operator/Makefile b/Examples/python/performance/hierarchy_operator/Makefile index 98a50ec29..8e65123cf 100644 --- a/Examples/python/performance/hierarchy_operator/Makefile +++ b/Examples/python/performance/hierarchy_operator/Makefile @@ -5,17 +5,17 @@ TARGET = Simple INTERFACE = Simple.i build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -module Simple_baseline' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -module Simple_baseline' \ TARGET='$(TARGET)_baseline' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -O -module Simple_optimized' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -O -module Simple_optimized' \ TARGET='$(TARGET)_optimized' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -builtin -O -module Simple_builtin' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -builtin -O -module Simple_builtin' \ TARGET='$(TARGET)_builtin' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean rm -f $(TARGET)_*.py diff --git a/Examples/python/performance/operator/Makefile b/Examples/python/performance/operator/Makefile index 98a50ec29..8e65123cf 100644 --- a/Examples/python/performance/operator/Makefile +++ b/Examples/python/performance/operator/Makefile @@ -5,17 +5,17 @@ TARGET = Simple INTERFACE = Simple.i build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -module Simple_baseline' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -module Simple_baseline' \ TARGET='$(TARGET)_baseline' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -O -module Simple_optimized' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -O -module Simple_optimized' \ TARGET='$(TARGET)_optimized' INTERFACE='$(INTERFACE)' python_cpp - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -builtin -O -module Simple_builtin' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG) -builtin -O -module Simple_builtin' \ TARGET='$(TARGET)_builtin' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean rm -f $(TARGET)_*.py diff --git a/Examples/python/pointer/Makefile b/Examples/python/pointer/Makefile index df3bc86ff..222916fa1 100644 --- a/Examples/python/pointer/Makefile +++ b/Examples/python/pointer/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/reference/Makefile b/Examples/python/reference/Makefile index e940c1f43..41cded284 100644 --- a/Examples/python/reference/Makefile +++ b/Examples/python/reference/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/simple/Makefile b/Examples/python/simple/Makefile index df3bc86ff..222916fa1 100644 --- a/Examples/python/simple/Makefile +++ b/Examples/python/simple/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/smartptr/Makefile b/Examples/python/smartptr/Makefile index aaba9cbbc..19609353d 100644 --- a/Examples/python/smartptr/Makefile +++ b/Examples/python/smartptr/Makefile @@ -7,15 +7,15 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/std_map/Makefile b/Examples/python/std_map/Makefile index 86a643415..f406dfaf4 100644 --- a/Examples/python/std_map/Makefile +++ b/Examples/python/std_map/Makefile @@ -7,15 +7,15 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/std_vector/Makefile b/Examples/python/std_vector/Makefile index 86a643415..f406dfaf4 100644 --- a/Examples/python/std_vector/Makefile +++ b/Examples/python/std_vector/Makefile @@ -7,15 +7,15 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/swigrun/Makefile b/Examples/python/swigrun/Makefile index c58f39caf..94f7d04e0 100644 --- a/Examples/python/swigrun/Makefile +++ b/Examples/python/swigrun/Makefile @@ -7,17 +7,17 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: $(SWIG) -python -external-runtime - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean rm -f swigpyrun.h diff --git a/Examples/python/template/Makefile b/Examples/python/template/Makefile index 86a643415..f406dfaf4 100644 --- a/Examples/python/template/Makefile +++ b/Examples/python/template/Makefile @@ -7,15 +7,15 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='mypython' INTERFACE='$(INTERFACE)' python_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/varargs/Makefile b/Examples/python/varargs/Makefile index 15ffa24c9..8ec6e9cc9 100644 --- a/Examples/python/varargs/Makefile +++ b/Examples/python/varargs/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/python/variables/Makefile b/Examples/python/variables/Makefile index df3bc86ff..222916fa1 100644 --- a/Examples/python/variables/Makefile +++ b/Examples/python/variables/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile python_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' python static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='mypython' INTERFACE='$(INTERFACE)' python_static clean: - $(MAKE) -f $(TOP)/Makefile TARGET='$(TARGET)' python_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' TARGET='$(TARGET)' python_clean diff --git a/Examples/r/class/Makefile b/Examples/r/class/Makefile index 8a64f49a9..3e5d6a6ca 100644 --- a/Examples/r/class/Makefile +++ b/Examples/r/class/Makefile @@ -5,11 +5,11 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile r_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' r_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' r_cpp clean: - $(MAKE) -f $(TOP)/Makefile INTERFACE='$(INTERFACE)' r_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' r_clean diff --git a/Examples/r/simple/Makefile b/Examples/r/simple/Makefile index 8a8e0e1c1..5cc41530c 100644 --- a/Examples/r/simple/Makefile +++ b/Examples/r/simple/Makefile @@ -5,11 +5,11 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile r_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' r_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' r clean: - $(MAKE) -f $(TOP)/Makefile INTERFACE='$(INTERFACE)' r_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' INTERFACE='$(INTERFACE)' r_clean diff --git a/Examples/ruby/class/Makefile b/Examples/ruby/class/Makefile index ef267bc44..516f842d7 100644 --- a/Examples/ruby/class/Makefile +++ b/Examples/ruby/class/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/constants/Makefile b/Examples/ruby/constants/Makefile index 7af9ec89e..561d5fd84 100644 --- a/Examples/ruby/constants/Makefile +++ b/Examples/ruby/constants/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/enum/Makefile b/Examples/ruby/enum/Makefile index ef267bc44..516f842d7 100644 --- a/Examples/ruby/enum/Makefile +++ b/Examples/ruby/enum/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/exception_class/Makefile b/Examples/ruby/exception_class/Makefile index f0ae7e573..6723a2a7c 100644 --- a/Examples/ruby/exception_class/Makefile +++ b/Examples/ruby/exception_class/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/free_function/Makefile b/Examples/ruby/free_function/Makefile index ef267bc44..516f842d7 100644 --- a/Examples/ruby/free_function/Makefile +++ b/Examples/ruby/free_function/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/funcptr/Makefile b/Examples/ruby/funcptr/Makefile index ddbc1ae30..15b39cf0d 100644 --- a/Examples/ruby/funcptr/Makefile +++ b/Examples/ruby/funcptr/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/funcptr2/Makefile b/Examples/ruby/funcptr2/Makefile index ddbc1ae30..15b39cf0d 100644 --- a/Examples/ruby/funcptr2/Makefile +++ b/Examples/ruby/funcptr2/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/functor/Makefile b/Examples/ruby/functor/Makefile index 662baa110..348bd66e3 100644 --- a/Examples/ruby/functor/Makefile +++ b/Examples/ruby/functor/Makefile @@ -5,15 +5,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/hashargs/Makefile b/Examples/ruby/hashargs/Makefile index 3933cf279..59a36c0dd 100644 --- a/Examples/ruby/hashargs/Makefile +++ b/Examples/ruby/hashargs/Makefile @@ -7,15 +7,15 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/import/Makefile b/Examples/ruby/import/Makefile index cd7719b5c..b5d06bdd7 100644 --- a/Examples/ruby/import/Makefile +++ b/Examples/ruby/import/Makefile @@ -4,17 +4,17 @@ SWIGOPT = LIBS = check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' ruby_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' ruby_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' ruby_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' ruby_cpp clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/import_template/Makefile b/Examples/ruby/import_template/Makefile index cd7719b5c..b5d06bdd7 100644 --- a/Examples/ruby/import_template/Makefile +++ b/Examples/ruby/import_template/Makefile @@ -4,17 +4,17 @@ SWIGOPT = LIBS = check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' ruby_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' ruby_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' ruby_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' ruby_cpp clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/java/Makefile b/Examples/ruby/java/Makefile index a71635baa..7d611abd2 100644 --- a/Examples/ruby/java/Makefile +++ b/Examples/ruby/java/Makefile @@ -6,17 +6,17 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: Example.class Example.h - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ CXXSHARED="gcj -fpic -shared Example.class" LIBS="-lstdc++" DEFS='' ruby_cpp clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean rm -f *.class Example.h -Example.class Example.h: Example.java - gcj -fPIC -C -c -g Example.java +Example.class Example.h: $(SRCDIR)Example.java + gcj -d . -fPIC -C -c -g $(SRCDIR)Example.java gcjh Example.class diff --git a/Examples/ruby/mark_function/Makefile b/Examples/ruby/mark_function/Makefile index ef267bc44..516f842d7 100644 --- a/Examples/ruby/mark_function/Makefile +++ b/Examples/ruby/mark_function/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/multimap/Makefile b/Examples/ruby/multimap/Makefile index ddbc1ae30..15b39cf0d 100644 --- a/Examples/ruby/multimap/Makefile +++ b/Examples/ruby/multimap/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/operator/Makefile b/Examples/ruby/operator/Makefile index 5fd4b077b..bdcf52646 100644 --- a/Examples/ruby/operator/Makefile +++ b/Examples/ruby/operator/Makefile @@ -7,15 +7,15 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/overloading/Makefile b/Examples/ruby/overloading/Makefile index ef267bc44..516f842d7 100644 --- a/Examples/ruby/overloading/Makefile +++ b/Examples/ruby/overloading/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/pointer/Makefile b/Examples/ruby/pointer/Makefile index ddbc1ae30..15b39cf0d 100644 --- a/Examples/ruby/pointer/Makefile +++ b/Examples/ruby/pointer/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/reference/Makefile b/Examples/ruby/reference/Makefile index ef267bc44..516f842d7 100644 --- a/Examples/ruby/reference/Makefile +++ b/Examples/ruby/reference/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/simple/Makefile b/Examples/ruby/simple/Makefile index ddbc1ae30..15b39cf0d 100644 --- a/Examples/ruby/simple/Makefile +++ b/Examples/ruby/simple/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/std_vector/Makefile b/Examples/ruby/std_vector/Makefile index 208a64495..370bd8fb6 100644 --- a/Examples/ruby/std_vector/Makefile +++ b/Examples/ruby/std_vector/Makefile @@ -7,15 +7,15 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/template/Makefile b/Examples/ruby/template/Makefile index 208a64495..370bd8fb6 100644 --- a/Examples/ruby/template/Makefile +++ b/Examples/ruby/template/Makefile @@ -7,15 +7,15 @@ LIBS = -lm SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ SWIGOPT='$(SWIGOPT)' TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/value/Makefile b/Examples/ruby/value/Makefile index ddbc1ae30..15b39cf0d 100644 --- a/Examples/ruby/value/Makefile +++ b/Examples/ruby/value/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/ruby/variables/Makefile b/Examples/ruby/variables/Makefile index ddbc1ae30..15b39cf0d 100644 --- a/Examples/ruby/variables/Makefile +++ b/Examples/ruby/variables/Makefile @@ -5,15 +5,15 @@ TARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile ruby_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' ruby static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='myruby' INTERFACE='$(INTERFACE)' ruby_static clean: - $(MAKE) -f $(TOP)/Makefile ruby_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' ruby_clean diff --git a/Examples/tcl/class/Makefile b/Examples/tcl/class/Makefile index db6149cb3..aacf30e04 100644 --- a/Examples/tcl/class/Makefile +++ b/Examples/tcl/class/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile tcl_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tcl_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mytclsh' INTERFACE='$(INTERFACE)' tclsh_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile tcl_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_clean diff --git a/Examples/tcl/constants/Makefile b/Examples/tcl/constants/Makefile index ed4d89f52..17c8afa3f 100644 --- a/Examples/tcl/constants/Makefile +++ b/Examples/tcl/constants/Makefile @@ -6,15 +6,15 @@ DLTARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile tcl_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh clean: - $(MAKE) -f $(TOP)/Makefile tcl_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_clean diff --git a/Examples/tcl/contract/Makefile b/Examples/tcl/contract/Makefile index ca6134e75..01fdc37b3 100644 --- a/Examples/tcl/contract/Makefile +++ b/Examples/tcl/contract/Makefile @@ -7,15 +7,15 @@ INTERFACE = example.i SWIGOPT = check: build - $(MAKE) -f $(TOP)/Makefile tcl_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh clean: - $(MAKE) -f $(TOP)/Makefile tcl_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_clean diff --git a/Examples/tcl/enum/Makefile b/Examples/tcl/enum/Makefile index db6149cb3..aacf30e04 100644 --- a/Examples/tcl/enum/Makefile +++ b/Examples/tcl/enum/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile tcl_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tcl_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mytclsh' INTERFACE='$(INTERFACE)' tclsh_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile tcl_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_clean diff --git a/Examples/tcl/funcptr/Makefile b/Examples/tcl/funcptr/Makefile index 919077918..7155bf3c3 100644 --- a/Examples/tcl/funcptr/Makefile +++ b/Examples/tcl/funcptr/Makefile @@ -6,15 +6,15 @@ DLTARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile tcl_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh clean: - $(MAKE) -f $(TOP)/Makefile tcl_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_clean diff --git a/Examples/tcl/import/Makefile b/Examples/tcl/import/Makefile index 81cd7c471..6aa48e7a8 100644 --- a/Examples/tcl/import/Makefile +++ b/Examples/tcl/import/Makefile @@ -4,18 +4,18 @@ SWIGOPT = LIBS = check: build - $(MAKE) -f $(TOP)/Makefile tcl_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='base' INTERFACE='base.i' tcl_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='foo' INTERFACE='foo.i' tcl_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='bar' INTERFACE='bar.i' tcl_cpp - $(MAKE) -f $(TOP)/Makefile SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \ LIBS='$(LIBS)' TARGET='spam' INTERFACE='spam.i' tcl_cpp clean: - $(MAKE) -f $(TOP)/Makefile tcl_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_clean diff --git a/Examples/tcl/java/Makefile b/Examples/tcl/java/Makefile index a3819ab7c..4be3764e2 100644 --- a/Examples/tcl/java/Makefile +++ b/Examples/tcl/java/Makefile @@ -6,17 +6,17 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile tcl_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: Example.class Example.h - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' \ TCLCXXSHARED="gcj -fpic -shared Example.class " LIBS="-lstdc++" DEFS='' tcl_cpp clean: - $(MAKE) -f $(TOP)/Makefile tcl_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_clean rm -f *.class Example.h -Example.class Example.h: Example.java - gcj -fPIC -C -c -g Example.java +Example.class Example.h: $(SRCDIR)Example.java + gcj -d . -fPIC -C -c -g $(SRCDIR)Example.java gcjh Example.class diff --git a/Examples/tcl/multimap/Makefile b/Examples/tcl/multimap/Makefile index 919077918..7155bf3c3 100644 --- a/Examples/tcl/multimap/Makefile +++ b/Examples/tcl/multimap/Makefile @@ -6,15 +6,15 @@ DLTARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile tcl_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh clean: - $(MAKE) -f $(TOP)/Makefile tcl_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_clean diff --git a/Examples/tcl/operator/Makefile b/Examples/tcl/operator/Makefile index 6c91c3d21..1c6e1be98 100644 --- a/Examples/tcl/operator/Makefile +++ b/Examples/tcl/operator/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile tcl_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tcl_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mytclsh' INTERFACE='$(INTERFACE)' tclsh_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile tcl_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_clean diff --git a/Examples/tcl/pointer/Makefile b/Examples/tcl/pointer/Makefile index 919077918..7155bf3c3 100644 --- a/Examples/tcl/pointer/Makefile +++ b/Examples/tcl/pointer/Makefile @@ -6,15 +6,15 @@ DLTARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile tcl_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh clean: - $(MAKE) -f $(TOP)/Makefile tcl_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_clean diff --git a/Examples/tcl/reference/Makefile b/Examples/tcl/reference/Makefile index db6149cb3..aacf30e04 100644 --- a/Examples/tcl/reference/Makefile +++ b/Examples/tcl/reference/Makefile @@ -6,15 +6,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile tcl_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tcl_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='mytclsh' INTERFACE='$(INTERFACE)' tclsh_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile tcl_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_clean diff --git a/Examples/tcl/simple/Makefile b/Examples/tcl/simple/Makefile index 919077918..7155bf3c3 100644 --- a/Examples/tcl/simple/Makefile +++ b/Examples/tcl/simple/Makefile @@ -6,15 +6,15 @@ DLTARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile tcl_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh clean: - $(MAKE) -f $(TOP)/Makefile tcl_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_clean diff --git a/Examples/tcl/std_vector/Makefile b/Examples/tcl/std_vector/Makefile index a150fc956..f29f933ba 100644 --- a/Examples/tcl/std_vector/Makefile +++ b/Examples/tcl/std_vector/Makefile @@ -7,15 +7,15 @@ INTERFACE = example.i LIBS = -lm check: build - $(MAKE) -f $(TOP)/Makefile tcl_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl_cpp static: - $(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh_cpp_static clean: - $(MAKE) -f $(TOP)/Makefile tcl_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_clean diff --git a/Examples/tcl/value/Makefile b/Examples/tcl/value/Makefile index 919077918..7155bf3c3 100644 --- a/Examples/tcl/value/Makefile +++ b/Examples/tcl/value/Makefile @@ -6,15 +6,15 @@ DLTARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile tcl_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh clean: - $(MAKE) -f $(TOP)/Makefile tcl_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_clean diff --git a/Examples/tcl/variables/Makefile b/Examples/tcl/variables/Makefile index 919077918..7155bf3c3 100644 --- a/Examples/tcl/variables/Makefile +++ b/Examples/tcl/variables/Makefile @@ -6,15 +6,15 @@ DLTARGET = example INTERFACE = example.i check: build - $(MAKE) -f $(TOP)/Makefile tcl_run + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_run build: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(DLTARGET)' INTERFACE='$(INTERFACE)' tcl static: - $(MAKE) -f $(TOP)/Makefile SRCS='$(SRCS)' SWIG='$(SWIG)' \ + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' tclsh clean: - $(MAKE) -f $(TOP)/Makefile tcl_clean + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' tcl_clean diff --git a/Examples/test-suite/allegrocl/Makefile.in b/Examples/test-suite/allegrocl/Makefile.in index 697c15a45..2803b7012 100644 --- a/Examples/test-suite/allegrocl/Makefile.in +++ b/Examples/test-suite/allegrocl/Makefile.in @@ -5,9 +5,15 @@ LANGUAGE = allegrocl ALLEGROCL = @ALLEGROCLBIN@ SCRIPTSUFFIX = _runme.lisp + srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = +else +SRCDIR = $(srcdir)/ +endif # these cpp tests generate warnings/errors when compiling diff --git a/Examples/test-suite/cffi/Makefile.in b/Examples/test-suite/cffi/Makefile.in index 473d395fd..a530e2243 100644 --- a/Examples/test-suite/cffi/Makefile.in +++ b/Examples/test-suite/cffi/Makefile.in @@ -5,9 +5,15 @@ LANGUAGE = cffi CFFI = @CFFIBIN@ SCRIPTSUFFIX = _runme.lisp + srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = +else +SRCDIR = $(srcdir)/ +endif include $(srcdir)/../common.mk diff --git a/Examples/test-suite/chicken/Makefile.in b/Examples/test-suite/chicken/Makefile.in index 4ee8cb0fa..ac02dad83 100644 --- a/Examples/test-suite/chicken/Makefile.in +++ b/Examples/test-suite/chicken/Makefile.in @@ -6,9 +6,16 @@ LANGUAGE = chicken VARIANT = SCRIPTSUFFIX = _runme.ss PROXYSUFFIX = _runme_proxy.ss + srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = +else +SRCDIR = $(srcdir)/ +endif + CHICKEN_CSI = @CHICKEN_CSI@ -quiet -batch -no-init SO = @SO@ diff --git a/Examples/test-suite/clisp/Makefile.in b/Examples/test-suite/clisp/Makefile.in index 1fe3c23ac..9db84c561 100644 --- a/Examples/test-suite/clisp/Makefile.in +++ b/Examples/test-suite/clisp/Makefile.in @@ -5,9 +5,15 @@ LANGUAGE = clisp CLISP = @CLISPBIN@ SCRIPTSUFFIX = _runme.lisp + srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = +else +SRCDIR = $(srcdir)/ +endif include $(srcdir)/../common.mk diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index bdd1cd471..37d660989 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -69,7 +69,7 @@ INCLUDES = -I$(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE) LIBS = -L. LIBPREFIX = lib ACTION = check -INTERFACEDIR = $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/ +INTERFACEDIR = ../ # Regenerate Makefile if Makefile.in or config.status have changed. ifeq (,$(TEST_SUITE_SUBDIR)) @@ -688,14 +688,14 @@ partialcheck: $(MAKE) check CC=true CXX=true LDSHARED=true CXXSHARED=true RUNTOOL=true COMPILETOOL=true swig_and_compile_cpp = \ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile CXXSRCS="$(CXXSRCS)" \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" CXXSRCS="$(CXXSRCS)" \ SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" \ INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT)" NOLINK=true \ TARGET="$(TARGETPREFIX)$*$(TARGETSUFFIX)" INTERFACEDIR="$(INTERFACEDIR)" INTERFACE="$*.i" \ $(LANGUAGE)$(VARIANT)_cpp swig_and_compile_c = \ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile CSRCS="$(CSRCS)" \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" CSRCS="$(CSRCS)" \ SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" \ INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT)" NOLINK=true \ TARGET="$(TARGETPREFIX)$*$(TARGETSUFFIX)" INTERFACEDIR="$(INTERFACEDIR)" INTERFACE="$*.i" \ @@ -703,7 +703,7 @@ swig_and_compile_c = \ swig_and_compile_multi_cpp = \ for f in `cat $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$*.list` ; do \ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile CXXSRCS="$(CXXSRCS)" \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" CXXSRCS="$(CXXSRCS)" \ SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" LIBS='$(LIBS)' \ INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT)" NOLINK=true \ TARGET="$(TARGETPREFIX)$${f}$(TARGETSUFFIX)" INTERFACEDIR="$(INTERFACEDIR)" INTERFACE="$$f.i" \ @@ -711,11 +711,11 @@ swig_and_compile_multi_cpp = \ done swig_and_compile_external = \ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" \ SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" \ TARGET="$*_wrap_hdr.h" \ $(LANGUAGE)$(VARIANT)_externalhdr; \ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile CXXSRCS="$(CXXSRCS) $*_external.cxx" \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" CXXSRCS="$(CXXSRCS) $*_external.cxx" \ SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" \ INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT)" NOLINK=true \ TARGET="$(TARGETPREFIX)$*$(TARGETSUFFIX)" INTERFACEDIR="$(INTERFACEDIR)" INTERFACE="$*.i" \ @@ -724,7 +724,7 @@ swig_and_compile_external = \ swig_and_compile_runtime = \ setup = \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ echo "$(ACTION)ing $(LANGUAGE) testcase $* (with run test)" ; \ else \ echo "$(ACTION)ing $(LANGUAGE) testcase $*" ; \ diff --git a/Examples/test-suite/csharp/Makefile.in b/Examples/test-suite/csharp/Makefile.in index e54edcc35..a2a0828fd 100644 --- a/Examples/test-suite/csharp/Makefile.in +++ b/Examples/test-suite/csharp/Makefile.in @@ -3,14 +3,21 @@ ####################################################################### LANGUAGE = csharp +SCRIPTDIR = $(srcdir) SCRIPTSUFFIX = _runme.cs CSHARPCILINTERPRETER = @CSHARPCILINTERPRETER@ CSHARPCILINTERPRETER_FLAGS = @CSHARPCILINTERPRETER_FLAGS@ CSHARPPATHSEPARATOR = "@CSHARPPATHSEPARATOR@" CSHARPCYGPATH_W = @CSHARPCYGPATH_W@ + srcdir = @srcdir@ top_srcdir = ../@top_srcdir@ top_builddir = ../@top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = ../ +else +SRCDIR = ../$(srcdir)/ +endif CPP_TEST_CASES = \ csharp_attributes \ @@ -57,7 +64,7 @@ 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 \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ echo "$(ACTION)ing $(LANGUAGE) testcase $* (with run test)" ; \ else \ echo "$(ACTION)ing $(LANGUAGE) testcase $*" ; \ @@ -71,10 +78,10 @@ setup = \ # Note C# uses LD_LIBRARY_PATH under Unix, PATH under Cygwin/Windows and SHLIB_PATH on HPUX. # DYLD_FALLBACK_LIBRARY_PATH is cleared for MacOSX. run_testcase = \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ $(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 && \ + CSHARPSRCS='`$(CSHARPCYGPATH_W) $(SCRIPTDIR)/$(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) $(CSHARPCILINTERPRETER) $(CSHARPCILINTERPRETER_FLAGS) ./$*_runme.exe; \ else \ cd $* && \ diff --git a/Examples/test-suite/d/Makefile.in b/Examples/test-suite/d/Makefile.in index 61c2749dc..0542bbad0 100644 --- a/Examples/test-suite/d/Makefile.in +++ b/Examples/test-suite/d/Makefile.in @@ -3,9 +3,15 @@ ####################################################################### LANGUAGE = d + srcdir = @srcdir@ -top_srcdir = ../@top_srcdir@ -top_builddir = ../@top_builddir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = +else +SRCDIR = $(srcdir)/ +endif ifeq (2,$(D_VERSION)) VERSIONSUFFIX = .2 diff --git a/Examples/test-suite/errors/Makefile.in b/Examples/test-suite/errors/Makefile.in index 843283e7c..c74e9c65b 100644 --- a/Examples/test-suite/errors/Makefile.in +++ b/Examples/test-suite/errors/Makefile.in @@ -22,9 +22,18 @@ TODOS = tr -d '\r' srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = +else +SRCDIR = $(srcdir)/ +endif + +# strip source directory from output, so that diffs compare +srcdir_regexp = $(shell echo $(srcdir)/ | sed 's/\./[.]/g') +STRIP_SRCDIR = sed 's|^$(srcdir_regexp)||' # 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)) +ALL_ERROR_TEST_CASES := $(patsubst %.i,%, $(notdir $(wildcard $(srcdir)/*.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)) @@ -40,13 +49,13 @@ include $(srcdir)/../common.mk # Rules for the different types of tests %.cpptest: echo "$(ACTION)ing errors testcase $*" - -$(SWIG) -c++ -python -Wall -Fstandard $(SWIGOPT) $*.i 2>&1 | $(TODOS) > $*.$(ERROR_EXT) - $(COMPILETOOL) diff -c $*.stderr $*.$(ERROR_EXT) + -$(SWIG) -c++ -python -Wall -Fstandard $(SWIGOPT) $(srcdir)/$*.i 2>&1 | $(TODOS) | $(STRIP_SRCDIR) > $*.$(ERROR_EXT) + $(COMPILETOOL) diff -c $(srcdir)/$*.stderr $*.$(ERROR_EXT) %.ctest: echo "$(ACTION)ing errors testcase $*" - -$(SWIG) -python -Wall -Fstandard $(SWIGOPT) $*.i 2>&1 | $(TODOS) > $*.$(ERROR_EXT) - $(COMPILETOOL) diff -c $*.stderr $*.$(ERROR_EXT) + -$(SWIG) -python -Wall -Fstandard $(SWIGOPT) $(srcdir)/$*.i 2>&1 | $(TODOS) | $(STRIP_SRCDIR) > $*.$(ERROR_EXT) + $(COMPILETOOL) diff -c $(srcdir)/$*.stderr $*.$(ERROR_EXT) %.clean: @exit 0 diff --git a/Examples/test-suite/go/Makefile.in b/Examples/test-suite/go/Makefile.in index 64a84f820..03f6f151e 100644 --- a/Examples/test-suite/go/Makefile.in +++ b/Examples/test-suite/go/Makefile.in @@ -9,6 +9,7 @@ GO1 = @GO1@ GO12 = @GO12@ GO13 = @GO13@ GOC = @GOC@ +SCRIPTDIR = $(srcdir) SCRIPTSUFFIX = _runme.go GOCOMPILEARG = `if $(GOGCC) ; then echo -c -g; elif $(GO1) ; then echo tool $(GOC:c=g) ; fi` @@ -23,6 +24,11 @@ SO = @SO@ srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = +else +SRCDIR = $(srcdir)/ +endif include $(srcdir)/../common.mk @@ -47,7 +53,7 @@ include $(srcdir)/../common.mk multi_import.multicpptest: $(setup) for f in multi_import_b multi_import_a; do \ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile CXXSRCS="$(CXXSRCS)" \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" CXXSRCS="$(CXXSRCS)" \ SWIG_LIB="$(SWIG_LIB)" SWIG="$(SWIG)" LIBS='$(LIBS)' \ INCLUDES="$(INCLUDES)" SWIGOPT="$(SWIGOPT)" NOLINK=true \ TARGET="$(TARGETPREFIX)$${f}$(TARGETSUFFIX)" INTERFACEDIR="$(INTERFACEDIR)" INTERFACE="$$f.i" \ @@ -57,8 +63,8 @@ multi_import.multicpptest: # Runs the testcase. run_testcase = \ - if test -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); then \ - $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ + if test -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); then \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ if $(GOGCC) ; then \ $(COMPILETOOL) $(GO) -o $*_runme $(SCRIPTPREFIX)$*_runme.@OBJEXT@ $*.@OBJEXT@ $*_wrap.@OBJEXT@; \ elif $(GO12) || $(GO13); then \ @@ -70,8 +76,8 @@ run_testcase = \ fi run_testcase_cpp = \ - if test -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); then \ - $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ + if test -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); then \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ if $(GOGCC) ; then \ $(COMPILETOOL) $(GO) -o $*_runme $(SCRIPTPREFIX)$*_runme.@OBJEXT@ $*.@OBJEXT@ $*_wrap.@OBJEXT@ -lstdc++; \ elif $(GO12) || $(GO13); then \ @@ -83,8 +89,8 @@ run_testcase_cpp = \ fi run_multi_testcase = \ - if test -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); then \ - $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) && \ + if test -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); then \ + $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(SCRIPTDIR)/$(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}_wrap.@OBJEXT@; done` -lstdc++; \ diff --git a/Examples/test-suite/guile/Makefile.in b/Examples/test-suite/guile/Makefile.in index 493dde4f5..5ac3de685 100644 --- a/Examples/test-suite/guile/Makefile.in +++ b/Examples/test-suite/guile/Makefile.in @@ -6,10 +6,18 @@ EXTRA_TEST_CASES += guile_ext_test.externaltest LANGUAGE = guile VARIANT = +SCRIPTDIR = $(srcdir) SCRIPTSUFFIX = _runme.scm + srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = +else +SRCDIR = $(srcdir)/ +endif + GUILE = @GUILE@ GUILE_RUNTIME= @@ -51,8 +59,8 @@ INCLUDES += -I$(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/guile # Runs the testcase. A testcase is only run if # a file is found which has _runme.scm appended after the testcase name. run_testcase = \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env GUILE_AUTO_COMPILE=0 LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(GUILE) -l $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + env GUILE_AUTO_COMPILE=0 LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(GUILE) -l $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ fi # Clean diff --git a/Examples/test-suite/java/Makefile.in b/Examples/test-suite/java/Makefile.in index e4e803d2a..a61452ed2 100644 --- a/Examples/test-suite/java/Makefile.in +++ b/Examples/test-suite/java/Makefile.in @@ -6,10 +6,17 @@ LANGUAGE = java JAVA = @JAVA@ JAVAC = @JAVAC@ JAVAFLAGS = -Xcheck:jni +SCRIPTDIR = $(srcdir) SCRIPTSUFFIX = _runme.java + srcdir = @srcdir@ top_srcdir = ../@top_srcdir@ top_builddir = ../@top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = ../ +else +SRCDIR = ../$(srcdir)/ +endif C_TEST_CASES = \ java_lib_arrays \ @@ -72,7 +79,7 @@ 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 \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ echo "$(ACTION)ing $(LANGUAGE) testcase $* (with run test)" ; \ else \ echo "$(ACTION)ing $(LANGUAGE) testcase $*" ; \ @@ -86,8 +93,8 @@ setup = \ # Note Java uses LD_LIBRARY_PATH under Unix, PATH under Cygwin/Windows, SHLIB_PATH on HPUX and DYLD_LIBRARY_PATH on Mac OS X. 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) && \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + $(COMPILETOOL) $(JAVAC) -classpath . -d . $(SCRIPTDIR)/$(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 diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index 7368ea9a3..6126bde74 100644 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -4,10 +4,18 @@ LANGUAGE = javascript NODEGYP = @NODEGYP@ +NODEJS = @NODEJS@ SCRIPTSUFFIX = _runme.js + srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = +else +SRCDIR = $(srcdir)/ +endif + SWIG = $(top_builddir)/preinst_swig ifneq (, $(ENGINE)) @@ -47,20 +55,27 @@ ifeq (node,$(JSENGINE)) constant_pointers.cpptest: GYP_CFLAGS = \"-Wno-ignored-qualifiers\" enum_thorough.cpptest: GYP_CFLAGS = \"-Wno-ignored-qualifiers\" + setup_node = \ + test -d $* || mkdir $*; \ + sed -e 's|$$testcase|$*|g; s|$$cflags|$(GYP_CFLAGS)|g; s|$$srcdir|$(srcdir)|g' \ + $(srcdir)/node_template/binding.gyp.in > $*/binding.gyp; \ + sed -e 's|$$testcase|$*|g;' \ + $(srcdir)/node_template/index.js.in > $*/index.js + # Note: we need to use swig in C parse mode, but make node-gyp believe it is c++ (via file extension) swig_and_compile_c = \ - sh ./setup_test.sh $* $(GYP_CFLAGS); \ - $(SWIG) -javascript $(SWIGOPT) -o $*_wrap.cxx ../$*.i; \ + $(setup_node); \ + $(SWIG) -javascript $(SWIGOPT) -o $*_wrap.cxx $(srcdir)/../$*.i; \ $(NODEGYP) --loglevel=silent --directory $* configure build 1>>/dev/null swig_and_compile_cpp = \ - sh ./setup_test.sh $* $(GYP_CFLAGS); \ - $(SWIG) -c++ -javascript $(SWIGOPT) ../$*.i; \ + $(setup_node); \ + $(SWIG) -c++ -javascript $(SWIGOPT) $(srcdir)/../$*.i; \ $(NODEGYP) --loglevel=silent --directory $* configure build 1>>/dev/null run_testcase = \ if [ -f $(srcdir)/$*$(SCRIPTSUFFIX) ]; then \ - node $(srcdir)/$*$(SCRIPTSUFFIX); \ + env NODE_PATH=$$PWD:$(srcdir) $(NODEJS) $(srcdir)/$*$(SCRIPTSUFFIX); \ fi @@ -83,7 +98,7 @@ else run_testcase = \ if [ -f $(srcdir)/$*$(SCRIPTSUFFIX) ]; then \ - $(top_srcdir)/Tools/javascript/javascript -$(JSENGINE) $(srcdir)/$*$(SCRIPTSUFFIX); \ + $(top_builddir)/Tools/javascript/javascript -$(JSENGINE) $(srcdir)/$*$(SCRIPTSUFFIX); \ fi %.ctest: diff --git a/Examples/test-suite/javascript/abstract_access_runme.js b/Examples/test-suite/javascript/abstract_access_runme.js index 8f87d2105..f61bb4358 100644 --- a/Examples/test-suite/javascript/abstract_access_runme.js +++ b/Examples/test-suite/javascript/abstract_access_runme.js @@ -1,4 +1,4 @@ -var abstract_access = require("./abstract_access"); +var abstract_access = require("abstract_access"); var d = new abstract_access.D() if (d.do_x() != 1) { diff --git a/Examples/test-suite/javascript/abstract_inherit_runme.js b/Examples/test-suite/javascript/abstract_inherit_runme.js index 3af2eae74..f732e8767 100644 --- a/Examples/test-suite/javascript/abstract_inherit_runme.js +++ b/Examples/test-suite/javascript/abstract_inherit_runme.js @@ -1,4 +1,4 @@ -var abstract_inherit = require("./abstract_inherit"); +var abstract_inherit = require("abstract_inherit"); // Shouldn't be able to instantiate any of these classes // since none of them implements the pure virtual function diff --git a/Examples/test-suite/javascript/abstract_typedef2_runme.js b/Examples/test-suite/javascript/abstract_typedef2_runme.js index c177e49c3..d8a533ab1 100644 --- a/Examples/test-suite/javascript/abstract_typedef2_runme.js +++ b/Examples/test-suite/javascript/abstract_typedef2_runme.js @@ -1,4 +1,4 @@ -var abstract_typedef2 = require("./abstract_typedef2"); +var abstract_typedef2 = require("abstract_typedef2"); var a = new abstract_typedef2.A_UF(); diff --git a/Examples/test-suite/javascript/abstract_typedef_runme.js b/Examples/test-suite/javascript/abstract_typedef_runme.js index abcfc581d..286328fa8 100644 --- a/Examples/test-suite/javascript/abstract_typedef_runme.js +++ b/Examples/test-suite/javascript/abstract_typedef_runme.js @@ -1,4 +1,4 @@ -var abstract_typedef = require("./abstract_typedef"); +var abstract_typedef = require("abstract_typedef"); var e = new abstract_typedef.Engine(); var a = new abstract_typedef.A() diff --git a/Examples/test-suite/javascript/abstract_virtual_runme.js b/Examples/test-suite/javascript/abstract_virtual_runme.js index 9e2814e41..9a9ce9988 100644 --- a/Examples/test-suite/javascript/abstract_virtual_runme.js +++ b/Examples/test-suite/javascript/abstract_virtual_runme.js @@ -1,4 +1,4 @@ -var abstract_virtual = require("./abstract_virtual"); +var abstract_virtual = require("abstract_virtual"); d = new abstract_virtual.D() diff --git a/Examples/test-suite/javascript/array_member_runme.js b/Examples/test-suite/javascript/array_member_runme.js index 8c4ef1da5..3d9bb0e5b 100644 --- a/Examples/test-suite/javascript/array_member_runme.js +++ b/Examples/test-suite/javascript/array_member_runme.js @@ -1,4 +1,4 @@ -var array_member = require("./array_member"); +var array_member = require("array_member"); var f = new array_member.Foo(); f.data = array_member.global_data; diff --git a/Examples/test-suite/javascript/arrays_global_runme.js b/Examples/test-suite/javascript/arrays_global_runme.js index fdb365f83..0cbb28efb 100644 --- a/Examples/test-suite/javascript/arrays_global_runme.js +++ b/Examples/test-suite/javascript/arrays_global_runme.js @@ -1,4 +1,4 @@ -var arrays_global = require("./arrays_global"); +var arrays_global = require("arrays_global"); arrays_global.array_i = arrays_global.array_const_i; diff --git a/Examples/test-suite/javascript/callback_runme.js b/Examples/test-suite/javascript/callback_runme.js index 9b1ef01a3..021888641 100644 --- a/Examples/test-suite/javascript/callback_runme.js +++ b/Examples/test-suite/javascript/callback_runme.js @@ -1,4 +1,4 @@ -var callback = require("./callback"); +var callback = require("callback"); if (callback.foo(2) !== 2) { throw new Error("Failed."); diff --git a/Examples/test-suite/javascript/char_binary_runme.js b/Examples/test-suite/javascript/char_binary_runme.js index 42abe6060..b2aac920c 100644 --- a/Examples/test-suite/javascript/char_binary_runme.js +++ b/Examples/test-suite/javascript/char_binary_runme.js @@ -1,4 +1,4 @@ -var char_binary = require("./char_binary"); +var char_binary = require("char_binary"); var t = new char_binary.Test(); if (t.strlen('hile') != 4) { diff --git a/Examples/test-suite/javascript/char_strings_runme.js b/Examples/test-suite/javascript/char_strings_runme.js index cca50d851..fe17cb982 100644 --- a/Examples/test-suite/javascript/char_strings_runme.js +++ b/Examples/test-suite/javascript/char_strings_runme.js @@ -1,4 +1,4 @@ -var char_strings = require("./char_strings"); +var char_strings = require("char_strings"); var assertIsEqual = function(expected, actual) { if (expected !== actual) { diff --git a/Examples/test-suite/javascript/class_ignore_runme.js b/Examples/test-suite/javascript/class_ignore_runme.js index f0a32a1c4..ffbe021c7 100644 --- a/Examples/test-suite/javascript/class_ignore_runme.js +++ b/Examples/test-suite/javascript/class_ignore_runme.js @@ -1,4 +1,4 @@ -var class_ignore = require("./class_ignore"); +var class_ignore = require("class_ignore"); a = new class_ignore.Bar(); diff --git a/Examples/test-suite/javascript/class_scope_weird_runme.js b/Examples/test-suite/javascript/class_scope_weird_runme.js index ac745d023..73c118d61 100644 --- a/Examples/test-suite/javascript/class_scope_weird_runme.js +++ b/Examples/test-suite/javascript/class_scope_weird_runme.js @@ -1,4 +1,4 @@ -var class_scope_weird = require("./class_scope_weird"); +var class_scope_weird = require("class_scope_weird"); f = new class_scope_weird.Foo(); g = new class_scope_weird.Foo(3); diff --git a/Examples/test-suite/javascript/complextest_runme.js b/Examples/test-suite/javascript/complextest_runme.js index 1fcc97648..b87d6bffa 100644 --- a/Examples/test-suite/javascript/complextest_runme.js +++ b/Examples/test-suite/javascript/complextest_runme.js @@ -1,4 +1,4 @@ -var complextest = require("./complextest"); +var complextest = require("complextest"); a = [-1,2]; diff --git a/Examples/test-suite/javascript/constover_runme.js b/Examples/test-suite/javascript/constover_runme.js index 764d8b328..9b192b5ff 100644 --- a/Examples/test-suite/javascript/constover_runme.js +++ b/Examples/test-suite/javascript/constover_runme.js @@ -1,4 +1,4 @@ -var constover = require("./constover"); +var constover = require("constover"); p = constover.test("test"); if (p != "test") { diff --git a/Examples/test-suite/javascript/constructor_copy_runme.js b/Examples/test-suite/javascript/constructor_copy_runme.js index 39dce52ce..179b9fb40 100644 --- a/Examples/test-suite/javascript/constructor_copy_runme.js +++ b/Examples/test-suite/javascript/constructor_copy_runme.js @@ -1,4 +1,4 @@ -var constructor_copy = require("./constructor_copy"); +var constructor_copy = require("constructor_copy"); f1 = new constructor_copy.Foo1(3); f11 = new constructor_copy.Foo1(f1); diff --git a/Examples/test-suite/javascript/cpp_enum_runme.js b/Examples/test-suite/javascript/cpp_enum_runme.js index 35f7c60ac..8a248c372 100644 --- a/Examples/test-suite/javascript/cpp_enum_runme.js +++ b/Examples/test-suite/javascript/cpp_enum_runme.js @@ -1,4 +1,4 @@ -var cpp_enum = require("./cpp_enum"); +var cpp_enum = require("cpp_enum"); var f = new cpp_enum.Foo() diff --git a/Examples/test-suite/javascript/cpp_namespace_runme.js b/Examples/test-suite/javascript/cpp_namespace_runme.js index 3bdfef3e9..a6ab79964 100644 --- a/Examples/test-suite/javascript/cpp_namespace_runme.js +++ b/Examples/test-suite/javascript/cpp_namespace_runme.js @@ -1,4 +1,4 @@ -var cpp_namespace = require("./cpp_namespace"); +var cpp_namespace = require("cpp_namespace"); var n = cpp_namespace.fact(4); if (n != 24){ diff --git a/Examples/test-suite/javascript/cpp_static_runme.js b/Examples/test-suite/javascript/cpp_static_runme.js index 2579aeafe..c7917e12e 100644 --- a/Examples/test-suite/javascript/cpp_static_runme.js +++ b/Examples/test-suite/javascript/cpp_static_runme.js @@ -1,4 +1,4 @@ -var cpp_static = require("./cpp_static"); +var cpp_static = require("cpp_static"); cpp_static.StaticFunctionTest.static_func(); cpp_static.StaticFunctionTest.static_func_2(1); diff --git a/Examples/test-suite/javascript/director_alternating_runme.js b/Examples/test-suite/javascript/director_alternating_runme.js index a0411eace..cff288d35 100644 --- a/Examples/test-suite/javascript/director_alternating_runme.js +++ b/Examples/test-suite/javascript/director_alternating_runme.js @@ -1,4 +1,4 @@ -var director_alternating = require("./director_alternating"); +var director_alternating = require("director_alternating"); id = director_alternating.getBar().id(); if (id != director_alternating.idFromGetBar()) diff --git a/Examples/test-suite/javascript/disown_runme.js b/Examples/test-suite/javascript/disown_runme.js index a4a6fd880..ea742b51e 100644 --- a/Examples/test-suite/javascript/disown_runme.js +++ b/Examples/test-suite/javascript/disown_runme.js @@ -1,4 +1,4 @@ -var disown = require("./disown"); +var disown = require("disown"); var a = new disown.A(); var tmp = a.thisown; diff --git a/Examples/test-suite/javascript/dynamic_cast_runme.js b/Examples/test-suite/javascript/dynamic_cast_runme.js index 0029cb0f8..32eabcf8b 100644 --- a/Examples/test-suite/javascript/dynamic_cast_runme.js +++ b/Examples/test-suite/javascript/dynamic_cast_runme.js @@ -1,4 +1,4 @@ -var dynamic_cast = require("./dynamic_cast"); +var dynamic_cast = require("dynamic_cast"); var f = new dynamic_cast.Foo(); var b = new dynamic_cast.Bar(); diff --git a/Examples/test-suite/javascript/empty_runme.js b/Examples/test-suite/javascript/empty_runme.js index db06b3902..7894379be 100644 --- a/Examples/test-suite/javascript/empty_runme.js +++ b/Examples/test-suite/javascript/empty_runme.js @@ -1 +1 @@ -var empty = require("./empty"); \ No newline at end of file +var empty = require("empty"); \ No newline at end of file diff --git a/Examples/test-suite/javascript/enum_template_runme.js b/Examples/test-suite/javascript/enum_template_runme.js index 20f8c3482..1e71e5f64 100644 --- a/Examples/test-suite/javascript/enum_template_runme.js +++ b/Examples/test-suite/javascript/enum_template_runme.js @@ -1,4 +1,4 @@ -var enum_template = require("./enum_template"); +var enum_template = require("enum_template"); if (enum_template.MakeETest() != 1) throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/infinity_runme.js b/Examples/test-suite/javascript/infinity_runme.js index 7b5182ff6..050c391a7 100644 --- a/Examples/test-suite/javascript/infinity_runme.js +++ b/Examples/test-suite/javascript/infinity_runme.js @@ -1,4 +1,4 @@ -var infinity = require("./infinity"); +var infinity = require("infinity"); var my_infinity = infinity.INFINITY; var ret_val = infinity.use_infinity(my_infinity); diff --git a/Examples/test-suite/javascript/namespace_virtual_method_runme.js b/Examples/test-suite/javascript/namespace_virtual_method_runme.js index 24d3bd487..4f1e05c84 100644 --- a/Examples/test-suite/javascript/namespace_virtual_method_runme.js +++ b/Examples/test-suite/javascript/namespace_virtual_method_runme.js @@ -1,3 +1,3 @@ -var namespace_virtual_method = require("./namespace_virtual_method"); +var namespace_virtual_method = require("namespace_virtual_method"); x = new namespace_virtual_method.Spam(); diff --git a/Examples/test-suite/javascript/node_template/binding.gyp.in b/Examples/test-suite/javascript/node_template/binding.gyp.in index 209774ae0..a82ac2f3e 100644 --- a/Examples/test-suite/javascript/node_template/binding.gyp.in +++ b/Examples/test-suite/javascript/node_template/binding.gyp.in @@ -3,7 +3,7 @@ { "target_name": "$testcase", "sources":[ "../$testcase_wrap.cxx" ], - "include_dirs": ["../.."], + "include_dirs": ["../$srcdir/.."], 'defines': [ 'BUILDING_NODE_EXTENSION=1', ], diff --git a/Examples/test-suite/javascript/nspace_extend_runme.js b/Examples/test-suite/javascript/nspace_extend_runme.js index ab81c19d3..8cabfe945 100644 --- a/Examples/test-suite/javascript/nspace_extend_runme.js +++ b/Examples/test-suite/javascript/nspace_extend_runme.js @@ -1,4 +1,4 @@ -var nspace_extend = require("./nspace_extend"); +var nspace_extend = require("nspace_extend"); // constructors and destructors var color1 = new nspace_extend.Outer.Inner1.Color(); diff --git a/Examples/test-suite/javascript/nspace_runme.js b/Examples/test-suite/javascript/nspace_runme.js index f1afff428..993610dd6 100644 --- a/Examples/test-suite/javascript/nspace_runme.js +++ b/Examples/test-suite/javascript/nspace_runme.js @@ -1,4 +1,4 @@ -var nspace = require("./nspace"); +var nspace = require("nspace"); var color1 = new nspace.Outer.Inner1.Color(); var color = new nspace.Outer.Inner1.Color(color1); diff --git a/Examples/test-suite/javascript/overload_copy_runme.js b/Examples/test-suite/javascript/overload_copy_runme.js index 1039ffda1..e2f610788 100644 --- a/Examples/test-suite/javascript/overload_copy_runme.js +++ b/Examples/test-suite/javascript/overload_copy_runme.js @@ -1,4 +1,4 @@ -var overload_copy = require("./overload_copy"); +var overload_copy = require("overload_copy"); f = new overload_copy.Foo(); g = new overload_copy.Foo(f); diff --git a/Examples/test-suite/javascript/preproc_include_runme.js b/Examples/test-suite/javascript/preproc_include_runme.js index 4b827fbcc..5ec72b842 100644 --- a/Examples/test-suite/javascript/preproc_include_runme.js +++ b/Examples/test-suite/javascript/preproc_include_runme.js @@ -1,4 +1,4 @@ -var preproc_include = require("./preproc_include"); +var preproc_include = require("preproc_include"); if (preproc_include.multiply10(10) != 100) throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/preproc_runme.js b/Examples/test-suite/javascript/preproc_runme.js index 669f9d1f0..167ca5ac1 100644 --- a/Examples/test-suite/javascript/preproc_runme.js +++ b/Examples/test-suite/javascript/preproc_runme.js @@ -1,4 +1,4 @@ -var preproc = require("./preproc"); +var preproc = require("preproc"); if (preproc.endif != 1) throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/rename1_runme.js b/Examples/test-suite/javascript/rename1_runme.js index 8374e6a89..68ecc11b6 100644 --- a/Examples/test-suite/javascript/rename1_runme.js +++ b/Examples/test-suite/javascript/rename1_runme.js @@ -1,4 +1,4 @@ -var rename = require("./rename1"); +var rename = require("rename1"); function part1() { var xyz = new rename.XYZInt(); diff --git a/Examples/test-suite/javascript/rename2_runme.js b/Examples/test-suite/javascript/rename2_runme.js index bc6a95a59..99f478596 100644 --- a/Examples/test-suite/javascript/rename2_runme.js +++ b/Examples/test-suite/javascript/rename2_runme.js @@ -1,4 +1,4 @@ -var rename = require("./rename2"); +var rename = require("rename2"); function part1() { var xyz = new rename.XYZInt(); diff --git a/Examples/test-suite/javascript/rename3_runme.js b/Examples/test-suite/javascript/rename3_runme.js index 9e57e80ea..237029fbb 100644 --- a/Examples/test-suite/javascript/rename3_runme.js +++ b/Examples/test-suite/javascript/rename3_runme.js @@ -1,4 +1,4 @@ -var rename = require("./rename3"); +var rename = require("rename3"); function part1() { var xyz = new rename.XYZInt(); diff --git a/Examples/test-suite/javascript/rename4_runme.js b/Examples/test-suite/javascript/rename4_runme.js index d651fc7a1..fed50dceb 100644 --- a/Examples/test-suite/javascript/rename4_runme.js +++ b/Examples/test-suite/javascript/rename4_runme.js @@ -1,4 +1,4 @@ -var rename = require("./rename4"); +var rename = require("rename4"); function part1() { var xyz = new rename.XYZInt(); diff --git a/Examples/test-suite/javascript/rename_scope_runme.js b/Examples/test-suite/javascript/rename_scope_runme.js index c0226df69..fea4d2ca9 100644 --- a/Examples/test-suite/javascript/rename_scope_runme.js +++ b/Examples/test-suite/javascript/rename_scope_runme.js @@ -1,4 +1,4 @@ -var rename_scope = require("./rename_scope"); +var rename_scope = require("rename_scope"); var a = new rename_scope.Natural_UP(); var b = new rename_scope.Natural_BP(); diff --git a/Examples/test-suite/javascript/rename_simple_runme.js b/Examples/test-suite/javascript/rename_simple_runme.js index 918dd68a5..21350cd3e 100644 --- a/Examples/test-suite/javascript/rename_simple_runme.js +++ b/Examples/test-suite/javascript/rename_simple_runme.js @@ -1,4 +1,4 @@ -var rename_simple = require("./rename_simple"); +var rename_simple = require("rename_simple"); var NewStruct = rename_simple.NewStruct; var s = new NewStruct(); diff --git a/Examples/test-suite/javascript/ret_by_value_runme.js b/Examples/test-suite/javascript/ret_by_value_runme.js index d9a77a20b..9d0840602 100644 --- a/Examples/test-suite/javascript/ret_by_value_runme.js +++ b/Examples/test-suite/javascript/ret_by_value_runme.js @@ -1,4 +1,4 @@ -var ret_by_value = require("./ret_by_value"); +var ret_by_value = require("ret_by_value"); a = ret_by_value.get_test(); if (a.myInt != 100) diff --git a/Examples/test-suite/javascript/setup_test.sh b/Examples/test-suite/javascript/setup_test.sh deleted file mode 100644 index 913a74c4b..000000000 --- a/Examples/test-suite/javascript/setup_test.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/sh -if [ ! -d $1 ]; then - mkdir $1; -fi -sed -e "s/\$testcase/$1/" -e "s/\$cflags/$2/" < node_template/binding.gyp.in > $1/binding.gyp -sed s/\$testcase/$1/ node_template/index.js.in > $1/index.js diff --git a/Examples/test-suite/javascript/string_simple_runme.js b/Examples/test-suite/javascript/string_simple_runme.js index dbdd4136d..39ae84e9e 100644 --- a/Examples/test-suite/javascript/string_simple_runme.js +++ b/Examples/test-suite/javascript/string_simple_runme.js @@ -1,4 +1,4 @@ -var string_simple = require("./string_simple"); +var string_simple = require("string_simple"); // Test unicode string var str = "olé"; diff --git a/Examples/test-suite/javascript/struct_value_runme.js b/Examples/test-suite/javascript/struct_value_runme.js index d6b26f726..5b171b8fe 100644 --- a/Examples/test-suite/javascript/struct_value_runme.js +++ b/Examples/test-suite/javascript/struct_value_runme.js @@ -1,4 +1,4 @@ -var struct_value = require("./struct_value"); +var struct_value = require("struct_value"); b = new struct_value.Bar(); diff --git a/Examples/test-suite/javascript/template_static_runme.js b/Examples/test-suite/javascript/template_static_runme.js index 477d97249..d6106138a 100644 --- a/Examples/test-suite/javascript/template_static_runme.js +++ b/Examples/test-suite/javascript/template_static_runme.js @@ -1,3 +1,3 @@ -var template_static = require("./template_static"); +var template_static = require("template_static"); template_static.Foo.bar_double(1); diff --git a/Examples/test-suite/javascript/typedef_class_runme.js b/Examples/test-suite/javascript/typedef_class_runme.js index 3e4dc9093..64e0051c3 100644 --- a/Examples/test-suite/javascript/typedef_class_runme.js +++ b/Examples/test-suite/javascript/typedef_class_runme.js @@ -1,4 +1,4 @@ -var typedef_class = require("./typedef_class"); +var typedef_class = require("typedef_class"); a = new typedef_class.RealA(); a.a = 3; diff --git a/Examples/test-suite/javascript/typedef_inherit_runme.js b/Examples/test-suite/javascript/typedef_inherit_runme.js index 4abcc2536..7590e1e6e 100644 --- a/Examples/test-suite/javascript/typedef_inherit_runme.js +++ b/Examples/test-suite/javascript/typedef_inherit_runme.js @@ -1,4 +1,4 @@ -var typedef_inherit = require("./typedef_inherit"); +var typedef_inherit = require("typedef_inherit"); a = new typedef_inherit.Foo(); b = new typedef_inherit.Bar(); diff --git a/Examples/test-suite/javascript/typedef_scope_runme.js b/Examples/test-suite/javascript/typedef_scope_runme.js index 0ac56884c..5c1368ab7 100644 --- a/Examples/test-suite/javascript/typedef_scope_runme.js +++ b/Examples/test-suite/javascript/typedef_scope_runme.js @@ -1,4 +1,4 @@ -var typedef_scope = require("./typedef_scope"); +var typedef_scope = require("typedef_scope"); b = new typedef_scope.Bar(); x = b.test1(42,"hello"); diff --git a/Examples/test-suite/javascript/typemap_arrays_runme.js b/Examples/test-suite/javascript/typemap_arrays_runme.js index cd6827ac9..610ecdd9c 100644 --- a/Examples/test-suite/javascript/typemap_arrays_runme.js +++ b/Examples/test-suite/javascript/typemap_arrays_runme.js @@ -1,4 +1,4 @@ -var typemap_arrays = require("./typemap_arrays"); +var typemap_arrays = require("typemap_arrays"); if (typemap_arrays.sumA(null) != 60) throw "RuntimeError, Sum is wrong"; diff --git a/Examples/test-suite/javascript/typemap_delete_runme.js b/Examples/test-suite/javascript/typemap_delete_runme.js index 4b3174956..1d42ce4da 100644 --- a/Examples/test-suite/javascript/typemap_delete_runme.js +++ b/Examples/test-suite/javascript/typemap_delete_runme.js @@ -1,4 +1,4 @@ -var typemap_delete = require("./typemap_delete"); +var typemap_delete = require("typemap_delete"); r = new typemap_delete.Rect(123); if (r.val != 123) diff --git a/Examples/test-suite/javascript/typemap_namespace_runme.js b/Examples/test-suite/javascript/typemap_namespace_runme.js index 614e0ffeb..2aa358024 100644 --- a/Examples/test-suite/javascript/typemap_namespace_runme.js +++ b/Examples/test-suite/javascript/typemap_namespace_runme.js @@ -1,4 +1,4 @@ -var typemap_namespace = require("./typemap_namespace"); +var typemap_namespace = require("typemap_namespace"); if (typemap_namespace.test1("hello") != "hello") throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/typemap_ns_using_runme.js b/Examples/test-suite/javascript/typemap_ns_using_runme.js index 9115c16ae..7e4019ab2 100644 --- a/Examples/test-suite/javascript/typemap_ns_using_runme.js +++ b/Examples/test-suite/javascript/typemap_ns_using_runme.js @@ -1,4 +1,4 @@ -var typemap_ns_using = require("./typemap_ns_using"); +var typemap_ns_using = require("typemap_ns_using"); if (typemap_ns_using.spam(37) != 37) throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/using1_runme.js b/Examples/test-suite/javascript/using1_runme.js index a2e37fcb6..2415156f0 100644 --- a/Examples/test-suite/javascript/using1_runme.js +++ b/Examples/test-suite/javascript/using1_runme.js @@ -1,4 +1,4 @@ -var using1 = require("./using1"); +var using1 = require("using1"); if (using1.spam(37) != 37) throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/using2_runme.js b/Examples/test-suite/javascript/using2_runme.js index aa5e9b15f..2ef08faca 100644 --- a/Examples/test-suite/javascript/using2_runme.js +++ b/Examples/test-suite/javascript/using2_runme.js @@ -1,4 +1,4 @@ -var using2 = require("./using2"); +var using2 = require("using2"); if (using2.spam(37) != 37) throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/varargs_runme.js b/Examples/test-suite/javascript/varargs_runme.js index 69d761e63..fc6d945c1 100644 --- a/Examples/test-suite/javascript/varargs_runme.js +++ b/Examples/test-suite/javascript/varargs_runme.js @@ -1,4 +1,4 @@ -var varargs = require("./varargs"); +var varargs = require("varargs"); if (varargs.test("Hello") != "Hello") { throw new Error("Failed"); diff --git a/Examples/test-suite/lua/Makefile.in b/Examples/test-suite/lua/Makefile.in index 0950c9d91..b35cc15ad 100644 --- a/Examples/test-suite/lua/Makefile.in +++ b/Examples/test-suite/lua/Makefile.in @@ -4,10 +4,17 @@ LANGUAGE = lua LUA = @LUABIN@ +SCRIPTDIR = $(srcdir) SCRIPTSUFFIX = _runme.lua + srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = +else +SRCDIR = $(srcdir)/ +endif # sorry, currently very few test cases work/have been written @@ -46,8 +53,8 @@ lua_no_module_global.%: SWIGOPT += -nomoduleglobal # Runs the testcase. A testcase is only run if # a file is found which has _runme.lua appended after the testcase name. run_testcase = \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LUA_PATH="$(srcdir)/?.lua;" $(RUNTOOL) $(LUA) $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + env LUA_PATH="$(srcdir)/?.lua;" $(RUNTOOL) $(LUA) $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ fi # Clean: (does nothing, we dont generate extra lua code) diff --git a/Examples/test-suite/mzscheme/Makefile.in b/Examples/test-suite/mzscheme/Makefile.in index 67b8bddf2..39fb1acbc 100644 --- a/Examples/test-suite/mzscheme/Makefile.in +++ b/Examples/test-suite/mzscheme/Makefile.in @@ -5,9 +5,15 @@ LANGUAGE = mzscheme MZSCHEME = mzscheme SCRIPTSUFFIX = _runme.scm + srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = +else +SRCDIR = $(srcdir)/ +endif include $(srcdir)/../common.mk diff --git a/Examples/test-suite/ocaml/Makefile.in b/Examples/test-suite/ocaml/Makefile.in index 63edec26a..5081e203e 100644 --- a/Examples/test-suite/ocaml/Makefile.in +++ b/Examples/test-suite/ocaml/Makefile.in @@ -6,9 +6,15 @@ LANGUAGE = ocaml OCAMLC = ocamlc VARIANT = _static SCRIPTSUFFIX = _runme.ml + srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = +else +SRCDIR = $(srcdir)/ +endif C_TEST_CASES = diff --git a/Examples/test-suite/octave/Makefile.in b/Examples/test-suite/octave/Makefile.in index e48d36a64..11cb7c076 100644 --- a/Examples/test-suite/octave/Makefile.in +++ b/Examples/test-suite/octave/Makefile.in @@ -4,10 +4,17 @@ LANGUAGE = octave OCTAVE = @OCTAVE@ +SCRIPTDIR = $(srcdir) SCRIPTSUFFIX = _runme.m + srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = +else +SRCDIR = $(srcdir)/ +endif CPP_TEST_CASES += \ li_std_pair_extra \ @@ -33,7 +40,7 @@ include $(srcdir)/../common.mk # Overridden variables here LIBS = -L. -CSRCS = $(srcdir)/octave_empty.c +CSRCS = octave_empty.c # Custom tests - tests with additional commandline options # none! @@ -57,8 +64,8 @@ CSRCS = $(srcdir)/octave_empty.c # Runs the testcase. A testcase is only run if # a file is found which has _runme.m appended after the testcase name. run_testcase = \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH OCTAVE_PATH=$(srcdir):$$OCTAVE_PATH $(RUNTOOL) $(OCTAVE) $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH OCTAVE_PATH=$(srcdir):$$OCTAVE_PATH $(RUNTOOL) $(OCTAVE) $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ fi # Clean: remove the generated .m file diff --git a/Examples/test-suite/perl5/Makefile.in b/Examples/test-suite/perl5/Makefile.in index 68f32a54a..6778f714e 100644 --- a/Examples/test-suite/perl5/Makefile.in +++ b/Examples/test-suite/perl5/Makefile.in @@ -4,11 +4,18 @@ LANGUAGE = perl5 PERL = @PERL@ +SCRIPTDIR = $(srcdir) SCRIPTSUFFIX = _runme.pl -TEST_RUNNER = run-perl-test.pl +TEST_RUNNER = $(srcdir)/run-perl-test.pl + srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = +else +SRCDIR = $(srcdir)/ +endif CPP_TEST_CASES += \ primitive_types \ @@ -49,8 +56,8 @@ include $(srcdir)/../common.mk # Runs the testcase. A testcase is only run if # a file is found which has _runme.pl appended after the testcase name. run_testcase = \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(PERL) $(TEST_RUNNER) $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(PERL) $(TEST_RUNNER) $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ fi # Clean: remove the generated .pm file diff --git a/Examples/test-suite/php/Makefile.in b/Examples/test-suite/php/Makefile.in index 735a3137e..b6e4fff1a 100644 --- a/Examples/test-suite/php/Makefile.in +++ b/Examples/test-suite/php/Makefile.in @@ -3,10 +3,17 @@ ####################################################################### LANGUAGE = php +SCRIPTDIR = $(srcdir) SCRIPTSUFFIX = _runme.php + srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = +else +SRCDIR = $(srcdir)/ +endif CPP_TEST_CASES += \ php_namewarn_rename \ @@ -56,10 +63,10 @@ missingtests: missingcpptests missingctests # Runs the testcase. Tries to run testcase_runme.php, and if that's not # found, runs testcase.php, except for multicpptests. run_testcase = \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile PHP_SCRIPT=$(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) RUNTOOL="$(RUNTOOL)" php_run; \ - elif [ -f $(srcdir)/$(SCRIPTPREFIX)$*.php -a ! -f $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$*.list ]; then \ - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile PHP_SCRIPT=$(srcdir)/$(SCRIPTPREFIX)$*.php RUNTOOL="$(RUNTOOL)" php_run; \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile PHP_SCRIPT=$(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) RUNTOOL="$(RUNTOOL)" php_run; \ + elif [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*.php -a ! -f $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$*.list ]; then \ + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile PHP_SCRIPT=$(SCRIPTDIR)/$(SCRIPTPREFIX)$*.php RUNTOOL="$(RUNTOOL)" php_run; \ fi # Clean: remove the generated .php file diff --git a/Examples/test-suite/pike/Makefile.in b/Examples/test-suite/pike/Makefile.in index c1ebb747b..36a34352a 100644 --- a/Examples/test-suite/pike/Makefile.in +++ b/Examples/test-suite/pike/Makefile.in @@ -5,9 +5,15 @@ LANGUAGE = pike PIKE = pike SCRIPTSUFFIX = _runme.pike + srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = +else +SRCDIR = $(srcdir)/ +endif include $(srcdir)/../common.mk diff --git a/Examples/test-suite/python/Makefile.in b/Examples/test-suite/python/Makefile.in index 389aed9ea..719e7d1a4 100644 --- a/Examples/test-suite/python/Makefile.in +++ b/Examples/test-suite/python/Makefile.in @@ -21,9 +21,16 @@ else SCRIPTSUFFIX = $(PY3SCRIPTSUFFIX) endif +SCRIPTDIR = . + srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = +else +SRCDIR = $(srcdir)/ +endif PY2TO3 = 2to3 -x import @@ -128,39 +135,43 @@ VALGRIND_OPT += --suppressions=pythonswig.supp $(run_testcase) -# Call 2to3 to generate Python 3.x test from the Python 2.x's *_runme.py file -%$(PY3SCRIPTSUFFIX): %$(PY2SCRIPTSUFFIX) - cp $< $@ - $(PY2TO3) -w $@ >/dev/null 2>&1 - - # Runs the testcase. A testcase is only run if # a file is found which has _runme.py (or _runme3.py for Python 3) appended after the testcase name. -run_python = env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH PYTHONPATH=.:$(srcdir):$$PYTHONPATH $(RUNTOOL) $(PYTHON) $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) +py_runme = $(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) +py2_runme = $(SCRIPTPREFIX)$*$(PY2SCRIPTSUFFIX) +py3_runme = $(SCRIPTPREFIX)$*$(PY3SCRIPTSUFFIX) -py2_runme = $(srcdir)/$(SCRIPTPREFIX)$*$(PY2SCRIPTSUFFIX) -py3_runme = $(srcdir)/$(SCRIPTPREFIX)$*$(PY3SCRIPTSUFFIX) +run_python = env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH PYTHONPATH=.:$(srcdir):$$PYTHONPATH $(RUNTOOL) $(PYTHON) $(py_runme) run_testcase = \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + if [ -f $(SCRIPTDIR)/$(py_runme) ]; then \ $(run_python);\ fi -ifeq (,$(PY3)) +# No copying/conversion needed for in-source-tree Python 2 scripts +ifeq ($(SCRIPTDIR)|$(SCRIPTSUFFIX),$(srcdir)|$(PY2SCRIPTSUFFIX)) convert_testcase = else + convert_testcase = \ - if [ -f $(py2_runme) ]; then \ - $(MAKE) -f $(srcdir)/Makefile $(py3_runme); \ + if [ -f $(srcdir)/$(py2_runme) ]; then \ + $(MAKE) $(SCRIPTDIR)/$(py_runme); \ fi + +$(SCRIPTDIR)/$(SCRIPTPREFIX)%$(SCRIPTSUFFIX): $(srcdir)/$(SCRIPTPREFIX)%$(PY2SCRIPTSUFFIX) + test x$< = x$@ || cp $< $@ || exit 1 + test x$(PY3) = x || $(PY2TO3) -w $@ >/dev/null 2>&1 || exit 1 + endif # Clean: remove the generated .py file +# We only remove the _runme3.py if it is generated by 2to3 from a _runme.py. %.clean: - @rm -f $*.py; - @#We only remove the _runme3.py if it is generated by 2to3 from a _runme.py. - @if [ -f $(py2_runme) ]; then rm -f $(py3_runme) $(py3_runme).bak; fi + @rm -f $*.py + @if [ -f $(srcdir)/$(py2_runme) ]; then \ + rm -f $(SCRIPTDIR)/$(py3_runme) $(SCRIPTDIR)/$(py3_runme).bak; \ + fi clean: $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile python_clean diff --git a/Examples/test-suite/r/Makefile.in b/Examples/test-suite/r/Makefile.in index 32d9b85da..9f0de1c5f 100644 --- a/Examples/test-suite/r/Makefile.in +++ b/Examples/test-suite/r/Makefile.in @@ -6,9 +6,15 @@ LANGUAGE = r SCRIPTSUFFIX = _runme.R WRAPSUFFIX = .R RUNR = R CMD BATCH --no-save --no-restore + srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = +else +SRCDIR = $(srcdir)/ +endif C_TEST_CASES += \ r_copy_struct \ diff --git a/Examples/test-suite/ruby/Makefile.in b/Examples/test-suite/ruby/Makefile.in index 40985e532..d0c65929a 100644 --- a/Examples/test-suite/ruby/Makefile.in +++ b/Examples/test-suite/ruby/Makefile.in @@ -4,10 +4,17 @@ LANGUAGE = ruby RUBY = @RUBY@ +SCRIPTDIR = $(srcdir) SCRIPTSUFFIX = _runme.rb + srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = +else +SRCDIR = $(srcdir)/ +endif CPP_TEST_CASES = \ kwargs_feature \ @@ -60,8 +67,8 @@ ruby_naming.cpptest: SWIGOPT += -autorename # Runs the testcase. A testcase is only run if # a file is found which has _runme.rb appended after the testcase name. run_testcase = \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(RUBY) -I$(srcdir):. $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(RUBY) -I$(srcdir):. $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ fi # Clean diff --git a/Examples/test-suite/tcl/Makefile.in b/Examples/test-suite/tcl/Makefile.in index 6ab293fb9..f8a196e26 100644 --- a/Examples/test-suite/tcl/Makefile.in +++ b/Examples/test-suite/tcl/Makefile.in @@ -4,10 +4,17 @@ LANGUAGE = tcl TCLSH = tclsh +SCRIPTDIR = $(srcdir) SCRIPTSUFFIX = _runme.tcl + srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = +else +SRCDIR = $(srcdir)/ +endif CPP_TEST_CASES += \ primitive_types \ @@ -45,8 +52,8 @@ include $(srcdir)/../common.mk # Runs the testcase. A testcase is only run if # a file is found which has _runme.tcl appended after the testcase name. run_testcase = \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(TCLSH) $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(TCLSH) $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ fi # Clean diff --git a/Examples/test-suite/uffi/Makefile.in b/Examples/test-suite/uffi/Makefile.in index 5fd000a96..9f3546da6 100644 --- a/Examples/test-suite/uffi/Makefile.in +++ b/Examples/test-suite/uffi/Makefile.in @@ -5,9 +5,15 @@ LANGUAGE = uffi UFFI = @UFFIBIN@ SCRIPTSUFFIX = _runme.lisp + srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ +ifeq (.,$(srcdir)) +SRCDIR = +else +SRCDIR = $(srcdir)/ +endif include $(srcdir)/../common.mk diff --git a/Makefile.in b/Makefile.in index 53ac47de5..8c6072b41 100644 --- a/Makefile.in +++ b/Makefile.in @@ -100,7 +100,7 @@ skip-errors = test -n "" ACTION = check NOSKIP = -chk-set-swiglib = SWIG_LIB=@ROOT_DIR@/Lib +chk-set-swiglib = SWIG_LIB=@ROOT_DIR@/$(srcdir)/Lib chk-set-swig = SWIG=@ROOT_DIR@/$(TARGET) chk-set-env = $(chk-set-swiglib) $(chk-set-swig) @@ -443,7 +443,7 @@ maintainer-clean: @echo maintainer-cleaning CCache @test -z "$(ENABLE_CCACHE)" || (cd $(CCACHE) && $(MAKE) $(FLAGS) maintainer-clean) @echo maintainer-cleaning docs - @cd $(DOCS) && $(MAKE) $(FLAGS) maintainer-clean + @test -d $(DOCS) || exit 0; cd $(DOCS) && $(MAKE) $(FLAGS) maintainer-clean @echo maintainer-cleaning Lib files @rm -f $(srcdir)/Lib/swigwarn.swg @echo distcleaning diff --git a/Tools/javascript/Makefile.in b/Tools/javascript/Makefile.in index 6fbca2384..d5c4711a0 100644 --- a/Tools/javascript/Makefile.in +++ b/Tools/javascript/Makefile.in @@ -53,7 +53,7 @@ JS_INTERPRETER_SRC = javascript.cxx js_shell.cxx $(JS_INTERPRETER_SRC_JSC) $(JS_ JS_INTERPRETER_OBJS = $(JS_INTERPRETER_SRC:.cxx=.o) -%.o: %.cxx +%.o: $(srcdir)/%.cxx $(JSCXX) $(JS_INTERPRETER_DEFINES) $(CXXFLAGS) $(JSINCLUDES) -o $@ -c $< javascript: $(JS_INTERPRETER_OBJS) diff --git a/configure.ac b/configure.ac index eeabd11b4..949986341 100644 --- a/configure.ac +++ b/configure.ac @@ -2677,6 +2677,41 @@ AC_CONFIG_FILES([ AC_CONFIG_FILES([preinst-swig], [chmod +x preinst-swig]) AC_CONFIG_FILES([CCache/ccache_swig_config.h]) +#-------------------------------------------------------------------- +# Building Examples/ out of source directory +#-------------------------------------------------------------------- + +# If building out of source tree, replicate Examples/ source tree in +# build directory, and copy over Makefiles from source directory. +# Prefix each Makefile with a header which sets SRCDIR to the relative +# source directory, and provides a rule for updating the Makefile from +# its original source. +AC_CONFIG_COMMANDS([Examples],[ + if test "x${srcdir}" != "x." ; then + AC_MSG_NOTICE([generating Examples build tree]) + for mkfile in `cd ${srcdir} && find Examples/ -type f -name Makefile`; do + dir=`dirname ${mkfile}` + d=${dir} + reldir=""; + while test "x$d" != "x." ; do + d=`dirname $d` + reldir="${reldir}../" + done + relsrcdir=${reldir}${srcdir}/ + AS_MKDIR_P([${dir}]) + cat <${mkfile} +# DO NOT EDIT: instead edit ${relsrcdir}${mkfile} +# and run (cd ${reldir} && ./config.status) to regenerate +SRCDIR = ${relsrcdir}${dir}/ + +EOF + cat ${srcdir}/${mkfile} >>${mkfile} + done + fi +]) + +#-------------------------------------------------------------------- + AC_OUTPUT langs="" From 9b0e484b8a786b043a6d8f39bd0b18ff2dd91823 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 12 May 2014 07:51:55 +0100 Subject: [PATCH 0925/1048] Tests for C nested classes symbol table not being in global space Tests for 55bda53145d2898bd4642926b25209c12738e558 --- Examples/test-suite/common.mk | 1 + .../java/nested_extend_c_runme.java | 38 ++++++++++ Examples/test-suite/nested_extend_c.i | 74 +++++++++++++++++++ 3 files changed, 113 insertions(+) create mode 100644 Examples/test-suite/java/nested_extend_c_runme.java create mode 100644 Examples/test-suite/nested_extend_c.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 2a4591524..4b10527db 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -602,6 +602,7 @@ C_TEST_CASES += \ memberin_extend_c \ name \ nested \ + nested_extend_c \ nested_structs \ newobject2 \ overload_extend \ diff --git a/Examples/test-suite/java/nested_extend_c_runme.java b/Examples/test-suite/java/nested_extend_c_runme.java new file mode 100644 index 000000000..9da093a09 --- /dev/null +++ b/Examples/test-suite/java/nested_extend_c_runme.java @@ -0,0 +1,38 @@ +import nested_extend_c.*; + +public class nested_extend_c_runme { + + static { + try { + System.loadLibrary("nested_extend_c"); + } 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 + { + { + hiA hi = new hiA(); + if (hi.hi_extend() != 'h') + throw new RuntimeException("test failed"); + } + { + lowA low = new lowA(); + if (low.low_extend() != 99) + throw new RuntimeException("test failed"); + } + + { + hiB hi = new hiB(); + if (hi.hi_extend() != 'h') + throw new RuntimeException("test failed"); + } + { + lowB low = new lowB(); + if (low.low_extend() != 99) + throw new RuntimeException("test failed"); + } + } +} diff --git a/Examples/test-suite/nested_extend_c.i b/Examples/test-suite/nested_extend_c.i new file mode 100644 index 000000000..3641cf78f --- /dev/null +++ b/Examples/test-suite/nested_extend_c.i @@ -0,0 +1,74 @@ +%module nested_extend_c + +%extend hiA { + hiA() { + union hiA *self = (union hiA *)malloc(sizeof(union hiA)); + self->c = 'h'; + return self; + } + char hi_extend() { + return $self->c; + } +} +%extend lowA { + lowA() { + struct lowA *self = (struct lowA *)malloc(sizeof(struct lowA)); + self->name = 0; + self->num = 99; + return self; + } + int low_extend() { + return $self->num; + } +} + +%extend hiB { + hiB() { + union hiB *self = (union hiB *)malloc(sizeof(union hiB)); + self->c = 'h'; + return self; + } + char hi_extend() { + return $self->c; + } +} +%extend lowB { + lowB() { + struct lowB *self = (struct lowB *)malloc(sizeof(struct lowB)); + self->name = 0; + self->num = 99; + return self; + } + int low_extend() { + return $self->num; + } +} + +%inline %{ +typedef struct NestedA { + int a; + union hiA { + char c; + int d; + } hiA_instance; + + struct lowA { + char *name; + int num; + } lowA_instance; +} NestedA; + +typedef struct { + int a; + union hiB { + char c; + int d; + } hiB_instance; + + struct lowB { + char *name; + int num; + } lowB_instance; +} NestedB; +%} + From caaf224b5960202034884a1a00a9c3d2c3881c08 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 12 May 2014 19:07:55 +0100 Subject: [PATCH 0926/1048] Turn off %extend nested test for cplusplusout languages --- Examples/test-suite/nested_extend_c.i | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Examples/test-suite/nested_extend_c.i b/Examples/test-suite/nested_extend_c.i index 3641cf78f..83d8c0601 100644 --- a/Examples/test-suite/nested_extend_c.i +++ b/Examples/test-suite/nested_extend_c.i @@ -1,5 +1,6 @@ %module nested_extend_c +#if !defined(SWIGOCTAVE) && !defined(SWIG_JAVASCRIPT_V8) %extend hiA { hiA() { union hiA *self = (union hiA *)malloc(sizeof(union hiA)); @@ -43,6 +44,7 @@ return $self->num; } } +#endif %inline %{ typedef struct NestedA { From 2aa540b9c0dee27e42e7eb6db2cb3e9ea24ca2ba Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Wed, 14 May 2014 00:51:36 +0400 Subject: [PATCH 0927/1048] %extend for nested unnamed C structs --- Source/CParse/parser.y | 9 ++++----- Source/Modules/main.cxx | 2 ++ Source/Modules/nested.cxx | 10 ++++++---- 3 files changed, 12 insertions(+), 9 deletions(-) diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 26af7be2d..a1a62cb62 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -41,7 +41,7 @@ int yyparse(); static Node *top = 0; /* Top of the generated parse tree */ static int unnamed = 0; /* Unnamed datatype counter */ -static Hash *extendhash = 0; /* Hash table of added methods */ +Hash *extendhash = 0; /* Hash table of added methods */ static Hash *classes = 0; /* Hash table of classes */ static Hash *classes_typedefs = 0; /* Hash table of typedef classes: typedef struct X {...} Y; */ static Symtab *prev_symtab = 0; @@ -655,7 +655,7 @@ static void add_symbols_copy(Node *n) { actually needs to take precedence. Therefore, we will selectively nuke symbols from the current symbol table, replacing them with the added methods */ -static void merge_extensions(Node *cls, Node *am) { +void merge_extensions(Node *cls, Node *am) { Node *n; Node *csym; @@ -708,7 +708,7 @@ static void merge_extensions(Node *cls, Node *am) { } } -static void append_previous_extension(Node *cls, Node *am) { +void append_previous_extension(Node *cls, Node *am) { Node *n, *ne; Node *pe = 0; Node *ae = 0; @@ -737,7 +737,7 @@ static void append_previous_extension(Node *cls, Node *am) { /* Check for unused %extend. Special case, don't report unused extensions for templates */ -static void check_extensions() { +void check_extensions() { Iterator ki; if (!extendhash) return; @@ -1579,7 +1579,6 @@ program : interface { Setattr(module_node,"name",ModuleName); } Setattr($1,"module",module_node); - check_extensions(); top = $1; } | PARSETYPE parm SEMI { diff --git a/Source/Modules/main.cxx b/Source/Modules/main.cxx index 833394b9c..d8f20c207 100644 --- a/Source/Modules/main.cxx +++ b/Source/Modules/main.cxx @@ -198,6 +198,7 @@ static String *external_runtime_name = 0; enum { STAGE1=1, STAGE2=2, STAGE3=4, STAGE4=8, STAGEOVERFLOW=16 }; static List *libfiles = 0; static List *all_output_files = 0; +extern "C" void check_extensions(); /* ----------------------------------------------------------------------------- * check_extension() @@ -1172,6 +1173,7 @@ int SWIG_main(int argc, char *argv[], Language *l) { Printf(stdout, "Processing unnamed structs...\n"); Swig_nested_name_unnamed_c_structs(top); } + check_extensions(); if (Verbose) { Printf(stdout, "Processing types...\n"); diff --git a/Source/Modules/nested.cxx b/Source/Modules/nested.cxx index 3b45e9f90..169263c3f 100644 --- a/Source/Modules/nested.cxx +++ b/Source/Modules/nested.cxx @@ -338,7 +338,9 @@ static void insertNodeAfter(Node *n, Node *c) { set_nextSibling(n, c); set_previousSibling(c, n); } - +extern "C" Hash *extendhash; +extern "C" void merge_extensions(Node *cls, Node *am); +extern "C" void append_previous_extension(Node *cls, Node *am); void Swig_nested_name_unnamed_c_structs(Node *n) { if (!classhash) classhash = Getattr(n, "classes"); @@ -377,15 +379,15 @@ void Swig_nested_name_unnamed_c_structs(Node *n) { } Delete(ty); // Check for extensions -/* // TODO: we can save extensions hash like class hash and move check_extensions() after nesting processing + // 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); + Delattr(extendhash, name); } - }*/ + } Swig_symbol_setscope(Swig_symbol_global_scope()); add_symbols_c(c); From 5d78f14b1c2a580ad08326de4900f51245560dd7 Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Wed, 14 May 2014 00:56:39 +0400 Subject: [PATCH 0928/1048] test added for nested unnamed C struct %extend --- Examples/test-suite/nested_extend_c.i | 15 +++++++++++++++ Source/Modules/nested.cxx | 2 -- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/Examples/test-suite/nested_extend_c.i b/Examples/test-suite/nested_extend_c.i index 83d8c0601..702c839b2 100644 --- a/Examples/test-suite/nested_extend_c.i +++ b/Examples/test-suite/nested_extend_c.i @@ -44,6 +44,13 @@ return $self->num; } } + +%extend FOO_bar { + void bar_extend() { + $self->d = 1; + } +}; + #endif %inline %{ @@ -72,5 +79,13 @@ typedef struct { int num; } lowB_instance; } NestedB; + +typedef struct { + int a; + union { + char c; + int d; + } bar; +} FOO; %} diff --git a/Source/Modules/nested.cxx b/Source/Modules/nested.cxx index 169263c3f..510270681 100644 --- a/Source/Modules/nested.cxx +++ b/Source/Modules/nested.cxx @@ -378,8 +378,6 @@ void Swig_nested_name_unnamed_c_structs(Node *n) { 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 From 3692e175bc980d1e1a06729465ff932e3bcc8e08 Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Thu, 15 May 2014 03:13:25 +0400 Subject: [PATCH 0929/1048] global unnamed structures ignored --- Examples/test-suite/nested_extend_c.i | 4 ++++ Source/Modules/nested.cxx | 7 ++++++- Source/Modules/typepass.cxx | 3 +++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/Examples/test-suite/nested_extend_c.i b/Examples/test-suite/nested_extend_c.i index 702c839b2..0e1495f86 100644 --- a/Examples/test-suite/nested_extend_c.i +++ b/Examples/test-suite/nested_extend_c.i @@ -87,5 +87,9 @@ typedef struct { int d; } bar; } FOO; + +struct { + int i; +} THING; %} diff --git a/Source/Modules/nested.cxx b/Source/Modules/nested.cxx index 510270681..ca1c79a31 100644 --- a/Source/Modules/nested.cxx +++ b/Source/Modules/nested.cxx @@ -396,7 +396,12 @@ void Swig_nested_name_unnamed_c_structs(Node *n) { Delete(ins); Delattr(c, "nested:outer"); } else { - // global unnamed struct - ignore it + // global unnamed struct - ignore it and it's instances + SetFlag(c, "feature:ignore"); + while (next && Getattr(next, "nested:unnamedtype") == c) { + SetFlag(next, "feature:ignore"); + next = nextSibling(next); + } c = next; continue; } diff --git a/Source/Modules/typepass.cxx b/Source/Modules/typepass.cxx index 329a601a8..ec6f64587 100644 --- a/Source/Modules/typepass.cxx +++ b/Source/Modules/typepass.cxx @@ -661,6 +661,9 @@ class TypePass:private Dispatcher { * ------------------------------------------------------------ */ virtual int cDeclaration(Node *n) { + if (GetFlag(n, "feature:ignore")) { + return SWIG_OK; + } if (NoExcept) { Delattr(n, "throws"); } From 2b5499a2628edda34f2deccd668001093d4a562d Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 13 May 2014 23:30:00 +0100 Subject: [PATCH 0930/1048] Slight simplification of test-suite build for new out-of-source changes Provide default SRCDIR and SCRIPTDIR variables in common.mk and override only where needed. --- Examples/Makefile.in | 4 ++-- Examples/test-suite/allegrocl/Makefile.in | 5 ----- Examples/test-suite/cffi/Makefile.in | 5 ----- Examples/test-suite/chicken/Makefile.in | 5 ----- Examples/test-suite/clisp/Makefile.in | 5 ----- Examples/test-suite/common.mk | 2 ++ Examples/test-suite/csharp/Makefile.in | 7 +------ Examples/test-suite/d/Makefile.in | 5 ----- Examples/test-suite/errors/Makefile.in | 5 ----- Examples/test-suite/go/Makefile.in | 6 ------ Examples/test-suite/guile/Makefile.in | 6 ------ Examples/test-suite/java/Makefile.in | 7 +------ Examples/test-suite/javascript/Makefile.in | 5 ----- Examples/test-suite/lua/Makefile.in | 6 ------ Examples/test-suite/mzscheme/Makefile.in | 5 ----- Examples/test-suite/ocaml/Makefile.in | 5 ----- Examples/test-suite/octave/Makefile.in | 6 ------ Examples/test-suite/perl5/Makefile.in | 6 ------ Examples/test-suite/php/Makefile.in | 6 ------ Examples/test-suite/pike/Makefile.in | 5 ----- Examples/test-suite/python/Makefile.in | 15 +++------------ Examples/test-suite/r/Makefile.in | 5 ----- Examples/test-suite/ruby/Makefile.in | 6 ------ Examples/test-suite/tcl/Makefile.in | 6 ------ Examples/test-suite/uffi/Makefile.in | 5 ----- 25 files changed, 9 insertions(+), 134 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index dcfbd83b9..d22a85abc 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -26,8 +26,8 @@ Makefile: @srcdir@/Makefile.in ../config.status cd .. && $(SHELL) ./config.status Examples/Makefile # SRCDIR is the relative path to the current source directory -# - For in-source-tree builds, SRCDIR with be either '', -# or '../' for some of the test suites (e.g. C#, Java) +# - For in-source-tree builds, SRCDIR with be either '' or './', but +# '../' for the test suites that build in a subdir (e.g. C#, Java) # - For out-of-source-tree builds, SRCDIR will be a relative # path ending with a '/' diff --git a/Examples/test-suite/allegrocl/Makefile.in b/Examples/test-suite/allegrocl/Makefile.in index 2803b7012..7c21e18cd 100644 --- a/Examples/test-suite/allegrocl/Makefile.in +++ b/Examples/test-suite/allegrocl/Makefile.in @@ -9,11 +9,6 @@ SCRIPTSUFFIX = _runme.lisp srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = -else -SRCDIR = $(srcdir)/ -endif # these cpp tests generate warnings/errors when compiling diff --git a/Examples/test-suite/cffi/Makefile.in b/Examples/test-suite/cffi/Makefile.in index a530e2243..164538e2b 100644 --- a/Examples/test-suite/cffi/Makefile.in +++ b/Examples/test-suite/cffi/Makefile.in @@ -9,11 +9,6 @@ SCRIPTSUFFIX = _runme.lisp srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = -else -SRCDIR = $(srcdir)/ -endif include $(srcdir)/../common.mk diff --git a/Examples/test-suite/chicken/Makefile.in b/Examples/test-suite/chicken/Makefile.in index ac02dad83..bdda02b7e 100644 --- a/Examples/test-suite/chicken/Makefile.in +++ b/Examples/test-suite/chicken/Makefile.in @@ -10,11 +10,6 @@ PROXYSUFFIX = _runme_proxy.ss srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = -else -SRCDIR = $(srcdir)/ -endif CHICKEN_CSI = @CHICKEN_CSI@ -quiet -batch -no-init SO = @SO@ diff --git a/Examples/test-suite/clisp/Makefile.in b/Examples/test-suite/clisp/Makefile.in index 9db84c561..525605254 100644 --- a/Examples/test-suite/clisp/Makefile.in +++ b/Examples/test-suite/clisp/Makefile.in @@ -9,11 +9,6 @@ SCRIPTSUFFIX = _runme.lisp srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = -else -SRCDIR = $(srcdir)/ -endif include $(srcdir)/../common.mk diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 37d660989..d93d788c9 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -70,6 +70,8 @@ LIBS = -L. LIBPREFIX = lib ACTION = check INTERFACEDIR = ../ +SRCDIR = $(srcdir)/ +SCRIPTDIR = $(srcdir) # Regenerate Makefile if Makefile.in or config.status have changed. ifeq (,$(TEST_SUITE_SUBDIR)) diff --git a/Examples/test-suite/csharp/Makefile.in b/Examples/test-suite/csharp/Makefile.in index a2a0828fd..7bec108eb 100644 --- a/Examples/test-suite/csharp/Makefile.in +++ b/Examples/test-suite/csharp/Makefile.in @@ -3,7 +3,6 @@ ####################################################################### LANGUAGE = csharp -SCRIPTDIR = $(srcdir) SCRIPTSUFFIX = _runme.cs CSHARPCILINTERPRETER = @CSHARPCILINTERPRETER@ CSHARPCILINTERPRETER_FLAGS = @CSHARPCILINTERPRETER_FLAGS@ @@ -13,11 +12,6 @@ CSHARPCYGPATH_W = @CSHARPCYGPATH_W@ srcdir = @srcdir@ top_srcdir = ../@top_srcdir@ top_builddir = ../@top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = ../ -else -SRCDIR = ../$(srcdir)/ -endif CPP_TEST_CASES = \ csharp_attributes \ @@ -37,6 +31,7 @@ CPP_TEST_CASES = \ include $(srcdir)/../common.mk # Overridden variables here +SRCDIR = ../$(srcdir)/ SWIGOPT += -namespace $*Namespace CSHARPFLAGSSPECIAL = diff --git a/Examples/test-suite/d/Makefile.in b/Examples/test-suite/d/Makefile.in index 0542bbad0..42fac00bc 100644 --- a/Examples/test-suite/d/Makefile.in +++ b/Examples/test-suite/d/Makefile.in @@ -7,11 +7,6 @@ LANGUAGE = d srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = -else -SRCDIR = $(srcdir)/ -endif ifeq (2,$(D_VERSION)) VERSIONSUFFIX = .2 diff --git a/Examples/test-suite/errors/Makefile.in b/Examples/test-suite/errors/Makefile.in index c74e9c65b..9ca6f6ecd 100644 --- a/Examples/test-suite/errors/Makefile.in +++ b/Examples/test-suite/errors/Makefile.in @@ -22,11 +22,6 @@ TODOS = tr -d '\r' srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = -else -SRCDIR = $(srcdir)/ -endif # strip source directory from output, so that diffs compare srcdir_regexp = $(shell echo $(srcdir)/ | sed 's/\./[.]/g') diff --git a/Examples/test-suite/go/Makefile.in b/Examples/test-suite/go/Makefile.in index 03f6f151e..204cf8a12 100644 --- a/Examples/test-suite/go/Makefile.in +++ b/Examples/test-suite/go/Makefile.in @@ -9,7 +9,6 @@ GO1 = @GO1@ GO12 = @GO12@ GO13 = @GO13@ GOC = @GOC@ -SCRIPTDIR = $(srcdir) SCRIPTSUFFIX = _runme.go GOCOMPILEARG = `if $(GOGCC) ; then echo -c -g; elif $(GO1) ; then echo tool $(GOC:c=g) ; fi` @@ -24,11 +23,6 @@ SO = @SO@ srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = -else -SRCDIR = $(srcdir)/ -endif include $(srcdir)/../common.mk diff --git a/Examples/test-suite/guile/Makefile.in b/Examples/test-suite/guile/Makefile.in index 5ac3de685..6cbf3b9b1 100644 --- a/Examples/test-suite/guile/Makefile.in +++ b/Examples/test-suite/guile/Makefile.in @@ -6,17 +6,11 @@ EXTRA_TEST_CASES += guile_ext_test.externaltest LANGUAGE = guile VARIANT = -SCRIPTDIR = $(srcdir) SCRIPTSUFFIX = _runme.scm srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = -else -SRCDIR = $(srcdir)/ -endif GUILE = @GUILE@ GUILE_RUNTIME= diff --git a/Examples/test-suite/java/Makefile.in b/Examples/test-suite/java/Makefile.in index a61452ed2..dd6c74a51 100644 --- a/Examples/test-suite/java/Makefile.in +++ b/Examples/test-suite/java/Makefile.in @@ -6,17 +6,11 @@ LANGUAGE = java JAVA = @JAVA@ JAVAC = @JAVAC@ JAVAFLAGS = -Xcheck:jni -SCRIPTDIR = $(srcdir) SCRIPTSUFFIX = _runme.java srcdir = @srcdir@ top_srcdir = ../@top_srcdir@ top_builddir = ../@top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = ../ -else -SRCDIR = ../$(srcdir)/ -endif C_TEST_CASES = \ java_lib_arrays \ @@ -49,6 +43,7 @@ CPP_TEST_CASES = \ include $(srcdir)/../common.mk # Overridden variables here +SRCDIR = ../$(srcdir)/ JAVA_PACKAGE = $* JAVA_PACKAGEOPT = -package $(JAVA_PACKAGE) SWIGOPT += $(JAVA_PACKAGEOPT) diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index 6126bde74..211310e86 100644 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -10,11 +10,6 @@ SCRIPTSUFFIX = _runme.js srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = -else -SRCDIR = $(srcdir)/ -endif SWIG = $(top_builddir)/preinst_swig diff --git a/Examples/test-suite/lua/Makefile.in b/Examples/test-suite/lua/Makefile.in index b35cc15ad..00f940825 100644 --- a/Examples/test-suite/lua/Makefile.in +++ b/Examples/test-suite/lua/Makefile.in @@ -4,17 +4,11 @@ LANGUAGE = lua LUA = @LUABIN@ -SCRIPTDIR = $(srcdir) SCRIPTSUFFIX = _runme.lua srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = -else -SRCDIR = $(srcdir)/ -endif # sorry, currently very few test cases work/have been written diff --git a/Examples/test-suite/mzscheme/Makefile.in b/Examples/test-suite/mzscheme/Makefile.in index 39fb1acbc..1c2466efc 100644 --- a/Examples/test-suite/mzscheme/Makefile.in +++ b/Examples/test-suite/mzscheme/Makefile.in @@ -9,11 +9,6 @@ SCRIPTSUFFIX = _runme.scm srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = -else -SRCDIR = $(srcdir)/ -endif include $(srcdir)/../common.mk diff --git a/Examples/test-suite/ocaml/Makefile.in b/Examples/test-suite/ocaml/Makefile.in index 5081e203e..c9c4bb603 100644 --- a/Examples/test-suite/ocaml/Makefile.in +++ b/Examples/test-suite/ocaml/Makefile.in @@ -10,11 +10,6 @@ SCRIPTSUFFIX = _runme.ml srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = -else -SRCDIR = $(srcdir)/ -endif C_TEST_CASES = diff --git a/Examples/test-suite/octave/Makefile.in b/Examples/test-suite/octave/Makefile.in index 11cb7c076..4f78371f4 100644 --- a/Examples/test-suite/octave/Makefile.in +++ b/Examples/test-suite/octave/Makefile.in @@ -4,17 +4,11 @@ LANGUAGE = octave OCTAVE = @OCTAVE@ -SCRIPTDIR = $(srcdir) SCRIPTSUFFIX = _runme.m srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = -else -SRCDIR = $(srcdir)/ -endif CPP_TEST_CASES += \ li_std_pair_extra \ diff --git a/Examples/test-suite/perl5/Makefile.in b/Examples/test-suite/perl5/Makefile.in index 6778f714e..9d9d460d8 100644 --- a/Examples/test-suite/perl5/Makefile.in +++ b/Examples/test-suite/perl5/Makefile.in @@ -4,18 +4,12 @@ LANGUAGE = perl5 PERL = @PERL@ -SCRIPTDIR = $(srcdir) SCRIPTSUFFIX = _runme.pl TEST_RUNNER = $(srcdir)/run-perl-test.pl srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = -else -SRCDIR = $(srcdir)/ -endif CPP_TEST_CASES += \ primitive_types \ diff --git a/Examples/test-suite/php/Makefile.in b/Examples/test-suite/php/Makefile.in index b6e4fff1a..5f56760ea 100644 --- a/Examples/test-suite/php/Makefile.in +++ b/Examples/test-suite/php/Makefile.in @@ -3,17 +3,11 @@ ####################################################################### LANGUAGE = php -SCRIPTDIR = $(srcdir) SCRIPTSUFFIX = _runme.php srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = -else -SRCDIR = $(srcdir)/ -endif CPP_TEST_CASES += \ php_namewarn_rename \ diff --git a/Examples/test-suite/pike/Makefile.in b/Examples/test-suite/pike/Makefile.in index 36a34352a..414fa1159 100644 --- a/Examples/test-suite/pike/Makefile.in +++ b/Examples/test-suite/pike/Makefile.in @@ -9,11 +9,6 @@ SCRIPTSUFFIX = _runme.pike srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = -else -SRCDIR = $(srcdir)/ -endif include $(srcdir)/../common.mk diff --git a/Examples/test-suite/python/Makefile.in b/Examples/test-suite/python/Makefile.in index 719e7d1a4..492396d15 100644 --- a/Examples/test-suite/python/Makefile.in +++ b/Examples/test-suite/python/Makefile.in @@ -14,6 +14,7 @@ PYTHON = $(PYBIN) #*_runme.py for Python 2.x, *_runme3.py for Python 3.x PY2SCRIPTSUFFIX = _runme.py PY3SCRIPTSUFFIX = _runme3.py +PY2TO3 = 2to3 -x import ifeq (,$(PY3)) SCRIPTSUFFIX = $(PY2SCRIPTSUFFIX) @@ -21,20 +22,9 @@ else SCRIPTSUFFIX = $(PY3SCRIPTSUFFIX) endif -SCRIPTDIR = . - srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = -else -SRCDIR = $(srcdir)/ -endif - - -PY2TO3 = 2to3 -x import - CPP_TEST_CASES += \ argcargvtest \ @@ -109,7 +99,8 @@ BUILTIN_NOT_BROKEN = $(filter-out $(BUILTIN_BROKEN),$(NOT_BROKEN_TEST_CASES)) builtin-check : $(BUILTIN_NOT_BROKEN) # Overridden variables here -LIBS = -L. +SCRIPTDIR = . +LIBS = -L. VALGRIND_OPT += --suppressions=pythonswig.supp # Custom tests - tests with additional commandline options diff --git a/Examples/test-suite/r/Makefile.in b/Examples/test-suite/r/Makefile.in index 9f0de1c5f..8bf537d8c 100644 --- a/Examples/test-suite/r/Makefile.in +++ b/Examples/test-suite/r/Makefile.in @@ -10,11 +10,6 @@ RUNR = R CMD BATCH --no-save --no-restore srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = -else -SRCDIR = $(srcdir)/ -endif C_TEST_CASES += \ r_copy_struct \ diff --git a/Examples/test-suite/ruby/Makefile.in b/Examples/test-suite/ruby/Makefile.in index d0c65929a..206617ecd 100644 --- a/Examples/test-suite/ruby/Makefile.in +++ b/Examples/test-suite/ruby/Makefile.in @@ -4,17 +4,11 @@ LANGUAGE = ruby RUBY = @RUBY@ -SCRIPTDIR = $(srcdir) SCRIPTSUFFIX = _runme.rb srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = -else -SRCDIR = $(srcdir)/ -endif CPP_TEST_CASES = \ kwargs_feature \ diff --git a/Examples/test-suite/tcl/Makefile.in b/Examples/test-suite/tcl/Makefile.in index f8a196e26..32454b09c 100644 --- a/Examples/test-suite/tcl/Makefile.in +++ b/Examples/test-suite/tcl/Makefile.in @@ -4,17 +4,11 @@ LANGUAGE = tcl TCLSH = tclsh -SCRIPTDIR = $(srcdir) SCRIPTSUFFIX = _runme.tcl srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = -else -SRCDIR = $(srcdir)/ -endif CPP_TEST_CASES += \ primitive_types \ diff --git a/Examples/test-suite/uffi/Makefile.in b/Examples/test-suite/uffi/Makefile.in index 9f3546da6..7184af40f 100644 --- a/Examples/test-suite/uffi/Makefile.in +++ b/Examples/test-suite/uffi/Makefile.in @@ -9,11 +9,6 @@ SCRIPTSUFFIX = _runme.lisp srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -ifeq (.,$(srcdir)) -SRCDIR = -else -SRCDIR = $(srcdir)/ -endif include $(srcdir)/../common.mk From beccd3258fc1fd9e0c3caef3a21fdaeffcef81d3 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 13 May 2014 23:52:55 +0100 Subject: [PATCH 0931/1048] Update all languages to use SCRIPTDIR R also to use SCRIPTPREFIX and SCRIPTSUFFIX --- Examples/test-suite/allegrocl/Makefile.in | 4 ++-- Examples/test-suite/cffi/Makefile.in | 4 ++-- Examples/test-suite/chicken/Makefile.in | 10 +++++----- Examples/test-suite/clisp/Makefile.in | 4 ++-- Examples/test-suite/d/Makefile.in | 8 ++++---- Examples/test-suite/javascript/Makefile.in | 2 +- Examples/test-suite/mzscheme/Makefile.in | 4 ++-- Examples/test-suite/ocaml/Makefile.in | 8 ++++---- Examples/test-suite/pike/Makefile.in | 4 ++-- Examples/test-suite/r/Makefile.in | 12 ++++++------ Examples/test-suite/uffi/Makefile.in | 4 ++-- 11 files changed, 32 insertions(+), 32 deletions(-) diff --git a/Examples/test-suite/allegrocl/Makefile.in b/Examples/test-suite/allegrocl/Makefile.in index 7c21e18cd..8c253a7f2 100644 --- a/Examples/test-suite/allegrocl/Makefile.in +++ b/Examples/test-suite/allegrocl/Makefile.in @@ -115,8 +115,8 @@ include $(srcdir)/../common.mk # Runs the testcase. A testcase is only run if # a file is found which has _runme.lisp appended after the testcase name. run_testcase = \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(ALLEGROCLBIN) -batch -s $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(ALLEGROCLBIN) -batch -s $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ fi %.clean: diff --git a/Examples/test-suite/cffi/Makefile.in b/Examples/test-suite/cffi/Makefile.in index 164538e2b..6e657ba46 100644 --- a/Examples/test-suite/cffi/Makefile.in +++ b/Examples/test-suite/cffi/Makefile.in @@ -39,8 +39,8 @@ CPP_TEST_CASES = # Runs the testcase. A testcase is only run if # a file is found which has _runme.lisp appended after the testcase name. run_testcase = \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(CFFI) -batch -s $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(CFFI) -batch -s $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ fi # Clean: (does nothing, we dont generate extra cffi code) diff --git a/Examples/test-suite/chicken/Makefile.in b/Examples/test-suite/chicken/Makefile.in index bdda02b7e..5a2ef3d8a 100644 --- a/Examples/test-suite/chicken/Makefile.in +++ b/Examples/test-suite/chicken/Makefile.in @@ -45,7 +45,7 @@ SWIGOPT += -nounit $(setup) +$(swig_and_compile_cpp) $(run_testcase) - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(PROXYSUFFIX) ]; then \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(PROXYSUFFIX) ]; then \ $(MAKE) $*.cppproxy; \ fi @@ -53,7 +53,7 @@ SWIGOPT += -nounit $(setup) +$(swig_and_compile_c) $(run_testcase) - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(PROXYSUFFIX) ]; then \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(PROXYSUFFIX) ]; then \ $(MAKE) $*.cproxy; \ fi @@ -61,7 +61,7 @@ SWIGOPT += -nounit $(setup) +$(swig_and_compile_multi_cpp) $(run_testcase) - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(PROXYSUFFIX) ]; then \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(PROXYSUFFIX) ]; then \ $(MAKE) $*.multiproxy; \ fi @@ -88,8 +88,8 @@ SWIGOPT += -nounit # Runs the testcase. A testcase is only run if # a file is found which has _runme.scm appended after the testcase name. run_testcase = \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(CHICKEN_CSI) $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(CHICKEN_CSI) $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ fi # Clean diff --git a/Examples/test-suite/clisp/Makefile.in b/Examples/test-suite/clisp/Makefile.in index 525605254..43f7159ff 100644 --- a/Examples/test-suite/clisp/Makefile.in +++ b/Examples/test-suite/clisp/Makefile.in @@ -39,8 +39,8 @@ CPP_TEST_CASES = # Runs the testcase. A testcase is only run if # a file is found which has _runme.lisp appended after the testcase name. run_testcase = \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(CLISP) -batch -s $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(CLISP) -batch -s $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ fi # Clean: (does nothing, we dont generate extra clisp code) diff --git a/Examples/test-suite/d/Makefile.in b/Examples/test-suite/d/Makefile.in index 42fac00bc..37a944b09 100644 --- a/Examples/test-suite/d/Makefile.in +++ b/Examples/test-suite/d/Makefile.in @@ -14,7 +14,7 @@ else VERSIONSUFFIX = .1 endif -TESTSUFFIX = _runme$(VERSIONSUFFIX).d +SCRIPTSUFFIX = _runme$(VERSIONSUFFIX).d CPP_TEST_CASES = \ d_nativepointers \ @@ -46,7 +46,7 @@ SWIGOPT+=-splitproxy -package $* # Makes a directory for the testcase if it does not exist setup = \ - if [ -f $(srcdir)/$(TESTPREFIX)$*$(TESTSUFFIX) ]; then \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ echo "$(ACTION)ing $(LANGUAGE) testcase $* (with run test)" ; \ else \ echo "$(ACTION)ing $(LANGUAGE) testcase $*" ; \ @@ -61,11 +61,11 @@ setup = \ # Compiles D files then runs the testcase. A testcase is only run if # a file is found which has _runme.d appended after the testcase name. run_testcase = \ - if [ -f $(srcdir)/$(TESTPREFIX)$*$(TESTSUFFIX) ]; then \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ cd $*$(VERSIONSUFFIX) && \ $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile \ DFLAGS='-of$*_runme' \ - DSRCS='../$(srcdir)/$(TESTPREFIX)$*$(TESTSUFFIX) `find $* -name *.d`' d_compile && \ + DSRCS='../$(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) `find $* -name *.d`' d_compile && \ env LD_LIBRARY_PATH=".:$$LD_LIBRARY_PATH" $(RUNTOOL) ./$*_runme; \ else \ cd $*$(VERSIONSUFFIX) && \ diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index 211310e86..87e4c6ecb 100644 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -22,7 +22,7 @@ endif include $(srcdir)/../common.mk _setup = \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ echo "$(ACTION)ing $(LANGUAGE) ($(JSENGINE)) testcase $* (with run test)" ; \ else \ echo "$(ACTION)ing $(LANGUAGE) ($(JSENGINE)) testcase $*" ; \ diff --git a/Examples/test-suite/mzscheme/Makefile.in b/Examples/test-suite/mzscheme/Makefile.in index 1c2466efc..034e52131 100644 --- a/Examples/test-suite/mzscheme/Makefile.in +++ b/Examples/test-suite/mzscheme/Makefile.in @@ -37,8 +37,8 @@ include $(srcdir)/../common.mk # Runs the testcase. A testcase is only run if # a file is found which has _runme.scm appended after the testcase name. run_testcase = \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(MZSCHEME) -r $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(MZSCHEME) -r $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ fi # Clean diff --git a/Examples/test-suite/ocaml/Makefile.in b/Examples/test-suite/ocaml/Makefile.in index c9c4bb603..ee93d534c 100644 --- a/Examples/test-suite/ocaml/Makefile.in +++ b/Examples/test-suite/ocaml/Makefile.in @@ -14,12 +14,12 @@ top_builddir = @top_builddir@ C_TEST_CASES = run_testcase = \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) -a \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) -a \ -f $(top_srcdir)/Examples/test-suite/$*.list ] ; then \ - $(COMPILETOOL) $(OCAMLC) -c $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + $(COMPILETOOL) $(OCAMLC) -c $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ $(COMPILETOOL) $(OCAMLC) swig.cmo -custom -g -cc '$(CXX)' -o runme `cat $(top_srcdir)/Examples/test-suite/$(*).list | sed -e 's/\(.*\)/\1_wrap.o \1.cmo/g'`&& $(RUNTOOL) ./runme; \ - elif [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - $(COMPILETOOL) $(OCAMLC) -c $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + elif [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + $(COMPILETOOL) $(OCAMLC) -c $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ $(COMPILETOOL) $(OCAMLC) swig.cmo -custom -g -cc '$(CXX)' -o runme $(srcdir)/$(*).cmo $(srcdir)/$(*)_runme.cmo $(srcdir)/$(*)_wrap.o && \ $(RUNTOOL) ./runme; \ fi ; diff --git a/Examples/test-suite/pike/Makefile.in b/Examples/test-suite/pike/Makefile.in index 414fa1159..579c7e28f 100644 --- a/Examples/test-suite/pike/Makefile.in +++ b/Examples/test-suite/pike/Makefile.in @@ -37,8 +37,8 @@ include $(srcdir)/../common.mk # Runs the testcase. A testcase is only run if # a file is found which has _runme.pike appended after the testcase name. run_testcase = \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(PIKE) $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(PIKE) $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ fi # Clean: remove the generated .pike file diff --git a/Examples/test-suite/r/Makefile.in b/Examples/test-suite/r/Makefile.in index 8bf537d8c..cab339bf7 100644 --- a/Examples/test-suite/r/Makefile.in +++ b/Examples/test-suite/r/Makefile.in @@ -49,19 +49,19 @@ include $(srcdir)/../common.mk # Run the runme if it exists. If not just load the R wrapper to # check for syntactic correctness run_testcase = \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH PATH=.:"$$PATH" $(RUNTOOL) $(RUNR) $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH PATH=.:"$$PATH" $(RUNTOOL) $(RUNR) $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ else \ - $(RUNTOOL) $(RUNR) $(srcdir)/$(SCRIPTPREFIX)$*$(WRAPSUFFIX); \ + $(RUNTOOL) $(RUNR) $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(WRAPSUFFIX); \ fi run_multitestcase = \ for f in `cat $(top_srcdir)/$(EXAMPLES)/$(TEST_SUITE)/$*.list` ; do \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$${f}$(SCRIPTSUFFIX) ]; then \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$${f}$(SCRIPTSUFFIX) ]; then \ env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH PATH=.:"$$PATH" \ - $(RUNTOOL) $(RUNR) $(srcdir)/$(SCRIPTPREFIX)$${f}$(SCRIPTSUFFIX); \ + $(RUNTOOL) $(RUNR) $(SCRIPTDIR)/$(SCRIPTPREFIX)$${f}$(SCRIPTSUFFIX); \ else \ - $(RUNTOOL) $(RUNR) $(srcdir)/$(SCRIPTPREFIX)$${f}$(WRAPSUFFIX); \ + $(RUNTOOL) $(RUNR) $(SCRIPTDIR)/$(SCRIPTPREFIX)$${f}$(WRAPSUFFIX); \ fi; \ done # Clean diff --git a/Examples/test-suite/uffi/Makefile.in b/Examples/test-suite/uffi/Makefile.in index 7184af40f..59aa33c6a 100644 --- a/Examples/test-suite/uffi/Makefile.in +++ b/Examples/test-suite/uffi/Makefile.in @@ -39,8 +39,8 @@ CPP_TEST_CASES = # Runs the testcase. A testcase is only run if # a file is found which has _runme.lisp appended after the testcase name. run_testcase = \ - if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ - env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(UFFI) -batch -s $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ + if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH $(RUNTOOL) $(UFFI) -batch -s $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ fi # Clean: (does nothing, we dont generate extra uffi code) From 28c3549e433620e6aa94571471e51433aad4d447 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Wed, 14 May 2014 00:48:51 +0100 Subject: [PATCH 0932/1048] Partially fix R out of source test-suite Fix when there is NOT a runme.R file --- Examples/test-suite/r/Makefile.in | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Examples/test-suite/r/Makefile.in b/Examples/test-suite/r/Makefile.in index cab339bf7..8ee73b279 100644 --- a/Examples/test-suite/r/Makefile.in +++ b/Examples/test-suite/r/Makefile.in @@ -52,7 +52,7 @@ run_testcase = \ if [ -f $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH PATH=.:"$$PATH" $(RUNTOOL) $(RUNR) $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX); \ else \ - $(RUNTOOL) $(RUNR) $(SCRIPTDIR)/$(SCRIPTPREFIX)$*$(WRAPSUFFIX); \ + $(RUNTOOL) $(RUNR) ./$(SCRIPTPREFIX)$*$(WRAPSUFFIX); \ fi run_multitestcase = \ @@ -61,7 +61,7 @@ run_multitestcase = \ env LD_LIBRARY_PATH=.:$$LD_LIBRARY_PATH PATH=.:"$$PATH" \ $(RUNTOOL) $(RUNR) $(SCRIPTDIR)/$(SCRIPTPREFIX)$${f}$(SCRIPTSUFFIX); \ else \ - $(RUNTOOL) $(RUNR) $(SCRIPTDIR)/$(SCRIPTPREFIX)$${f}$(WRAPSUFFIX); \ + $(RUNTOOL) $(RUNR) ./$(SCRIPTPREFIX)$${f}$(WRAPSUFFIX); \ fi; \ done # Clean From 4e47bbee06405811523f5426e812620ac58e86d4 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Wed, 14 May 2014 00:50:06 +0100 Subject: [PATCH 0933/1048] gitignore to ignore build directory names --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index ce6a3c4b7..efb6cf096 100644 --- a/.gitignore +++ b/.gitignore @@ -138,4 +138,4 @@ Examples/test-suite/uffi/*/ Examples/scratch # Out of source tree build directories -_build*/ +*build*/ From d927fa5376d7c1c19568ab653f1097ef082cae00 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Wed, 14 May 2014 22:23:40 +0100 Subject: [PATCH 0934/1048] Remove unnecessary make invocation when running test-suite --- Makefile.in | 3 --- 1 file changed, 3 deletions(-) diff --git a/Makefile.in b/Makefile.in index 8c6072b41..da9dfdce5 100644 --- a/Makefile.in +++ b/Makefile.in @@ -285,9 +285,6 @@ check-test-suite: \ check-javascript-test-suite check-%-test-suite: - @if test -d Examples/test-suite/$*; then \ - cd Examples/test-suite/$* && $(MAKE) Makefile; \ - fi @if test -z "$(skip-$*)"; then \ echo $* unknown; \ exit 1; \ From 18d72f4562745f725e981443248b8fbea1a55cae Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 15 May 2014 20:27:01 +0100 Subject: [PATCH 0935/1048] Add in CPPFLAGS and LDFLAGS to examples/test-suite - Split current usage of CXXFLAGS into the conventional CPPFLAGS CXXFLAGS and LDFLAGS - Split current usage of CFLAGS into the conventional CPPFLAGS CFLAGS and LDFLAGS - This restores 'make whatever CXXFLAGS=-g' which stopped working during the recently added suppport for out of source builds. - LDFLAGS is currently empty, but is there for future use --- Examples/Makefile.in | 230 ++++++++++++++-------------- Examples/chicken/class/Makefile | 1 - Examples/chicken/constants/Makefile | 1 - Examples/chicken/multimap/Makefile | 1 - Examples/chicken/overload/Makefile | 1 - Examples/chicken/simple/Makefile | 1 - Tools/javascript/Makefile.in | 10 +- 7 files changed, 121 insertions(+), 124 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index d22a85abc..7c2d23647 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -45,8 +45,10 @@ endif TARGET = CC = @CC@ CXX = @CXX@ -CFLAGS = $(SRCDIR_INCLUDE) @PLATCFLAGS@ -CXXFLAGS = $(SRCDIR_INCLUDE) @BOOST_CPPFLAGS@ @PLATCXXFLAGS@ +CPPFLAGS = $(SRCDIR_INCLUDE) +CFLAGS = @PLATCFLAGS@ +CXXFLAGS = @BOOST_CPPFLAGS@ @PLATCXXFLAGS@ +LDFLAGS = prefix = @prefix@ exec_prefix= @exec_prefix@ SRCS = @@ -155,12 +157,12 @@ TCL_SCRIPT = $(SRCDIR)$(RUNME).tcl tclsh: $(SRCDIR_SRCS) $(SWIG) -tcl8 $(SWIGOPT) $(TCL_SWIGOPTS) -ltclsh.i -o $(ISRCS) $(INTERFACEPATH) - $(CC) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(TCL_INCLUDE) \ + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(TCL_INCLUDE) \ $(TCL_LIB) $(TCL_OPTS) $(LIBS) $(SYSLIBS) -o $(TARGET) tclsh_cpp: $(SRCDIR_SRCS) $(SWIG) -tcl8 -c++ $(SWIGOPT) $(TCL_SWIGOPTS) -ltclsh.i -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) \ + $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) \ $(TCL_LIB) $(TCL_OPTS) $(LIBS) $(SYSLIBS) -o $(TARGET) # ----------------------------------------------------------- @@ -169,8 +171,8 @@ tclsh_cpp: $(SRCDIR_SRCS) tcl: $(SRCDIR_SRCS) $(SWIG) -tcl8 $(SWIGOPT) $(TCL_SWIGOPTS) -o $(ISRCS) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(TCL_INCLUDE) - $(TCLLDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(TCL_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(TCL_SO) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(TCL_INCLUDE) + $(TCLLDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(TCL_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(TCL_SO) # ----------------------------------------------------------- # Build a Tcl7.5 dynamic loadable module for C++ @@ -178,8 +180,8 @@ tcl: $(SRCDIR_SRCS) tcl_cpp: $(SRCDIR_SRCS) $(SWIG) -tcl8 -c++ $(SWIGOPT) $(TCL_SWIGOPTS) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) - $(TCLCXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(TCL_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(TCL_SO) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(TCL_INCLUDE) + $(TCLCXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(TCL_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(TCL_SO) # ----------------------------------------------------------------- # Run Tcl example @@ -230,8 +232,8 @@ PERL5_SCRIPT = $(SRCDIR)$(RUNME).pl perl5: $(SRCDIR_SRCS) $(SWIG) -perl5 $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - $(CC) -c -Dbool=char $(CCSHARED) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(PERL5_CCFLAGS) $(PERL5_CCCDLFLAGS) -I$(PERL5_INCLUDE) - $(LDSHARED) $(CFLAGS) $(PERL5_CCDLFLAGS) $(OBJS) $(IOBJS) $(PERL5_LDFLAGS) $(PERL5_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(CC) -c -Dbool=char $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(PERL5_CCFLAGS) $(PERL5_CCCDLFLAGS) -I$(PERL5_INCLUDE) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(PERL5_CCDLFLAGS) $(OBJS) $(IOBJS) $(PERL5_LDFLAGS) $(PERL5_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ---------------------------------------------------------------- # Build a Perl5 dynamically loadable module (C++) @@ -239,15 +241,15 @@ perl5: $(SRCDIR_SRCS) perl5_cpp: $(SRCDIR_SRCS) $(SWIG) -perl5 -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(PERL5_CCFLAGS) $(PERL5_CCCDLFLAGS) -I$(PERL5_INCLUDE) - $(CXXSHARED) $(CXXFLAGS) $(PERL5_CCDLFLAGS) $(OBJS) $(IOBJS) $(PERL5_LDFLAGS) $(PERL5_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(PERL5_CCFLAGS) $(PERL5_CCCDLFLAGS) -I$(PERL5_INCLUDE) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(PERL5_CCDLFLAGS) $(OBJS) $(IOBJS) $(PERL5_LDFLAGS) $(PERL5_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ---------------------------------------------------------------- # Build a module from existing XS C source code. (ie. from xsubpp). # ---------------------------------------------------------------- perl5_xs: $(SRCDIR_SRCS) - $(CC) -c $(CCSHARED) $(CFLAGS) $(SRCDIR_SRCS) $(INCLUDES) -I$(PERL5_INCLUDE) - $(LDSHARED) $(CFLAGS) $(OBJS) $(LIBS) -o $(TARGET)$(SO) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(SRCDIR_SRCS) $(INCLUDES) -I$(PERL5_INCLUDE) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $(TARGET)$(SO) # ---------------------------------------------------------------- # Build a statically linked Perl5 executable @@ -255,11 +257,11 @@ perl5_xs: $(SRCDIR_SRCS) perl5_static: $(SRCDIR_SRCS) $(SWIG) -perl5 -static -lperlmain.i $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - $(CC) $(CFLAGS) -Dbool=char $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) -I$(PERL5_INCLUDE) $(PERL5_LIB) $(LIBS) -o $(TARGET) + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -Dbool=char $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) -I$(PERL5_INCLUDE) $(PERL5_LIB) $(LIBS) -o $(TARGET) perl5_static_cpp: $(SRCDIR_SRCS) $(SWIG) -perl5 -c++ -static -lperlmain.i $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) -I$(PERL5_INCLUDE) $(PERL5_LIB) $(LIBS) -o $(TARGET) + $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) -I$(PERL5_INCLUDE) $(PERL5_LIB) $(LIBS) -o $(TARGET) # ----------------------------------------------------------------- # Running a Perl5 example @@ -324,8 +326,8 @@ endif python: $(SRCDIR_SRCS) $(SWIGPYTHON) $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(PYTHON_INCLUDE) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(PYTHON_DLNK) $(LIBS) -o $(LIBPREFIX)_$(TARGET)$(PYTHON_SO) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(PYTHON_INCLUDE) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(PYTHON_DLNK) $(LIBS) -o $(LIBPREFIX)_$(TARGET)$(PYTHON_SO) # ----------------------------------------------------------------- # Build a C++ dynamically loadable module @@ -333,8 +335,8 @@ python: $(SRCDIR_SRCS) python_cpp: $(SRCDIR_SRCS) $(SWIGPYTHON) -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(PYTHON_INCLUDE) - $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(PYTHON_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)_$(TARGET)$(PYTHON_SO) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(PYTHON_INCLUDE) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(PYTHON_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)_$(TARGET)$(PYTHON_SO) # ----------------------------------------------------------------- # Build statically linked Python interpreter @@ -349,12 +351,12 @@ PYTHON_LIBOPTS = $(PYTHON_LINK) @LIBS@ $(TKINTER) $(SYSLIBS) python_static: $(SRCDIR_SRCS) $(SWIGPYTHON) -lembed.i $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - $(CC) $(CFLAGS) @LINKFORSHARED@ $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) \ + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) @LINKFORSHARED@ $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) \ $(PYTHON_INCLUDE) $(LIBS) -L$(PYTHON_LIB) $(PYTHON_LIBOPTS) -o $(TARGET) python_static_cpp: $(SRCDIR_SRCS) $(SWIGPYTHON) -c++ -lembed.i $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) \ + $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) \ $(PYTHON_INCLUDE) $(LIBS) -L$(PYTHON_LIB) $(PYTHON_LIBOPTS) -o $(TARGET) # ----------------------------------------------------------------- @@ -423,9 +425,9 @@ OCTAVE_SCRIPT = $(SRCDIR)$(RUNME).m octave: $(SRCDIR_SRCS) $(SWIG) -octave $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) -g -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(INCLUDES) $(OCTAVE_CXX) - $(CC) -g -c $(CCSHARED) $(CFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CSRCS) $(INCLUDES) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(OCTAVE_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(OCTAVE_SO) + $(CXX) -g -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(ICXXSRCS) $(INCLUDES) $(OCTAVE_CXX) + $(CC) -g -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CSRCS) $(INCLUDES) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(OCTAVE_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(OCTAVE_SO) # ----------------------------------------------------------------- # Build a C++ dynamically loadable module @@ -433,8 +435,8 @@ octave: $(SRCDIR_SRCS) octave_cpp: $(SRCDIR_SRCS) $(SWIG) -c++ -octave $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) -g -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(OCTAVE_CXX) - $(CXXSHARED) -g $(CXXFLAGS) $(OBJS) $(IOBJS) $(OCTAVE_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(OCTAVE_SO) + $(CXX) -g -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(OCTAVE_CXX) + $(CXXSHARED) -g $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(OCTAVE_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(OCTAVE_SO) # ----------------------------------------------------------------- # Running an Octave example @@ -478,14 +480,14 @@ GUILE_SCRIPT = $(SRCDIR)$(RUNME).scm #------------------------------------------------------------------ guile: $(SRCDIR_SRCS) $(SWIG) -guile -Linkage passive $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(INCLUDES) $(GUILE_CFLAGS) $(ISRCS) $(SRCDIR_SRCS) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(GUILE_LIBS) $(LIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(INCLUDES) $(GUILE_CFLAGS) $(ISRCS) $(SRCDIR_SRCS) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(GUILE_LIBS) $(LIBS) -o $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO) guile_cpp: $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO) $(GUILE_LIBPREFIX)$(TARGET)$(GUILE_SO): $(SRCDIR_SRCS) $(SWIG) -c++ -guile -Linkage passive $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(INCLUDES) $(GUILE_CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) - $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(GUILE_LIBS) $(LIBS) $(CPP_DLLIBS) -o $@ + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(INCLUDES) $(GUILE_CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(GUILE_LIBS) $(LIBS) $(CPP_DLLIBS) -o $@ guile_externalhdr: $(SWIG) -guile -external-runtime $(TARGET) @@ -496,7 +498,7 @@ guile_externalhdr: guile_augmented: $(SRCDIR_SRCS) $(SWIG) -guile $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - $(CC) $(CXXFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(GUILE_CFLAGS) $(GUILE_LIBS) $(LIBS) -o $(TARGET) + $(CC) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(GUILE_CFLAGS) $(GUILE_LIBS) $(LIBS) -o $(TARGET) # ----------------------------------------------------------------- # Build statically linked Guile interpreter @@ -504,24 +506,24 @@ guile_augmented: $(SRCDIR_SRCS) guile_static: $(SRCDIR_SRCS) $(SWIG) -guile -lguilemain.i -Linkage ltdlmod $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - $(CC) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) \ + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) \ -DSWIGINIT="SCM scm_init_$(TARGET)_module(void); scm_init_$(TARGET)_module();" \ $(GUILE_CFLAGS) $(GUILE_LIBS) $(LIBS) $(GUILE_LIBOPTS) -o $(TARGET)-guile guile_static_cpp: $(SRCDIR_SRCS) $(SWIG) -c++ -guile -lguilemain.i -Linkage ltdlmod $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) \ + $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) \ -DSWIGINIT="SCM scm_init_$(TARGET)_module(void); scm_init_$(TARGET)_module();" \ $(GUILE_CFLAGS) $(GUILE_LIBS) $(LIBS) $(GUILE_LIBOPTS) -o $(TARGET)-guile guile_simple: $(SRCDIR_SRCS) $(SWIG) -guile -lguilemain.i -Linkage simple $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - $(CC) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) \ + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) \ $(GUILE_CFLAGS) $(GUILE_LIBS) $(LIBS) $(GUILE_LIBOPTS) -o $(TARGET)-guile guile_simple_cpp: $(SRCDIR_SRCS) $(SWIG) -c++ -guile -lguilemain.i -Linkage simple $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) \ + $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) \ $(GUILE_CFLAGS) $(GUILE_LIBS) $(LIBS) $(GUILE_LIBOPTS) -o $(TARGET)-guile # ----------------------------------------------------------------- @@ -575,8 +577,8 @@ JAVAC = @JAVAC@ -d . java: $(SRCDIR_SRCS) $(SWIG) -java $(SWIGOPT) -o $(ISRCS) $(realpath $(INTERFACEPATH)) - $(CC) -c $(CCSHARED) $(CFLAGS) $(JAVACFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(JAVA_INCLUDE) - $(JAVALDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JAVA_DLNK) $(LIBS) -o $(JAVA_LIBPREFIX)$(TARGET)$(JAVASO) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(JAVACFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(JAVA_INCLUDE) + $(JAVALDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JAVA_DLNK) $(LIBS) -o $(JAVA_LIBPREFIX)$(TARGET)$(JAVASO) # ---------------------------------------------------------------- # Build a java dynamically loadable module (C++) @@ -584,8 +586,8 @@ java: $(SRCDIR_SRCS) java_cpp: $(SRCDIR_SRCS) $(SWIG) -java -c++ $(SWIGOPT) -o $(ICXXSRCS) $(realpath $(INTERFACEPATH)) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(JAVACFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(JAVA_INCLUDE) - $(JAVACXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(JAVA_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(JAVA_LIBPREFIX)$(TARGET)$(JAVASO) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(JAVACFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(JAVA_INCLUDE) + $(JAVACXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JAVA_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(JAVA_LIBPREFIX)$(TARGET)$(JAVASO) # ---------------------------------------------------------------- # Compile java files @@ -646,16 +648,16 @@ javascript_wrapper_cpp: $(SRCDIR_SRCS) $(SWIG) -javascript -c++ $(SWIGOPT) -o $(INTERFACEDIR)$(TARGET)_wrap.cxx $(INTERFACEPATH) javascript_build: $(SRCDIR_SRCS) - $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(JSINCLUDES) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(JSINCLUDES) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) javascript_build_cpp: $(SRCDIR_SRCS) ifeq (node,$(JSENGINE)) sed -e 's|$$srcdir|./$(SRCDIR)|g' $(SRCDIR)binding.gyp.in > binding.gyp $(NODEGYP) --loglevel=silent configure build 1>>/dev/null else - $(CXX) -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(JSINCLUDES) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(JSINCLUDES) + $(CXXSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) endif @@ -664,17 +666,17 @@ endif javascript: $(SRCDIR_SRCS) javascript_custom_interpreter $(SWIG) -javascript $(SWIGOPT) $(INTERFACEPATH) ifeq (jsc, $(ENGINE)) - $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(JSINCLUDES) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(JSINCLUDES) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) else # (v8 | node) # v8 and node must be compiled as c++ - $(CXX) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(JSINCLUDES) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(JSINCLUDES) + $(CXXSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) endif javascript_cpp: $(SRCDIR_SRCS) javascript_custom_interpreter $(SWIG) -javascript -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(JSINCLUDES) - $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(JSINCLUDES) + $(CXXSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- # Running a Javascript example @@ -797,8 +799,6 @@ MODULA3_INCLUDE= @MODULA3INC@ modula3: $(SRCDIR_SRCS) $(SWIG) -modula3 $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) -# $(CC) -c $(CCSHARED) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) \ -# $(OBJS) $(IOBJS) $(LIBS) modula3_cpp: $(SRCDIR_SRCS) $(SWIG) -modula3 -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) @@ -848,7 +848,7 @@ mzscheme: $(SRCDIR_SRCS) mzscheme_cpp: $(SRCDIR_SRCS) $(SWIG) -mzscheme -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) $(COMPILETOOL) $(MZC) `echo $(INCLUDES) | sed 's/-I/++ccf -I/g'` --cc $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) - $(CXXSHARED) $(CXXFLAGS) -o $(LIBPREFIX)$(TARGET)$(MZSCHEME_SO) $(OBJS) $(IOBJS) $(MZDYNOBJ) $(CPP_DLLIBS) + $(CXXSHARED) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) -o $(LIBPREFIX)$(TARGET)$(MZSCHEME_SO) $(OBJS) $(IOBJS) $(MZDYNOBJ) $(CPP_DLLIBS) # ----------------------------------------------------------------- # Run mzscheme example @@ -913,7 +913,7 @@ ocaml_dynamic: $(SRCDIR_SRCS) $(OCAMLCORE) $(SWIG) -ocaml $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) $(OCC) -g -c -ccopt -g -ccopt "$(INCLUDES)" $(ISRCS) $(SRCDIR_SRCS) - $(CXXSHARED) $(CXXFLAGS) $(CCSHARED) $(CFLAGS) -o $(INTERFACE:%.i=%@SO@) \ + $(CXXSHARED) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) $(CCSHARED) -o $(INTERFACE:%.i=%@SO@) \ $(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) $(LIBS) $(OCAMLDLGEN) $(INTERFACE:%.i=%.ml) $(INTERFACE:%.i=%@SO@) > \ $(INTERFACE:%.i=%_dynamic.ml) @@ -984,7 +984,7 @@ ocaml_dynamic_cpp: $(SRCDIR_SRCS) cp $(ICXXSRCS) $(ICXXSRCS:%.cxx=%.c) $(OCC) -cc '$(CXX) -Wno-write-strings' -g -c -ccopt -g -ccopt "-xc++ $(INCLUDES)" \ $(ICXXSRCS:%.cxx=%.c) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) -ccopt -fPIC - $(CXXSHARED) $(CXXFLAGS) -o $(INTERFACE:%.i=%@SO@) \ + $(CXXSHARED) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) -o $(INTERFACE:%.i=%@SO@) \ $(INTERFACE:%.i=%_wrap.@OBJEXT@) $(OBJS) \ $(CPP_DLLIBS) $(LIBS) $(OCAMLDLGEN) $(INTERFACE:%.i=%.ml) $(INTERFACE:%.i=%@SO@) > \ @@ -1045,8 +1045,8 @@ RUBY_SCRIPT = $(SRCDIR)$(RUNME).rb ruby: $(SRCDIR_SRCS) $(SWIG) -ruby $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(RUBY_CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(RUBY_INCLUDE) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(RUBY_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(RUBY_SO) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(RUBY_CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(RUBY_INCLUDE) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(RUBY_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(RUBY_SO) # ----------------------------------------------------------------- # Build a C++ dynamically loadable module @@ -1054,8 +1054,8 @@ ruby: $(SRCDIR_SRCS) ruby_cpp: $(SRCDIR_SRCS) $(SWIG) -c++ -ruby $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(RUBY_CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(RUBY_INCLUDE) - $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(RUBY_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(RUBY_SO) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(RUBY_CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(RUBY_INCLUDE) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(RUBY_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(RUBY_SO) # ----------------------------------------------------------------- # Build statically linked Ruby interpreter @@ -1066,12 +1066,12 @@ ruby_cpp: $(SRCDIR_SRCS) ruby_static: $(SRCDIR_SRCS) $(SWIG) -ruby -lembed.i $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - $(CC) $(CFLAGS) $(RUBY_CFLAGS) @LINKFORSHARED@ $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) \ + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) $(RUBY_CFLAGS) @LINKFORSHARED@ $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) \ $(RUBY_INCLUDE) $(LIBS) -L$(RUBY_LIB) $(RUBY_LIBOPTS) -o $(TARGET) ruby_cpp_static: $(SRCDIR_SRCS) $(SWIG) -c++ -ruby -lembed.i $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) $(CXXFLAGS) $(RUBY_CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) \ + $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) $(RUBY_CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) \ $(RUBY_INCLUDE) $(LIBS) -L$(RUBY_LIB) $(RUBY_LIBOPTS) -o $(TARGET) # ----------------------------------------------------------------- @@ -1112,8 +1112,8 @@ PHP_SCRIPT = $(SRCDIR)$(RUNME).php php: $(SRCDIR_SRCS) $(SWIG) -php $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(PHP_INCLUDE) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(PHP_SO) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(PHP_INCLUDE) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(PHP_SO) # -------------------------------------------------------------------- # Build a PHP dynamically loadable module (C++) @@ -1121,8 +1121,8 @@ php: $(SRCDIR_SRCS) php_cpp: $(SRCDIR_SRCS) $(SWIG) -php -cppext cxx -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(PHP_INCLUDE) - $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(PHP_SO) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(PHP_INCLUDE) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(PHP_SO) # ----------------------------------------------------------------- # Running a PHP example @@ -1166,8 +1166,8 @@ PIKE_SCRIPT = $(RUNME).pike pike: $(SRCDIR_SRCS) $(SWIG) -pike $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(PIKE_CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(PIKE_INCLUDE) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(PIKE_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(PIKE_CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(PIKE_INCLUDE) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(PIKE_DLNK) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- # Build a C++ dynamically loadable module @@ -1175,8 +1175,8 @@ pike: $(SRCDIR_SRCS) pike_cpp: $(SRCDIR_SRCS) $(SWIG) -c++ -pike $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(PIKE_CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(PIKE_INCLUDE) - $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(PIKE_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(PIKE_CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(PIKE_INCLUDE) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(PIKE_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- # Build statically linked Pike interpreter @@ -1187,12 +1187,12 @@ pike_cpp: $(SRCDIR_SRCS) pike_static: $(SRCDIR_SRCS) $(SWIG) -pike -lembed.i $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - $(CC) $(CFLAGS) $(PIKE_CFLAGS) @LINKFORSHARED@ $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) \ + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) $(PIKE_CFLAGS) @LINKFORSHARED@ $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) \ $(PIKE_INCLUDE) $(LIBS) -L$(PIKE_LIB) $(PIKE_LIBOPTS) -o $(TARGET) pike_cpp_static: $(SRCDIR_SRCS) $(SWIG) -c++ -pike -lembed.i $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) $(CXXFLAGS) $(PIKE_CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) \ + $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) $(PIKE_CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) \ $(PIKE_INCLUDE) $(LIBS) -L$(PIKE_LIB) $(PIKE_LIBOPTS) -o $(TARGET) # ----------------------------------------------------------------- @@ -1253,9 +1253,9 @@ chicken_direct: $(SRCDIR_SRCS) $(CHICKEN) $(CHICKEN_GENERATED_SCHEME) $(CHICKENOPTS) \ -dynamic -feature chicken-compile-shared \ -output-file $(CHICKEN_COMPILED_SCHEME) - $(CC) -c $(CCSHARED) $(CFLAGS) $(CHICKEN_CFLAGS) \ + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(CHICKEN_CFLAGS) \ $(INCLUDES) $(CHICKEN_INCLUDE) $(ISRCS) $(SRCDIR_SRCS) $(CHICKEN_COMPILED_SCHEME) - $(LDSHARED) $(CFLAGS) $(CHICKEN_COMPILED_OBJECT) $(OBJS) $(IOBJS) \ + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(CHICKEN_COMPILED_OBJECT) $(OBJS) $(IOBJS) \ $(LIBS) $(CHICKEN_SHAREDLIBOPTS) -o $(LIBPREFIX)$(TARGET)$(SO) chicken_direct_cpp: $(SRCDIR_CXXSRCS) $(CHICKSRCS) @@ -1263,9 +1263,9 @@ chicken_direct_cpp: $(SRCDIR_CXXSRCS) $(CHICKSRCS) $(CHICKEN) $(CHICKEN_GENERATED_SCHEME) $(CHICKENOPTS) \ -dynamic -feature chicken-compile-shared \ -output-file $(CHICKEN_COMPILED_SCHEME) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(CHICKEN_CFLAGS) \ + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(CHICKEN_CFLAGS) \ $(INCLUDES) $(CHICKEN_INCLUDE) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(CHICKEN_COMPILED_SCHEME) - $(CXXSHARED) $(CXXFLAGS) $(CHICKEN_COMPILED_OBJECT) $(OBJS) $(IOBJS) \ + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(CHICKEN_COMPILED_OBJECT) $(OBJS) $(IOBJS) \ $(LIBS) $(CPP_DLLIBS) $(CHICKEN_SHAREDLIBOPTS) -o $(LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- @@ -1279,10 +1279,10 @@ chicken_static: $(SRCDIR_SRCS) $(CHICKSRCS) -output-file $(CHICKEN_COMPILED_SCHEME) $(CHICKEN) $(CHICKEN_MAIN) $(CHICKENOPTS) \ -output-file $(CHICKEN_MAIN:.scm=_chicken.c) - $(CC) -c $(CCSHARED) $(CFLAGS) $(CHICKEN_CFLAGS) \ + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(CHICKEN_CFLAGS) \ $(INCLUDES) $(CHICKEN_INCLUDE) $(ISRCS) $(SRCDIR_SRCS) \ $(CHICKEN_COMPILED_SCHEME) $(CHICKEN_COMPILED_MAIN) - $(CC) $(CHICKEN_COMPILED_OBJECT) $(CHICKEN_COMPILED_MAIN_OBJECT) \ + $(CC) $(CFLAGS) $(LDFLAGS) $(CHICKEN_COMPILED_OBJECT) $(CHICKEN_COMPILED_MAIN_OBJECT) \ $(OBJS) $(IOBJS) $(LIBS) $(CHICKEN_SHAREDLIBOPTS) -o $(TARGET) chicken_static_cpp: $(SRCDIR_CXXSRCS) $(CHICKSRCS) @@ -1291,10 +1291,10 @@ chicken_static_cpp: $(SRCDIR_CXXSRCS) $(CHICKSRCS) -output-file $(CHICKEN_COMPILED_SCHEME) $(CHICKEN) $(CHICKEN_MAIN) $(CHICKENOPTS) \ -output-file $(CHICKEN_MAIN:.scm=_chicken.c) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(CHICKEN_CFLAGS) \ + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(CHICKEN_CFLAGS) \ $(INCLUDES) $(CHICKEN_INCLUDE) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) \ $(CHICKEN_COMPILED_SCHEME) $(CHICKEN_COMPILED_MAIN) - $(CXX) $(CHICKEN_COMPILED_OBJECT) $(CHICKEN_COMPILED_MAIN_OBJECT) \ + $(CXX) $(CXXFLAGS) $(LDFLAGS) $(CHICKEN_COMPILED_OBJECT) $(CHICKEN_COMPILED_MAIN_OBJECT) \ $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) $(CHICKEN_SHAREDLIBOPTS) -o $(TARGET) # ---------------------------------------------------------------- @@ -1355,8 +1355,8 @@ CSHARP_RUNME = $(CSHARPCILINTERPRETER) $(CSHARPCILINTERPRETER_FLAGS) ./$(RUNME). csharp: $(SRCDIR_SRCS) $(SWIG) -csharp $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(CSHARPCFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(CSHARP_DLNK) $(LIBS) -o $(CSHARP_LIBPREFIX)$(TARGET)$(CSHARPSO) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(CSHARPCFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(CSHARP_DLNK) $(LIBS) -o $(CSHARP_LIBPREFIX)$(TARGET)$(CSHARPSO) # ---------------------------------------------------------------- # Build a CSharp dynamically loadable module (C++) @@ -1364,8 +1364,8 @@ csharp: $(SRCDIR_SRCS) csharp_cpp: $(SRCDIR_SRCS) $(SWIG) -csharp -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(CSHARPCFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) - $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(CSHARP_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(CSHARP_LIBPREFIX)$(TARGET)$(CSHARPSO) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(CSHARPCFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(CSHARP_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(CSHARP_LIBPREFIX)$(TARGET)$(CSHARPSO) # ---------------------------------------------------------------- # Compile CSharp files @@ -1428,8 +1428,8 @@ LUA_INTERP = ../lua.c lua: $(SRCDIR_SRCS) $(SWIG) -lua $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(LUA_INCLUDE) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(LUA_LIB) -o $(LIBPREFIX)$(TARGET)$(LUA_SO) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(LUA_INCLUDE) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(LUA_LIB) -o $(LIBPREFIX)$(TARGET)$(LUA_SO) # ----------------------------------------------------------------- # Build a C++ dynamically loadable module @@ -1437,8 +1437,8 @@ lua: $(SRCDIR_SRCS) lua_cpp: $(SRCDIR_SRCS) $(GENCXXSRCS) $(SWIG) -c++ -lua $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(GENCXXSRCS) $(INCLUDES) $(LUA_INCLUDE) - $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(LUA_LIB) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(LUA_SO) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(GENCXXSRCS) $(INCLUDES) $(LUA_INCLUDE) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(LUA_LIB) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(LUA_SO) # ----------------------------------------------------------------- # Build statically linked Lua interpreter @@ -1446,12 +1446,12 @@ lua_cpp: $(SRCDIR_SRCS) $(GENCXXSRCS) lua_static: $(SRCDIR_SRCS) $(SWIG) -lua -module example $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - $(CC) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(SRCDIR)$(LUA_INTERP) $(INCLUDES) \ + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(SRCDIR)$(LUA_INTERP) $(INCLUDES) \ $(LUA_INCLUDE) $(LIBS) $(LUA_LIB) -o $(TARGET) lua_static_cpp: $(SRCDIR_SRCS) $(GENCXXSRCS) $(SWIG) -c++ -lua -module example $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(GENCXXSRCS) $(SRCDIR)$(LUA_INTERP) $(INCLUDES) \ + $(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(GENCXXSRCS) $(SRCDIR)$(LUA_INTERP) $(INCLUDES) \ $(LUA_INCLUDE) $(LIBS) $(LUA_LIB) -o $(TARGET) # ----------------------------------------------------------------- @@ -1489,13 +1489,13 @@ ALLEGROCL_SCRIPT=$(RUNME).lisp allegrocl: $(SRCDIR_SRCS) $(SWIG) -allegrocl -cwrap $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCDIR_SRCS) - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCDIR_SRCS) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) allegrocl_cpp: $(SRCDIR_SRCS) $(SWIG) -c++ -allegrocl $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) - $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- # Run ALLEGRO CL example @@ -1565,13 +1565,13 @@ CFFI_SCRIPT=$(RUNME).lisp cffi: $(SRCDIR_SRCS) $(SWIG) -cffi $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) -# $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCDIR_SRCS) -# $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) +# $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCDIR_SRCS) +# $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) cffi_cpp: $(SRCDIR_SRCS) $(SWIG) -c++ -cffi $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) - $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- # Run CFFI example @@ -1605,13 +1605,13 @@ UFFI_SCRIPT=$(RUNME).lisp uffi: $(SRCDIR_SRCS) $(SWIG) -uffi $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) -# $(CC) -c $(CCSHARED) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCDIR_SRCS) -# $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) +# $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ISRCS) $(INCLUDES) $(SRCDIR_SRCS) +# $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) uffi_cpp: $(SRCDIR_SRCS) $(SWIG) -c++ -uffi $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) -# $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) -# $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) +# $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) +# $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- # Run UFFI example @@ -1657,7 +1657,7 @@ R_SCRIPT=$(RUNME).R r: $(SRCDIR_SRCS) $(SWIG) -r $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) ifneq ($(SRCDIR_SRCS),) - $(CC) -g -c $(CFLAGS) $(R_CFLAGS) $(SRCDIR_SRCS) $(INCLUDES) + $(CC) -g -c $(CPPFLAGS) $(CFLAGS) $(R_CFLAGS) $(SRCDIR_SRCS) $(INCLUDES) endif +( PKG_CPPFLAGS="$(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(ISRCS) $(OBJS) > /dev/null ) @@ -1668,7 +1668,7 @@ endif r_cpp: $(SRCDIR_CXXSRCS) $(SWIG) -c++ -r $(SWIGOPT) -o $(RCXXSRCS) $(INTERFACEPATH) ifneq ($(SRCDIR_CXXSRCS),) - $(CXX) -g -c $(CXXFLAGS) $(R_CFLAGS) $(SRCDIR_CXXSRCS) $(INCLUDES) + $(CXX) -g -c $(CPPFLAGS) $(CXXFLAGS) $(R_CFLAGS) $(SRCDIR_CXXSRCS) $(INCLUDES) endif +( PKG_CPPFLAGS="$(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(RCXXSRCS) $(OBJS) > /dev/null ) @@ -1732,10 +1732,10 @@ GOGCCOBJS = $(GOSRCS:.go=.@OBJEXT@) go: $(SRCDIR_SRCS) $(SWIG) -go $(GOOPT) $(GOSWIGARG) $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) if $(GO12) || $(GO13) || $(GOGCC); then \ - $(CC) -g -c $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES); \ + $(CC) -g -c $(CPPFLAGS) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES); \ else \ - $(CC) -g -c $(CCSHARED) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES); \ - $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO); \ + $(CC) -g -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES); \ + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO); \ fi $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(GOSRCS) if ! $(GOGCC) ; then \ @@ -1755,7 +1755,7 @@ go: $(SRCDIR_SRCS) if $(GOGCC) ; then \ $(COMPILETOOL) $(GO) -o $(RUNME) $(RUNME).@OBJEXT@ $(GOGCCOBJS) $(OBJS) $(IOBJS); \ elif $(GO12) || $(GO13); then \ - $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld "$(CC)" -extldflags "$(CFLAGS)" -o $(RUNME) $(RUNME).$(GOOBJEXT); \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld "$(CC)" -extldflags "$(CFLAGS) $(LDFLAGS)" -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; \ @@ -1768,10 +1768,10 @@ go: $(SRCDIR_SRCS) go_cpp: $(SRCDIR_SRCS) $(SWIG) -go -c++ $(GOOPT) $(GOSWIGARG) $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) if $(GO12) || $(GO13) || $(GOGCC); then \ - $(CXX) -g -c $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES); \ + $(CXX) -g -c $(CPPFLAGS) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES); \ else \ - $(CXX) -g -c $(CCSHARED) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES); \ - $(CXXSHARED) $(CXXFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO); \ + $(CXX) -g -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES); \ + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO); \ fi $(COMPILETOOL) $(GO) $(GOCOMPILEARG) -I . $(GOSRCS) if ! $(GOGCC) ; then \ @@ -1791,7 +1791,7 @@ go_cpp: $(SRCDIR_SRCS) if $(GOGCC) ; then \ $(COMPILETOOL) $(GO) -o $(RUNME) $(RUNME).@OBJEXT@ $(GOGCCOBJS) $(OBJS) $(IOBJS) -lstdc++; \ elif $(GO12) || $(GO13); then \ - $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld "$(CXX)" -extldflags "$(CXXFLAGS)" -o $(RUNME) $(RUNME).$(GOOBJEXT); \ + $(COMPILETOOL) $(GOTOOL) $(GOLD) -linkmode external -extld "$(CXX)" -extldflags "$(CXXFLAGS) $(LDFLAGS)" -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; \ @@ -1846,8 +1846,8 @@ D_RUNME = ./$(RUNME) d: $(SRCDIR_SRCS) $(SWIGD) $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - $(CC) -c $(CCSHARED) $(CFLAGS) $(DCFLAGS) $(EXTRA_CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) - $(LDSHARED) $(CFLAGS) $(DCFLAGS) $(EXTRA_LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(DLIBPREFIX)$(TARGET)$(SO) + $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(DCFLAGS) $(EXTRA_CFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) + $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(DCFLAGS) $(EXTRA_LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) -o $(DLIBPREFIX)$(TARGET)$(SO) # ---------------------------------------------------------------- # Build a dynamically loadable D wrapper for a C++ module @@ -1855,8 +1855,8 @@ d: $(SRCDIR_SRCS) d_cpp: $(SRCDIR_SRCS) $(SWIGD) -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CXXFLAGS) $(DCFLAGS) $(EXTRA_CFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) - $(CXXSHARED) $(CXXFLAGS) $(DCFLAGS) $(EXTRA_LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(DLIBPREFIX)$(TARGET)$(SO) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(DCFLAGS) $(EXTRA_CFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(DCFLAGS) $(EXTRA_LDFLAGS) $(OBJS) $(IOBJS) $(LIBS) $(CPP_DLLIBS) -o $(DLIBPREFIX)$(TARGET)$(SO) # ---------------------------------------------------------------- # Compile D files diff --git a/Examples/chicken/class/Makefile b/Examples/chicken/class/Makefile index 5fafa5c15..a37ea4a85 100644 --- a/Examples/chicken/class/Makefile +++ b/Examples/chicken/class/Makefile @@ -6,7 +6,6 @@ CXXSRCS = example.cxx TARGET = class INCLUDE = SWIGOPT = -CFLAGS = VARIANT = # uncomment the following lines to build a static exe (only pick one of the CHICKEN_MAIN lines) diff --git a/Examples/chicken/constants/Makefile b/Examples/chicken/constants/Makefile index a6100f757..7167e866b 100644 --- a/Examples/chicken/constants/Makefile +++ b/Examples/chicken/constants/Makefile @@ -6,7 +6,6 @@ CXXSRCS = TARGET = constants INCLUDE = SWIGOPT = -CFLAGS = VARIANT = # uncomment the following two lines to build a static exe diff --git a/Examples/chicken/multimap/Makefile b/Examples/chicken/multimap/Makefile index 79282be17..e8192e9cd 100644 --- a/Examples/chicken/multimap/Makefile +++ b/Examples/chicken/multimap/Makefile @@ -6,7 +6,6 @@ CXXSRCS = TARGET = multimap INCLUDE = SWIGOPT = -CFLAGS = VARIANT = # uncomment the following two lines to build a static exe diff --git a/Examples/chicken/overload/Makefile b/Examples/chicken/overload/Makefile index 717abd335..a9647d93e 100644 --- a/Examples/chicken/overload/Makefile +++ b/Examples/chicken/overload/Makefile @@ -6,7 +6,6 @@ CXXSRCS = example.cxx TARGET = overload INCLUDE = SWIGOPT = -proxy -unhideprimitive -CFLAGS = VARIANT = # uncomment the following lines to build a static exe diff --git a/Examples/chicken/simple/Makefile b/Examples/chicken/simple/Makefile index 9d1f34fa0..c07075efa 100644 --- a/Examples/chicken/simple/Makefile +++ b/Examples/chicken/simple/Makefile @@ -6,7 +6,6 @@ CXXSRCS = TARGET = simple INCLUDE = SWIGOPT = -CFLAGS = VARIANT = # uncomment the following two lines to build a static exe diff --git a/Tools/javascript/Makefile.in b/Tools/javascript/Makefile.in index d5c4711a0..960c661b2 100644 --- a/Tools/javascript/Makefile.in +++ b/Tools/javascript/Makefile.in @@ -16,9 +16,11 @@ all: javascript CC = @CC@ # HACK: under OSX a g++ compiled interpreter is seg-faulting when loading module libraries # with 'c++' it works... probably some missing flags? -JSCXX = @JSINTERPRETERCXX@ +JSCXX = @JSINTERPRETERCXX@ +CPPFLAGS = @BOOST_CPPFLAGS@ CFLAGS = @PLATCFLAGS@ -CXXFLAGS = @BOOST_CPPFLAGS@ @PLATCXXFLAGS@ +CXXFLAGS = @PLATCXXFLAGS@ +LDFLAGS = LINKFLAGS = @JSINTERPRETERLINKFLAGS@ ROOT_DIR = @ROOT_DIR@ @@ -54,10 +56,10 @@ JS_INTERPRETER_SRC = javascript.cxx js_shell.cxx $(JS_INTERPRETER_SRC_JSC) $(JS_ JS_INTERPRETER_OBJS = $(JS_INTERPRETER_SRC:.cxx=.o) %.o: $(srcdir)/%.cxx - $(JSCXX) $(JS_INTERPRETER_DEFINES) $(CXXFLAGS) $(JSINCLUDES) -o $@ -c $< + $(JSCXX) $(JS_INTERPRETER_DEFINES) $(CPPFLAGS) $(CXXFLAGS) $(JSINCLUDES) -o $@ -c $< javascript: $(JS_INTERPRETER_OBJS) - $(JSCXX) $^ $(CXXFLAGS) -o javascript $(JSDYNAMICLINKING) $(LINKFLAGS) + $(JSCXX) $^ $(CXXFLAGS) $(LDFLAGS) -o javascript $(JSDYNAMICLINKING) $(LINKFLAGS) clean: rm -f *.o From ce5f49463e98fe2825e87f1b1f76e6602f32f4f0 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 15 May 2014 20:50:05 +0100 Subject: [PATCH 0936/1048] Remove duplicate test target in CCache Makefile --- CCache/Makefile.in | 2 -- 1 file changed, 2 deletions(-) diff --git a/CCache/Makefile.in b/CCache/Makefile.in index ae77ae745..6703e2ac0 100644 --- a/CCache/Makefile.in +++ b/CCache/Makefile.in @@ -59,8 +59,6 @@ uninstall: $(PACKAGE_NAME)$(EXEEXT) $(PACKAGE_NAME).1 clean: /bin/rm -f $(OBJS) *~ $(PACKAGE_NAME)$(EXEEXT) -check : test - test: test.sh SWIG_LIB='$(SWIG_LIB)' PATH=../..:$$PATH SWIG='$(SWIG)' CC='$(CC)' NOSOFTLINKSTEST='$(NOSOFTLINKSTEST)' $(srcdir)/test.sh From 8ece62b9457a6b61de544c6885772d3bc8150299 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 15 May 2014 22:04:54 +0100 Subject: [PATCH 0937/1048] Neaten up test-suite Makefile regeneration --- Examples/test-suite/common.mk | 5 +---- Examples/test-suite/errors/Makefile.in | 7 ++----- 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index d93d788c9..ef697b131 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -74,11 +74,8 @@ SRCDIR = $(srcdir)/ SCRIPTDIR = $(srcdir) # Regenerate Makefile if Makefile.in or config.status have changed. -ifeq (,$(TEST_SUITE_SUBDIR)) -TEST_SUITE_SUBDIR = $(LANGUAGE) -endif Makefile: $(srcdir)/Makefile.in ../../../config.status - cd ../../../ && $(SHELL) ./config.status $(EXAMPLES)/$(TEST_SUITE)/$(TEST_SUITE_SUBDIR)/Makefile + cd ../../../ && $(SHELL) ./config.status $(EXAMPLES)/$(TEST_SUITE)/$(LANGUAGE)/Makefile # # Please keep test cases in alphabetical order. diff --git a/Examples/test-suite/errors/Makefile.in b/Examples/test-suite/errors/Makefile.in index 9ca6f6ecd..da67db8bd 100644 --- a/Examples/test-suite/errors/Makefile.in +++ b/Examples/test-suite/errors/Makefile.in @@ -13,7 +13,7 @@ # file (.stderr) in addition to the test case itself. ####################################################################### -LANGUAGE = python +LANGUAGE = errors ERROR_EXT = newerr # Portable dos2unix / todos for stripping CR TODOS = tr -d '\r' @@ -35,9 +35,6 @@ C_ERROR_TEST_CASES := $(filter-out $(CPP_ERROR_TEST_CASES), $(ALL_ERROR_TEST_CAS ERROR_TEST_CASES := $(CPP_ERROR_TEST_CASES:=.cpptest) \ $(C_ERROR_TEST_CASES:=.ctest) -# For rebuilding Makefile from Makefile.in in common.mk -TEST_SUITE_SUBDIR = errors - include $(srcdir)/../common.mk @@ -56,5 +53,5 @@ include $(srcdir)/../common.mk @exit 0 clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile $(LANGUAGE)_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile python_clean @rm -f *.$(ERROR_EXT) *.py From 61818533129e7d88124e00c69b81088f060b4b39 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Wed, 14 May 2014 00:36:38 +0100 Subject: [PATCH 0938/1048] Fix out of source clean-android-examples --- Examples/Makefile.in | 2 +- Examples/android/class/Makefile | 2 +- Examples/android/extend/Makefile | 2 +- Examples/android/simple/Makefile | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 7c2d23647..c47c075e9 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -782,7 +782,7 @@ android_version: # ----------------------------------------------------------------- android_clean: - ant -q -logfile /dev/null clean + cd $(SRCDIR) && ant -q -logfile /dev/null clean rm -f $(INTERFACEDIR)$(TARGET)_wrap.* rm -f `find $(PACKAGEDIR) -name \*.java | grep -v $(PROJECTNAME).java` rm -rf obj diff --git a/Examples/android/class/Makefile b/Examples/android/class/Makefile index 44d33de0a..574566623 100644 --- a/Examples/android/class/Makefile +++ b/Examples/android/class/Makefile @@ -3,7 +3,7 @@ SWIG = $(TOP)/../preinst-swig TARGET = example INTERFACE = example.i INTERFACEDIR = jni/ -PACKAGEDIR = src/org/swig +PACKAGEDIR = $(SRCDIR)src/org/swig PACKAGENAME= org.swig.classexample SWIGOPT = -package $(PACKAGENAME) -outdir $(PACKAGEDIR)/classexample PROJECTNAME= SwigClass diff --git a/Examples/android/extend/Makefile b/Examples/android/extend/Makefile index 3d0609a08..fb974d22c 100644 --- a/Examples/android/extend/Makefile +++ b/Examples/android/extend/Makefile @@ -3,7 +3,7 @@ SWIG = $(TOP)/../preinst-swig TARGET = example INTERFACE = example.i INTERFACEDIR = jni/ -PACKAGEDIR = src/org/swig +PACKAGEDIR = $(SRCDIR)src/org/swig PACKAGENAME= org.swig.extendexample SWIGOPT = -package $(PACKAGENAME) -outdir $(PACKAGEDIR)/extendexample PROJECTNAME= SwigExtend diff --git a/Examples/android/simple/Makefile b/Examples/android/simple/Makefile index d71b9880c..2bf41968a 100644 --- a/Examples/android/simple/Makefile +++ b/Examples/android/simple/Makefile @@ -3,7 +3,7 @@ SWIG = $(TOP)/../preinst-swig TARGET = example INTERFACE = example.i INTERFACEDIR = jni/ -PACKAGEDIR = src/org/swig +PACKAGEDIR = $(SRCDIR)src/org/swig PACKAGENAME= org.swig.simple SWIGOPT = -package $(PACKAGENAME) -outdir $(PACKAGEDIR)/simple PROJECTNAME= SwigSimple From 81335c5a91f134c3bbd32ecf7c7fa299f356b4f2 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 15 May 2014 23:27:26 +0100 Subject: [PATCH 0939/1048] Configured languages display improvement --- configure.ac | 53 ++++++++++++++++++++++++---------------------------- 1 file changed, 24 insertions(+), 29 deletions(-) diff --git a/configure.ac b/configure.ac index 949986341..e2cbe9fca 100644 --- a/configure.ac +++ b/configure.ac @@ -2715,38 +2715,33 @@ EOF AC_OUTPUT langs="" -test -n "$SKIP_ALLEGROCL" || langs="$langs allegrocl" -test -n "$SKIP_CFFI" || langs="$langs cffi" -test -n "$SKIP_CHICKEN" || langs="$langs chicken" -test -n "$SKIP_CLISP" || langs="$langs clisp" -test -n "$SKIP_CSHARP" || langs="$langs csharp" -test -n "$SKIP_D" || langs="$langs d" -test -n "$SKIP_GO" || langs="$langs go" -test -n "$SKIP_GUILE" || langs="$langs guile" -test -n "$SKIP_JAVA" || langs="$langs java" -test -n "$SKIP_JAVASCRIPT" || langs="$langs javascript" -test -n "$SKIP_LUA" || langs="$langs lua" -test -n "$SKIP_MODULA3" || langs="$langs modula3" -test -n "$SKIP_MZSCHEME" || langs="$langs mzscheme" -test -n "$SKIP_OCAML" || langs="$langs ocaml" -test -n "$SKIP_OCTAVE" || langs="$langs octave" -test -n "$SKIP_PERL5" || langs="$langs perl5" -test -n "$SKIP_PHP" || langs="$langs php" -test -n "$SKIP_PIKE" || langs="$langs pike" -test -n "$SKIP_PYTHON" || langs="$langs python" -test -n "$SKIP_R" || langs="$langs r" -test -n "$SKIP_RUBY" || langs="$langs ruby" -test -n "$SKIP_TCL" || langs="$langs tcl" -test -n "$SKIP_UFFI" || langs="$langs uffi" +test -n "$SKIP_ALLEGROCL" || langs="${langs}allegrocl " +test -n "$SKIP_CFFI" || langs="${langs}cffi " +test -n "$SKIP_CHICKEN" || langs="${langs}chicken " +test -n "$SKIP_CLISP" || langs="${langs}clisp " +test -n "$SKIP_CSHARP" || langs="${langs}csharp " +test -n "$SKIP_D" || langs="${langs}d " +test -n "$SKIP_GO" || langs="${langs}go " +test -n "$SKIP_GUILE" || langs="${langs}guile " +test -n "$SKIP_JAVA" || langs="${langs}java " +test -n "$SKIP_JAVASCRIPT" || langs="${langs}javascript " +test -n "$SKIP_LUA" || langs="${langs}lua " +test -n "$SKIP_MODULA3" || langs="${langs}modula3 " +test -n "$SKIP_MZSCHEME" || langs="${langs}mzscheme " +test -n "$SKIP_OCAML" || langs="${langs}ocaml " +test -n "$SKIP_OCTAVE" || langs="${langs}octave " +test -n "$SKIP_PERL5" || langs="${langs}perl5 " +test -n "$SKIP_PHP" || langs="${langs}php " +test -n "$SKIP_PIKE" || langs="${langs}pike " +test -n "$SKIP_PYTHON" || langs="${langs}python " +test -n "$SKIP_R" || langs="${langs}r " +test -n "$SKIP_RUBY" || langs="${langs}ruby " +test -n "$SKIP_TCL" || langs="${langs}tcl " +test -n "$SKIP_UFFI" || langs="${langs}uffi " echo " -======================================================== - -SWIG is configured for use with the following languages: - +The SWIG test-suite and examples are configured for the following languages: $langs - -======================================================== " dnl configure.ac ends here From 2e0f6a21639f3a658126d49eb0e998a3f7b81a14 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 15 May 2014 23:55:36 +0100 Subject: [PATCH 0940/1048] Travis testing - add folding to less interesting commands See https://github.com/travis-ci/travis-ci/issues/2285 for fold syntax info. --- .travis.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.travis.yml b/.travis.yml index 26cb18910..95e433952 100644 --- a/.travis.yml +++ b/.travis.yml @@ -68,16 +68,22 @@ before_install: - if test "$SWIGLANG" = "python" -a "$VER"; then sudo add-apt-repository -y ppa:fkrull/deadsnakes && sudo apt-get -qq update && sudo apt-get -qq install python${VER}-dev && export CONFIGOPTS="--with-python${PY3}=python${VER}"; fi - if test "$SWIGLANG" = "tcl"; then sudo apt-get -qq install tcl8.4-dev; fi script: + - echo 'Configuring...' && echo -en 'travis_fold:start:script.1\\r' - ./autogen.sh && ./configure $CONFIGOPTS + - echo -en 'travis_fold:end:script.1\\r' - make -s $SWIGJOBS - ./swig -version && ./swig -pcreversion - if test -z "$SWIGLANG"; then make -s $SWIGJOBS check-ccache; fi - if test -z "$SWIGLANG"; then make -s $SWIGJOBS check-errors-test-suite; fi + - echo 'Installing...' && echo -en 'travis_fold:start:script.1\\r' - if test -z "$SWIGLANG"; then sudo make -s install && swig -version && ccache-swig -V; fi + - echo -en 'travis_fold:end:script.2\\r' - 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 + - echo -n 'Cleaning...' && echo -en 'travis_fold:start:script.3\\r' - make maintainer-clean + - echo -en 'travis_fold:end:script.3\\r' branches: only: - master From 3b0a549d72fc47616c62d28abeb9d3aafab0fbc0 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 16 May 2014 06:11:39 +0100 Subject: [PATCH 0941/1048] Travis folding correction --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 95e433952..5d42d3ac5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -75,7 +75,7 @@ script: - ./swig -version && ./swig -pcreversion - if test -z "$SWIGLANG"; then make -s $SWIGJOBS check-ccache; fi - if test -z "$SWIGLANG"; then make -s $SWIGJOBS check-errors-test-suite; fi - - echo 'Installing...' && echo -en 'travis_fold:start:script.1\\r' + - echo 'Installing...' && echo -en 'travis_fold:start:script.2\\r' - if test -z "$SWIGLANG"; then sudo make -s install && swig -version && ccache-swig -V; fi - echo -en 'travis_fold:end:script.2\\r' - if test -n "$SWIGLANG"; then make -s check-$SWIGLANG-version; fi From 06d2c79c2869b709fd6ea3bb646051319bf79e7a Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 16 May 2014 06:50:37 +0100 Subject: [PATCH 0942/1048] Another Travis folding correction --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 5d42d3ac5..a7a16f5fd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -81,7 +81,7 @@ script: - 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 - - echo -n 'Cleaning...' && echo -en 'travis_fold:start:script.3\\r' + - echo 'Cleaning...' && echo -en 'travis_fold:start:script.3\\r' - make maintainer-clean - echo -en 'travis_fold:end:script.3\\r' branches: From 17abb00f2046bd4b52010bb6e0235cb5e13ffbd8 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 16 May 2014 06:55:11 +0100 Subject: [PATCH 0943/1048] Modify Travis builds to build out of source Closes #167 --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index a7a16f5fd..1e7d9c657 100644 --- a/.travis.yml +++ b/.travis.yml @@ -69,7 +69,7 @@ before_install: - if test "$SWIGLANG" = "tcl"; then sudo apt-get -qq install tcl8.4-dev; fi script: - echo 'Configuring...' && echo -en 'travis_fold:start:script.1\\r' - - ./autogen.sh && ./configure $CONFIGOPTS + - ./autogen.sh && mkdir -p build/build && cd build/build && ../../configure $CONFIGOPTS - echo -en 'travis_fold:end:script.1\\r' - make -s $SWIGJOBS - ./swig -version && ./swig -pcreversion From 8b19918a83d0a83c1b212fb1deedae4b965b6595 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 16 May 2014 08:02:11 +0100 Subject: [PATCH 0944/1048] Travis builds - add compiler version display --- .travis.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 1e7d9c657..da5929e1e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -50,8 +50,8 @@ matrix: # None before_install: - date -u - - lsb_release -a - uname -a + - lsb_release -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 @@ -67,6 +67,8 @@ before_install: - if test "$SWIGLANG" = "python" -a "$PY3" -a -z "$VER"; then sudo apt-get install -qq python3-dev; fi - if test "$SWIGLANG" = "python" -a "$VER"; then sudo add-apt-repository -y ppa:fkrull/deadsnakes && sudo apt-get -qq update && sudo apt-get -qq install python${VER}-dev && export CONFIGOPTS="--with-python${PY3}=python${VER}"; fi - if test "$SWIGLANG" = "tcl"; then sudo apt-get -qq install tcl8.4-dev; fi + - $CC --version + - $CXX --version script: - echo 'Configuring...' && echo -en 'travis_fold:start:script.1\\r' - ./autogen.sh && mkdir -p build/build && cd build/build && ../../configure $CONFIGOPTS From 50f5b4f7f448e79d7460a14795d752a74b60eaaf Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 16 May 2014 20:46:35 +0100 Subject: [PATCH 0945/1048] Fix in source android examples clean --- Examples/Makefile.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index c47c075e9..954a41c07 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -782,7 +782,7 @@ android_version: # ----------------------------------------------------------------- android_clean: - cd $(SRCDIR) && ant -q -logfile /dev/null clean + test -n "$(SRCDIR)" && cd $(SRCDIR) ; ant -q -logfile /dev/null clean rm -f $(INTERFACEDIR)$(TARGET)_wrap.* rm -f `find $(PACKAGEDIR) -name \*.java | grep -v $(PROJECTNAME).java` rm -rf obj From 46e5f722c337320807deeacc0e20c6a598390936 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 16 May 2014 21:08:06 +0100 Subject: [PATCH 0946/1048] Travis testing: check configure still runs after make maintainer-clean --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index da5929e1e..96e4fc9a7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -84,7 +84,7 @@ script: - 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 - echo 'Cleaning...' && echo -en 'travis_fold:start:script.3\\r' - - make maintainer-clean + - make maintainer-clean && ../../configure $CONFIGOPTS - echo -en 'travis_fold:end:script.3\\r' branches: only: From b8b61be301a40521c2908e0236f04369e71749d3 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 17 May 2014 23:32:09 +0100 Subject: [PATCH 0947/1048] Detect Javascript v8 on 64 bit Linux --- configure.ac | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/configure.ac b/configure.ac index e2cbe9fca..2ff5dc8db 100644 --- a/configure.ac +++ b/configure.ac @@ -1259,7 +1259,7 @@ else AC_MSG_CHECKING(for V8 Javascript library) AC_ARG_WITH(jsv8lib,[ --with-v8lib=path Set location of V8 Javascript library directory],[JSV8LIBDIR="$withval"], [JSV8LIB=]) - v8libdirs="$JSV8LIBDIR /usr/lib/ /usr/local/lib/" + v8libdirs="$JSV8LIBDIR /usr/lib*/ /usr/local/lib*/" for d in $v8libdirs ; do if test -r $d/libv8.so; then JSV8LIBDIR=$d From ac89f7f7854907f8b45b42ef1f447234d5eb1c64 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 18 May 2014 00:59:47 +0100 Subject: [PATCH 0948/1048] Javascript examples tidy up - Remove empty files - Improve clean --- .gitignore | 11 +++++++---- Examples/Makefile.in | 3 ++- Examples/javascript/functor/Makefile | 2 +- Examples/javascript/functor/binding.gyp.in | 2 +- Examples/javascript/functor/example.cxx | 0 Examples/javascript/pointer/typemaps.i | 0 Examples/test-suite/javascript/Makefile.in | 9 +++------ 7 files changed, 14 insertions(+), 13 deletions(-) delete mode 100644 Examples/javascript/functor/example.cxx delete mode 100644 Examples/javascript/pointer/typemaps.i diff --git a/.gitignore b/.gitignore index efb6cf096..c7961efd7 100644 --- a/.gitignore +++ b/.gitignore @@ -124,16 +124,19 @@ Examples/test-suite/uffi/*/ *_wrap.c *_wrap.cxx +# C# generated files +*_runme.exe.mdb +*_runme.exe + +# Javascript generated files +*.gyp + # Python generated files, based on: # https://github.com/github/gitignore/blob/master/Python.gitignore *.py[cod] */__pycache__/ /__pycache__/ -# C# generated files -*_runme.exe.mdb -*_runme.exe - # Scratch directories Examples/scratch diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 954a41c07..b22fd2e76 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -730,7 +730,8 @@ javascript_clean: rm -f *_wrap* $(RUNME) rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *@JSSO@ *.$(SO) - (cd $(ROOT_DIR)/Tools/javascript && $(MAKE) -s clean) + rm -f binding.gyp + cd $(ROOT_DIR)/Tools/javascript && $(MAKE) -s clean ################################################################## ##### ANDROID ###### diff --git a/Examples/javascript/functor/Makefile b/Examples/javascript/functor/Makefile index 54a8f7b03..0402f8d09 100644 --- a/Examples/javascript/functor/Makefile +++ b/Examples/javascript/functor/Makefile @@ -1,3 +1,3 @@ -SRCS = example.cxx +SRCS = include $(SRCDIR)../example.mk diff --git a/Examples/javascript/functor/binding.gyp.in b/Examples/javascript/functor/binding.gyp.in index c56a650e9..59779aef4 100644 --- a/Examples/javascript/functor/binding.gyp.in +++ b/Examples/javascript/functor/binding.gyp.in @@ -2,7 +2,7 @@ "targets": [ { "target_name": "example", - "sources": [ "$srcdir/example.cxx", "example_wrap.cxx" ], + "sources": [ "example_wrap.cxx" ], "include_dirs": ["$srcdir"] } ] diff --git a/Examples/javascript/functor/example.cxx b/Examples/javascript/functor/example.cxx deleted file mode 100644 index e69de29bb..000000000 diff --git a/Examples/javascript/pointer/typemaps.i b/Examples/javascript/pointer/typemaps.i deleted file mode 100644 index e69de29bb..000000000 diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index 87e4c6ecb..fc5255155 100644 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -116,9 +116,6 @@ endif %.clean: rm -rf $* - -clean: - rm -f *_wrap.cxx - rm -f *_wrap.c - rm -f *.so - rm -f *.o + rm -f $*_wrap.* + rm -f $*.so + rm -f $*.o From 176c697c8b50856de8c2be99e1674c4a82c9f800 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 18 May 2014 01:06:56 +0100 Subject: [PATCH 0949/1048] Remove PHP director_basic runtime test until fixed. See #164 --- Examples/test-suite/php/director_basic_runme.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Examples/test-suite/php/director_basic_runme.php b/Examples/test-suite/php/director_basic_runme.php index de6b50502..1458725f1 100644 --- a/Examples/test-suite/php/director_basic_runme.php +++ b/Examples/test-suite/php/director_basic_runme.php @@ -3,6 +3,7 @@ require "tests.php"; require "director_basic.php"; +/* Removed until runtime error is fixed, see https://github.com/swig/swig/issues/164 // No new functions check::functions(array(foo_ping,foo_pong,foo_get_self,a_f,a_rg,a1_ff,myclass_method,myclass_vmethod,myclass_pmethod,myclass_cmethod,myclass_get_self,myclass_call_pmethod,myclasst_i_method)); // No new classes @@ -53,6 +54,7 @@ $cc->method($b); check::equal($bc->x, 34, "bc failed"); check::equal($bd->x, 16, "bd failed"); +*/ check::done(); ?> From 46cfdba5ca7c1385840005470ec433bef0ea8768 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 18 May 2014 01:36:29 +0100 Subject: [PATCH 0950/1048] Attempt to fix li_boost_intrusive_ptr C# compile error Using boost 1.36 and gcc-4.3.4 --- Examples/test-suite/li_boost_intrusive_ptr.i | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Examples/test-suite/li_boost_intrusive_ptr.i b/Examples/test-suite/li_boost_intrusive_ptr.i index 4916d0285..01613be0e 100644 --- a/Examples/test-suite/li_boost_intrusive_ptr.i +++ b/Examples/test-suite/li_boost_intrusive_ptr.i @@ -14,13 +14,13 @@ %warnfilter(SWIGWARN_LANG_SMARTPTR_MISSING) KlassDerivedDerived; %{ -template void intrusive_ptr_add_ref(const T* r) { r->addref(); } -template void intrusive_ptr_release(const T* r) { r->release(); } - #include #include #include +template void intrusive_ptr_add_ref(const T* r) { r->addref(); } +template void intrusive_ptr_release(const T* r) { r->release(); } + // Uncomment macro below to turn on intrusive_ptr memory leak checking as described above //#define INTRUSIVE_PTR_WRAPPER From def3c08943ea533102dbb2b4b7a64607516f5d3b Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Sun, 18 May 2014 20:20:30 +1200 Subject: [PATCH 0951/1048] Fix comment typos --- Examples/test-suite/lua/operator_overload_runme.lua | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Examples/test-suite/lua/operator_overload_runme.lua b/Examples/test-suite/lua/operator_overload_runme.lua index 5ba06ff08..c34c09021 100644 --- a/Examples/test-suite/lua/operator_overload_runme.lua +++ b/Examples/test-suite/lua/operator_overload_runme.lua @@ -1,4 +1,4 @@ --- demo of lua swig capacilities (operator overloading) +-- demo of lua swig capacities (operator overloading) require("import") -- the import fn import("operator_overload") -- import lib @@ -33,7 +33,7 @@ assert(b>=c) assert(b>d) assert(b>=d) --- lua does not support += operators: skiping +-- lua does not support += operators: skipping -- test + f=Op(1) @@ -50,7 +50,7 @@ assert(f/g==Op(1)) --lua 5.0.2 defines that unary - is __unm(self,nil) --lua 5.1.2 defines that unary - is __unm(self,self) ---C++ expectes unary - as operator-() +--C++ expects unary - as operator-() --however the latest version of SWIG strictly checks the number of args --and will complain if too many args are provided --therefore disabling these tests for now @@ -79,7 +79,7 @@ assert(tostring(Op(1))=="Op(1)") assert(tostring(Op(-3))=="Op(-3)") --- check that operator overloads are correctly propogated down inheritance hierarchy +-- check that operator overloads are correctly propagated down inheritance hierarchy a_d=OpDerived() b_d=OpDerived(5) From 95f09b49d2be5804501e5e1eafe3cf8f58ff3510 Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Sun, 18 May 2014 20:38:43 +1200 Subject: [PATCH 0952/1048] Don't use // comments in C code. --- Lib/lua/luarun.swg | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index d038f4af1..ad735a541 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -268,7 +268,7 @@ typedef struct swig_lua_class { swig_lua_method *methods; swig_lua_attribute *attributes; swig_lua_namespace *cls_static; - swig_lua_method *metatable; // 0 for -eluac + swig_lua_method *metatable; /* 0 for -eluac */ struct swig_lua_class **bases; const char **base_names; } swig_lua_class; @@ -1629,7 +1629,7 @@ SWIGINTERN void SWIG_Lua_elua_class_register_instance(lua_State *L, swig_lua_cla lua_pop(L,1); assert(lua_gettop(L) == begin); } -#endif // elua && eluac +#endif /* elua && eluac */ /* ----------------------------------------------------------------------------- * Class/structure conversion fns From aa55154ccfa967297181e886a350a36b03c64e07 Mon Sep 17 00:00:00 2001 From: Eric Wing Date: Sun, 18 May 2014 01:29:45 -0700 Subject: [PATCH 0953/1048] JavaScript: Added missing static modifiers to avoid duplicate symbol problems with multiple SWIG modules. --- Lib/javascript/jsc/javascriptcode.swg | 42 ++++++++++++------------ Lib/javascript/jsc/javascripthelpers.swg | 10 +++--- Lib/javascript/v8/javascripthelpers.swg | 12 +++---- 3 files changed, 32 insertions(+), 32 deletions(-) diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index 738b54d70..a5f395944 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -8,7 +8,7 @@ * ----------------------------------------------------------------------------- */ %fragment ("js_ctor", "templates") %{ -JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +static JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { $jslocals if(argc != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); @@ -28,7 +28,7 @@ JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size_t argc * ----------------------------------------------------------------------------- */ %fragment ("js_veto_ctor", "templates") %{ -JSObjectRef $jswrapper(JSContextRef context, JSObjectRef ctorObject, +static JSObjectRef $jswrapper(JSContextRef context, JSObjectRef ctorObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { SWIG_exception(SWIG_ERROR, "Class $jsname can not be instantiated"); @@ -44,7 +44,7 @@ JSObjectRef $jswrapper(JSContextRef context, JSObjectRef ctorObject, * ----------------------------------------------------------------------------- */ %fragment ("js_ctor_dispatcher", "templates") %{ -JSObjectRef $jswrapper(JSContextRef context, JSObjectRef ctorObject, +static JSObjectRef $jswrapper(JSContextRef context, JSObjectRef ctorObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { JSObjectRef thisObject = NULL; @@ -70,7 +70,7 @@ JSObjectRef $jswrapper(JSContextRef context, JSObjectRef ctorObject, * ----------------------------------------------------------------------------- */ %fragment ("js_overloaded_ctor", "templates") %{ -JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +static JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { $jslocals $jscode @@ -105,7 +105,7 @@ JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size_t argc * ----------------------------------------------------------------------------- */ %fragment ("js_dtor", "templates") %{ -void $jswrapper(JSObjectRef thisObject) +static void $jswrapper(JSObjectRef thisObject) { SwigPrivData* t = (SwigPrivData*) JSObjectGetPrivate(thisObject); if(t && t->swigCMemOwn) free (($jstype)t->swigCObject); @@ -121,7 +121,7 @@ void $jswrapper(JSObjectRef thisObject) * ----------------------------------------------------------------------------- */ %fragment ("js_dtoroverride", "templates") %{ -void $jswrapper(JSObjectRef thisObject) +static void $jswrapper(JSObjectRef thisObject) { SwigPrivData* t = (SwigPrivData*) JSObjectGetPrivate(thisObject); if(t && t->swigCMemOwn) { @@ -140,7 +140,7 @@ void $jswrapper(JSObjectRef thisObject) * ----------------------------------------------------------------------------- */ %fragment ("js_getter", "templates") %{ -JSValueRef $jswrapper(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +static JSValueRef $jswrapper(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) { $jslocals JSValueRef jsresult; @@ -162,7 +162,7 @@ JSValueRef $jswrapper(JSContextRef context, JSObjectRef thisObject, JSStringRef * ----------------------------------------------------------------------------- */ %fragment ("js_setter", "templates") %{ -bool $jswrapper(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +static bool $jswrapper(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) { $jslocals $jscode @@ -183,7 +183,7 @@ bool $jswrapper(JSContextRef context, JSObjectRef thisObject, JSStringRef proper * ----------------------------------------------------------------------------- */ %fragment ("js_function", "templates") %{ -JSValueRef $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +static JSValueRef $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { $jslocals JSValueRef jsresult; @@ -208,7 +208,7 @@ JSValueRef $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef th * ----------------------------------------------------------------------------- */ %fragment ("js_function_dispatcher", "templates") %{ -JSValueRef $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +static JSValueRef $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { $jslocals JSValueRef jsresult; @@ -232,7 +232,7 @@ JSValueRef $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef th * ----------------------------------------------------------------------------- */ %fragment ("js_overloaded_function", "templates") %{ -int $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception, JSValueRef* p_result) +static int $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception, JSValueRef* p_result) { $jslocals JSValueRef jsresult; @@ -291,11 +291,11 @@ int $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObjec * ----------------------------------------------------------------------------- */ %fragment ("jsc_class_declaration", "templates") %{ -JSClassDefinition $jsmangledname_classDefinition; +static JSClassDefinition $jsmangledname_classDefinition; -JSClassDefinition $jsmangledname_objectDefinition; +static JSClassDefinition $jsmangledname_objectDefinition; -JSClassRef $jsmangledname_classRef; +static JSClassRef $jsmangledname_classRef; %} /* ----------------------------------------------------------------------------- @@ -308,22 +308,22 @@ JSClassRef $jsmangledname_classRef; * ----------------------------------------------------------------------------- */ %fragment ("jsc_class_tables", "templates") %{ -JSStaticValue $jsmangledname_staticValues[] = { +static JSStaticValue $jsmangledname_staticValues[] = { $jsstaticclassvariables { 0, 0, 0, 0 } }; -JSStaticFunction $jsmangledname_staticFunctions[] = { +static JSStaticFunction $jsmangledname_staticFunctions[] = { $jsstaticclassfunctions { 0, 0, 0 } }; -JSStaticValue $jsmangledname_values[] = { +static JSStaticValue $jsmangledname_values[] = { $jsclassvariables { 0, 0, 0, 0 } }; -JSStaticFunction $jsmangledname_functions[] = { +static JSStaticFunction $jsmangledname_functions[] = { $jsclassfunctions { 0, 0, 0 } }; @@ -382,17 +382,17 @@ JSStaticFunction $jsmangledname_functions[] = { * ----------------------------------------------------------------------------- */ %fragment ("jsc_nspace_declaration", "templates") %{ -JSStaticValue $jsnspace_values[] = { +static JSStaticValue $jsnspace_values[] = { $jsglobalvariables { 0, 0, 0, 0 } }; -JSStaticFunction $jsnspace_functions[] = { +static JSStaticFunction $jsnspace_functions[] = { $jsglobalfunctions { 0, 0, 0 } }; -JSClassDefinition $jsnspace_classDefinition; +static JSClassDefinition $jsnspace_classDefinition; %} /* ----------------------------------------------------------------------------- diff --git a/Lib/javascript/jsc/javascripthelpers.swg b/Lib/javascript/jsc/javascripthelpers.swg index 820075ca6..405280161 100644 --- a/Lib/javascript/jsc/javascripthelpers.swg +++ b/Lib/javascript/jsc/javascripthelpers.swg @@ -1,6 +1,6 @@ %insert(wrapper) %{ -bool JS_registerClass(JSGlobalContextRef context, JSObjectRef parentObject, +SWIGINTERN bool JS_registerClass(JSGlobalContextRef context, JSObjectRef parentObject, const char* className, JSClassDefinition* definition) { @@ -14,7 +14,7 @@ bool JS_registerClass(JSGlobalContextRef context, JSObjectRef parentObject, return true; } -bool JS_registerNamespace(JSGlobalContextRef context, +SWIGINTERN bool JS_registerNamespace(JSGlobalContextRef context, JSObjectRef namespaceObj, JSObjectRef parentNamespace, const char* name) { @@ -28,7 +28,7 @@ bool JS_registerNamespace(JSGlobalContextRef context, } -bool JS_registerFunction(JSGlobalContextRef context, JSObjectRef object, +SWIGINTERN bool JS_registerFunction(JSGlobalContextRef context, JSObjectRef object, const char* functionName, JSObjectCallAsFunctionCallback callback) { JSStringRef js_functionName = JSStringCreateWithUTF8CString(functionName); @@ -39,7 +39,7 @@ bool JS_registerFunction(JSGlobalContextRef context, JSObjectRef object, return true; } -bool JS_veto_set_variable(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +SWIGINTERN bool JS_veto_set_variable(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) { char buffer[256]; char msg[512]; @@ -57,7 +57,7 @@ bool JS_veto_set_variable(JSContextRef context, JSObjectRef thisObject, JSString return false; } -JSValueRef JS_CharPtrToJSValue(JSContextRef context, char* cstr) { +SWIGINTERN JSValueRef JS_CharPtrToJSValue(JSContextRef context, char* cstr) { JSValueRef val; JSStringRef jsstring = JSStringCreateWithUTF8CString((char*) cstr); diff --git a/Lib/javascript/v8/javascripthelpers.swg b/Lib/javascript/v8/javascripthelpers.swg index 8da6627e2..f6303cced 100644 --- a/Lib/javascript/v8/javascripthelpers.swg +++ b/Lib/javascript/v8/javascripthelpers.swg @@ -16,7 +16,7 @@ typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfoVoid; /** * Creates a class template for a class with specified initialization function. */ -v8::Handle SWIGV8_CreateClassTemplate(const char* symbol) { +SWIGRUNTIME v8::Handle SWIGV8_CreateClassTemplate(const char* symbol) { v8::HandleScope scope; v8::Local class_templ = v8::FunctionTemplate::New(); class_templ->SetClassName(v8::String::NewSymbol(symbol)); @@ -36,7 +36,7 @@ v8::Handle SWIGV8_CreateClassTemplate(const char* symbol) /** * Registers a class method with given name for a given class template. */ -void SWIGV8_AddMemberFunction(v8::Handle class_templ, const char* symbol, +SWIGRUNTIME void SWIGV8_AddMemberFunction(v8::Handle class_templ, const char* symbol, SwigV8FunctionCallback _func) { v8::Handle proto_templ = class_templ->PrototypeTemplate(); proto_templ->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)); @@ -45,7 +45,7 @@ void SWIGV8_AddMemberFunction(v8::Handle class_templ, cons /** * Registers a class property with given name for a given class template. */ -void SWIGV8_AddMemberVariable(v8::Handle class_templ, const char* symbol, +SWIGRUNTIME void SWIGV8_AddMemberVariable(v8::Handle class_templ, const char* symbol, SwigV8AccessorGetterCallback getter, SwigV8AccessorSetterCallback setter) { v8::Handle proto_templ = class_templ->InstanceTemplate(); proto_templ->SetAccessor(v8::String::NewSymbol(symbol), getter, setter); @@ -54,7 +54,7 @@ void SWIGV8_AddMemberVariable(v8::Handle class_templ, cons /** * Registers a class method with given name for a given object. */ -void SWIGV8_AddStaticFunction(v8::Handle obj, const char* symbol, +SWIGRUNTIME void SWIGV8_AddStaticFunction(v8::Handle obj, const char* symbol, const SwigV8FunctionCallback& _func) { obj->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)->GetFunction()); } @@ -62,12 +62,12 @@ void SWIGV8_AddStaticFunction(v8::Handle obj, const char* symbol, /** * Registers a class method with given name for a given object. */ -void SWIGV8_AddStaticVariable(v8::Handle obj, const char* symbol, +SWIGRUNTIME void SWIGV8_AddStaticVariable(v8::Handle obj, const char* symbol, SwigV8AccessorGetterCallback getter, SwigV8AccessorSetterCallback setter) { obj->SetAccessor(v8::String::NewSymbol(symbol), getter, setter); } -void JS_veto_set_variable(v8::Local property, v8::Local value, +SWIGRUNTIME void JS_veto_set_variable(v8::Local property, v8::Local value, const SwigV8PropertyCallbackInfoVoid& info) { char buffer[256]; From b4534a481aa370a58d376522ea67072fcc446d8f Mon Sep 17 00:00:00 2001 From: Eric Wing Date: Sun, 18 May 2014 01:32:26 -0700 Subject: [PATCH 0954/1048] JavaScriptCore: Bug fix for finalizer. The finalizer needs to be set on the objectDefinition, not the classDefinition. Otherwise, all the finalize callbacks get NULL back for the PrivateData and can't free the SwigPrivData, causing massive leakage. --- Lib/javascript/jsc/javascriptcode.swg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index a5f395944..da6130a6a 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -341,7 +341,7 @@ static JSStaticFunction $jsmangledname_functions[] = { $jsmangledname_classDefinition.staticFunctions = $jsmangledname_staticFunctions; $jsmangledname_classDefinition.staticValues = $jsmangledname_staticValues; $jsmangledname_classDefinition.callAsConstructor = $jsctor; - $jsmangledname_classDefinition.finalize = $jsdtor; + $jsmangledname_objectDefinition.finalize = $jsdtor; $jsmangledname_objectDefinition.staticValues = $jsmangledname_values; $jsmangledname_objectDefinition.staticFunctions = $jsmangledname_functions; $jsclass_inheritance From fcb48336605474e97e73ca2bc89076ee01e0b8fa Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sun, 18 May 2014 20:33:10 +0200 Subject: [PATCH 0955/1048] JavascriptCore: fix cleanup code. --- Lib/javascript/jsc/javascriptcode.swg | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index da6130a6a..3fe9d49e9 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -108,8 +108,13 @@ static JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size static void $jswrapper(JSObjectRef thisObject) { SwigPrivData* t = (SwigPrivData*) JSObjectGetPrivate(thisObject); - if(t && t->swigCMemOwn) free (($jstype)t->swigCObject); - if(t) free(t); + if(t) { + if (t->swigCMemOwn) { + free (($jstype)t->swigCObject); + } + JSObjectSetPrivate(thisObject, NULL); + free(t); + } } %} @@ -124,11 +129,15 @@ static void $jswrapper(JSObjectRef thisObject) static void $jswrapper(JSObjectRef thisObject) { SwigPrivData* t = (SwigPrivData*) JSObjectGetPrivate(thisObject); - if(t && t->swigCMemOwn) { - $jstype arg1 = ($jstype)t->swigCObject; - ${destructor_action} + if(t) { + if (t->swigCMemOwn) { + $jstype arg1 = ($jstype)t->swigCObject; + ${destructor_action} + } + /* remove the private data to make sure that it isn't accessed elsewhere */ + JSObjectSetPrivate(thisObject, NULL); + free(t); } - if(t) free(t); } %} From 486e903de1bbf847a0a60aa85ab1e1a44c8ca159 Mon Sep 17 00:00:00 2001 From: Eric Wing Date: Sun, 18 May 2014 01:35:46 -0700 Subject: [PATCH 0956/1048] JavaScriptCore: Bug fix for SWIGJSC_AppendOutput. This function requires a return value. I think it should be arr, but somebody should scrutinize this. --- Lib/javascript/jsc/javascriptrun.swg | 1 + 1 file changed, 1 insertion(+) diff --git a/Lib/javascript/jsc/javascriptrun.swg b/Lib/javascript/jsc/javascriptrun.swg index 3463d2351..95f00659d 100644 --- a/Lib/javascript/jsc/javascriptrun.swg +++ b/Lib/javascript/jsc/javascriptrun.swg @@ -295,4 +295,5 @@ JSValueRef SWIGJSC_AppendOutput(JSContextRef context, JSValueRef value, JSValueR length = SWIGJSC_ArrayLength(context, arr); JSObjectSetPropertyAtIndex(context, arr, length, obj, 0); + return arr; } From fade0bcbdef3a1127d677f6ff72be064bcda5a57 Mon Sep 17 00:00:00 2001 From: Eric Wing Date: Sun, 18 May 2014 01:50:05 -0700 Subject: [PATCH 0957/1048] JavaScriptCore: C89: declare variables at the top for antiquated compilers like Microsoft Visual Studio. --- Lib/javascript/jsc/javascriptrun.swg | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Lib/javascript/jsc/javascriptrun.swg b/Lib/javascript/jsc/javascriptrun.swg index 95f00659d..fce22a452 100644 --- a/Lib/javascript/jsc/javascriptrun.swg +++ b/Lib/javascript/jsc/javascriptrun.swg @@ -128,11 +128,12 @@ int SWIG_JSC_ConvertInstancePtr(JSContextRef context, JSObjectRef objRef, void** } int SWIG_JSC_ConvertPtr(JSContextRef context, JSValueRef valRef, void** ptr, swig_type_info *info, int flags) { + JSObjectRef objRef; if(!JSValueIsObject(context, valRef)) { return SWIG_TypeError; } - JSObjectRef objRef = JSValueToObject(context, valRef, NULL); + objRef = JSValueToObject(context, valRef, NULL); if(objRef == NULL) { return SWIG_ERROR; } From 8498e4878d130a6ae24843084408339f3bf910ce Mon Sep 17 00:00:00 2001 From: Eric Wing Date: Sun, 18 May 2014 03:03:46 -0700 Subject: [PATCH 0958/1048] JavaScriptCore: More missing static modifiers. --- Lib/javascript/jsc/javascriptrun.swg | 36 ++++++++++++++-------------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/Lib/javascript/jsc/javascriptrun.swg b/Lib/javascript/jsc/javascriptrun.swg index fce22a452..813c7deb4 100644 --- a/Lib/javascript/jsc/javascriptrun.swg +++ b/Lib/javascript/jsc/javascriptrun.swg @@ -7,13 +7,13 @@ #define SWIG_exception(code, msg) SWIG_JSC_exception(context, exception, code, msg) #define SWIG_fail goto fail -void SWIG_Javascript_Raise(JSContextRef context, JSValueRef *exception, const char* type) { +SWIGRUNTIME void SWIG_Javascript_Raise(JSContextRef context, JSValueRef *exception, const char* type) { JSStringRef message = JSStringCreateWithUTF8CString(type); *exception = JSValueMakeString(context, message); JSStringRelease(message); } -void SWIG_JSC_exception(JSContextRef context, JSValueRef *exception, int code, const char* msg) { +SWIGRUNTIME void SWIG_JSC_exception(JSContextRef context, JSValueRef *exception, int code, const char* msg) { SWIG_Javascript_Raise(context, exception, msg); } @@ -28,7 +28,7 @@ typedef struct { swig_type_info *info; } SwigPrivData; -JSValueRef _wrap_SwigObject_disown(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +SWIGRUNTIME JSValueRef _wrap_SwigObject_disown(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { JSValueRef jsresult; @@ -41,7 +41,7 @@ JSValueRef _wrap_SwigObject_disown(JSContextRef context, JSObjectRef function, J return jsresult; } -JSValueRef _wrap_SwigObject_getCPtr(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +SWIGRUNTIME JSValueRef _wrap_SwigObject_getCPtr(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { JSValueRef jsresult; long result; @@ -55,7 +55,7 @@ JSValueRef _wrap_SwigObject_getCPtr(JSContextRef context, JSObjectRef function, return jsresult; } -JSValueRef _wrap_SwigObject_equals(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +SWIGRUNTIME JSValueRef _wrap_SwigObject_equals(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { JSValueRef jsresult; bool result; @@ -72,13 +72,13 @@ JSValueRef _wrap_SwigObject_equals(JSContextRef context, JSObjectRef function, J return jsresult; } -JSStaticValue _SwigObject_values[] = { +SWIGRUNTIME JSStaticValue _SwigObject_values[] = { { 0, 0, 0, 0 } }; -JSStaticFunction _SwigObject_functions[] = { +SWIGRUNTIME JSStaticFunction _SwigObject_functions[] = { { "disown",_wrap_SwigObject_disown, kJSPropertyAttributeNone }, @@ -93,12 +93,12 @@ JSStaticFunction _SwigObject_functions[] = { } }; -JSClassDefinition _SwigObject_objectDefinition; +SWIGRUNTIME JSClassDefinition _SwigObject_objectDefinition; -JSClassRef _SwigObject_classRef; +SWIGRUNTIME JSClassRef _SwigObject_classRef; -int SWIG_JSC_ConvertInstancePtr(JSContextRef context, JSObjectRef objRef, void** ptr, swig_type_info *info, int flags) { +SWIGRUNTIME int SWIG_JSC_ConvertInstancePtr(JSContextRef context, JSObjectRef objRef, void** ptr, swig_type_info *info, int flags) { SwigPrivData *cdata = (SwigPrivData *) JSObjectGetPrivate(objRef); if(cdata == NULL) { return SWIG_ERROR; @@ -127,7 +127,7 @@ int SWIG_JSC_ConvertInstancePtr(JSContextRef context, JSObjectRef objRef, void** return SWIG_OK; } -int SWIG_JSC_ConvertPtr(JSContextRef context, JSValueRef valRef, void** ptr, swig_type_info *info, int flags) { +SWIGRUNTIME int SWIG_JSC_ConvertPtr(JSContextRef context, JSValueRef valRef, void** ptr, swig_type_info *info, int flags) { JSObjectRef objRef; if(!JSValueIsObject(context, valRef)) { return SWIG_TypeError; @@ -141,7 +141,7 @@ int SWIG_JSC_ConvertPtr(JSContextRef context, JSValueRef valRef, void** ptr, swi return SWIG_JSC_ConvertInstancePtr(context, objRef, ptr, info, flags); } -JSObjectRef SWIG_JSC_NewPointerObj(JSContextRef context, void *ptr, swig_type_info *info, int flags) { +SWIGRUNTIME JSObjectRef SWIG_JSC_NewPointerObj(JSContextRef context, void *ptr, swig_type_info *info, int flags) { JSClassRef classRef; if(info->clientdata == NULL) { @@ -182,18 +182,18 @@ typedef struct { swig_type_info *type; } SwigPackedData; -JSStaticValue _SwigPackedData_values[] = { +SWIGRUNTIME JSStaticValue _SwigPackedData_values[] = { { 0, 0, 0, 0 } }; -JSStaticFunction _SwigPackedData_functions[] = { +SWIGRUNTIME JSStaticFunction _SwigPackedData_functions[] = { { 0, 0, 0 } }; -JSClassDefinition _SwigPackedData_objectDefinition; -JSClassRef _SwigPackedData_classRef; +SWIGRUNTIME JSClassDefinition _SwigPackedData_objectDefinition; +SWIGRUNTIME JSClassRef _SwigPackedData_classRef; SWIGRUNTIMEINLINE int SwigJSCPacked_Check(JSContextRef context, JSValueRef valRef) { @@ -244,7 +244,7 @@ JSValueRef SWIG_JSC_NewPackedObj(JSContextRef context, void *data, size_t size, } /* SwigPackedData wrappers */ - +SWIGRUNTIME void _wrap_SwigPackedData_delete(JSObjectRef obj) { SwigPackedData* cdata = (SwigPackedData*) JSObjectGetPrivate(obj); @@ -263,7 +263,7 @@ void _wrap_SwigPackedData_delete(JSObjectRef obj) * Support for IN/OUTPUT typemaps (see Lib/typemaps/inoutlist.swg) * * ---------------------------------------------------------------------------*/ - +SWIGRUNTIME unsigned int SWIGJSC_ArrayLength(JSContextRef context, JSObjectRef arr) { static JSStringRef LENGTH = 0; JSValueRef exception = NULL; From 05ed0325dc4bd9ddc126d3dacc6b38686f7382cf Mon Sep 17 00:00:00 2001 From: Eric Wing Date: Sun, 18 May 2014 03:43:47 -0700 Subject: [PATCH 0959/1048] JavaScriptCore: ConvertPtr should allow JavaScript null to be a valid value. It is common in C to accept NULL to functions for pointer parameters. extern void DoSomething(struct Foo* foo); ... DoSomething(NULL); Thus, JavaScript null should be allowed: module.DoSomething(null); But the current ConvertPtr definition accepts only objects. This modifies it to allow null. --- Lib/javascript/jsc/javascriptrun.swg | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Lib/javascript/jsc/javascriptrun.swg b/Lib/javascript/jsc/javascriptrun.swg index 813c7deb4..9655b0eb6 100644 --- a/Lib/javascript/jsc/javascriptrun.swg +++ b/Lib/javascript/jsc/javascriptrun.swg @@ -129,6 +129,13 @@ SWIGRUNTIME int SWIG_JSC_ConvertInstancePtr(JSContextRef context, JSObjectRef ob SWIGRUNTIME int SWIG_JSC_ConvertPtr(JSContextRef context, JSValueRef valRef, void** ptr, swig_type_info *info, int flags) { JSObjectRef objRef; + + /* special case: JavaScript null => C NULL pointer */ + if(JSValueIsNull(context, valRef)) { + *ptr=0; + return SWIG_OK; + } + if(!JSValueIsObject(context, valRef)) { return SWIG_TypeError; } From 7824322b146f67590c1a460f88379bce3a7d4d58 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Sun, 18 May 2014 22:40:22 +0200 Subject: [PATCH 0960/1048] Javascript: fix warnings in li_std_string test. Old typemaps for std::string were in place instead of delegating to UTL. --- Lib/javascript/jsc/std_string.i | 70 +---------------------------- Lib/javascript/v8/std_string.i | 80 +-------------------------------- 2 files changed, 2 insertions(+), 148 deletions(-) diff --git a/Lib/javascript/jsc/std_string.i b/Lib/javascript/jsc/std_string.i index fb1bd62b5..dc1378ae6 100644 --- a/Lib/javascript/jsc/std_string.i +++ b/Lib/javascript/jsc/std_string.i @@ -1,69 +1 @@ -/* ----------------------------------------------------------------------------- - * std_string.i - * - * Typemaps for const std::string&. - * To use non-const std::string references use the following %apply: - * %apply const std::string & {std::string &}; - * - * ----------------------------------------------------------------------------- */ - -%{ -#include - -std::string SWIGJSC_valueToString(JSContextRef context, JSValueRef value) { - JSStringRef jsstring = JSValueToStringCopy(context, value, /* JSValueRef *exception */ 0); - unsigned int length = JSStringGetLength(jsstring); - char *cstr = new char[length + 1]; - JSStringGetUTF8CString(jsstring, cstr, length + 1); - - // create a copy - std::string result(cstr); - - JSStringRelease(jsstring); - delete[] cstr; - - return result; -} - -JSValueRef SWIGJSC_stringToValue(JSContextRef context, const std::string& s) -{ - JSValueRef result; - JSStringRef jsstring = JSStringCreateWithUTF8CString(s.c_str()); - result = JSValueMakeString(context, jsstring); - JSStringRelease(jsstring); - return result; -} -%} - -namespace std { - %naturalvar string; - - class string; - - - %typemap(in) string - %{ - $1 = SWIGJSC_valueToString(context, $input); - %} - - %typemap(in) const string & - %{ - $1 = new std::string(SWIGJSC_valueToString(context, $input)); - %} - - %typemap(freearg) const string & - %{ - delete $1; - %} - - %typemap(out) string - %{ - $result = SWIGJSC_stringToValue(context, $1); - %} - - %typemap(out) const string & - %{ - $result = SWIGJSC_stringToValue(context, *$1); - %} - -} +%include diff --git a/Lib/javascript/v8/std_string.i b/Lib/javascript/v8/std_string.i index 5ad1ead27..dc1378ae6 100644 --- a/Lib/javascript/v8/std_string.i +++ b/Lib/javascript/v8/std_string.i @@ -1,79 +1 @@ -/* ----------------------------------------------------------------------------- - * std_string.i - * - * Typemaps for std::string and const std::string&. - * - * To use non-const std::string references use the following %apply: - * %apply const std::string & {std::string &}; - * - * ----------------------------------------------------------------------------- */ - -%{ -#include -%} - -%fragment("SWIGV8_valueToString", "header", fragment="SWIG_AsCharPtrAndSize") { -std::string* SWIGV8_valueToStringPtr(v8::Handle val) { - - if (!val->IsString()) return 0; - - int alloc; - size_t size; - char* chars; - int res = SWIG_AsCharPtrAndSize(val, &chars, &size, &alloc); - - if(res != SWIG_OK) { - v8::ThrowException(v8::Exception::TypeError(v8::String::New("Could not convert to string."))); - return 0; - } - - // copies the data (again) - std::string *str = new std::string(chars); - - if (alloc) delete[] chars; - - return str; -} -} - -%fragment("SWIGV8_stringToValue", "header", fragment="SWIG_FromCharPtrAndSize") { -v8::Handle SWIGV8_stringToValue(const std::string &str) { - return SWIG_FromCharPtrAndSize(str.c_str(), str.length()); -} -} - -namespace std { - %naturalvar string; - - class string; - - %typemap(in, fragment="SWIGV8_valueToString") string (std::string* tmp) - %{ - tmp = SWIGV8_valueToStringPtr($input); - $1 = *tmp; - if (tmp == 0) { v8::ThrowException(v8::Exception::TypeError(v8::String::New("Null pointer."))); goto fail; } - if (tmp) delete tmp; - %} - - %typemap(in, fragment="SWIGV8_valueToString") const string & - %{ - $1 = SWIGV8_valueToStringPtr($input); - if ($1 == 0) { v8::ThrowException(v8::Exception::TypeError(v8::String::New("Null pointer."))); goto fail; } - %} - - %typemap(freearg) const string & - %{ - if ($1) delete $1; - %} - - %typemap(out, fragment="SWIGV8_stringToValue") string - %{ - $result = SWIGV8_stringToValue($1); - %} - - %typemap(out, fragment="SWIGV8_stringToValue") const string & - %{ - $result = SWIGV8_stringToValue(*$1); - %} - -} +%include From d2ab75f9071ae15d98dbf091f6461ef397d66ef5 Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Mon, 19 May 2014 02:05:23 +0400 Subject: [PATCH 0961/1048] obscure case workaround in std::set wrapper, where ignored type still need to be processed --- Source/Modules/typepass.cxx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Source/Modules/typepass.cxx b/Source/Modules/typepass.cxx index ec6f64587..3e323f910 100644 --- a/Source/Modules/typepass.cxx +++ b/Source/Modules/typepass.cxx @@ -661,15 +661,15 @@ class TypePass:private Dispatcher { * ------------------------------------------------------------ */ virtual int cDeclaration(Node *n) { - if (GetFlag(n, "feature:ignore")) { - return SWIG_OK; - } if (NoExcept) { Delattr(n, "throws"); } /* Normalize types. */ SwigType *ty = Getattr(n, "type"); + if (!ty) { + return SWIG_OK; + } normalize_type(ty); SwigType *decl = Getattr(n, "decl"); if (decl) { From 0c42158723ad29ddd199fc1eeb959bf777f7062f Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 19 May 2014 00:20:19 +0200 Subject: [PATCH 0962/1048] Javascript: preparations for using Language::getNSpace(). --- Source/Modules/javascript.cxx | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 20af76f9f..e535bc179 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -318,6 +318,10 @@ public: **/ virtual int fragmentDirective(Node *n); +public: + + virtual String *getNSpace() const; + private: JSEmitter *emitter; @@ -467,6 +471,10 @@ int JAVASCRIPT::fragmentDirective(Node *n) { return SWIG_OK; } +String *JAVASCRIPT::getNSpace() const { + return Language::getNSpace(); +} + /* --------------------------------------------------------------------- * top() * @@ -1346,14 +1354,26 @@ int JSEmitter::switchNamespace(Node *n) { return SWIG_OK; } - String *nspace = Getattr(n, "sym:nspace"); - // if nspace is deactivated, everything goes into the global scope if (!GetFlag(n, "feature:nspace")) { current_namespace = Getattr(namespaces, "::"); return SWIG_OK; } +// EXPERIMENTAL: we want to use Language::getNSpace() here +// However, it is not working yet. +// For namespace functions Language::getNSpace() does not give a valid result +#if 0 + JAVASCRIPT *lang = static_cast(Language::instance()); + String *_nspace = lang->getNSpace(); + if (!Equal(nspace, _nspace)) { + Printf(stdout, "##### Custom vs Language::getNSpace(): %s | %s\n", nspace, _nspace); + Swig_print_node(n); + } +#endif + + String *nspace = Getattr(n, "sym:nspace"); + if (nspace == NULL) { // It seems that only classes have 'sym:nspace' set. // We try to get the namespace from the qualified name (i.e., everything before the last '::') From 11963788e0d008e1c6e997577086cd8dd584c03f Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 19 May 2014 00:21:21 +0200 Subject: [PATCH 0963/1048] Javascript: support null pointers. We allow to set pointer types using JS null. --- .../javascript/null_pointer_runme.js | 9 +++++++++ Lib/javascript/jsc/javascriptrun.swg | 18 +++++++++++++----- Lib/javascript/v8/javascriptrun.swg | 12 ++++++++++-- 3 files changed, 32 insertions(+), 7 deletions(-) create mode 100644 Examples/test-suite/javascript/null_pointer_runme.js diff --git a/Examples/test-suite/javascript/null_pointer_runme.js b/Examples/test-suite/javascript/null_pointer_runme.js new file mode 100644 index 000000000..7c0d61244 --- /dev/null +++ b/Examples/test-suite/javascript/null_pointer_runme.js @@ -0,0 +1,9 @@ +var null_pointer = require("null_pointer"); + +if (!null_pointer.func(null)) { + throw new Error("Javascript 'null' should be converted into NULL."); +} + +if (null_pointer.getnull() != null) { + throw new Error("NULL should be converted into Javascript 'null'."); +} diff --git a/Lib/javascript/jsc/javascriptrun.swg b/Lib/javascript/jsc/javascriptrun.swg index 9655b0eb6..1ff10a183 100644 --- a/Lib/javascript/jsc/javascriptrun.swg +++ b/Lib/javascript/jsc/javascriptrun.swg @@ -99,7 +99,9 @@ SWIGRUNTIME JSClassRef _SwigObject_classRef; SWIGRUNTIME int SWIG_JSC_ConvertInstancePtr(JSContextRef context, JSObjectRef objRef, void** ptr, swig_type_info *info, int flags) { - SwigPrivData *cdata = (SwigPrivData *) JSObjectGetPrivate(objRef); + SwigPrivData *cdata; + + cdata = (SwigPrivData *) JSObjectGetPrivate(objRef); if(cdata == NULL) { return SWIG_ERROR; } @@ -135,7 +137,7 @@ SWIGRUNTIME int SWIG_JSC_ConvertPtr(JSContextRef context, JSValueRef valRef, voi *ptr=0; return SWIG_OK; } - + if(!JSValueIsObject(context, valRef)) { return SWIG_TypeError; } @@ -149,17 +151,23 @@ SWIGRUNTIME int SWIG_JSC_ConvertPtr(JSContextRef context, JSValueRef valRef, voi } SWIGRUNTIME JSObjectRef SWIG_JSC_NewPointerObj(JSContextRef context, void *ptr, swig_type_info *info, int flags) { - JSClassRef classRef; + JSObjectRef result; + SwigPrivData *cdata; + + if (ptr == NULL) { + return JSValueToObject(context, JSValueMakeNull(context), 0); + } + if(info->clientdata == NULL) { classRef = _SwigObject_classRef; } else { classRef = (JSClassRef) info->clientdata; } - JSObjectRef result = JSObjectMake(context, classRef, NULL); + result = JSObjectMake(context, classRef, NULL); - SwigPrivData* cdata = (SwigPrivData*) malloc(sizeof(SwigPrivData)); + cdata = (SwigPrivData*) malloc(sizeof(SwigPrivData)); cdata->swigCObject = ptr; cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; cdata->info = info; diff --git a/Lib/javascript/v8/javascriptrun.swg b/Lib/javascript/v8/javascriptrun.swg index 2e0a46717..f200f1520 100644 --- a/Lib/javascript/v8/javascriptrun.swg +++ b/Lib/javascript/v8/javascriptrun.swg @@ -220,7 +220,11 @@ void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info int SWIG_V8_ConvertPtr(v8::Handle valRef, void** ptr, swig_type_info *info, int flags) { v8::HandleScope scope; - + /* special case: JavaScript null => C NULL pointer */ + if(valRef->IsNull()) { + *ptr=0; + return SWIG_OK; + } if(!valRef->IsObject()) { return SWIG_TypeError; } @@ -228,10 +232,14 @@ int SWIG_V8_ConvertPtr(v8::Handle valRef, void** ptr, swig_type_info return SWIG_V8_ConvertInstancePtr(objRef, ptr, info, flags); } -v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, int flags) { +v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, int flags) { v8::HandleScope scope; v8::Handle class_templ; + if (ptr == NULL) { + return scope.Close(v8::Null()); + } + #if (SWIG_V8_VERSION < 0x031900) if(info->clientdata != 0) { class_templ = ((SWIGV8_ClientData*) info->clientdata)->class_templ; From 243671700fd8ac0e18880962c19bf10cf4d91e1b Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sun, 18 May 2014 23:09:58 +0100 Subject: [PATCH 0964/1048] Fix li_boost_intrusive_ptr for various versions of boost Modify testcase to fix compile errors on various versions of boost. Tested using various combinations from boost-1.33/gcc-3.4.2 to boost-1.53/gcc-4.7.3. Originally noticed as broken on boost-1.36/gcc-4.3.4 on SLE 11. Add in some diagnostics when reference count is wrong... which does still happen occasionally. --- .../java/li_boost_intrusive_ptr_runme.java | 20 ++++++++++--------- Examples/test-suite/li_boost_intrusive_ptr.i | 15 +++++++++++--- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/Examples/test-suite/java/li_boost_intrusive_ptr_runme.java b/Examples/test-suite/java/li_boost_intrusive_ptr_runme.java index 530008a87..750ec5067 100644 --- a/Examples/test-suite/java/li_boost_intrusive_ptr_runme.java +++ b/Examples/test-suite/java/li_boost_intrusive_ptr_runme.java @@ -33,7 +33,7 @@ public class li_boost_intrusive_ptr_runme { // Change loop count to run for a long time to monitor memory final int loopCount = 5000; //5000; for (int i=0; i #include #include -template void intrusive_ptr_add_ref(const T* r) { r->addref(); } -template void intrusive_ptr_release(const T* r) { r->release(); } - // Uncomment macro below to turn on intrusive_ptr memory leak checking as described above //#define INTRUSIVE_PTR_WRAPPER @@ -132,6 +135,8 @@ struct Klass { void release(void) const { if (--count == 0) delete this; } int use_count(void) const { return count; } static long getTotal_count() { return total_count; } + friend void intrusive_ptr_add_ref(const Klass* r) { r->addref(); } + friend void intrusive_ptr_release(const Klass* r) { r->release(); } private: static void increment() { ++total_count; if (debug_shared) cout << " ++xxxxx Klass::increment tot: " << total_count << endl;} @@ -177,6 +182,8 @@ struct IgnoredRefCountingBase { void addref(void) const { ++count; } void release(void) const { if (--count == 0) delete this; } int use_count(void) const { return count; } + inline friend void intrusive_ptr_add_ref(const IgnoredRefCountingBase* r) { r->addref(); } + inline friend void intrusive_ptr_release(const IgnoredRefCountingBase* r) { r->release(); } static long getTotal_count() { return total_count; } private: @@ -414,6 +421,8 @@ template struct Base { void addref(void) const { count++; } void release(void) const { if (--count == 0) delete this; } int use_count(void) const { return count; } + inline friend void intrusive_ptr_add_ref(const Base* r) { r->addref(); } + inline friend void intrusive_ptr_release(const Base* r) { r->release(); } }; %} From a64549034c5579a148c37c7f3e070c8704dca459 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 19 May 2014 00:58:32 +0200 Subject: [PATCH 0965/1048] Javascript: generalise test-case 'typemap_variables' so that it can be used for Javascript V8. The original version contains output typemaps that produced incompatible code. Introduce a pre-processor macro that is set to a valid value for v8. --- Examples/test-suite/javascript/Makefile.in | 8 ------- Examples/test-suite/typemap_variables.i | 27 +++++++++++++++------- 2 files changed, 19 insertions(+), 16 deletions(-) diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index fc5255155..be4350d1e 100644 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -28,14 +28,6 @@ _setup = \ echo "$(ACTION)ing $(LANGUAGE) ($(JSENGINE)) testcase $*" ; \ fi; -ifneq (jsc,$(ENGINE)) - - # This test can not be run with v8 as it uses v8 API incompatible output typemaps - typemap_variables.cpptest: - echo "skipping $(LANGUAGE) ($(JSENGINE)) testcase typemap_variables" ; - -endif - ifeq (node,$(JSENGINE)) SWIGOPT += -v8 -DBUILDING_NODE_EXTENSION=1 diff --git a/Examples/test-suite/typemap_variables.i b/Examples/test-suite/typemap_variables.i index 142e35060..047007a1c 100644 --- a/Examples/test-suite/typemap_variables.i +++ b/Examples/test-suite/typemap_variables.i @@ -13,33 +13,44 @@ %} #endif +// For Javascript V8 we can not use '0' for out typemaps +#if defined(SWIG_JAVASCRIPT_V8) +%header %{ +#define OUT_NULL_VALUE v8::Null() +%} +#else +%header %{ +#define OUT_NULL_VALUE 0 +%} +#endif + // Scripting languages use varin/varout for variables (except non-static member variables where in/out are used ???) %typemap(varin) int "this_will_not_compile_varin " %typemap(varout) int "this_will_not_compile_varout" %typemap(varin) int globul "/*int globul varin */ TYPEMAP_VARIABLES_FAIL" -%typemap(varout) int globul "/*int globul varout*/ $result=0;" +%typemap(varout) int globul "/*int globul varout*/ $result=OUT_NULL_VALUE;" %typemap(varin) int Space::nspace "/*int nspace varin */ TYPEMAP_VARIABLES_FAIL" -%typemap(varout) int Space::nspace "/*int nspace varout*/ $result=0;" +%typemap(varout) int Space::nspace "/*int nspace varout*/ $result=OUT_NULL_VALUE;" //%typemap(varin) int member "/*int member varin */" -//%typemap(varout) int member "/*int member varout*/ $result=0;" +//%typemap(varout) int member "/*int member varout*/ $result=OUT_NULL_VALUE;" %typemap(varin) int Space::Struct::smember "/*int smember varin */ TYPEMAP_VARIABLES_FAIL" -%typemap(varout) int Space::Struct::smember "/*int smember varout*/ $result=0;" +%typemap(varout) int Space::Struct::smember "/*int smember varout*/ $result=OUT_NULL_VALUE;" // Statically typed languages use in/out for variables %typemap(in) int "this_will_not_compile_in " %typemap(out) int "this_will_not_compile_out" %typemap(in) int globul "/*int globul in */ $1=0;" -%typemap(out) int globul "/*int globul out*/ $result=0;" +%typemap(out) int globul "/*int globul out*/ $result=OUT_NULL_VALUE;" %typemap(in) int Space::nspace "/*int nspace in */ $1=0;" -%typemap(out) int Space::nspace "/*int nspace out*/ $result=0;" +%typemap(out) int Space::nspace "/*int nspace out*/ $result=OUT_NULL_VALUE;" %typemap(in) int member "/*int member in */ $1=0;" #ifdef SWIGTCL %typemap(out) int member "/*int member out*/" #else -%typemap(out) int member "/*int member out*/ $result=0;" +%typemap(out) int member "/*int member out*/ $result=OUT_NULL_VALUE;" #endif %typemap(in) int Space::Struct::smember "/*int smember in */ $1=0;" -%typemap(out) int Space::Struct::smember "/*int smember out*/ $result=0;" +%typemap(out) int Space::Struct::smember "/*int smember out*/ $result=OUT_NULL_VALUE;" %typemap(javain) int "this_will_not_compile_javain " %typemap(javaout) int "this_will_not_compile_javaout" From 7cc617a19d2c7834ee877af920a824cd29a92a89 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 19 May 2014 11:46:21 +0200 Subject: [PATCH 0966/1048] Revert "Javascript: support null pointers." This reverts commit 11963788e0d008e1c6e997577086cd8dd584c03f. --- .../javascript/null_pointer_runme.js | 9 --------- Lib/javascript/jsc/javascriptrun.swg | 18 +++++------------- Lib/javascript/v8/javascriptrun.swg | 12 ++---------- 3 files changed, 7 insertions(+), 32 deletions(-) delete mode 100644 Examples/test-suite/javascript/null_pointer_runme.js diff --git a/Examples/test-suite/javascript/null_pointer_runme.js b/Examples/test-suite/javascript/null_pointer_runme.js deleted file mode 100644 index 7c0d61244..000000000 --- a/Examples/test-suite/javascript/null_pointer_runme.js +++ /dev/null @@ -1,9 +0,0 @@ -var null_pointer = require("null_pointer"); - -if (!null_pointer.func(null)) { - throw new Error("Javascript 'null' should be converted into NULL."); -} - -if (null_pointer.getnull() != null) { - throw new Error("NULL should be converted into Javascript 'null'."); -} diff --git a/Lib/javascript/jsc/javascriptrun.swg b/Lib/javascript/jsc/javascriptrun.swg index 1ff10a183..9655b0eb6 100644 --- a/Lib/javascript/jsc/javascriptrun.swg +++ b/Lib/javascript/jsc/javascriptrun.swg @@ -99,9 +99,7 @@ SWIGRUNTIME JSClassRef _SwigObject_classRef; SWIGRUNTIME int SWIG_JSC_ConvertInstancePtr(JSContextRef context, JSObjectRef objRef, void** ptr, swig_type_info *info, int flags) { - SwigPrivData *cdata; - - cdata = (SwigPrivData *) JSObjectGetPrivate(objRef); + SwigPrivData *cdata = (SwigPrivData *) JSObjectGetPrivate(objRef); if(cdata == NULL) { return SWIG_ERROR; } @@ -137,7 +135,7 @@ SWIGRUNTIME int SWIG_JSC_ConvertPtr(JSContextRef context, JSValueRef valRef, voi *ptr=0; return SWIG_OK; } - + if(!JSValueIsObject(context, valRef)) { return SWIG_TypeError; } @@ -151,23 +149,17 @@ SWIGRUNTIME int SWIG_JSC_ConvertPtr(JSContextRef context, JSValueRef valRef, voi } SWIGRUNTIME JSObjectRef SWIG_JSC_NewPointerObj(JSContextRef context, void *ptr, swig_type_info *info, int flags) { + JSClassRef classRef; - JSObjectRef result; - SwigPrivData *cdata; - - if (ptr == NULL) { - return JSValueToObject(context, JSValueMakeNull(context), 0); - } - if(info->clientdata == NULL) { classRef = _SwigObject_classRef; } else { classRef = (JSClassRef) info->clientdata; } - result = JSObjectMake(context, classRef, NULL); + JSObjectRef result = JSObjectMake(context, classRef, NULL); - cdata = (SwigPrivData*) malloc(sizeof(SwigPrivData)); + SwigPrivData* cdata = (SwigPrivData*) malloc(sizeof(SwigPrivData)); cdata->swigCObject = ptr; cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; cdata->info = info; diff --git a/Lib/javascript/v8/javascriptrun.swg b/Lib/javascript/v8/javascriptrun.swg index f200f1520..2e0a46717 100644 --- a/Lib/javascript/v8/javascriptrun.swg +++ b/Lib/javascript/v8/javascriptrun.swg @@ -220,11 +220,7 @@ void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info int SWIG_V8_ConvertPtr(v8::Handle valRef, void** ptr, swig_type_info *info, int flags) { v8::HandleScope scope; - /* special case: JavaScript null => C NULL pointer */ - if(valRef->IsNull()) { - *ptr=0; - return SWIG_OK; - } + if(!valRef->IsObject()) { return SWIG_TypeError; } @@ -232,14 +228,10 @@ int SWIG_V8_ConvertPtr(v8::Handle valRef, void** ptr, swig_type_info return SWIG_V8_ConvertInstancePtr(objRef, ptr, info, flags); } -v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, int flags) { +v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, int flags) { v8::HandleScope scope; v8::Handle class_templ; - if (ptr == NULL) { - return scope.Close(v8::Null()); - } - #if (SWIG_V8_VERSION < 0x031900) if(info->clientdata != 0) { class_templ = ((SWIGV8_ClientData*) info->clientdata)->class_templ; From d9bb3a84150990cc9e1980398f3dc7afd2dead79 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 19 May 2014 11:46:29 +0200 Subject: [PATCH 0967/1048] Revert "JavaScriptCore: ConvertPtr should allow JavaScript null to be a valid value." This reverts commit 05ed0325dc4bd9ddc126d3dacc6b38686f7382cf. --- Lib/javascript/jsc/javascriptrun.swg | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Lib/javascript/jsc/javascriptrun.swg b/Lib/javascript/jsc/javascriptrun.swg index 9655b0eb6..813c7deb4 100644 --- a/Lib/javascript/jsc/javascriptrun.swg +++ b/Lib/javascript/jsc/javascriptrun.swg @@ -129,13 +129,6 @@ SWIGRUNTIME int SWIG_JSC_ConvertInstancePtr(JSContextRef context, JSObjectRef ob SWIGRUNTIME int SWIG_JSC_ConvertPtr(JSContextRef context, JSValueRef valRef, void** ptr, swig_type_info *info, int flags) { JSObjectRef objRef; - - /* special case: JavaScript null => C NULL pointer */ - if(JSValueIsNull(context, valRef)) { - *ptr=0; - return SWIG_OK; - } - if(!JSValueIsObject(context, valRef)) { return SWIG_TypeError; } From 2471e4ad9f1b6b9f851cf359fd6fd6b9aa34e9b8 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 19 May 2014 12:11:15 +0200 Subject: [PATCH 0968/1048] Javascript: Use RUNTOOL for running tests. --- Examples/test-suite/javascript/Makefile.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index be4350d1e..a54fcd7e7 100644 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -85,7 +85,7 @@ else run_testcase = \ if [ -f $(srcdir)/$*$(SCRIPTSUFFIX) ]; then \ - $(top_builddir)/Tools/javascript/javascript -$(JSENGINE) $(srcdir)/$*$(SCRIPTSUFFIX); \ + $(RUNTOOL) $(top_builddir)/Tools/javascript/javascript -$(JSENGINE) $(srcdir)/$*$(SCRIPTSUFFIX); \ fi %.ctest: From d5ea32d7607c1991ae74293472d73740c90e5db8 Mon Sep 17 00:00:00 2001 From: Eric Wing Date: Sun, 18 May 2014 03:43:47 -0700 Subject: [PATCH 0969/1048] JavaScriptCore: ConvertPtr should allow JavaScript null to be a valid value. It is common in C to accept NULL to functions for pointer parameters. extern void DoSomething(struct Foo* foo); ... DoSomething(NULL); Thus, JavaScript null should be allowed: module.DoSomething(null); But the current ConvertPtr definition accepts only objects. This modifies it to allow null. --- Lib/javascript/jsc/javascriptrun.swg | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Lib/javascript/jsc/javascriptrun.swg b/Lib/javascript/jsc/javascriptrun.swg index 813c7deb4..9655b0eb6 100644 --- a/Lib/javascript/jsc/javascriptrun.swg +++ b/Lib/javascript/jsc/javascriptrun.swg @@ -129,6 +129,13 @@ SWIGRUNTIME int SWIG_JSC_ConvertInstancePtr(JSContextRef context, JSObjectRef ob SWIGRUNTIME int SWIG_JSC_ConvertPtr(JSContextRef context, JSValueRef valRef, void** ptr, swig_type_info *info, int flags) { JSObjectRef objRef; + + /* special case: JavaScript null => C NULL pointer */ + if(JSValueIsNull(context, valRef)) { + *ptr=0; + return SWIG_OK; + } + if(!JSValueIsObject(context, valRef)) { return SWIG_TypeError; } From 3f0f58889131baacb23583a7deb35d9394bfc141 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 19 May 2014 00:21:21 +0200 Subject: [PATCH 0970/1048] Javascript: support null pointers. We allow to set pointer types using JS null. --- .../javascript/null_pointer_runme.js | 9 +++++++++ Lib/javascript/jsc/javascriptrun.swg | 18 +++++++++++++----- Lib/javascript/v8/javascriptrun.swg | 12 ++++++++++-- 3 files changed, 32 insertions(+), 7 deletions(-) create mode 100644 Examples/test-suite/javascript/null_pointer_runme.js diff --git a/Examples/test-suite/javascript/null_pointer_runme.js b/Examples/test-suite/javascript/null_pointer_runme.js new file mode 100644 index 000000000..7c0d61244 --- /dev/null +++ b/Examples/test-suite/javascript/null_pointer_runme.js @@ -0,0 +1,9 @@ +var null_pointer = require("null_pointer"); + +if (!null_pointer.func(null)) { + throw new Error("Javascript 'null' should be converted into NULL."); +} + +if (null_pointer.getnull() != null) { + throw new Error("NULL should be converted into Javascript 'null'."); +} diff --git a/Lib/javascript/jsc/javascriptrun.swg b/Lib/javascript/jsc/javascriptrun.swg index 9655b0eb6..1ff10a183 100644 --- a/Lib/javascript/jsc/javascriptrun.swg +++ b/Lib/javascript/jsc/javascriptrun.swg @@ -99,7 +99,9 @@ SWIGRUNTIME JSClassRef _SwigObject_classRef; SWIGRUNTIME int SWIG_JSC_ConvertInstancePtr(JSContextRef context, JSObjectRef objRef, void** ptr, swig_type_info *info, int flags) { - SwigPrivData *cdata = (SwigPrivData *) JSObjectGetPrivate(objRef); + SwigPrivData *cdata; + + cdata = (SwigPrivData *) JSObjectGetPrivate(objRef); if(cdata == NULL) { return SWIG_ERROR; } @@ -135,7 +137,7 @@ SWIGRUNTIME int SWIG_JSC_ConvertPtr(JSContextRef context, JSValueRef valRef, voi *ptr=0; return SWIG_OK; } - + if(!JSValueIsObject(context, valRef)) { return SWIG_TypeError; } @@ -149,17 +151,23 @@ SWIGRUNTIME int SWIG_JSC_ConvertPtr(JSContextRef context, JSValueRef valRef, voi } SWIGRUNTIME JSObjectRef SWIG_JSC_NewPointerObj(JSContextRef context, void *ptr, swig_type_info *info, int flags) { - JSClassRef classRef; + JSObjectRef result; + SwigPrivData *cdata; + + if (ptr == NULL) { + return JSValueToObject(context, JSValueMakeNull(context), 0); + } + if(info->clientdata == NULL) { classRef = _SwigObject_classRef; } else { classRef = (JSClassRef) info->clientdata; } - JSObjectRef result = JSObjectMake(context, classRef, NULL); + result = JSObjectMake(context, classRef, NULL); - SwigPrivData* cdata = (SwigPrivData*) malloc(sizeof(SwigPrivData)); + cdata = (SwigPrivData*) malloc(sizeof(SwigPrivData)); cdata->swigCObject = ptr; cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; cdata->info = info; diff --git a/Lib/javascript/v8/javascriptrun.swg b/Lib/javascript/v8/javascriptrun.swg index 2e0a46717..f200f1520 100644 --- a/Lib/javascript/v8/javascriptrun.swg +++ b/Lib/javascript/v8/javascriptrun.swg @@ -220,7 +220,11 @@ void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info int SWIG_V8_ConvertPtr(v8::Handle valRef, void** ptr, swig_type_info *info, int flags) { v8::HandleScope scope; - + /* special case: JavaScript null => C NULL pointer */ + if(valRef->IsNull()) { + *ptr=0; + return SWIG_OK; + } if(!valRef->IsObject()) { return SWIG_TypeError; } @@ -228,10 +232,14 @@ int SWIG_V8_ConvertPtr(v8::Handle valRef, void** ptr, swig_type_info return SWIG_V8_ConvertInstancePtr(objRef, ptr, info, flags); } -v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, int flags) { +v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, int flags) { v8::HandleScope scope; v8::Handle class_templ; + if (ptr == NULL) { + return scope.Close(v8::Null()); + } + #if (SWIG_V8_VERSION < 0x031900) if(info->clientdata != 0) { class_templ = ((SWIGV8_ClientData*) info->clientdata)->class_templ; From 61b7da1671f5d88127eae0cde4561cd7883c825b Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Mon, 19 May 2014 15:59:14 +0200 Subject: [PATCH 0971/1048] JavascriptCore: Bugfix for null-pointer support. This solution must be considered as a preliminary workaround. --- Lib/javascript/jsc/javascriptrun.swg | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Lib/javascript/jsc/javascriptrun.swg b/Lib/javascript/jsc/javascriptrun.swg index 1ff10a183..ae1567e87 100644 --- a/Lib/javascript/jsc/javascriptrun.swg +++ b/Lib/javascript/jsc/javascriptrun.swg @@ -156,7 +156,11 @@ SWIGRUNTIME JSObjectRef SWIG_JSC_NewPointerObj(JSContextRef context, void *ptr, SwigPrivData *cdata; if (ptr == NULL) { - return JSValueToObject(context, JSValueMakeNull(context), 0); + // HACK: it is not possible to use JSValueToObject (causing seg-fault) + // This static cast turned out to be a workaround + // In future, we should change the interface of this method + // to return JSValueRef instead of JSObjectRef. + return (JSObjectRef) JSValueMakeNull(context); } if(info->clientdata == NULL) { From 71e72c45ed89457e2a17f412219d37aad67040be Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Wed, 21 May 2014 19:16:15 +0100 Subject: [PATCH 0972/1048] Create separate extetnd.c file for handling extensions / %extend This is just a simple code refactor, moving and function renaming to remove the %extend code out of the parser into its own file now that it isn't just used in the parser. --- Source/CParse/cparse.h | 2 +- Source/CParse/parser.y | 179 ++++++++------------------------------ Source/CParse/util.c | 14 +++ Source/Makefile.am | 1 + Source/Modules/main.cxx | 3 +- Source/Modules/nested.cxx | 16 ++-- Source/Swig/extend.c | 141 ++++++++++++++++++++++++++++++ Source/Swig/swig.h | 7 ++ 8 files changed, 205 insertions(+), 158 deletions(-) create mode 100644 Source/Swig/extend.c diff --git a/Source/CParse/cparse.h b/Source/CParse/cparse.h index 6d7342a45..5a0d52d23 100644 --- a/Source/CParse/cparse.h +++ b/Source/CParse/cparse.h @@ -59,7 +59,7 @@ extern "C" { extern void cparse_normalize_void(Node *); extern Parm *Swig_cparse_parm(String *s); extern ParmList *Swig_cparse_parms(String *s, Node *file_line_node); - + extern Node *new_node(const_String_or_char_ptr tag); /* templ.c */ extern int Swig_cparse_template_expand(Node *n, String *rname, ParmList *tparms, Symtab *tscope); diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index a1a62cb62..4ce8f0e6d 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -41,7 +41,6 @@ int yyparse(); static Node *top = 0; /* Top of the generated parse tree */ static int unnamed = 0; /* Unnamed datatype counter */ -Hash *extendhash = 0; /* Hash table of added methods */ static Hash *classes = 0; /* Hash table of classes */ static Hash *classes_typedefs = 0; /* Hash table of typedef classes: typedef struct X {...} Y; */ static Symtab *prev_symtab = 0; @@ -71,14 +70,6 @@ static void yyerror (const char *e) { (void)e; } -static Node *new_node(const_String_or_char_ptr tag) { - Node *n = NewHash(); - set_nodeType(n,tag); - Setfile(n,cparse_file); - Setline(n,cparse_line); - return n; -} - /* Copies a node. Does not copy tree links or symbol table data (except for sym:name) */ @@ -650,106 +641,6 @@ static void add_symbols_copy(Node *n) { } } -/* Extension merge. This function is used to handle the %extend directive - when it appears before a class definition. To handle this, the %extend - actually needs to take precedence. Therefore, we will selectively nuke symbols - from the current symbol table, replacing them with the added methods */ - -void merge_extensions(Node *cls, Node *am) { - Node *n; - Node *csym; - - n = firstChild(am); - while (n) { - String *symname; - if (Strcmp(nodeType(n),"constructor") == 0) { - symname = Getattr(n,"sym:name"); - if (symname) { - if (Strcmp(symname,Getattr(n,"name")) == 0) { - /* If the name and the sym:name of a constructor are the same, - then it hasn't been renamed. However---the name of the class - itself might have been renamed so we need to do a consistency - check here */ - if (Getattr(cls,"sym:name")) { - Setattr(n,"sym:name", Getattr(cls,"sym:name")); - } - } - } - } - - symname = Getattr(n,"sym:name"); - DohIncref(symname); - if ((symname) && (!Getattr(n,"error"))) { - /* Remove node from its symbol table */ - Swig_symbol_remove(n); - csym = Swig_symbol_add(symname,n); - if (csym != n) { - /* Conflict with previous definition. Nuke previous definition */ - String *e = NewStringEmpty(); - String *en = NewStringEmpty(); - String *ec = NewStringEmpty(); - Printf(ec,"Identifier '%s' redefined by %%extend (ignored),",symname); - Printf(en,"%%extend definition of '%s'.",symname); - SWIG_WARN_NODE_BEGIN(n); - Swig_warning(WARN_PARSE_REDEFINED,Getfile(csym),Getline(csym),"%s\n",ec); - Swig_warning(WARN_PARSE_REDEFINED,Getfile(n),Getline(n),"%s\n",en); - SWIG_WARN_NODE_END(n); - Printf(e,"%s:%d:%s\n%s:%d:%s\n",Getfile(csym),Getline(csym),ec, - Getfile(n),Getline(n),en); - Setattr(csym,"error",e); - Delete(e); - Delete(en); - Delete(ec); - Swig_symbol_remove(csym); /* Remove class definition */ - Swig_symbol_add(symname,n); /* Insert extend definition */ - } - } - n = nextSibling(n); - } -} - -void append_previous_extension(Node *cls, Node *am) { - Node *n, *ne; - Node *pe = 0; - Node *ae = 0; - - if (!am) return; - - n = firstChild(am); - while (n) { - ne = nextSibling(n); - set_nextSibling(n,0); - /* typemaps and fragments need to be prepended */ - if (((Cmp(nodeType(n),"typemap") == 0) || (Cmp(nodeType(n),"fragment") == 0))) { - if (!pe) pe = new_node("extend"); - appendChild(pe, n); - } else { - if (!ae) ae = new_node("extend"); - appendChild(ae, n); - } - n = ne; - } - if (pe) prependChild(cls,pe); - if (ae) appendChild(cls,ae); -} - - -/* Check for unused %extend. Special case, don't report unused - extensions for templates */ - -void check_extensions() { - Iterator ki; - - if (!extendhash) return; - for (ki = First(extendhash); ki.key; ki = Next(ki)) { - if (!Strchr(ki.key,'<')) { - SWIG_WARN_NODE_BEGIN(ki.item); - Swig_warning(WARN_PARSE_EXTEND_UNDEF,Getfile(ki.item), Getline(ki.item), "%%extend defined for an undeclared class %s.\n", SwigType_namestr(ki.key)); - SWIG_WARN_NODE_END(ki.item); - } - } -} - /* Check a set of declarations to see if any are pure-abstract */ static List *pure_abstracts(Node *n) { @@ -1682,14 +1573,13 @@ extend_directive : EXTEND options idcolon LBRACE { cplus_mode = CPLUS_PUBLIC; if (!classes) classes = NewHash(); if (!classes_typedefs) classes_typedefs = NewHash(); - if (!extendhash) extendhash = NewHash(); clsname = make_class_name($3); cls = Getattr(classes,clsname); if (!cls) { cls = Getattr(classes_typedefs, clsname); if (!cls) { /* No previous definition. Create a new scope */ - Node *am = Getattr(extendhash,clsname); + Node *am = Getattr(Swig_extend_hash(),clsname); if (!am) { Swig_symbol_newscope(); Swig_symbol_setscopename($3); @@ -1735,13 +1625,13 @@ extend_directive : EXTEND options idcolon LBRACE { appendChild(current_class,$$); } else { /* We store the extensions in the extensions hash */ - Node *am = Getattr(extendhash,clsname); + Node *am = Getattr(Swig_extend_hash(),clsname); if (am) { /* Append the members to the previous extend methods */ appendChild(am,$6); } else { appendChild($$,$6); - Setattr(extendhash,clsname,$$); + Setattr(Swig_extend_hash(),clsname,$$); } } current_class = 0; @@ -2824,8 +2714,7 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va /* !!! This may be broken. We may have to add the %extend methods at the beginning of the class */ - - if (extendhash) { + { String *stmp = 0; String *clsname; Node *am; @@ -2834,32 +2723,32 @@ template_directive: SWIGTEMPLATE LPAREN idstringopt RPAREN idcolonnt LESSTHAN va } else { clsname = Getattr(templnode,"name"); } - am = Getattr(extendhash,clsname); + am = Getattr(Swig_extend_hash(),clsname); if (am) { Symtab *st = Swig_symbol_current(); Swig_symbol_setscope(Getattr(templnode,"symtab")); /* Printf(stdout,"%s: %s %p %p\n", Getattr(templnode,"name"), clsname, Swig_symbol_current(), Getattr(templnode,"symtab")); */ - merge_extensions(templnode,am); + Swig_extend_merge(templnode,am); Swig_symbol_setscope(st); - append_previous_extension(templnode,am); - Delattr(extendhash,clsname); + Swig_extend_append_previous(templnode,am); + Delattr(Swig_extend_hash(),clsname); } if (stmp) Delete(stmp); } - /* Add to classes hash */ - if (!classes) classes = NewHash(); - { - if (Namespaceprefix) { - String *temp = NewStringf("%s::%s", Namespaceprefix, Getattr(templnode,"name")); - Setattr(classes,temp,templnode); - Delete(temp); - } else { - String *qs = Swig_symbol_qualifiedscopename(templnode); - Setattr(classes, qs,templnode); - Delete(qs); - } - } + /* Add to classes hash */ + if (!classes) + classes = NewHash(); + + if (Namespaceprefix) { + String *temp = NewStringf("%s::%s", Namespaceprefix, Getattr(templnode,"name")); + Setattr(classes,temp,templnode); + Delete(temp); + } else { + String *qs = Swig_symbol_qualifiedscopename(templnode); + Setattr(classes, qs,templnode); + Delete(qs); + } } } @@ -3571,13 +3460,12 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { Setattr($$,"abstracts", pure_abstracts($7)); /* This bit of code merges in a previously defined %extend directive (if any) */ - - if (extendhash) { + { String *clsname = Swig_symbol_qualifiedscopename(0); - am = Getattr(extendhash, clsname); + am = Getattr(Swig_extend_hash(), clsname); if (am) { - merge_extensions($$, am); - Delattr(extendhash, clsname); + Swig_extend_merge($$, am); + Delattr(Swig_extend_hash(), clsname); } Delete(clsname); } @@ -3588,7 +3476,7 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { appendChild($$, $7); if (am) - append_previous_extension($$, am); + Swig_extend_append_previous($$, am); p = $9; if (p && !nscope_inner) { @@ -3787,15 +3675,16 @@ cpp_class_decl : storage_class cpptype idcolon inherit LBRACE { n = nextSibling(n); } n = $8; - /* Check for previous extensions */ - if (extendhash) { + + /* Check for previous extensions */ + { String *clsname = Swig_symbol_qualifiedscopename(0); - Node *am = Getattr(extendhash,clsname); + Node *am = Getattr(Swig_extend_hash(),clsname); if (am) { - /* Merge the extension into the symbol table */ - merge_extensions($$,am); - append_previous_extension($$,am); - Delattr(extendhash,clsname); + /* Merge the extension into the symbol table */ + Swig_extend_merge($$,am); + Swig_extend_append_previous($$,am); + Delattr(Swig_extend_hash(),clsname); } Delete(clsname); } diff --git a/Source/CParse/util.c b/Source/CParse/util.c index 7572dff10..320671d9a 100644 --- a/Source/CParse/util.c +++ b/Source/CParse/util.c @@ -88,3 +88,17 @@ void cparse_normalize_void(Node *n) { } } } + +/* ----------------------------------------------------------------------------- + * new_node() + * + * Create an empty parse node, setting file and line number information + * ----------------------------------------------------------------------------- */ + +Node *new_node(const_String_or_char_ptr tag) { + Node *n = NewHash(); + set_nodeType(n,tag); + Setfile(n,cparse_file); + Setline(n,cparse_line); + return n; +} diff --git a/Source/Makefile.am b/Source/Makefile.am index d5331cba1..da65b2326 100644 --- a/Source/Makefile.am +++ b/Source/Makefile.am @@ -77,6 +77,7 @@ eswig_SOURCES = CParse/cscanner.c \ Swig/cwrap.c \ Swig/deprecate.c \ Swig/error.c \ + Swig/extend.c \ Swig/fragment.c \ Swig/getopt.c \ Swig/include.c \ diff --git a/Source/Modules/main.cxx b/Source/Modules/main.cxx index d8f20c207..47d0d374b 100644 --- a/Source/Modules/main.cxx +++ b/Source/Modules/main.cxx @@ -198,7 +198,6 @@ static String *external_runtime_name = 0; enum { STAGE1=1, STAGE2=2, STAGE3=4, STAGE4=8, STAGEOVERFLOW=16 }; static List *libfiles = 0; static List *all_output_files = 0; -extern "C" void check_extensions(); /* ----------------------------------------------------------------------------- * check_extension() @@ -1173,7 +1172,7 @@ int SWIG_main(int argc, char *argv[], Language *l) { Printf(stdout, "Processing unnamed structs...\n"); Swig_nested_name_unnamed_c_structs(top); } - check_extensions(); + Swig_extend_unused_check(); if (Verbose) { Printf(stdout, "Processing types...\n"); diff --git a/Source/Modules/nested.cxx b/Source/Modules/nested.cxx index ca1c79a31..9ec52ead1 100644 --- a/Source/Modules/nested.cxx +++ b/Source/Modules/nested.cxx @@ -338,9 +338,7 @@ static void insertNodeAfter(Node *n, Node *c) { set_nextSibling(n, c); set_previousSibling(c, n); } -extern "C" Hash *extendhash; -extern "C" void merge_extensions(Node *cls, Node *am); -extern "C" void append_previous_extension(Node *cls, Node *am); + void Swig_nested_name_unnamed_c_structs(Node *n) { if (!classhash) classhash = Getattr(n, "classes"); @@ -378,13 +376,11 @@ void Swig_nested_name_unnamed_c_structs(Node *n) { decl = nextSibling(decl); } Delete(ty); - 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, name); - } + if (Node *am = Getattr(Swig_extend_hash(), name)) { + // Merge the extension into the symbol table + Swig_extend_merge(c, am); + Swig_extend_append_previous(c, am); + Delattr(Swig_extend_hash(), name); } Swig_symbol_setscope(Swig_symbol_global_scope()); add_symbols_c(c); diff --git a/Source/Swig/extend.c b/Source/Swig/extend.c new file mode 100644 index 000000000..30097b434 --- /dev/null +++ b/Source/Swig/extend.c @@ -0,0 +1,141 @@ +/* ----------------------------------------------------------------------------- + * 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. + * + * extend.c + * + * Extensions support (%extend) + * ----------------------------------------------------------------------------- */ + +#include "swig.h" +#include "cparse.h" + +static Hash *extendhash = 0; /* Hash table of added methods */ + +/* ----------------------------------------------------------------------------- + * Swig_extend_hash() + * + * Access the extend hash + * ----------------------------------------------------------------------------- */ +Hash *Swig_extend_hash(void) { + if (!extendhash) + extendhash = NewHash(); + return extendhash; +} + +/* ----------------------------------------------------------------------------- + * Swig_extend_merge() + * + * Extension merge. This function is used to handle the %extend directive + * when it appears before a class definition. To handle this, the %extend + * actually needs to take precedence. Therefore, we will selectively nuke symbols + * from the current symbol table, replacing them with the added methods. + * ----------------------------------------------------------------------------- */ + +void Swig_extend_merge(Node *cls, Node *am) { + Node *n; + Node *csym; + + n = firstChild(am); + while (n) { + String *symname; + if (Strcmp(nodeType(n),"constructor") == 0) { + symname = Getattr(n,"sym:name"); + if (symname) { + if (Strcmp(symname,Getattr(n,"name")) == 0) { + /* If the name and the sym:name of a constructor are the same, + then it hasn't been renamed. However---the name of the class + itself might have been renamed so we need to do a consistency + check here */ + if (Getattr(cls,"sym:name")) { + Setattr(n,"sym:name", Getattr(cls,"sym:name")); + } + } + } + } + + symname = Getattr(n,"sym:name"); + DohIncref(symname); + if ((symname) && (!Getattr(n,"error"))) { + /* Remove node from its symbol table */ + Swig_symbol_remove(n); + csym = Swig_symbol_add(symname,n); + if (csym != n) { + /* Conflict with previous definition. Nuke previous definition */ + String *e = NewStringEmpty(); + String *en = NewStringEmpty(); + String *ec = NewStringEmpty(); + Printf(ec,"Identifier '%s' redefined by %%extend (ignored),",symname); + Printf(en,"%%extend definition of '%s'.",symname); + SWIG_WARN_NODE_BEGIN(n); + Swig_warning(WARN_PARSE_REDEFINED,Getfile(csym),Getline(csym),"%s\n",ec); + Swig_warning(WARN_PARSE_REDEFINED,Getfile(n),Getline(n),"%s\n",en); + SWIG_WARN_NODE_END(n); + Printf(e,"%s:%d:%s\n%s:%d:%s\n",Getfile(csym),Getline(csym),ec, + Getfile(n),Getline(n),en); + Setattr(csym,"error",e); + Delete(e); + Delete(en); + Delete(ec); + Swig_symbol_remove(csym); /* Remove class definition */ + Swig_symbol_add(symname,n); /* Insert extend definition */ + } + } + n = nextSibling(n); + } +} + +/* ----------------------------------------------------------------------------- + * Swig_extend_append_previous() + * ----------------------------------------------------------------------------- */ + +void Swig_extend_append_previous(Node *cls, Node *am) { + Node *n, *ne; + Node *pe = 0; + Node *ae = 0; + + if (!am) return; + + n = firstChild(am); + while (n) { + ne = nextSibling(n); + set_nextSibling(n,0); + /* typemaps and fragments need to be prepended */ + if (((Cmp(nodeType(n),"typemap") == 0) || (Cmp(nodeType(n),"fragment") == 0))) { + if (!pe) pe = new_node("extend"); + appendChild(pe, n); + } else { + if (!ae) ae = new_node("extend"); + appendChild(ae, n); + } + n = ne; + } + if (pe) prependChild(cls,pe); + if (ae) appendChild(cls,ae); +} + + +/* ----------------------------------------------------------------------------- + * Swig_extend_unused_check() + * + * Check for unused %extend. Special case, don't report unused + * extensions for templates + * ----------------------------------------------------------------------------- */ + +void Swig_extend_unused_check(void) { + Iterator ki; + + if (!extendhash) return; + for (ki = First(extendhash); ki.key; ki = Next(ki)) { + if (!Strchr(ki.key,'<')) { + SWIG_WARN_NODE_BEGIN(ki.item); + Swig_warning(WARN_PARSE_EXTEND_UNDEF,Getfile(ki.item), Getline(ki.item), "%%extend defined for an undeclared class %s.\n", SwigType_namestr(ki.key)); + SWIG_WARN_NODE_END(ki.item); + } + } +} + diff --git a/Source/Swig/swig.h b/Source/Swig/swig.h index 5334a29f0..5ee7f8d95 100644 --- a/Source/Swig/swig.h +++ b/Source/Swig/swig.h @@ -420,6 +420,13 @@ extern int ParmList_is_compactdefargs(ParmList *p); extern void Swig_fragment_emit(String *name); extern void Swig_fragment_clear(String *section); +/* --- Extension support --- */ + + extern Hash *Swig_extend_hash(void); + extern void Swig_extend_merge(Node *cls, Node *am); + extern void Swig_extend_append_previous(Node *cls, Node *am); + extern void Swig_extend_unused_check(void); + /* hacks defined in C++ ! */ extern int Swig_director_mode(void); extern int Swig_director_protected_mode(void); From d9cac664620d282aa423d3f0ef55ab9a677156a4 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Wed, 21 May 2014 20:04:48 +0100 Subject: [PATCH 0973/1048] Add missing entries into changes files. --- CHANGES.current | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/CHANGES.current b/CHANGES.current index 8b67392b2..e73a91c3f 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,18 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.1 (in progress) =========================== +2014-05-18: vkalinin + Bug #175 - Restore %extend to work for unnamed nested structures by using a C + symbol comprising the outer structure name and unnamed variable instance name. + +2014-05-15: kwwette + Add #166 - 'make check' now works out of source. This required te examples to build + out of source. The main languages have been tested - C#, Go, Guile, Java, Javascript, + Lua, Octave, Perl, PHP, Python, Ruby and Tcl. + +2014-05-01: Oliver Buchtala + Javascript support added, see Javascript chapter in the documentation. + 2014-05-01: olly [PHP] The generated __isset() method now returns true for read-only properties. From 9846f3f1eac0835e9d1870f41ea0c03f3006a687 Mon Sep 17 00:00:00 2001 From: Harvey Falcic Date: Wed, 16 Apr 2014 11:13:21 -0400 Subject: [PATCH 0974/1048] Python 3 byte string output: use errors="surrogateescape" ... if available on the version of Python that's in use. This allows obtaining the original byte string (and potentially trying a fallback encoding) if the bytes can't be decoded as UTF-8. Previously, a UnicodeDecodeError would be raised with no way to treat the data as bytes or try another codec. --- Lib/python/pystrings.swg | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Lib/python/pystrings.swg b/Lib/python/pystrings.swg index f6a4eba8a..2b14547ad 100644 --- a/Lib/python/pystrings.swg +++ b/Lib/python/pystrings.swg @@ -89,7 +89,11 @@ SWIG_FromCharPtrAndSize(const char* carray, size_t size) SWIG_InternalNewPointerObj(%const_cast(carray,char *), pchar_descriptor, 0) : SWIG_Py_Void(); } else { %#if PY_VERSION_HEX >= 0x03000000 +%#if PY_VERSION_HEX >= 0x03010000 + return PyUnicode_DecodeUTF8(carray, %numeric_cast(size,int), "surrogateescape"); +%#else return PyUnicode_FromStringAndSize(carray, %numeric_cast(size,int)); +%#endif %#else return PyString_FromStringAndSize(carray, %numeric_cast(size,int)); %#endif From 791f070e66ee4cf96f0df0a4d00e1fe688f6bb80 Mon Sep 17 00:00:00 2001 From: Harvey Falcic Date: Thu, 22 May 2014 22:53:07 -0400 Subject: [PATCH 0975/1048] Add "unicode_strings" test case for new Python 3 behavior --- Examples/test-suite/common.mk | 1 + .../test-suite/python/unicode_strings_runme.py | 4 ++++ Examples/test-suite/unicode_strings.i | 15 +++++++++++++++ 3 files changed, 20 insertions(+) create mode 100644 Examples/test-suite/python/unicode_strings_runme.py create mode 100644 Examples/test-suite/unicode_strings.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index bfb960fe5..bc1ca5cb8 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -473,6 +473,7 @@ CPP_TEST_CASES += \ typemap_various \ typename \ types_directive \ + unicode_strings \ union_scope \ using1 \ using2 \ diff --git a/Examples/test-suite/python/unicode_strings_runme.py b/Examples/test-suite/python/unicode_strings_runme.py new file mode 100644 index 000000000..2d26599aa --- /dev/null +++ b/Examples/test-suite/python/unicode_strings_runme.py @@ -0,0 +1,4 @@ +import unicode_strings + +unicode_strings.test_c_str() +unicode_strings.test_std_string() diff --git a/Examples/test-suite/unicode_strings.i b/Examples/test-suite/unicode_strings.i new file mode 100644 index 000000000..f4a8b8b50 --- /dev/null +++ b/Examples/test-suite/unicode_strings.i @@ -0,0 +1,15 @@ +%module unicode_strings + +%include + +%inline %{ + +const char* test_c_str(void) { + return "h\xe9llo"; +} + +std::string test_std_string(void) { + return std::string("h\xe9llo"); +} + +%} From 5fc851a1e0928d5c179c2b9336e76d5e19324d25 Mon Sep 17 00:00:00 2001 From: Harvey Falcic Date: Fri, 23 May 2014 15:24:35 -0400 Subject: [PATCH 0976/1048] Add Python 3 'surrogateescape' documentation --- Doc/Manual/Python.html | 87 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/Doc/Manual/Python.html b/Doc/Manual/Python.html index bdb1ada30..45725065d 100644 --- a/Doc/Manual/Python.html +++ b/Doc/Manual/Python.html @@ -116,6 +116,7 @@

  • Function annotation
  • Buffer interface
  • Abstract base classes +
  • Byte string output conversion @@ -5928,6 +5929,92 @@ For details of abstract base class, please see PEP 3119.

    +

    35.12.4 Byte string output conversion

    + + +

    +By default, any byte string (char* or std::string) returned +from C or C++ code is decoded to text as UTF-8. This decoding uses the +surrogateescape error handler under Python 3.1 or higher -- this +error handler decodes invalid byte sequences to high surrogate characters +in the range U+DC80 to U+DCFF. + +As an example, consider the following SWIG interface, which exposes a byte +string that cannot be completely decoded as UTF-8: +

    + +
    +%module example
    +
    +%include <std_string.i>
    +
    +%inline %{
    +
    +const char* non_utf8_c_str(void) {
    +        return "h\xe9llo w\xc3\xb6rld";
    +}
    +
    +%}
    +
    + +

    +When this method is called from Python 3, the return value is the following +text string: +

    + +
    +>>> s = test.non_utf8_c_str()
    +>>> s
    +'h\udce9llo wörld'
    +
    + +

    +Since the C string contains bytes that cannot be decoded as UTF-8, those raw +bytes are represented as high surrogate characters that can be used to obtain +the original byte sequence: +

    + +
    +>>> b = s.encode('utf-8', errors='surrogateescape')
    +>>> b
    +b'h\xe9llo w\xc3\xb6rld'
    +
    + +

    +One can then attempt a different encoding, if desired (or simply leave the +byte string as a raw sequence of bytes for use in binary protocols): +

    + +
    +>>> b.decode('latin-1')
    +'héllo wörld'
    +
    + +

    +Note, however, that text strings containing surrogate characters are rejected +with the default strict codec error handler. For example: +

    + +
    +>>> with open('test', 'w') as f:
    +...     print(s, file=f)
    +...
    +Traceback (most recent call last):
    +  File "<stdin>", line 2, in <module>
    +UnicodeEncodeError: 'utf-8' codec can't encode character '\udce9' in position 1: surrogates not allowed
    +
    + +

    +This requires the user to check most strings returned by SWIG bindings, but +the alternative is for a non-UTF8 byte string to be completely inaccessible +in Python 3 code. +

    + +

    +For more details about the surrogateescape error handler, please see +PEP 383. +

    + From 8d3902a6666799a01ff23ee501c478b1371d19a1 Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Sat, 24 May 2014 11:10:57 +1200 Subject: [PATCH 0977/1048] Work towards C90 compatibility for Lua --- Lib/lua/luarun.swg | 49 ++++++++++++++++++++++++++-------------------- 1 file changed, 28 insertions(+), 21 deletions(-) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index ad735a541..dd668587f 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -392,8 +392,9 @@ static int swig_lua_elua_emulate_unique_key; /* 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) { + int i, table_parsed, parsed_tables_array, target_table; assert(lua_istable(L,-1)); - int target_table = lua_gettop(L); + 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)) { @@ -402,11 +403,10 @@ SWIGINTERN void SWIG_Lua_elua_emulate_register(lua_State *L, const swig_elua_ent lua_pushvalue(L,-1); lua_rawsetp(L,LUA_REGISTRYINDEX,(void*)(&swig_lua_elua_emulate_unique_key)); } - int parsed_tables_array = lua_gettop(L); + parsed_tables_array = lua_gettop(L); lua_pushvalue(L,target_table); lua_rawsetp(L, parsed_tables_array, table); - int i; - int table_parsed = 0; + table_parsed = 0; const int SWIGUNUSED pairs_start = lua_gettop(L); for(i = 0;table[i].key.type != LUA_TNIL || table[i].value.type != LUA_TNIL;i++) { @@ -606,7 +606,7 @@ 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; + int i; /* 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); @@ -753,11 +753,13 @@ SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info * SWIGUNUSED /* 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 original_metatable; size_t bases_count; + int result; + lua_getmetatable(L,first_arg); + original_metatable = last_arg + 1; SWIG_LUA_INIT_BASE_SEARCH(bases_count); - int result = SWIG_ERROR; + result = SWIG_ERROR; if(ret) *ret = 0; if(bases_count>0) @@ -766,10 +768,11 @@ SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info * SWIGUNUSED int j; int subcall_first_arg = lua_gettop(L) + 1;/* Here a copy of first_arg and arguments begin */ int valid = 1; + int subcall_last_arg; + swig_type_info *base_swig_type = 0; 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; + subcall_last_arg = lua_gettop(L); /* Trick: temporarily replacing original metatable with metatable for base class and call getter */ for(i=0;ifqname); /* get the name */ @@ -1499,7 +1507,6 @@ SWIGINTERN void SWIG_Lua_class_register_instance(lua_State *L,swig_lua_class *c } 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]); @@ -1604,6 +1611,7 @@ SWIGINTERN void SWIG_Lua_class_register(lua_State *L,swig_lua_class *clss) SWIGINTERN void SWIG_Lua_elua_class_register_instance(lua_State *L, swig_lua_class *clss) { const int SWIGUNUSED begin = lua_gettop(L); + int i; /* 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 */ @@ -1615,7 +1623,6 @@ SWIGINTERN void SWIG_Lua_elua_class_register_instance(lua_State *L, swig_lua_cla } 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]); From 1a0b8abec735ec0db088a1c4c2da1b71cad7ff0e Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Sat, 24 May 2014 11:11:51 +1200 Subject: [PATCH 0978/1048] Fix comment typo --- Lib/lua/luarun.swg | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index dd668587f..7cfcff212 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -1838,8 +1838,8 @@ SWIG_Lua_InstallConstants(lua_State *L, swig_lua_const_info constants[]) { #endif /* Executes a C string in Lua which is a really simple way of calling lua from C Unfortunately lua keeps changing its APIs, so we need a conditional compile -In lua 5.0.X its lua_dostring() -In lua 5.1.X its luaL_dostring() +In lua 5.0.X it's lua_dostring() +In lua 5.1.X it's luaL_dostring() */ SWIGINTERN int SWIG_Lua_dostring(lua_State *L, const char *str) { From 879296f71bcfd56a7659355942c784176ae06e6c Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 24 May 2014 00:12:27 +0100 Subject: [PATCH 0979/1048] Correct CFLAGS CXXFLAGS for Javascript and guile examples --- Examples/Makefile.in | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index b22fd2e76..3a91cddd3 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -498,7 +498,7 @@ guile_externalhdr: guile_augmented: $(SRCDIR_SRCS) $(SWIG) -guile $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) - $(CC) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(GUILE_CFLAGS) $(GUILE_LIBS) $(LIBS) -o $(TARGET) + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(GUILE_CFLAGS) $(GUILE_LIBS) $(LIBS) -o $(TARGET) # ----------------------------------------------------------------- # Build statically linked Guile interpreter @@ -656,8 +656,8 @@ ifeq (node,$(JSENGINE)) sed -e 's|$$srcdir|./$(SRCDIR)|g' $(SRCDIR)binding.gyp.in > binding.gyp $(NODEGYP) --loglevel=silent configure build 1>>/dev/null else - $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(JSINCLUDES) - $(CXXSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(JSINCLUDES) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) endif @@ -669,14 +669,14 @@ ifeq (jsc, $(ENGINE)) $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(INCLUDES) $(JSINCLUDES) $(LDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) else # (v8 | node) # v8 and node must be compiled as c++ - $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(JSINCLUDES) - $(CXXSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(ISRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(JSINCLUDES) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) endif javascript_cpp: $(SRCDIR_SRCS) javascript_custom_interpreter $(SWIG) -javascript -c++ $(SWIGOPT) $(INTERFACEPATH) - $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(JSINCLUDES) - $(CXXSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(ICXXSRCS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(INCLUDES) $(JSINCLUDES) + $(CXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) # ----------------------------------------------------------------- # Running a Javascript example From f39ed94419e4a30b8b2ba1d49c138fd245010262 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 24 May 2014 00:14:01 +0100 Subject: [PATCH 0980/1048] Fix compiler warnings in examples when using -std=c++98 -std=gnu89 -pedantic -Wreturn-type --- Examples/csharp/extend/example.h | 2 +- Examples/csharp/reference/example.cxx | 2 +- Examples/csharp/variables/example.c | 4 ++-- Examples/d/extend/example.h | 2 +- Examples/d/variables/example.c | 4 ++-- Examples/go/extend/example.h | 2 +- Examples/go/reference/reference.cxx | 2 +- Examples/java/extend/example.h | 2 +- Examples/java/reference/example.cxx | 2 +- Examples/java/variables/example.c | 4 ++-- Examples/javascript/reference/example.cxx | 2 +- Examples/javascript/variables/example.cxx | 4 ++-- Examples/lua/arrays/example.c | 2 +- Examples/lua/dual/dual.cpp | 6 +++--- Examples/lua/embed2/embed2.c | 10 +++++----- Examples/lua/functest/example.i | 13 ++++++------- Examples/lua/owner/example.cxx | 11 +++++++---- Examples/lua/variables/example.c | 4 ++-- Examples/modula3/reference/example.cxx | 2 +- Examples/octave/extend/example.h | 2 +- Examples/octave/reference/example.cxx | 2 +- Examples/octave/variables/example.c | 4 ++-- Examples/perl5/extend/example.h | 2 +- Examples/perl5/reference/example.cxx | 2 +- Examples/perl5/value/example.i | 2 +- Examples/perl5/variables/example.c | 4 ++-- Examples/php/extend/example.h | 2 +- Examples/php/reference/example.cxx | 10 +++++----- Examples/php/reference/example.i | 2 +- Examples/php/sync/example.cxx | 2 +- Examples/php/value/example.i | 2 +- Examples/php/variables/example.c | 4 ++-- Examples/python/extend/example.h | 2 +- Examples/python/reference/example.cxx | 2 +- Examples/python/swigrun/example.cxx | 2 +- Examples/python/swigrun/example.h | 2 +- Examples/python/variables/example.c | 4 ++-- Examples/ruby/reference/example.cxx | 2 +- Examples/ruby/value/example.i | 2 +- Examples/ruby/variables/example.c | 4 ++-- Examples/tcl/reference/example.cxx | 2 +- Examples/tcl/value/example.i | 2 +- Examples/tcl/variables/example.c | 4 ++-- 43 files changed, 75 insertions(+), 73 deletions(-) diff --git a/Examples/csharp/extend/example.h b/Examples/csharp/extend/example.h index b27ab9711..ca1aed28f 100644 --- a/Examples/csharp/extend/example.h +++ b/Examples/csharp/extend/example.h @@ -14,7 +14,7 @@ public: 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); } + virtual ~Employee() { printf("~Employee() @ %p\n", (void *)this); } }; diff --git a/Examples/csharp/reference/example.cxx b/Examples/csharp/reference/example.cxx index 8a513bf49..9dbaed2ee 100644 --- a/Examples/csharp/reference/example.cxx +++ b/Examples/csharp/reference/example.cxx @@ -19,7 +19,7 @@ Vector operator+(const Vector &a, const Vector &b) { char *Vector::print() { static char temp[512]; - sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z); + sprintf(temp,"Vector %p (%g,%g,%g)", (void *)this, x,y,z); return temp; } diff --git a/Examples/csharp/variables/example.c b/Examples/csharp/variables/example.c index 05e17c8c5..85685fe72 100644 --- a/Examples/csharp/variables/example.c +++ b/Examples/csharp/variables/example.c @@ -52,9 +52,9 @@ void print_vars() { printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); printf("cstrvar = %s\n", cstrvar); - printf("iptrvar = %p\n", iptrvar); + printf("iptrvar = %p\n", (void *)iptrvar); printf("name = %s\n", name); - printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); + printf("ptptr = %p (%d, %d)\n", (void *)ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); printf("pt = (%d, %d)\n", pt.x, pt.y); printf("status = %d\n", status); } diff --git a/Examples/d/extend/example.h b/Examples/d/extend/example.h index 7ad93fbc1..7a8c04c33 100644 --- a/Examples/d/extend/example.h +++ b/Examples/d/extend/example.h @@ -14,7 +14,7 @@ public: 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); } + virtual ~Employee() { printf("~Employee() @ %p\n", (void *)this); } }; diff --git a/Examples/d/variables/example.c b/Examples/d/variables/example.c index 3b4e9f346..f5356c755 100644 --- a/Examples/d/variables/example.c +++ b/Examples/d/variables/example.c @@ -52,9 +52,9 @@ void print_vars() { printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); printf("cstrvar = %s\n", cstrvar); - printf("iptrvar = %p\n", iptrvar); + printf("iptrvar = %p\n", (void *)iptrvar); printf("name = %s\n", name); - printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); + printf("ptptr = %p (%d, %d)\n", (void *)ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); printf("pt = (%d, %d)\n", pt.x, pt.y); printf("status = %d\n", status); } diff --git a/Examples/go/extend/example.h b/Examples/go/extend/example.h index b27ab9711..ca1aed28f 100644 --- a/Examples/go/extend/example.h +++ b/Examples/go/extend/example.h @@ -14,7 +14,7 @@ public: 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); } + virtual ~Employee() { printf("~Employee() @ %p\n", (void *)this); } }; diff --git a/Examples/go/reference/reference.cxx b/Examples/go/reference/reference.cxx index 8a513bf49..9dbaed2ee 100644 --- a/Examples/go/reference/reference.cxx +++ b/Examples/go/reference/reference.cxx @@ -19,7 +19,7 @@ Vector operator+(const Vector &a, const Vector &b) { char *Vector::print() { static char temp[512]; - sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z); + sprintf(temp,"Vector %p (%g,%g,%g)", (void *)this, x,y,z); return temp; } diff --git a/Examples/java/extend/example.h b/Examples/java/extend/example.h index b27ab9711..ca1aed28f 100644 --- a/Examples/java/extend/example.h +++ b/Examples/java/extend/example.h @@ -14,7 +14,7 @@ public: 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); } + virtual ~Employee() { printf("~Employee() @ %p\n", (void *)this); } }; diff --git a/Examples/java/reference/example.cxx b/Examples/java/reference/example.cxx index 8a513bf49..9dbaed2ee 100644 --- a/Examples/java/reference/example.cxx +++ b/Examples/java/reference/example.cxx @@ -19,7 +19,7 @@ Vector operator+(const Vector &a, const Vector &b) { char *Vector::print() { static char temp[512]; - sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z); + sprintf(temp,"Vector %p (%g,%g,%g)", (void *)this, x,y,z); return temp; } diff --git a/Examples/java/variables/example.c b/Examples/java/variables/example.c index 05e17c8c5..85685fe72 100644 --- a/Examples/java/variables/example.c +++ b/Examples/java/variables/example.c @@ -52,9 +52,9 @@ void print_vars() { printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); printf("cstrvar = %s\n", cstrvar); - printf("iptrvar = %p\n", iptrvar); + printf("iptrvar = %p\n", (void *)iptrvar); printf("name = %s\n", name); - printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); + printf("ptptr = %p (%d, %d)\n", (void *)ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); printf("pt = (%d, %d)\n", pt.x, pt.y); printf("status = %d\n", status); } diff --git a/Examples/javascript/reference/example.cxx b/Examples/javascript/reference/example.cxx index 8a513bf49..9dbaed2ee 100644 --- a/Examples/javascript/reference/example.cxx +++ b/Examples/javascript/reference/example.cxx @@ -19,7 +19,7 @@ Vector operator+(const Vector &a, const Vector &b) { char *Vector::print() { static char temp[512]; - sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z); + sprintf(temp,"Vector %p (%g,%g,%g)", (void *)this, x,y,z); return temp; } diff --git a/Examples/javascript/variables/example.cxx b/Examples/javascript/variables/example.cxx index f10390a9e..15314b383 100644 --- a/Examples/javascript/variables/example.cxx +++ b/Examples/javascript/variables/example.cxx @@ -57,9 +57,9 @@ void print_vars() { printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); printf("cstrvar = %s\n", cstrvar); - printf("iptrvar = %p\n", iptrvar); + printf("iptrvar = %p\n", (void *)iptrvar); printf("name = %s\n", name); - printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); + printf("ptptr = %p (%d, %d)\n", (void *)ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); printf("pt = (%d, %d)\n", pt.x, pt.y); printf("status = %d\n", status); } diff --git a/Examples/lua/arrays/example.c b/Examples/lua/arrays/example.c index ed23738c8..da1bd755a 100644 --- a/Examples/lua/arrays/example.c +++ b/Examples/lua/arrays/example.c @@ -13,7 +13,7 @@ void sort_int(int* arr, int len) qsort(arr, len, sizeof(int), compare_int); } -// ditto doubles +/* ditto doubles */ int compare_double(const void * a, const void * b) { return (int)( *(double*)a - *(double*)b ); diff --git a/Examples/lua/dual/dual.cpp b/Examples/lua/dual/dual.cpp index b54e44de1..2108a7275 100644 --- a/Examples/lua/dual/dual.cpp +++ b/Examples/lua/dual/dual.cpp @@ -45,14 +45,14 @@ void testModule(lua_State *L) swig_type_info *pTypeInfo=0,*pTypeInfo2=0; swig_module_info *pModule=0; pModule=SWIG_GetModule(L); - DEBUG2(" SWIG_GetModule() returns %p\n",pModule) + DEBUG2(" SWIG_GetModule() returns %p\n", (void *)pModule) if(pModule==0) return; pTypeInfo = SWIG_TypeQuery(L,"Foo *"); DEBUG2(" Type (Foo*) is %s\n",pTypeInfo==0?"unknown":"known"); - DEBUG3(" Module %p typeinfo(Foo*) %p\n",pModule,pTypeInfo); + DEBUG3(" Module %p typeinfo(Foo*) %p\n", (void *)pModule, (void *)pTypeInfo); pTypeInfo2 = SWIG_TypeQuery(L,"Bar *"); DEBUG2(" Type (Bar*) is %s\n",pTypeInfo2==0?"unknown":"known"); - DEBUG3(" Module %p typeinfo(Bar*) %p\n",pModule,pTypeInfo2); + DEBUG3(" Module %p typeinfo(Bar*) %p\n", (void *)pModule, (void *)pTypeInfo2); } int main(int argc,char* argv[]) diff --git a/Examples/lua/embed2/embed2.c b/Examples/lua/embed2/embed2.c index 7b2ca9b67..0ce9f8f7f 100644 --- a/Examples/lua/embed2/embed2.c +++ b/Examples/lua/embed2/embed2.c @@ -53,7 +53,7 @@ int call_add(lua_State *L,int a,int b,int* res) { 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 + lua_settop(L,top); return 0; } lua_pushnumber(L,a); @@ -61,18 +61,18 @@ int call_add(lua_State *L,int a,int b,int* res) { if (lua_pcall(L, 2, 1, 0) != 0) /* call function with 2 arguments and 1 result */ { printf("[C] error running function `add': %s\n",lua_tostring(L, -1)); - lua_settop(L,top); // reset + lua_settop(L,top); return 0; } - // check results + /* check results */ if (!lua_isnumber(L,-1)) { printf("[C] error: returned value is not a number\n"); - lua_settop(L,top); // reset + lua_settop(L,top); return 0; } *res=(int)lua_tonumber(L,-1); lua_settop(L,top); /* reset stack */ - return 1; // ok + return 1; } /* This is a variargs call function for calling from C into Lua. diff --git a/Examples/lua/functest/example.i b/Examples/lua/functest/example.i index 631e0602d..9bb64cbf5 100644 --- a/Examples/lua/functest/example.i +++ b/Examples/lua/functest/example.i @@ -1,13 +1,12 @@ /* File : example.i */ %module example -%include "typemaps.i" // you must have this for the typemaps for ptrs -// basic function testing -// +%include "typemaps.i" + %inline %{ -extern int add1(int x, int y); // return x+y -- basic function test -extern void add2(int x, int *INPUT, int *OUTPUT); // *z = x+*y -- argin and argout test -extern int add3(int x, int y, int *OUTPUT); // return x+y, *z=x-y -- returning 2 values -extern void add4(int x, int *INOUT); // *y += x -- INOUT dual purpose variable +extern int add1(int x, int y); /* return x+y -- basic function test */ +extern void add2(int x, int *INPUT, int *OUTPUT); /* *z = x+*y -- argin and argout test */ +extern int add3(int x, int y, int *OUTPUT); /* return x+y, *z=x-y -- returning 2 values */ +extern void add4(int x, int *INOUT); /* *y += x -- INOUT dual purpose variable */ %} diff --git a/Examples/lua/owner/example.cxx b/Examples/lua/owner/example.cxx index bce484aea..c2c073d79 100644 --- a/Examples/lua/owner/example.cxx +++ b/Examples/lua/owner/example.cxx @@ -39,12 +39,15 @@ Square* createSquare(double w) return new Square(w); } -ShapeOwner::ShapeOwner() {printf(" ShapeOwner(%p)\n",this);} +ShapeOwner::ShapeOwner() { + printf(" ShapeOwner(%p)\n", (void *)this); +} + ShapeOwner::~ShapeOwner() { - printf(" ~ShapeOwner(%p)\n",this); - for(unsigned i=0;ix : 0, ptptr ? ptptr->y : 0); + printf("ptptr = %p (%d, %d)\n", (void *)ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); printf("pt = (%d, %d)\n", pt.x, pt.y); printf("status = %d\n", status); } diff --git a/Examples/modula3/reference/example.cxx b/Examples/modula3/reference/example.cxx index 649b0169c..9dbaed2ee 100644 --- a/Examples/modula3/reference/example.cxx +++ b/Examples/modula3/reference/example.cxx @@ -19,7 +19,7 @@ Vector operator+(const Vector &a, const Vector &b) { char *Vector::print() { static char temp[512]; - sprintf(temp,"Vector %x (%g,%g,%g)", (int)this, x,y,z); + sprintf(temp,"Vector %p (%g,%g,%g)", (void *)this, x,y,z); return temp; } diff --git a/Examples/octave/extend/example.h b/Examples/octave/extend/example.h index 9e15cf8e4..77a26ec95 100644 --- a/Examples/octave/extend/example.h +++ b/Examples/octave/extend/example.h @@ -14,7 +14,7 @@ public: 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); } + virtual ~Employee() { printf("~Employee() @ %p\n", (void *)this); } }; diff --git a/Examples/octave/reference/example.cxx b/Examples/octave/reference/example.cxx index 9b72ca6a2..632a03a5b 100644 --- a/Examples/octave/reference/example.cxx +++ b/Examples/octave/reference/example.cxx @@ -19,7 +19,7 @@ Vector operator+(const Vector &a, const Vector &b) { char *Vector::print() { static char temp[512]; - sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z); + sprintf(temp,"Vector %p (%g,%g,%g)", (void *)this, x,y,z); return temp; } diff --git a/Examples/octave/variables/example.c b/Examples/octave/variables/example.c index e2b72e0ea..a9102a9d5 100644 --- a/Examples/octave/variables/example.c +++ b/Examples/octave/variables/example.c @@ -52,9 +52,9 @@ void print_vars() { printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); printf("cstrvar = %s\n", cstrvar); - printf("iptrvar = %p\n", iptrvar); + printf("iptrvar = %p\n", (void *)iptrvar); printf("name = %s\n", name); - printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); + printf("ptptr = %p (%d, %d)\n", (void *)ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); printf("pt = (%d, %d)\n", pt.x, pt.y); printf("status = %d\n", status); } diff --git a/Examples/perl5/extend/example.h b/Examples/perl5/extend/example.h index b27ab9711..ca1aed28f 100644 --- a/Examples/perl5/extend/example.h +++ b/Examples/perl5/extend/example.h @@ -14,7 +14,7 @@ public: 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); } + virtual ~Employee() { printf("~Employee() @ %p\n", (void *)this); } }; diff --git a/Examples/perl5/reference/example.cxx b/Examples/perl5/reference/example.cxx index 8a513bf49..9dbaed2ee 100644 --- a/Examples/perl5/reference/example.cxx +++ b/Examples/perl5/reference/example.cxx @@ -19,7 +19,7 @@ Vector operator+(const Vector &a, const Vector &b) { char *Vector::print() { static char temp[512]; - sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z); + sprintf(temp,"Vector %p (%g,%g,%g)", (void *)this, x,y,z); return temp; } diff --git a/Examples/perl5/value/example.i b/Examples/perl5/value/example.i index 98fd60ed5..39663c6b8 100644 --- a/Examples/perl5/value/example.i +++ b/Examples/perl5/value/example.i @@ -26,7 +26,7 @@ Vector *new_Vector(double x, double y, double z) { } void vector_print(Vector *v) { - printf("Vector %p = (%g, %g, %g)\n", v, v->x, v->y, v->z); + printf("Vector %p = (%g, %g, %g)\n", (void *)v, v->x, v->y, v->z); } %} diff --git a/Examples/perl5/variables/example.c b/Examples/perl5/variables/example.c index 05e17c8c5..85685fe72 100644 --- a/Examples/perl5/variables/example.c +++ b/Examples/perl5/variables/example.c @@ -52,9 +52,9 @@ void print_vars() { printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); printf("cstrvar = %s\n", cstrvar); - printf("iptrvar = %p\n", iptrvar); + printf("iptrvar = %p\n", (void *)iptrvar); printf("name = %s\n", name); - printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); + printf("ptptr = %p (%d, %d)\n", (void *)ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); printf("pt = (%d, %d)\n", pt.x, pt.y); printf("status = %d\n", status); } diff --git a/Examples/php/extend/example.h b/Examples/php/extend/example.h index b27ab9711..ca1aed28f 100644 --- a/Examples/php/extend/example.h +++ b/Examples/php/extend/example.h @@ -14,7 +14,7 @@ public: 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); } + virtual ~Employee() { printf("~Employee() @ %p\n", (void *)this); } }; diff --git a/Examples/php/reference/example.cxx b/Examples/php/reference/example.cxx index 13e47eade..7ead7fbf6 100644 --- a/Examples/php/reference/example.cxx +++ b/Examples/php/reference/example.cxx @@ -19,23 +19,23 @@ Vector operator+(const Vector &a, const Vector &b) { char *Vector::as_string() { static char temp[512]; - sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z); + sprintf(temp,"Vector %p (%g,%g,%g)", (void *)this, x,y,z); return temp; } VectorArray::VectorArray(int size) { items = new Vector[size]; maxsize = size; - printf("VectorArray new: self=%p\n",this); + printf("VectorArray new: self=%p\n", (void *)this); } VectorArray::~VectorArray() { - printf("VectorArray delete: self=%p\n",this); + printf("VectorArray delete: self=%p\n", (void *)this); delete [] items; } Vector &VectorArray::operator[](int index) { - printf("VectorArray: read[%d] self=%p\n",index,this); + printf("VectorArray: read[%d] self=%p\n", index, (void *)this); if ((index < 0) || (index >= maxsize)) { printf("Panic! Array index out of bounds.\n"); exit(1); @@ -44,6 +44,6 @@ Vector &VectorArray::operator[](int index) { } int VectorArray::size() { - printf("VectorArray: size %d self=%p\n",maxsize,this); + printf("VectorArray: size %d self=%p\n", maxsize, (void *)this); return maxsize; } diff --git a/Examples/php/reference/example.i b/Examples/php/reference/example.i index d6122866b..a372439b1 100644 --- a/Examples/php/reference/example.i +++ b/Examples/php/reference/example.i @@ -37,7 +37,7 @@ public: /* This wrapper provides an alternative to the [] operator */ %extend { Vector &get(int index) { - printf("VectorArray extended get: %p %d\n",$self,index); + printf("VectorArray extended get: %p %d\n", (void *)$self, index); return (*$self)[index]; } void set(int index, Vector &a) { diff --git a/Examples/php/sync/example.cxx b/Examples/php/sync/example.cxx index 31ed2021b..0942279b2 100644 --- a/Examples/php/sync/example.cxx +++ b/Examples/php/sync/example.cxx @@ -10,4 +10,4 @@ void Sync::printer(void) { printf("The value of global x is %d\n", x); printf("The value of class s is %s\n", s); printf("The value of class x is %d\n", x); -}; +} diff --git a/Examples/php/value/example.i b/Examples/php/value/example.i index 386fa3b84..20a453468 100644 --- a/Examples/php/value/example.i +++ b/Examples/php/value/example.i @@ -11,7 +11,7 @@ %inline %{ void vector_print(Vector *v) { - printf("Vector %p = (%g, %g, %g)\n", v, v->x, v->y, v->z); + printf("Vector %p = (%g, %g, %g)\n", (void *)v, v->x, v->y, v->z); } %} diff --git a/Examples/php/variables/example.c b/Examples/php/variables/example.c index b21dee32d..d4c6d026d 100644 --- a/Examples/php/variables/example.c +++ b/Examples/php/variables/example.c @@ -52,9 +52,9 @@ void print_vars() { printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); printf("cstrvar = %s\n", cstrvar); - printf("iptrvar = %p\n", iptrvar); + printf("iptrvar = %p\n", (void *)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 ) ); + printf("ptptr = %p %s\n", (void *)ptptr, Point_print( ptptr ) ); printf("pt = (%d, %d)\n", pt.x, pt.y); printf("status = %d\n", status); } diff --git a/Examples/python/extend/example.h b/Examples/python/extend/example.h index b27ab9711..ca1aed28f 100644 --- a/Examples/python/extend/example.h +++ b/Examples/python/extend/example.h @@ -14,7 +14,7 @@ public: 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); } + virtual ~Employee() { printf("~Employee() @ %p\n", (void *)this); } }; diff --git a/Examples/python/reference/example.cxx b/Examples/python/reference/example.cxx index 8a513bf49..9dbaed2ee 100644 --- a/Examples/python/reference/example.cxx +++ b/Examples/python/reference/example.cxx @@ -19,7 +19,7 @@ Vector operator+(const Vector &a, const Vector &b) { char *Vector::print() { static char temp[512]; - sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z); + sprintf(temp,"Vector %p (%g,%g,%g)", (void *)this, x,y,z); return temp; } diff --git a/Examples/python/swigrun/example.cxx b/Examples/python/swigrun/example.cxx index 25906a559..2d2471301 100644 --- a/Examples/python/swigrun/example.cxx +++ b/Examples/python/swigrun/example.cxx @@ -9,7 +9,7 @@ Manager* convert_to_Manager(PyObject *py_obj) { Manager* c_ptr; swig_type_info *ty = SWIG_TypeQuery("Manager *"); - printf("manager ty %p \n", ty); + printf("manager ty %p \n", (void *)ty); if (SWIG_ConvertPtr(py_obj, (void **) &c_ptr, ty, 0) == -1) { c_ptr = 0; } else { diff --git a/Examples/python/swigrun/example.h b/Examples/python/swigrun/example.h index 69e6fe4de..e89f7baaa 100644 --- a/Examples/python/swigrun/example.h +++ b/Examples/python/swigrun/example.h @@ -14,7 +14,7 @@ public: 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); } + virtual ~Employee() { printf("~Employee() @ %p\n", (void *)this); } }; diff --git a/Examples/python/variables/example.c b/Examples/python/variables/example.c index 05e17c8c5..85685fe72 100644 --- a/Examples/python/variables/example.c +++ b/Examples/python/variables/example.c @@ -52,9 +52,9 @@ void print_vars() { printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); printf("cstrvar = %s\n", cstrvar); - printf("iptrvar = %p\n", iptrvar); + printf("iptrvar = %p\n", (void *)iptrvar); printf("name = %s\n", name); - printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); + printf("ptptr = %p (%d, %d)\n", (void *)ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); printf("pt = (%d, %d)\n", pt.x, pt.y); printf("status = %d\n", status); } diff --git a/Examples/ruby/reference/example.cxx b/Examples/ruby/reference/example.cxx index 8a513bf49..9dbaed2ee 100644 --- a/Examples/ruby/reference/example.cxx +++ b/Examples/ruby/reference/example.cxx @@ -19,7 +19,7 @@ Vector operator+(const Vector &a, const Vector &b) { char *Vector::print() { static char temp[512]; - sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z); + sprintf(temp,"Vector %p (%g,%g,%g)", (void *)this, x,y,z); return temp; } diff --git a/Examples/ruby/value/example.i b/Examples/ruby/value/example.i index 98fd60ed5..39663c6b8 100644 --- a/Examples/ruby/value/example.i +++ b/Examples/ruby/value/example.i @@ -26,7 +26,7 @@ Vector *new_Vector(double x, double y, double z) { } void vector_print(Vector *v) { - printf("Vector %p = (%g, %g, %g)\n", v, v->x, v->y, v->z); + printf("Vector %p = (%g, %g, %g)\n", (void *)v, v->x, v->y, v->z); } %} diff --git a/Examples/ruby/variables/example.c b/Examples/ruby/variables/example.c index 05e17c8c5..85685fe72 100644 --- a/Examples/ruby/variables/example.c +++ b/Examples/ruby/variables/example.c @@ -52,9 +52,9 @@ void print_vars() { printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); printf("cstrvar = %s\n", cstrvar); - printf("iptrvar = %p\n", iptrvar); + printf("iptrvar = %p\n", (void *)iptrvar); printf("name = %s\n", name); - printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); + printf("ptptr = %p (%d, %d)\n", (void *)ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); printf("pt = (%d, %d)\n", pt.x, pt.y); printf("status = %d\n", status); } diff --git a/Examples/tcl/reference/example.cxx b/Examples/tcl/reference/example.cxx index 8a513bf49..9dbaed2ee 100644 --- a/Examples/tcl/reference/example.cxx +++ b/Examples/tcl/reference/example.cxx @@ -19,7 +19,7 @@ Vector operator+(const Vector &a, const Vector &b) { char *Vector::print() { static char temp[512]; - sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z); + sprintf(temp,"Vector %p (%g,%g,%g)", (void *)this, x,y,z); return temp; } diff --git a/Examples/tcl/value/example.i b/Examples/tcl/value/example.i index 98fd60ed5..39663c6b8 100644 --- a/Examples/tcl/value/example.i +++ b/Examples/tcl/value/example.i @@ -26,7 +26,7 @@ Vector *new_Vector(double x, double y, double z) { } void vector_print(Vector *v) { - printf("Vector %p = (%g, %g, %g)\n", v, v->x, v->y, v->z); + printf("Vector %p = (%g, %g, %g)\n", (void *)v, v->x, v->y, v->z); } %} diff --git a/Examples/tcl/variables/example.c b/Examples/tcl/variables/example.c index 05e17c8c5..85685fe72 100644 --- a/Examples/tcl/variables/example.c +++ b/Examples/tcl/variables/example.c @@ -52,9 +52,9 @@ void print_vars() { printf("cvar = %c\n", cvar); printf("strvar = %s\n", strvar ? strvar : "(null)"); printf("cstrvar = %s\n", cstrvar); - printf("iptrvar = %p\n", iptrvar); + printf("iptrvar = %p\n", (void *)iptrvar); printf("name = %s\n", name); - printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); + printf("ptptr = %p (%d, %d)\n", (void *)ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); printf("pt = (%d, %d)\n", pt.x, pt.y); printf("status = %d\n", status); } From 3191473523de629d75181b134c75a83f7fd7297b Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 24 May 2014 00:14:18 +0100 Subject: [PATCH 0981/1048] Fix compiler warnings in generated code when using -std=c++98 -std=gnu89 -pedantic -Wreturn-type --- Lib/guile/guile_scm_run.swg | 3 +- Lib/javascript/v8/javascriptinit.swg | 2 +- Lib/lua/lua_fnptr.i | 1 - Lib/lua/luarun.swg | 122 ++++++++++++++++----------- Lib/lua/luaruntime.swg | 2 +- Lib/lua/typemaps.i | 2 +- Lib/php/const.i | 4 +- Lib/php/utils.i | 2 +- Lib/ruby/file.i | 2 +- 9 files changed, 80 insertions(+), 60 deletions(-) diff --git a/Lib/guile/guile_scm_run.swg b/Lib/guile/guile_scm_run.swg index 322d660c5..94cf4d101 100644 --- a/Lib/guile/guile_scm_run.swg +++ b/Lib/guile/guile_scm_run.swg @@ -27,8 +27,7 @@ scm_module_variable (SCM module, SCM sym) #endif #if SCM_MAJOR_VERSION >= 2 -// scm_c_define_gsubr takes a different parameter type -// depending on the guile version +/* scm_c_define_gsubr takes a different parameter type depending on the guile version */ typedef scm_t_subr swig_guile_proc; #else diff --git a/Lib/javascript/v8/javascriptinit.swg b/Lib/javascript/v8/javascriptinit.swg index de1fe91f4..b428d4af9 100644 --- a/Lib/javascript/v8/javascriptinit.swg +++ b/Lib/javascript/v8/javascriptinit.swg @@ -113,6 +113,6 @@ void SWIGV8_INIT (v8::Handle exports, v8::Handle /*modul } #if defined(BUILDING_NODE_EXTENSION) -NODE_MODULE($jsname, $jsname_initialize); +NODE_MODULE($jsname, $jsname_initialize) #endif %} diff --git a/Lib/lua/lua_fnptr.i b/Lib/lua/lua_fnptr.i index 4e2c8dc6a..481cfafa6 100644 --- a/Lib/lua/lua_fnptr.i +++ b/Lib/lua/lua_fnptr.i @@ -103,7 +103,6 @@ void swiglua_ref_clear(SWIGLUA_REF* pref){ } void swiglua_ref_set(SWIGLUA_REF* pref,lua_State* L,int idx){ -// swiglua_ref_clear(pref); /* just in case */ pref->L=L; lua_pushvalue(L,idx); /* copy obj to top */ pref->ref=luaL_ref(L,LUA_REGISTRYINDEX); /* remove obj from top & put into registry */ diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index 7cfcff212..1dd3b9f09 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -630,10 +630,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) { + swig_lua_class **classes; + /* 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; + classes = ns->ns_classes; if( classes != 0 ) { while(*classes != 0) { @@ -650,6 +652,7 @@ SWIGINTERN void SWIG_Lua_add_namespace_classes(lua_State *L, swig_lua_namespace */ SWIGINTERN void SWIG_Lua_namespace_register(lua_State *L, swig_lua_namespace *ns, int reg) { + swig_lua_namespace **sub_namespace; /* 1 argument - table on the top of the stack */ const int SWIGUNUSED begin = lua_gettop(L); assert(lua_istable(L,-1)); /* just in case. This is supposed to be module table or parent namespace table */ @@ -681,7 +684,7 @@ SWIGINTERN void 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; + sub_namespace = ns->ns_namespaces; if( sub_namespace != 0) { while(*sub_namespace != 0) { SWIG_Lua_namespace_register(L, *sub_namespace, 1); @@ -753,22 +756,21 @@ SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info * SWIGUNUSED /* 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 */ - int original_metatable; + int original_metatable = last_arg + 1; size_t bases_count; - int result; + int result = SWIG_ERROR; lua_getmetatable(L,first_arg); - original_metatable = last_arg + 1; SWIG_LUA_INIT_BASE_SEARCH(bases_count); - result = SWIG_ERROR; if(ret) *ret = 0; if(bases_count>0) { + int to_remove; size_t i; int j; + int subcall_last_arg; int subcall_first_arg = lua_gettop(L) + 1;/* Here a copy of first_arg and arguments begin */ int valid = 1; - int subcall_last_arg; swig_type_info *base_swig_type = 0; for(j=first_arg;j<=last_arg;j++) lua_pushvalue(L,j); @@ -792,7 +794,7 @@ SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info * SWIGUNUSED lua_pushvalue(L,original_metatable); lua_setmetatable(L,first_arg); /* Clear - remove everything between last_arg and subcall_last_arg including */ - const int to_remove = subcall_last_arg - last_arg; + to_remove = subcall_last_arg - last_arg; for(j=0;jtype; + int result; + swig_lua_userdata *usr; + swig_type_info *type; int ret = 0; - int result = SWIG_Lua_class_do_get(L,type,1,&ret); + assert(lua_isuserdata(L,1)); + usr=(swig_lua_userdata*)lua_touserdata(L,1); /* get data */ + type = usr->type; + result = SWIG_Lua_class_do_get(L,type,1,&ret); if(result == SWIG_OK) return ret; @@ -902,6 +905,7 @@ SWIGINTERN int SWIG_Lua_class_do_set(lua_State *L, swig_type_info *type, int fi (3) any for the new value */ + int bases_search_result; int substack_start = lua_gettop(L) - 3; lua_checkstack(L,5); assert(lua_isuserdata(L,substack_start+1)); /* just in case */ @@ -944,14 +948,12 @@ SWIGINTERN int SWIG_Lua_class_do_set(lua_State *L, swig_type_info *type, int fi lua_pop(L,1); /* remove value */ lua_pop(L,1); /* remove metatable */ - { - /* Search among bases */ - int bases_search_result = SWIG_Lua_iterate_bases(L,type,first_arg,SWIG_Lua_class_do_set,ret); - if(ret) - assert(*ret == 0); - assert(lua_gettop(L) == substack_start + 3); - return bases_search_result; - } + /* Search among bases */ + bases_search_result = SWIG_Lua_iterate_bases(L,type,first_arg,SWIG_Lua_class_do_set,ret); + if(ret) + assert(*ret == 0); + assert(lua_gettop(L) == substack_start + 3); + return bases_search_result; } /* This is the actual method exported to Lua. It calls SWIG_Lua_class_do_set and correctly @@ -964,11 +966,14 @@ SWIGINTERN int SWIG_Lua_class_set(lua_State *L) (2) string name of the attribute (3) any for the new value */ - 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_set(L,type,1,&ret); + int result; + swig_lua_userdata *usr; + swig_type_info *type; + assert(lua_isuserdata(L,1)); + usr=(swig_lua_userdata*)lua_touserdata(L,1); /* get data */ + type = usr->type; + 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); @@ -1004,13 +1009,15 @@ SWIGINTERN int SWIG_Lua_class_tostring(lua_State *L) { /* there should be 1 param passed in (1) userdata (not the metatable) */ + const char *className; + void* userData; assert(lua_isuserdata(L,1)); /* just in case */ - void* userData = lua_touserdata(L,1); /* get the userdata address for later */ + userData = 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); + className = lua_tostring(L, -1); lua_pushfstring(L, "<%s userdata: %p>", className, userData); return 1; @@ -1238,10 +1245,10 @@ SWIGINTERN void SWIG_Lua_add_class_user_metamethods(lua_State *L, swig_lua_class SWIGINTERN void SWIG_Lua_add_class_instance_details(lua_State *L, swig_lua_class *clss) { int i; + size_t bases_count = 0; /* Add bases to .bases table */ SWIG_Lua_get_table(L,".bases"); assert(lua_istable(L,-1)); /* just in case */ - size_t bases_count = 0; for(i=0;clss->bases[i];i++) { SWIG_Lua_get_class_metatable(L,clss->bases[i]->fqname); @@ -1296,7 +1303,7 @@ SWIGRUNTIME int SWIG_Lua_resolve_metamethod(lua_State *L); /*forward declaration /* The real function that resolves a metamethod. * Function searches given class and all it's bases(recursively) for first instance of something that is - * not equal to SWIG_Lua_resolve_metatmethod. (Almost always this 'something' is actuall metamethod implementation + * not equal to SWIG_Lua_resolve_metatmethod. (Almost always this 'something' is actual metamethod implementation * and it is a SWIG-generated C function.). It returns value on the top of the L and there is no garbage below the * answer. * Returns 1 if found, 0 otherwise. @@ -1310,6 +1317,9 @@ SWIGINTERN int SWIG_Lua_do_resolve_metamethod(lua_State *L, const swig_lua_class int skip_check) { /* This function is called recursively */ + int result = 0; + int i = 0; + if (!skip_check) { SWIG_Lua_get_class_metatable(L, clss->fqname); lua_pushvalue(L, metamethod_name_idx); @@ -1326,8 +1336,6 @@ SWIGINTERN int SWIG_Lua_do_resolve_metamethod(lua_State *L, const swig_lua_class } /* Forwarding calls to bases */ - int result = 0; - int i = 0; for(i=0;clss->bases[i];i++) { result = SWIG_Lua_do_resolve_metamethod(L, clss->bases[i], metamethod_name_idx, 0); @@ -1342,21 +1350,26 @@ SWIGINTERN int SWIG_Lua_do_resolve_metamethod(lua_State *L, const swig_lua_class * and calls it */ SWIGRUNTIME int SWIG_Lua_resolve_metamethod(lua_State *L) { + int numargs; + int metamethod_name_idx; + const swig_lua_class* clss; + int result; + lua_checkstack(L,5); - const int numargs = lua_gettop(L); /* number of arguments to pass to actuall metamethod */ + numargs = lua_gettop(L); /* number of arguments to pass to actual metamethod */ /* Get upvalues from closure */ lua_pushvalue(L, lua_upvalueindex(1)); /*Get function name*/ - const int metamethod_name_idx = lua_gettop(L); + metamethod_name_idx = lua_gettop(L); lua_pushvalue(L, lua_upvalueindex(2)); - const swig_lua_class* clss = (const swig_lua_class*)(lua_touserdata(L,-1)); + clss = (const swig_lua_class*)(lua_touserdata(L,-1)); lua_pop(L,1); /* remove lightuserdata with clss from stack */ - /* Actuall work */ - const int result = SWIG_Lua_do_resolve_metamethod(L, clss, metamethod_name_idx, 1); + /* Actual work */ + result = SWIG_Lua_do_resolve_metamethod(L, clss, metamethod_name_idx, 1); if (!result) { - SWIG_Lua_pushferrstring(L,"The metamethod proxy is set, but it failed to find actuall metamethod. Memory corruption is most likely explanation."); + SWIG_Lua_pushferrstring(L,"The metamethod proxy is set, but it failed to find actual metamethod. Memory corruption is most likely explanation."); lua_error(L); return 0; } @@ -1374,10 +1387,14 @@ SWIGRUNTIME int SWIG_Lua_resolve_metamethod(lua_State *L) */ SWIGINTERN int SWIG_Lua_add_class_user_metamethod(lua_State *L, swig_lua_class *clss, const int metatable_index) { + int key_index; + int success = 0; + int i = 0; + /* metamethod name - on the top of the stack */ assert(lua_isstring(L,-1)); - const int key_index = lua_gettop(L); + key_index = lua_gettop(L); /* Check whether method is already defined in metatable */ lua_pushvalue(L,key_index); /* copy of the key */ @@ -1389,8 +1406,6 @@ SWIGINTERN int SWIG_Lua_add_class_user_metamethod(lua_State *L, swig_lua_class * lua_pop(L,1); /* Iterating over immediate bases */ - int success = 0; - int i = 0; for(i=0;clss->bases[i];i++) { const swig_lua_class *base = clss->bases[i]; @@ -1420,11 +1435,15 @@ SWIGINTERN int SWIG_Lua_add_class_user_metamethod(lua_State *L, swig_lua_class * SWIGINTERN void SWIG_Lua_add_class_user_metamethods(lua_State *L, swig_lua_class *clss) { + int metatable_index; + int metamethods_info_index; + int tostring_undefined; + SWIG_Lua_get_class_metatable(L, clss->fqname); - const int metatable_index = lua_gettop(L); + metatable_index = lua_gettop(L); SWIG_Lua_get_inheritable_metamethods(L); assert(lua_istable(L,-1)); - const int metamethods_info_index = lua_gettop(L); + metamethods_info_index = lua_gettop(L); lua_pushnil(L); /* first key */ while(lua_next(L, metamethods_info_index) != 0 ) { /* key at index -2, value at index -1 */ @@ -1442,7 +1461,7 @@ SWIGINTERN void SWIG_Lua_add_class_user_metamethods(lua_State *L, swig_lua_class lua_pushstring(L, "__tostring"); lua_pushvalue(L,-1); lua_rawget(L,metatable_index); - const int tostring_undefined = lua_isnil(L,-1); + tostring_undefined = lua_isnil(L,-1); lua_pop(L,1); if( tostring_undefined ) { lua_pushcfunction(L, SWIG_Lua_class_tostring); @@ -1494,6 +1513,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 new_metatable_index; const int SWIGUNUSED begin = lua_gettop(L); int i; /* if name already there (class is already registered) then do nothing */ @@ -1520,11 +1540,12 @@ 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 */ - const int new_metatable_index = lua_absindex(L,-1); + new_metatable_index = lua_absindex(L,-1); for(i=0;clss->bases[i];i++) { + int base_metatable; SWIG_Lua_get_class_metatable(L,clss->bases[i]->fqname); - const int base_metatable = lua_absindex(L,-1); + base_metatable = lua_absindex(L,-1); SWIG_Lua_merge_tables_by_index(L,new_metatable_index, base_metatable); lua_pop(L,1); } @@ -1573,6 +1594,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) { + int SWIGUNUSED begin; 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); @@ -1587,7 +1609,7 @@ SWIGINTERN void SWIG_Lua_class_register(lua_State *L,swig_lua_class *clss) * | ".set" --> .... * |=============================== ".instance" */ - const int SWIGUNUSED begin = lua_gettop(L); + begin = lua_gettop(L); lua_pushstring(L,clss->cls_static->name); lua_rawget(L,-2); /* get class static table */ assert(lua_istable(L,-1)); diff --git a/Lib/lua/luaruntime.swg b/Lib/lua/luaruntime.swg index 26dab93f6..89908044b 100644 --- a/Lib/lua/luaruntime.swg +++ b/Lib/lua/luaruntime.swg @@ -29,6 +29,7 @@ SWIGEXPORT int SWIG_init(lua_State* L) /* default Lua action */ { #if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC) /* valid for both Lua and eLua */ int i; + int globalRegister = 0; /* start with global table */ lua_pushglobaltable (L); /* SWIG's internal initialisation */ @@ -49,7 +50,6 @@ SWIGEXPORT int SWIG_init(lua_State* L) /* default Lua action */ SWIG_Lua_init_base_class(L,(swig_lua_class*)(swig_types[i]->clientdata)); } } - int globalRegister = 0; #ifdef SWIG_LUA_MODULE_GLOBAL globalRegister = 1; #endif diff --git a/Lib/lua/typemaps.i b/Lib/lua/typemaps.i index 7a095a1e0..c662cd31e 100644 --- a/Lib/lua/typemaps.i +++ b/Lib/lua/typemaps.i @@ -296,7 +296,7 @@ This is one giant macro to define the typemaps & the helpers for array handling */ %define SWIG_TYPEMAP_NUM_ARR(NAME,TYPE) -%{SWIG_DECLARE_TYPEMAP_ARR_FN(NAME,TYPE);%} +%{SWIG_DECLARE_TYPEMAP_ARR_FN(NAME,TYPE)%} // fixed size array's %typemap(in) TYPE INPUT[ANY] diff --git a/Lib/php/const.i b/Lib/php/const.i index 82c48022b..329b0cf07 100644 --- a/Lib/php/const.i +++ b/Lib/php/const.i @@ -34,12 +34,12 @@ SWIGTYPE &&, SWIGTYPE [] { zval *z_var; + zend_constant c; + size_t len = sizeof("$symname") - 1; MAKE_STD_ZVAL(z_var); SWIG_SetPointerZval(z_var, (void*)$value, $1_descriptor, 0); - zend_constant c; c.value = *z_var; zval_copy_ctor(&c.value); - size_t len = sizeof("$symname") - 1; c.name = zend_strndup("$symname", len); c.name_len = len+1; c.flags = CONST_CS | CONST_PERSISTENT; diff --git a/Lib/php/utils.i b/Lib/php/utils.i index 4e53e25a7..408a3b366 100644 --- a/Lib/php/utils.i +++ b/Lib/php/utils.i @@ -92,6 +92,7 @@ %fragment("t_output_helper","header") %{ static void t_output_helper(zval **target, zval *o TSRMLS_DC) { + zval *tmp; if ( (*target)->type == IS_ARRAY ) { /* it's already an array, just append */ add_next_index_zval( *target, o ); @@ -102,7 +103,6 @@ t_output_helper(zval **target, zval *o TSRMLS_DC) { FREE_ZVAL(o); return; } - zval *tmp; ALLOC_INIT_ZVAL(tmp); *tmp = **target; zval_copy_ctor(tmp); diff --git a/Lib/ruby/file.i b/Lib/ruby/file.i index d64937ed1..f9aaa2754 100644 --- a/Lib/ruby/file.i +++ b/Lib/ruby/file.i @@ -4,7 +4,7 @@ extern "C" { #endif -// Ruby 1.9 changed the file name of this header +/* Ruby 1.9 changed the file name of this header */ #ifdef HAVE_RUBY_IO_H #include "ruby/io.h" #else From c2368a40b244e3454a0300e5c671ebe6e98048ab Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 24 May 2014 09:30:37 +0100 Subject: [PATCH 0982/1048] Javascript warnings for c++98 - remove vla --- Lib/javascript/jsc/javascriptstrings.swg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/javascript/jsc/javascriptstrings.swg b/Lib/javascript/jsc/javascriptstrings.swg index 10a0e252a..b3f46ae41 100644 --- a/Lib/javascript/jsc/javascriptstrings.swg +++ b/Lib/javascript/jsc/javascriptstrings.swg @@ -53,7 +53,7 @@ SWIG_JSC_FromCharPtrAndSize(JSContextRef context, const char* carray, size_t siz } else { JSStringRef jsstring; if(size < 2) { - char c[size+1]; + char c[2]; int i; for(i=0;i Date: Sat, 24 May 2014 10:12:06 +0100 Subject: [PATCH 0983/1048] Refactor Lua class base search to make ISO c/c++ compliant --- Lib/lua/luarun.swg | 85 +++++++++++++++++++++++----------------------- 1 file changed, 43 insertions(+), 42 deletions(-) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index 1dd3b9f09..6f2068e7a 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -708,46 +708,6 @@ SWIGINTERN void SWIG_Lua_namespace_register(lua_State *L, swig_lua_namespace *ns SWIGINTERN void SWIG_Lua_get_class_metatable(lua_State *L,const char *cname); -/* Macros for iteration among class bases */ -#if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) -#define SWIG_LUA_INIT_BASE_SEARCH(bases_count)\ - (void)swig_type;\ - SWIG_Lua_get_table(L,".bases");\ - assert(lua_istable(L,-1));\ - bases_count = lua_rawlen(L,-1);\ - const 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 = 0;\ - lua_pop(L,1);\ - } else\ - valid = 1; - -#else /* In 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;\ - 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 = 0;\ - else {\ - valid = 1;\ - SWIG_Lua_get_class_metatable(L,base_class->fqname);\ - base_swig_type = SWIG_TypeQueryModule(module,module,base_names[i]);\ - assert(base_swig_type != 0);\ - } - -#endif - typedef int (*swig_lua_base_iterator_func)(lua_State*,swig_type_info*, int, int *ret); SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info * SWIGUNUSED swig_type, @@ -759,8 +719,28 @@ SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info * SWIGUNUSED int original_metatable = last_arg + 1; size_t bases_count; int result = SWIG_ERROR; + int bases_table; + (void)swig_type; lua_getmetatable(L,first_arg); - SWIG_LUA_INIT_BASE_SEARCH(bases_count); + + /* initialise base search */ +#if (SWIG_LUA_TARGET == SWIG_LUA_FLAVOR_LUA) + SWIG_Lua_get_table(L,".bases"); + assert(lua_istable(L,-1)); + bases_count = lua_rawlen(L,-1); + bases_table = lua_gettop(L); +#else + /* In elua .bases table doesn't exist. Use table from swig_lua_class */ + (void)bases_table; + 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; + bases_count = 0; + for(;base_names[bases_count]; + bases_count++);/* get length of bases */ +#endif + if(ret) *ret = 0; if(bases_count>0) @@ -778,7 +758,28 @@ SWIGINTERN int SWIG_Lua_iterate_bases(lua_State *L, swig_type_info * SWIGUNUSED /* Trick: temporarily replacing original metatable with metatable for base class and call getter */ for(i=0;ifqname); + base_swig_type = SWIG_TypeQueryModule(module,module,base_names[i]); + assert(base_swig_type != 0); + } +#endif + if(!valid) continue; assert(lua_isuserdata(L, subcall_first_arg)); From ab86f8a8f51a877615f173c37cd9da34f8bd5905 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 24 May 2014 10:29:34 +0100 Subject: [PATCH 0984/1048] Warning fixes in test-suite --- .../test-suite/smart_pointer_templatemethods.i | 2 +- Examples/test-suite/struct_initialization.i | 2 +- Examples/test-suite/typemap_array_qualifiers.i | 14 +++++++------- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/Examples/test-suite/smart_pointer_templatemethods.i b/Examples/test-suite/smart_pointer_templatemethods.i index f79bbcc9d..bd8808aff 100644 --- a/Examples/test-suite/smart_pointer_templatemethods.i +++ b/Examples/test-suite/smart_pointer_templatemethods.i @@ -45,7 +45,7 @@ public: %template(QueryInterfaceObjct) Objct::QueryInterface; #endif -}; // namespace +} // namespace %} diff --git a/Examples/test-suite/struct_initialization.i b/Examples/test-suite/struct_initialization.i index c378ba31d..da1604f1b 100644 --- a/Examples/test-suite/struct_initialization.i +++ b/Examples/test-suite/struct_initialization.i @@ -3,7 +3,7 @@ %inline %{ -// Named types +/* Named types */ struct StructA { int x; } instanceA1; diff --git a/Examples/test-suite/typemap_array_qualifiers.i b/Examples/test-suite/typemap_array_qualifiers.i index 14df649d3..cbc6c95ff 100644 --- a/Examples/test-suite/typemap_array_qualifiers.i +++ b/Examples/test-suite/typemap_array_qualifiers.i @@ -43,8 +43,8 @@ $1 = 0; /* Correct typemap for $symname: $type */ } %inline %{ - void func1a(myarray x) {}; - void func1b(volatile myarray x) {}; + void func1a(myarray x) {} + void func1b(volatile myarray x) {} %} CLEAR_SWIGTYPE_TYPEMAPS; @@ -57,9 +57,9 @@ $1 = 0; /* Correct typemap for $symname: $type */ } %inline %{ - void func2a(const myarray x) {}; - void func2b(const myconstarray x) {}; - void func2c(const volatile myconstarray x) {}; + void func2a(const myarray x) {} + void func2b(const myconstarray x) {} + void func2c(const volatile myconstarray x) {} %} CLEAR_SWIGTYPE_TYPEMAPS; @@ -72,7 +72,7 @@ $1 = 0; /* Correct typemap for $symname: $type */ } %inline %{ - void func3a(const mycrazyarray x, const mycrazyarray y[7]) {}; + void func3a(const mycrazyarray x, const mycrazyarray y[7]) {} %} CLEAR_SWIGTYPE_TYPEMAPS; @@ -81,5 +81,5 @@ $1 = 0; /* Correct typemap for $symname: $type */ } %inline %{ - void func4a(mycrazyfunc *const x, const mycrazyfuncptr y) {}; + void func4a(mycrazyfunc *const x, const mycrazyfuncptr y) {} %} From 5990872cf741fa31523e2b72ee66fdc8d27da442 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 24 May 2014 00:12:00 +0100 Subject: [PATCH 0985/1048] Travis testing - examples use stricter CFLAGS and CXXFLAGS --- .travis.yml | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 96e4fc9a7..5859c946f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -67,6 +67,35 @@ before_install: - if test "$SWIGLANG" = "python" -a "$PY3" -a -z "$VER"; then sudo apt-get install -qq python3-dev; fi - if test "$SWIGLANG" = "python" -a "$VER"; then sudo add-apt-repository -y ppa:fkrull/deadsnakes && sudo apt-get -qq update && sudo apt-get -qq install python${VER}-dev && export CONFIGOPTS="--with-python${PY3}=python${VER}"; fi - if test "$SWIGLANG" = "tcl"; then sudo apt-get -qq install tcl8.4-dev; fi + # Stricter compile flags for examples. Various headers and SWIG generated code prevents full use of -pedantic. + - declare -A CFLAGS_EXAMPLES && CFLAGS_EXAMPLES=( + ["csharp"]="-Werror -std=gnu89 -fdiagnostics-show-option -Wno-long-long -Wreturn-type" + ["go"]="-Werror -std=gnu89 -fdiagnostics-show-option -Wno-long-long -Wreturn-type" + ["guile"]="-Werror -std=gnu89 -fdiagnostics-show-option -Wno-long-long -Wreturn-type" + ["java"]="-Werror -std=gnu89 -fdiagnostics-show-option -pedantic -Wno-long-long -Wreturn-type" + ["javascript"]="-Werror -std=gnu89 -fdiagnostics-show-option -pedantic -Wno-long-long -Wreturn-type" + ["lua"]="-Werror -std=gnu89 -fdiagnostics-show-option -pedantic -Wno-long-long -Wreturn-type" + ["octave"]="-Werror -std=gnu89 -fdiagnostics-show-option -pedantic -Wno-long-long -Wreturn-type" + ["perl5"]="-Werror -std=gnu89 -fdiagnostics-show-option -Wno-long-long -Wreturn-type" + ["php"]="-Werror -std=gnu89 -fdiagnostics-show-option -Wno-long-long -Wreturn-type" + ["python"]="-Werror -std=gnu89 -fdiagnostics-show-option -Wno-long-long -Wreturn-type" + ["ruby"]="-Werror -std=gnu89 -fdiagnostics-show-option -Wno-long-long -Wreturn-type" + ["tcl"]="-Werror -std=gnu89 -fdiagnostics-show-option -Wno-long-long -Wreturn-type" + ) + - declare -A CXXFLAGS_EXAMPLES && CXXFLAGS_EXAMPLES=( + ["csharp"]="-Werror -std=c++98 -fdiagnostics-show-option -pedantic -Wno-long-long -Wreturn-type" + ["go"]="-Werror -std=c++98 -fdiagnostics-show-option -pedantic -Wno-long-long -Wreturn-type" + ["guile"]="-Werror -std=c++98 -fdiagnostics-show-option -Wno-long-long -Wreturn-type" + ["java"]="-Werror -std=c++98 -fdiagnostics-show-option -pedantic -Wno-long-long -Wreturn-type" + ["javascript"]="-Werror -std=c++98 -fdiagnostics-show-option -pedantic -Wno-long-long -Wreturn-type" + ["lua"]="-Werror -std=c++98 -fdiagnostics-show-option -pedantic -Wno-long-long -Wreturn-type" + ["octave"]="-Werror -std=c++98 -fdiagnostics-show-option -Wno-long-long -Wreturn-type" + ["perl5"]="-Werror -std=c++98 -fdiagnostics-show-option -Wno-long-long -Wreturn-type" + ["php"]="-Werror -std=c++98 -fdiagnostics-show-option -pedantic -Wno-long-long -Wreturn-type" + ["python"]="-Werror -std=c++98 -fdiagnostics-show-option -pedantic -Wno-long-long -Wreturn-type" + ["ruby"]="-Werror -std=c++98 -fdiagnostics-show-option -pedantic -Wno-long-long -Wreturn-type" + ["tcl"]="-Werror -std=c++98 -fdiagnostics-show-option -Wno-long-long -Wreturn-type" + ) - $CC --version - $CXX --version script: @@ -81,7 +110,7 @@ script: - if test -z "$SWIGLANG"; then sudo make -s install && swig -version && ccache-swig -V; fi - echo -en 'travis_fold:end:script.2\\r' - 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-examples CFLAGS="${CFLAGS_EXAMPLES[$SWIGLANG]}" CXXFLAGS="${CXXFLAGS_EXAMPLES[$SWIGLANG]}"; fi - if test -n "$SWIGLANG"; then make -k $SWIGJOBS check-$SWIGLANG-test-suite; fi - echo 'Cleaning...' && echo -en 'travis_fold:start:script.3\\r' - make maintainer-clean && ../../configure $CONFIGOPTS From 20ddfb7fcded992bd0e98b9ef8797104fe0900fd Mon Sep 17 00:00:00 2001 From: Harvey Falcic Date: Sat, 24 May 2014 13:22:41 -0400 Subject: [PATCH 0986/1048] Python 3 'surrogateescape' docs: fix div class for Python code --- Doc/Manual/Python.html | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Doc/Manual/Python.html b/Doc/Manual/Python.html index 45725065d..6dc0ff9ba 100644 --- a/Doc/Manual/Python.html +++ b/Doc/Manual/Python.html @@ -5962,8 +5962,8 @@ When this method is called from Python 3, the return value is the following text string:

    -
    ->>> s = test.non_utf8_c_str()
    +
    +>>> s = example.non_utf8_c_str()
     >>> s
     'h\udce9llo wörld'
     
    @@ -5974,7 +5974,7 @@ bytes are represented as high surrogate characters that can be used to obtain the original byte sequence:

    -
    +
     >>> b = s.encode('utf-8', errors='surrogateescape')
     >>> b
     b'h\xe9llo w\xc3\xb6rld'
    @@ -5985,7 +5985,7 @@ One can then attempt a different encoding, if desired (or simply leave the
     byte string as a raw sequence of bytes for use in binary protocols):
     

    -
    +
     >>> b.decode('latin-1')
     'héllo wörld'
     
    @@ -5995,7 +5995,7 @@ Note, however, that text strings containing surrogate characters are rejected with the default strict codec error handler. For example:

    -
    +
     >>> with open('test', 'w') as f:
     ...     print(s, file=f)
     ...
    
    From bdc63e5a9faf8b2cc0a8b311ab0eea9edd026d02 Mon Sep 17 00:00:00 2001
    From: Karl Wette 
    Date: Sat, 24 May 2014 20:07:52 +0200
    Subject: [PATCH 0987/1048] Remove example Makefiles when running
     distclean-examples in out-of-src build
    
    ---
     Makefile.in | 5 +++++
     1 file changed, 5 insertions(+)
    
    diff --git a/Makefile.in b/Makefile.in
    index da9dfdce5..a040d41a1 100644
    --- a/Makefile.in
    +++ b/Makefile.in
    @@ -420,6 +420,11 @@ distclean-examples:
     	@echo distcleaning Examples
     	@$(MAKE) $(FLAGS) clean-examples
     	@cd Examples && $(MAKE) $(FLAGS) distclean
    +	@if test "x$(srcdir)" != "x."; then \
    +		for mkfile in `cd $(srcdir) && find Examples/ -type f -name Makefile`; do \
    +			rm -f "$$mkfile"; \
    +		done; \
    +	fi
     
     distclean-ccache:
     	@test -z "$(ENABLE_CCACHE)" || (cd $(CCACHE) && $(MAKE) $(FLAGS) distclean)
    
    From 3e978fce9ff9d655a7e9469a59c5d6ccc73fb7cb Mon Sep 17 00:00:00 2001
    From: Karl Wette 
    Date: Sat, 24 May 2014 20:25:56 +0200
    Subject: [PATCH 0988/1048] Record files left over after maintainer-clean in
     Travis build
    
    ---
     .travis.yml | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/.travis.yml b/.travis.yml
    index 5859c946f..89bed90a1 100644
    --- a/.travis.yml
    +++ b/.travis.yml
    @@ -113,7 +113,7 @@ script:
       - if test -n "$SWIGLANG"; then make -k $SWIGJOBS check-$SWIGLANG-examples CFLAGS="${CFLAGS_EXAMPLES[$SWIGLANG]}" CXXFLAGS="${CXXFLAGS_EXAMPLES[$SWIGLANG]}"; fi
       - if test -n "$SWIGLANG"; then make -k $SWIGJOBS check-$SWIGLANG-test-suite; fi
       - echo 'Cleaning...' && echo -en 'travis_fold:start:script.3\\r'
    -  - make maintainer-clean && ../../configure $CONFIGOPTS
    +  - make maintainer-clean && find . -type f | sed 's/^/File left after maintainer-clean - /' && ../../configure $CONFIGOPTS
       - echo -en 'travis_fold:end:script.3\\r'
     branches:
       only:
    
    From 5c5dfc106f00b4125f1ae7a173463afc8cdeccad Mon Sep 17 00:00:00 2001
    From: Harvey Falcic 
    Date: Sat, 24 May 2014 15:39:53 -0400
    Subject: [PATCH 0989/1048] Python unicode_strings test case: restrict to
     Python > 3.0
    
    Also adjust the test method names and content to match the docs.
    ---
     Examples/test-suite/python/unicode_strings_runme.py | 7 +++++--
     Examples/test-suite/unicode_strings.i               | 8 ++++----
     2 files changed, 9 insertions(+), 6 deletions(-)
    
    diff --git a/Examples/test-suite/python/unicode_strings_runme.py b/Examples/test-suite/python/unicode_strings_runme.py
    index 2d26599aa..162f40972 100644
    --- a/Examples/test-suite/python/unicode_strings_runme.py
    +++ b/Examples/test-suite/python/unicode_strings_runme.py
    @@ -1,4 +1,7 @@
    +import sys
    +
     import unicode_strings
     
    -unicode_strings.test_c_str()
    -unicode_strings.test_std_string()
    +if sys.version_info > (3, 0):
    +    unicode_strings.non_utf8_c_str()
    +    unicode_strings.non_utf8_std_string()
    diff --git a/Examples/test-suite/unicode_strings.i b/Examples/test-suite/unicode_strings.i
    index f4a8b8b50..56063c8a4 100644
    --- a/Examples/test-suite/unicode_strings.i
    +++ b/Examples/test-suite/unicode_strings.i
    @@ -4,12 +4,12 @@
     
     %inline %{
     
    -const char* test_c_str(void) {
    -        return "h\xe9llo";
    +const char* non_utf8_c_str(void) {
    +        return "h\xe9llo w\xc3\xb6rld";
     }
     
    -std::string test_std_string(void) {
    -        return std::string("h\xe9llo");
    +std::string non_utf8_std_string(void) {
    +        return std::string("h\xe9llo w\xc3\xb6rld");
     }
     
     %}
    
    From 2533d0210fb2f3b2e9f441c38bd03b99f4a57a44 Mon Sep 17 00:00:00 2001
    From: Harvey Falcic 
    Date: Sat, 24 May 2014 16:50:33 -0400
    Subject: [PATCH 0990/1048] unicode_strings test: check return values
    
    ---
     Examples/test-suite/python/unicode_strings_runme.py | 9 +++++++--
     1 file changed, 7 insertions(+), 2 deletions(-)
    
    diff --git a/Examples/test-suite/python/unicode_strings_runme.py b/Examples/test-suite/python/unicode_strings_runme.py
    index 162f40972..0e2e1af06 100644
    --- a/Examples/test-suite/python/unicode_strings_runme.py
    +++ b/Examples/test-suite/python/unicode_strings_runme.py
    @@ -2,6 +2,11 @@ import sys
     
     import unicode_strings
     
    +# The 'u' string prefix isn't valid in Python 3.0 - 3.2 and is redundant
    +# in 3.3+. Since this file is run through 2to3 before testing, though,
    +# mark this as a unicode string in 2.x so it'll become a str in 3.x.
    +test_string = u'h\udce9llo w\u00f6rld'
    +
     if sys.version_info > (3, 0):
    -    unicode_strings.non_utf8_c_str()
    -    unicode_strings.non_utf8_std_string()
    +    assert unicode_strings.non_utf8_c_str() == test_string
    +    assert unicode_strings.non_utf8_std_string() == test_string
    
    From ab527b0e4bf592e55b038a6de0fb8fe4540eea92 Mon Sep 17 00:00:00 2001
    From: Harvey Falcic 
    Date: Sat, 24 May 2014 17:54:53 -0400
    Subject: [PATCH 0991/1048] unicode_strings_runme.py: fix version check
    
    Python 3.0.1 shouldn't pass.
    ---
     Examples/test-suite/python/unicode_strings_runme.py | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/Examples/test-suite/python/unicode_strings_runme.py b/Examples/test-suite/python/unicode_strings_runme.py
    index 0e2e1af06..2110c5ce7 100644
    --- a/Examples/test-suite/python/unicode_strings_runme.py
    +++ b/Examples/test-suite/python/unicode_strings_runme.py
    @@ -7,6 +7,6 @@ import unicode_strings
     # mark this as a unicode string in 2.x so it'll become a str in 3.x.
     test_string = u'h\udce9llo w\u00f6rld'
     
    -if sys.version_info > (3, 0):
    +if sys.version_info[0:2] >= (3, 1):
         assert unicode_strings.non_utf8_c_str() == test_string
         assert unicode_strings.non_utf8_std_string() == test_string
    
    From 91e93838fc6dbc181181f6ffacb024b6a87cfe63 Mon Sep 17 00:00:00 2001
    From: Harvey Falcic 
    Date: Sat, 24 May 2014 18:00:04 -0400
    Subject: [PATCH 0992/1048] unicode_strings test: manually check values instead
     of using assert
    
    ---
     Examples/test-suite/python/unicode_strings_runme.py | 6 ++++--
     1 file changed, 4 insertions(+), 2 deletions(-)
    
    diff --git a/Examples/test-suite/python/unicode_strings_runme.py b/Examples/test-suite/python/unicode_strings_runme.py
    index 2110c5ce7..e1fc7adec 100644
    --- a/Examples/test-suite/python/unicode_strings_runme.py
    +++ b/Examples/test-suite/python/unicode_strings_runme.py
    @@ -8,5 +8,7 @@ import unicode_strings
     test_string = u'h\udce9llo w\u00f6rld'
     
     if sys.version_info[0:2] >= (3, 1):
    -    assert unicode_strings.non_utf8_c_str() == test_string
    -    assert unicode_strings.non_utf8_std_string() == test_string
    +    if unicode_strings.non_utf8_c_str() != test_string:
    +        raise ValueError('Test comparison mismatch')
    +    if unicode_strings.non_utf8_std_string() != test_string:
    +        raise ValueError('Test comparison mismatch')
    
    From 575ac1c170cbfb9de6ced5f9e7075b928d4a4227 Mon Sep 17 00:00:00 2001
    From: William S Fulton 
    Date: Sun, 25 May 2014 00:01:24 +0100
    Subject: [PATCH 0993/1048] Add 3.0.1 release notes summary
    
    ---
     RELEASENOTES | 8 ++++++++
     1 file changed, 8 insertions(+)
    
    diff --git a/RELEASENOTES b/RELEASENOTES
    index 949f58e38..542ff4b10 100644
    --- a/RELEASENOTES
    +++ b/RELEASENOTES
    @@ -4,6 +4,14 @@ and CHANGES files.
     
     Release Notes
     =============
    +SWIG-3.0.1 summary:
    +- Javascript module added. This supports JavascriptCore (Safari/Webkit),
    +  v8 (Chromium) and node.js currently.
    +- A few notable regressions introduced in 3.0.0 have been fixed - in 
    +  Lua, nested classes and parsing of operator <<.
    +- The usual round of bug fixes and minor improvements for:
    +  C#, GCJ, Go, Java, Lua, PHP and Python.
    +
     SWIG-3.0.0 summary:
     - This is a major new release focusing primarily on C++ improvements.
     - C++11 support added. Please see documentation for details of supported
    
    From 4ab2eb96cd34503f2ceaa3ee88c22801cb546dda Mon Sep 17 00:00:00 2001
    From: William S Fulton 
    Date: Sun, 25 May 2014 00:29:32 +0100
    Subject: [PATCH 0994/1048] R examples building out-of-source
    
    They still don't run though
    ---
     Examples/Makefile.in | 6 +++---
     1 file changed, 3 insertions(+), 3 deletions(-)
    
    diff --git a/Examples/Makefile.in b/Examples/Makefile.in
    index 3a91cddd3..caf848596 100644
    --- a/Examples/Makefile.in
    +++ b/Examples/Makefile.in
    @@ -14,7 +14,7 @@
     #
     # 2.   To use this makefile, set required variables, eg SRCS, INTERFACE,
     #      INTERFACEDIR, INCLUDES, LIBS, TARGET, and do a
    -#           $(MAKE) -f Makefile.template.in SRCS='$(SRCS)' \
    +#           $(MAKE) -f Makefile.template.in SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' \
     #           INCLUDES='$(INCLUDES) LIBS='$(LIBS)' INTERFACE='$(INTERFACE)' \
     #           INTERFACEDIR='$(INTERFACEDIR)' TARGET='$(TARGET)' method
     #
    @@ -1660,7 +1660,7 @@ r: $(SRCDIR_SRCS)
     ifneq ($(SRCDIR_SRCS),)
     	$(CC) -g -c $(CPPFLAGS) $(CFLAGS) $(R_CFLAGS) $(SRCDIR_SRCS) $(INCLUDES)
     endif
    -	+( PKG_CPPFLAGS="$(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(ISRCS) $(OBJS) > /dev/null )
    +	+( PKG_CPPFLAGS="$(CPPFLAGS) $(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(ISRCS) $(OBJS) > /dev/null )
     
     # ----------------------------------------------------------------
     # Build a R dynamically loadable module (C++)
    @@ -1671,7 +1671,7 @@ r_cpp: $(SRCDIR_CXXSRCS)
     ifneq ($(SRCDIR_CXXSRCS),)
     	$(CXX) -g -c $(CPPFLAGS) $(CXXFLAGS) $(R_CFLAGS) $(SRCDIR_CXXSRCS) $(INCLUDES)
     endif
    -	+( PKG_CPPFLAGS="$(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(RCXXSRCS) $(OBJS) > /dev/null )
    +	+( PKG_CPPFLAGS="$(CPPFLAGS) $(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(RCXXSRCS) $(OBJS) > /dev/null )
     
     # -----------------------------------------------------------------
     # Run R example
    
    From 597c671e8630f959b48d716ffbc0be57990dc585 Mon Sep 17 00:00:00 2001
    From: William S Fulton 
    Date: Sun, 25 May 2014 12:00:42 +0100
    Subject: [PATCH 0995/1048] More diagnostics for csharp_exceptions testcase for
     diagnosing erratic failures
    
    ---
     Examples/test-suite/csharp/csharp_exceptions_runme.cs | 6 ++++--
     1 file changed, 4 insertions(+), 2 deletions(-)
    
    diff --git a/Examples/test-suite/csharp/csharp_exceptions_runme.cs b/Examples/test-suite/csharp/csharp_exceptions_runme.cs
    index 43585b106..51805ce87 100644
    --- a/Examples/test-suite/csharp/csharp_exceptions_runme.cs
    +++ b/Examples/test-suite/csharp/csharp_exceptions_runme.cs
    @@ -323,7 +323,9 @@ public class TestThread {
              } catch (ArgumentOutOfRangeException e) {
                String expectedMessage = "caught:" + i + "\n" + "Parameter name: input";
                if (e.Message.Replace(runme.CRLF,"\n") != expectedMessage)
    -             throw new Exception("Exception message incorrect. Expected:\n[" + expectedMessage + "]\n" + "Received:\n[" + e.Message + "]");
    +             throw new Exception("Exception message incorrect. Expected:\n[" + 
    +                 expectedMessage + "]\n" + "Received:\n[" + 
    +                 e.Message + "]");
                if (e.ParamName != "input")
                  throw new Exception("Exception ParamName incorrect. Expected:\n[input]\n" + "Received:\n[" + e.ParamName + "]");
                if (e.InnerException != null)
    @@ -333,7 +335,7 @@ public class TestThread {
                throw new Exception("throwsException.dub = " + throwsClass.dub + " expected: 1234.5678");
            }
          } catch (Exception e) {
    -       Console.Error.WriteLine("Test failed (thread " + threadId + "): " + e.Message);
    +       Console.Error.WriteLine("Test failed (thread " + threadId + "): " + e.Message + "\n  TestThread Inner stack trace: " + e.StackTrace);
            Failed = true;
          }
        }
    
    From 01f8253b192224d8996e5bffd3c8121fa32ad0ea Mon Sep 17 00:00:00 2001
    From: Oliver Buchtala 
    Date: Mon, 26 May 2014 21:38:00 +0200
    Subject: [PATCH 0996/1048] Javascript: added a section about known issues.
    
    ---
     Doc/Manual/Javascript.html | 32 +++++++++++---------------------
     1 file changed, 11 insertions(+), 21 deletions(-)
    
    diff --git a/Doc/Manual/Javascript.html b/Doc/Manual/Javascript.html
    index 011e61051..e6f422bd8 100644
    --- a/Doc/Manual/Javascript.html
    +++ b/Doc/Manual/Javascript.html
    @@ -128,33 +128,23 @@ $ make check-javascript-examples ENGINE=jsc
     $ make check-javascript-test-suite ENGINE=jsc
    -

    Tests should run without any problems, i.e., have been tried out, on the following platforms/interpreters:

    -
    -
    -- Ubuntu Precise 12.04 64bit
    -    - JavascriptCore (Webkit 1.8.3)
    -    - Node.js (0.10.26)
    -    - v8 (3.7.12)
    -- Ubuntu Saucy 13.10 64bit
    -    - JavascriptCore (Webkit 1.10.2)
    -    - Node.js
    -    - v8 (3.14.5)
    -- Mac OSX Mountain Lion 10.8
    -    - JavascriptCore (built-in)
    -    - Node.js
    -- Windows 7 64bit (VS 2010)
    -    - Node.js
    -
    -

    26.2.3 Future work

    +

    26.2.1 Known Issues

    +

    At the moment, the Javascript generators pass all tests syntactically, i.e., the generated source code compiles. However, there are still remaining runtime issues.

    -

    The Javascript module is not yet as mature as other modules and some things are still missing. As it makes use of SWIG's Unified Typemap Library (UTL), many typemaps are inherited. We could work on that if requested:

      -
    • More typemaps: compared to other modules there are only a few typemaps implemented. For instance a lot of the std_*.i typemaps are missing, such as std_iostream, for instance.

    • -
    • Director support: this would allow to extend a C++ abstract base class in Javascript. A pragmatic intermediate step for the most important usecase would be to support Javascript callbacks as arguments.

    • +
    • Default optional arguments do not work for all targeted interpreters

    • +
    • Mutliple output arguments do not work for JSC

    • +
    • Memory leaks have been observed for all generators

    • +
    • C89 incompatibily: the JSC generator might still generate C89 violating code

    • +
    • long long is not supported q

    • +
    • Javascript callbacks are not supported

    • +
    • instanceOf does not work under JSC

    +

    The primary development environment has been Linux (Ubuntu 12.04). Windows and OSX have been tested sporadically. Therefore, the generators might have more issues on those platforms. Please report back any problem you observe to help us improving this module quickly.

    +

    26.3 Integration

    From 6f69555225d818530e60cc50a7cd57f8bafd46f1 Mon Sep 17 00:00:00 2001 From: Eric Wing Date: Mon, 19 May 2014 17:15:49 -0700 Subject: [PATCH 0997/1048] JavaScriptCore: Fixed exception object so sourceURL (file name), line (number), and message can be recovered. The current implementation only returns an error string. But this is insufficient for debugging (what file and line number did it fail at?). As documented here: http://parmanoir.com/Taming_JavascriptCore_within_and_without_WebView converting the JSValueRef of string to an JSObjectRef (via JSValueToObject) will trigger JSCore into filling the "sourceURL" and "line" properties into the object so they can be inspected by the caller. Additionally, JavaScriptCore has a "message" property which contains the message string. JSCore doesn't seem to be filling this in for us automatically, unlike "sourceURL" and "line". So this patch also fills that property in too. Thanks to Brian Barnes for the detailed information about "sourceURL", "line", and "message". Below is an example (derived from Brian Barnes's information) on how you typically use/extract these exception details. void script_exception_to_string(JSContextRef js_context,JSValueRef exception_value_ref,char* return_error_string, int return_error_string_max_length) { JSObjectRef exception_object; JSValueRef value_ref; JSStringRef jsstring_property_name = NULL; JSValueRef temporary_exception = NULL; JSStringRef js_return_string = NULL; size_t bytes_needed; char* c_result_string = NULL; exception_object = JSValueToObject(js_context, exception_value_ref, NULL); // source and line numbers strcpy(return_error_string,"["); jsstring_property_name = JSStringCreateWithUTF8CString("sourceURL"); value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &temporary_exception); JSStringRelease(jsstring_property_name); js_return_string = JSValueToStringCopy(js_context, value_ref, NULL); bytes_needed = JSStringGetMaximumUTF8CStringSize(js_return_string); c_result_string = (char*)calloc(bytes_needed, sizeof(char)); JSStringGetUTF8CString(js_return_string, c_result_string, bytes_needed); SDL_Log("c_result_string: %s\n", c_result_string); JSStringRelease(js_return_string); strncat(return_error_string, c_result_string, return_error_string_max_length-1); free(c_result_string); strncat(return_error_string, ":", return_error_string_max_length-1); jsstring_property_name = JSStringCreateWithUTF8CString("line"); value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &temporary_exception); JSStringRelease(jsstring_property_name); js_return_string = JSValueToStringCopy(js_context, value_ref, NULL); bytes_needed = JSStringGetMaximumUTF8CStringSize(js_return_string); c_result_string = (char*)calloc(bytes_needed, sizeof(char)); JSStringGetUTF8CString(js_return_string, c_result_string, bytes_needed); SDL_Log("c_result_string: %s\n", c_result_string); JSStringRelease(js_return_string); strncat(return_error_string, c_result_string, return_error_string_max_length-1); //SDL_Log("c_result_string: %s\n", c_result_string); free(c_result_string); strncat(return_error_string, "]", return_error_string_max_length-1); /* get message */ jsstring_property_name = JSStringCreateWithUTF8CString("message"); value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &temporary_exception); JSStringRelease(jsstring_property_name); if(NULL == value_ref) { strncat(return_error_string, "Unknown Error", return_error_string_max_length-1); } else { js_return_string = JSValueToStringCopy(js_context, value_ref, NULL); bytes_needed = JSStringGetMaximumUTF8CStringSize(js_return_string); c_result_string = (char*)calloc(bytes_needed, sizeof(char)); JSStringGetUTF8CString(js_return_string, c_result_string, bytes_needed); SDL_Log("c_result_string: %s\n", c_result_string); JSStringRelease(js_return_string); strncat(return_error_string, c_result_string, return_error_string_max_length-1); //SDL_Log("c_result_string: %s\n", c_result_string); free(c_result_string); } } To use: if(js_exception) { char return_error_string[256]; script_exception_to_string(js_context, js_exception, return_error_string, 256); SDL_Log("Compile error is %s", return_error_string); } --- Lib/javascript/jsc/javascriptrun.swg | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) diff --git a/Lib/javascript/jsc/javascriptrun.swg b/Lib/javascript/jsc/javascriptrun.swg index ae1567e87..1fde8855b 100644 --- a/Lib/javascript/jsc/javascriptrun.swg +++ b/Lib/javascript/jsc/javascriptrun.swg @@ -9,8 +9,29 @@ SWIGRUNTIME void SWIG_Javascript_Raise(JSContextRef context, JSValueRef *exception, const char* type) { JSStringRef message = JSStringCreateWithUTF8CString(type); - *exception = JSValueMakeString(context, message); - JSStringRelease(message); + JSStringRef message_property_key; + JSObjectRef exception_object; + JSValueRef exception_value; + JSValueRef message_value; + exception_value = JSValueMakeString(context, message); + /* Converting the result to an object will let JavascriptCore add "sourceURL" (file) and "line" (number) to the exception, + instead of just returning a raw string. This is extremely important for debugging your errors. + */ + exception_object = JSValueToObject(context, exception_value, NULL); + + /* Additionally, JSCore uses "message" which contains the error description. + But it seems that unlike "sourceURL" and "line", converting to an object is not automatically doing this. + So we can add it ourselves. + */ + message_property_key = JSStringCreateWithUTF8CString("message"); + message_value = JSValueMakeString(context, message); + JSObjectSetProperty(context, exception_object, message_property_key, message_value, kJSClassAttributeNone, NULL); + + /* Return the exception_object */ + *exception = exception_object; + + JSStringRelease(message_property_key); + JSStringRelease(message); } SWIGRUNTIME void SWIG_JSC_exception(JSContextRef context, JSValueRef *exception, int code, const char* msg) { From f1c331f2c5b5df607edb581cf7711b7f40d2fb09 Mon Sep 17 00:00:00 2001 From: Eric Wing Date: Mon, 19 May 2014 17:42:00 -0700 Subject: [PATCH 0998/1048] JavaScriptCore: Returning NULL for wrapper functions that expect JSValueRef may crash program. According to this: http://parmanoir.com/Taming_JavascriptCore_within_and_without_WebView Returning NULL instead of an actual JSValueRef for a return value of a function could lead to crashes. I think I have seen related weirdness in the past when I failed to return a proper type to JSCore which resulted in very hard to understand behavior. So this patch changes those return NULLs to return JSValueMakeUndefined(). I thought about JSObjectMakeError, but I don't fully understand the intent of the Error object and can't find any relevant real world examples of it being used. However, everybody seems to be using JSValueMakeUndefined(). This patch should be low impact since this is only triggered on an error condition. --- Lib/javascript/jsc/javascriptcode.swg | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index 3fe9d49e9..f8c5a200f 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -17,7 +17,7 @@ static JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); goto fail; fail: - return NULL; + return JSValueMakeUndefined(context); } %} @@ -78,7 +78,7 @@ static JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size goto fail; fail: - return NULL; + return JSValueMakeUndefined(context); } %} @@ -159,7 +159,7 @@ static JSValueRef $jswrapper(JSContextRef context, JSObjectRef thisObject, JSStr goto fail; fail: - return NULL; + return JSValueMakeUndefined(context); } %} @@ -204,7 +204,7 @@ static JSValueRef $jswrapper(JSContextRef context, JSObjectRef function, JSObjec goto fail; fail: - return NULL; + return JSValueMakeUndefined(context); } %} @@ -229,7 +229,7 @@ static JSValueRef $jswrapper(JSContextRef context, JSObjectRef function, JSObjec goto fail; fail: - return NULL; + return JSValueMakeUndefined(context); } %} From e7b20624cc32d1220d5ad53370bfc1d92c8657c4 Mon Sep 17 00:00:00 2001 From: Eric Wing Date: Mon, 19 May 2014 19:00:43 -0700 Subject: [PATCH 0999/1048] JavaScriptCore: Reverted 2 of the JSValueMakeUndefined replacements because those functions are tied to JSObjectRef instead of JSValueRef. The C compiler will allow this, but C++ will reject the conversion. It is unclear what the correct handling is for JavaScriptCore. (Nobody bothers to document this in JSCore.) Unlike our other problem where we incorrectly assume JSObjectRef when the functions want JSValueRef, this time Apple is demanding the JSObjectRef. Like our other problem, I assume it is unsafe to try to convert Undefined into a JSObjectRef. So reverting to NULL seems like the safer bet for this specific case. Perhaps the other alternative is to return an exception object or an error object. But I would like to see JSCore document this before trying. --- Lib/javascript/jsc/javascriptcode.swg | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg index f8c5a200f..c18902fce 100644 --- a/Lib/javascript/jsc/javascriptcode.swg +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -17,7 +17,7 @@ static JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); goto fail; fail: - return JSValueMakeUndefined(context); + return NULL; } %} @@ -78,7 +78,7 @@ static JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size goto fail; fail: - return JSValueMakeUndefined(context); + return NULL; } %} From 1766e67a1af127f42c908090e8d46b49de30ce19 Mon Sep 17 00:00:00 2001 From: Eric Wing Date: Wed, 21 May 2014 03:43:52 -0700 Subject: [PATCH 1000/1048] JavaScriptCore: Improved code that uses JSObjectMakeError instead of JSValueToObject to create the exception object. JSObjectMakeError automatically populates the "message" field, and possibly other fields I don't know about. This seems to be the most robust way to create an exception object. Thanks to Brian Barnes again for the tip on JSObjectMakeError. --- Lib/javascript/jsc/javascriptrun.swg | 40 ++++++++++++---------------- 1 file changed, 17 insertions(+), 23 deletions(-) diff --git a/Lib/javascript/jsc/javascriptrun.swg b/Lib/javascript/jsc/javascriptrun.swg index 1fde8855b..676a45833 100644 --- a/Lib/javascript/jsc/javascriptrun.swg +++ b/Lib/javascript/jsc/javascriptrun.swg @@ -8,30 +8,24 @@ #define SWIG_fail goto fail SWIGRUNTIME void SWIG_Javascript_Raise(JSContextRef context, JSValueRef *exception, const char* type) { - JSStringRef message = JSStringCreateWithUTF8CString(type); - JSStringRef message_property_key; - JSObjectRef exception_object; - JSValueRef exception_value; - JSValueRef message_value; - exception_value = JSValueMakeString(context, message); - /* Converting the result to an object will let JavascriptCore add "sourceURL" (file) and "line" (number) to the exception, - instead of just returning a raw string. This is extremely important for debugging your errors. - */ - exception_object = JSValueToObject(context, exception_value, NULL); - - /* Additionally, JSCore uses "message" which contains the error description. - But it seems that unlike "sourceURL" and "line", converting to an object is not automatically doing this. - So we can add it ourselves. + JSStringRef message = JSStringCreateWithUTF8CString(type); + JSValueRef error_arguments[1]; + JSObjectRef exception_object; + JSValueRef exception_value; + exception_value = JSValueMakeString(context, message); + /* Converting the result to an object will let JavascriptCore add + "sourceURL" (file) and "line" (number) and "message" to the exception, + instead of just returning a raw string. This is extremely important for debugging your errors. + Using JSObjectMakeError is better than JSValueToObject because the latter only populates + "sourceURL" and "line", but not "message" or any others I don't know about. */ - message_property_key = JSStringCreateWithUTF8CString("message"); - message_value = JSValueMakeString(context, message); - JSObjectSetProperty(context, exception_object, message_property_key, message_value, kJSClassAttributeNone, NULL); - - /* Return the exception_object */ - *exception = exception_object; - - JSStringRelease(message_property_key); - JSStringRelease(message); + error_arguments[0] = exception_value; + exception_object = JSObjectMakeError(context, 1, error_arguments, NULL); + + /* Return the exception_object */ + *exception = exception_object; + + JSStringRelease(message); } SWIGRUNTIME void SWIG_JSC_exception(JSContextRef context, JSValueRef *exception, int code, const char* msg) { From 1df7ca77a061b961e054689bc8b61e60ed9ad93d Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 27 May 2014 10:40:16 +0200 Subject: [PATCH 1001/1048] JavascriptCore: added documentation about how to extract details from JSC errors. This code is necessary for embedding applications to present details about JS exceptions. --- Doc/Manual/Javascript.html | 83 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/Doc/Manual/Javascript.html b/Doc/Manual/Javascript.html index e6f422bd8..246669a22 100644 --- a/Doc/Manual/Javascript.html +++ b/Doc/Manual/Javascript.html @@ -41,6 +41,7 @@
  • Code Templates
  • Emitter
  • Emitter states +
  • Handling Exceptions in JavascriptCore
  • @@ -870,5 +871,87 @@ state.clazz(RESET); state.clazz(NAME, Getattr(n, "sym:name"));

    State information can be retrieved using state.clazz(NAME) or with Getattr on state.clazz() which actually returns a Hash instance.

    + + +

    26.5.5. Handling Exceptions in JavascriptCore

    + + +

    Applications with an embedded JavascriptCore should be able to present detailed exception messages that occur in the Javascript engine. Below is an example derived from code provided by Brian Barnes on how these exception details can be extracted.

    +
    +
    +void script_exception_to_string(JSContextRef js_context,JSValueRef exception_value_ref,char* return_error_string, int return_error_string_max_length)
    +{
    +  JSObjectRef exception_object;
    +  JSValueRef value_ref;
    +  JSStringRef jsstring_property_name = NULL;
    +  JSValueRef temporary_exception = NULL;
    +  JSStringRef js_return_string = NULL;
    +  size_t bytes_needed;
    +  char* c_result_string = NULL;
    +  exception_object = JSValueToObject(js_context, exception_value_ref, NULL);
    +
    +  /* source url */
    +  strcpy(return_error_string,"[");
    +  jsstring_property_name = JSStringCreateWithUTF8CString("sourceURL");
    +  value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &temporary_exception);
    +  JSStringRelease(jsstring_property_name);
    +  js_return_string = JSValueToStringCopy(js_context, value_ref, NULL);
    +  bytes_needed = JSStringGetMaximumUTF8CStringSize(js_return_string);
    +  c_result_string = (char*)calloc(bytes_needed, sizeof(char));
    +  JSStringGetUTF8CString(js_return_string, c_result_string, bytes_needed);
    +  JSStringRelease(js_return_string);
    +  strncat(return_error_string, c_result_string, return_error_string_max_length-1);
    +  free(c_result_string);
    +
    +  strncat(return_error_string, ":", return_error_string_max_length-1);
    +
    +  /* line number */
    +
    +  jsstring_property_name = JSStringCreateWithUTF8CString("line");
    +  value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &temporary_exception);
    +  JSStringRelease(jsstring_property_name);
    +  js_return_string = JSValueToStringCopy(js_context, value_ref, NULL);
    +  bytes_needed = JSStringGetMaximumUTF8CStringSize(js_return_string);
    +  c_result_string = (char*)calloc(bytes_needed, sizeof(char));
    +  JSStringGetUTF8CString(js_return_string, c_result_string, bytes_needed);
    +  JSStringRelease(js_return_string);
    +  strncat(return_error_string, c_result_string, return_error_string_max_length-1);
    +  free(c_result_string);
    +
    +  strncat(return_error_string, "]", return_error_string_max_length-1);
    +
    +  /* error message */
    +
    +  jsstring_property_name = JSStringCreateWithUTF8CString("message");
    +  value_ref = JSObjectGetProperty(js_context, exception_object, jsstring_property_name, &temporary_exception);
    +  JSStringRelease(jsstring_property_name);
    +  if(NULL == value_ref)
    +  {
    +    strncat(return_error_string, "Unknown Error", return_error_string_max_length-1);
    +  }
    +  else
    +  {
    +    js_return_string = JSValueToStringCopy(js_context, value_ref, NULL);
    +    bytes_needed = JSStringGetMaximumUTF8CStringSize(js_return_string);
    +    c_result_string = (char*)calloc(bytes_needed, sizeof(char));
    +    JSStringGetUTF8CString(js_return_string, c_result_string, bytes_needed);
    +    JSStringRelease(js_return_string);
    +    strncat(return_error_string, c_result_string, return_error_string_max_length-1);
    +    free(c_result_string);
    +  }
    +}
    +
    + +

    It would be used in the following way:

    +
    +
    +if(js_exception)
    +{
    +  char return_error_string[256];
    +  script_exception_to_string(js_context, js_exception, return_error_string, 256);
    +  printf("Compile error is %s", return_error_string);
    +}
    +
    + From 5d307b2cbfc9e2caa06805df425161617868bea8 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 27 May 2014 10:41:39 +0200 Subject: [PATCH 1002/1048] JavascriptCore: updated documentation about how to register an initialized module. --- Doc/Manual/Javascript.html | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/Doc/Manual/Javascript.html b/Doc/Manual/Javascript.html index 246669a22..97197b670 100644 --- a/Doc/Manual/Javascript.html +++ b/Doc/Manual/Javascript.html @@ -223,13 +223,21 @@ $ sudo apt-get remove gyp
     #import "appDelegate.h"
     
    -extern bool example_initialize(JSGlobalContextRef context);
    +extern bool example_initialize(JSGlobalContextRef context, JSObjectRef* exports);
     
     
     @implementation ExampleAppDelegate
     
     @synthesize webView;
     
    +- (void)addGlobalObject:(JSContextRef) context:(NSString *)objectName:(JSObjectRef) theObject {
    +  JSObjectRef global = JSContextGetGlobalObject(context);
    +  JSStringRef objectJSName = JSStringCreateWithCFString( (CFStringRef) objectName )
    +  if ( objectJSName != NULL ) {
    +    JSObjectSetProperty(context, global, objectJSName, theObject, kJSPropertyAttributeReadOnly, NULL);
    +    JSStringRelease( objectJSName );
    +  }
    +}
     
     - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
     
    @@ -240,7 +248,11 @@ extern bool example_initialize(JSGlobalContextRef context);
       WebFrame *webframe = [webView mainFrame];
       JSGlobalContextRef context = [webframe globalContext];
     
    -  example_initialize(context);
    +  JSObjectRef example;
    +  example_initialize(context, &example);
    +  [self addGlobalObject:context:@"example":example]
    +
    +  JSObjectSetProperty(context, global, JSStringRef propertyName, example, JSPropertyAttributes attributes, NULL);
     
       [ [webView mainFrame] loadRequest:
         [NSURLRequest requestWithURL: [NSURL URLWithString:url] ]
    @@ -273,7 +285,13 @@ int main(int argc, char* argv[])
         WebKitWebView *webView = WEBKIT_WEB_VIEW(webkit_web_view_new());
         WebFrame *webframe = webkit_web_view_get_main_frame(webView);
         JSGlobalContextRef context = webkit_web_frame_get_global_context(webFrame);
    -    example_initialize(context);
    +    JSObjectRef global = JSContextGetGlobalObject(context);
    +
    +    JSObjectRef exampleModule;
    +    example_initialize(context, &exampleModule);
    +    JSStringRef jsName = JSStringCreateWithUTF8CString("example");
    +    JSObjectSetProperty(context, global, jsName, exampleModule, kJSPropertyAttributeReadOnly, NULL);
    +    JSStringRelease(jsName);
     
         ...
     
    
    From a22f97eb3337bdd0b58d6ec764aeb23395c31d70 Mon Sep 17 00:00:00 2001
    From: Oliver Buchtala 
    Date: Tue, 27 May 2014 10:44:13 +0200
    Subject: [PATCH 1003/1048] Javascript: updated documentation about known
     issues.
    
    [skip ci]
    ---
     Doc/Manual/Javascript.html | 6 +++---
     1 file changed, 3 insertions(+), 3 deletions(-)
    
    diff --git a/Doc/Manual/Javascript.html b/Doc/Manual/Javascript.html
    index 97197b670..a4cc02d02 100644
    --- a/Doc/Manual/Javascript.html
    +++ b/Doc/Manual/Javascript.html
    @@ -15,7 +15,7 @@
     
     
  • Integration
      @@ -137,9 +137,9 @@ $ make check-javascript-test-suite ENGINE=jsc
    • Default optional arguments do not work for all targeted interpreters

    • Mutliple output arguments do not work for JSC

    • -
    • Memory leaks have been observed for all generators

    • C89 incompatibily: the JSC generator might still generate C89 violating code

    • -
    • long long is not supported q

    • +
    • long long is not supported

    • +
    • %native is not supported

    • Javascript callbacks are not supported

    • instanceOf does not work under JSC

    From c342bc1b281d9da9a73d88bfe3fca617cc5dab2d Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 27 May 2014 21:37:18 +0200 Subject: [PATCH 1004/1048] Javascript: added a link to the v8 web-site to the documentation. --- Doc/Manual/Javascript.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Doc/Manual/Javascript.html b/Doc/Manual/Javascript.html index a4cc02d02..bfe91aa09 100644 --- a/Doc/Manual/Javascript.html +++ b/Doc/Manual/Javascript.html @@ -57,7 +57,7 @@

    Javascript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. Its arguably the most popular language for web development. Javascript has gone beyond being a browser-based scripting language and with node.js, it is also used as a backend development language.

    Native Javascript extensions can be used for applications that embed a web-browser view or that embed a Javascript engine (such as node.js). Extending a general purpose web-browser is not possible as this would be a severe security issue.

    -

    SWIG Javascript currently supports JavascriptCore, the Javascript engine used by Safari/Webkit, and v8, which is used by Chromium and node.js.

    +

    SWIG Javascript currently supports JavascriptCore, the Javascript engine used by Safari/Webkit, and v8, which is used by Chromium and node.js.

    WebKit is a modern browser implementation available as open-source which can be embedded into an application. With node-webkit there is a platform which uses Google's Chromium as Web-Browser widget and node.js for javascript extensions.

    From b531956467f7e0e064cd9928c044be64fa0a3a0a Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 27 May 2014 21:55:17 +0100 Subject: [PATCH 1005/1048] Warning fixes compiling with Visual Studio --- Source/Modules/javascript.cxx | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index e535bc179..8b7a74037 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -724,19 +724,19 @@ int JSEmitter::emitWrapperFunction(Node *n) { // detected via the 'view' attribute. || (Equal(kind, "variable") && Equal(Getattr(n, "view"), "globalfunctionHandler")) ) { - bool is_member = GetFlag(n, "ismember") | GetFlag(n, "feature:extend"); - bool is_static = GetFlag(state.function(), IS_STATIC); + bool is_member = GetFlag(n, "ismember") != 0 || GetFlag(n, "feature:extend") != 0; + bool is_static = GetFlag(state.function(), IS_STATIC) != 0; ret = emitFunction(n, is_member, is_static); } else if (Cmp(kind, "variable") == 0) { - bool is_static = GetFlag(state.variable(), IS_STATIC); + bool is_static = GetFlag(state.variable(), IS_STATIC) != 0; // HACK: smartpointeraccessed static variables are not treated as statics if (GetFlag(n, "allocate:smartpointeraccess")) { is_static = false; } - bool is_member = GetFlag(n, "ismember"); - bool is_setter = GetFlag(n, "memberset") || GetFlag(n, "varset"); - bool is_getter = GetFlag(n, "memberget") || GetFlag(n, "varget"); + bool is_member = GetFlag(n, "ismember") != 0; + bool is_setter = GetFlag(n, "memberset") != 0 || GetFlag(n, "varset") != 0; + bool is_getter = GetFlag(n, "memberget") != 0 || GetFlag(n, "varget") != 0; if (is_setter) { ret = emitSetter(n, is_member, is_static); } else if (is_getter) { @@ -840,7 +840,7 @@ int JSEmitter::emitCtor(Node *n) { Wrapper *wrapper = NewWrapper(); - bool is_overloaded = GetFlag(n, "sym:overloaded"); + bool is_overloaded = GetFlag(n, "sym:overloaded") != 0; Template t_ctor(getTemplate("js_ctor")); @@ -1160,7 +1160,7 @@ int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { Wrapper *wrapper = NewWrapper(); Template t_function(getTemplate("js_function")); - bool is_overloaded = GetFlag(n, "sym:overloaded"); + bool is_overloaded = GetFlag(n, "sym:overloaded") != 0; // prepare the function wrapper name String *iname = Getattr(n, "sym:name"); @@ -1288,7 +1288,7 @@ void JSEmitter::marshalOutput(Node *n, ParmList *params, Wrapper *wrapper, Strin cresult = defaultResultName; tm = Swig_typemap_lookup_out("out", n, cresult, wrapper, actioncode); - bool should_own = GetFlag(n, "feature:new"); + bool should_own = GetFlag(n, "feature:new") != 0; if (tm) { Replaceall(tm, "$objecttype", Swig_scopename_last(SwigType_str(SwigType_strip_qualifiers(type), 0))); @@ -1628,8 +1628,8 @@ int JSCEmitter::enterFunction(Node *n) { int JSCEmitter::exitFunction(Node *n) { Template t_function = getTemplate("jsc_function_declaration"); - bool is_member = GetFlag(n, "ismember") | GetFlag(n, "feature:extend"); - bool is_overloaded = GetFlag(n, "sym:overloaded"); + bool is_member = GetFlag(n, "ismember") != 0 || GetFlag(n, "feature:extend") != 0; + bool is_overloaded = GetFlag(n, "sym:overloaded") != 0; // handle overloaded functions if (is_overloaded) { @@ -2077,10 +2077,10 @@ int V8Emitter::exitVariable(Node *n) { } int V8Emitter::exitFunction(Node *n) { - bool is_member = GetFlag(n, "ismember") | GetFlag(n, "feature:extend"); + bool is_member = GetFlag(n, "ismember") != 0 || GetFlag(n, "feature:extend") != 0; // create a dispatcher for overloaded functions - bool is_overloaded = GetFlag(n, "sym:overloaded"); + bool is_overloaded = GetFlag(n, "sym:overloaded") != 0; if (is_overloaded) { if (!Getattr(n, "sym:nextSibling")) { //state.function(WRAPPER_NAME, Swig_name_wrapper(Getattr(n, "name"))); From f03bff152c44203ece2084aac03f14ac55a33b5c Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 27 May 2014 07:22:46 +0100 Subject: [PATCH 1006/1048] Python 3 byte string output: use errors="surrogateescape" change note --- CHANGES.current | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/CHANGES.current b/CHANGES.current index e73a91c3f..399a05415 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.1 (in progress) =========================== +2014-05-25: hfalcic + [Python] Python 3 byte string output: use errors="surrogateescape" + if available on the version of Python that's in use. This allows + obtaining the original byte string (and potentially trying a fallback + encoding) if the bytes can't be decoded as UTF-8. + + Previously, a UnicodeDecodeError would be raised with no way to treat + the data as bytes or try another codec. + 2014-05-18: vkalinin Bug #175 - Restore %extend to work for unnamed nested structures by using a C symbol comprising the outer structure name and unnamed variable instance name. From eeb113360633fdd69c4d81a3a508853f3cafe9e3 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 27 May 2014 07:27:33 +0100 Subject: [PATCH 1007/1048] Javascript html links and typo fixes --- Doc/Manual/Contents.html | 4 +++- Doc/Manual/Javascript.html | 9 +++++---- Doc/Manual/Python.html | 2 +- Doc/Manual/Sections.html | 2 +- 4 files changed, 10 insertions(+), 7 deletions(-) diff --git a/Doc/Manual/Contents.html b/Doc/Manual/Contents.html index 37a5aacff..4dd454352 100644 --- a/Doc/Manual/Contents.html +++ b/Doc/Manual/Contents.html @@ -1056,7 +1056,7 @@
  • Integration
  • @@ -1566,6 +1567,7 @@
  • Function annotation
  • Buffer interface
  • Abstract base classes +
  • Byte string output conversion
  • diff --git a/Doc/Manual/Javascript.html b/Doc/Manual/Javascript.html index bfe91aa09..fc2c45126 100644 --- a/Doc/Manual/Javascript.html +++ b/Doc/Manual/Javascript.html @@ -6,7 +6,7 @@ -

    26 SWIG and Javascript

    +

    26 SWIG and Javascript

      @@ -130,13 +130,14 @@ $ make check-javascript-examples ENGINE=jsc
    $ make check-javascript-test-suite ENGINE=jsc
    -

    26.2.1 Known Issues

    +

    26.2.3 Known Issues

    +

    At the moment, the Javascript generators pass all tests syntactically, i.e., the generated source code compiles. However, there are still remaining runtime issues.

    • Default optional arguments do not work for all targeted interpreters

    • -
    • Mutliple output arguments do not work for JSC

    • +
    • Multiple output arguments do not work for JSC

    • C89 incompatibily: the JSC generator might still generate C89 violating code

    • long long is not supported

    • %native is not supported

    • @@ -891,7 +892,7 @@ state.clazz(NAME, Getattr(n, "sym:name"));

      State information can be retrieved using state.clazz(NAME) or with Getattr on state.clazz() which actually returns a Hash instance.

      -

      26.5.5. Handling Exceptions in JavascriptCore

      +

      26.5.5 Handling Exceptions in JavascriptCore

      Applications with an embedded JavascriptCore should be able to present detailed exception messages that occur in the Javascript engine. Below is an example derived from code provided by Brian Barnes on how these exception details can be extracted.

      diff --git a/Doc/Manual/Python.html b/Doc/Manual/Python.html index 6dc0ff9ba..8b4f42a43 100644 --- a/Doc/Manual/Python.html +++ b/Doc/Manual/Python.html @@ -5929,7 +5929,7 @@ For details of abstract base class, please see PEP 3119.

      -

      35.12.4 Byte string output conversion

      +

      36.12.4 Byte string output conversion

      diff --git a/Doc/Manual/Sections.html b/Doc/Manual/Sections.html index 99d1dfe0d..b616371df 100644 --- a/Doc/Manual/Sections.html +++ b/Doc/Manual/Sections.html @@ -42,7 +42,7 @@ Last update : SWIG-3.0.1 (in progress)

    • Go support
    • Guile support
    • Java support
    • -
    • Javascript support
    • +
    • Javascript support
    • Common Lisp support
    • Lua support
    • Modula3 support
    • From 85413bc84dd1207baf7f1aca08ce0a3771115430 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 27 May 2014 18:37:05 +0100 Subject: [PATCH 1008/1048] Add 3.0.1 release date --- ANNOUNCE | 2 +- CHANGES.current | 2 +- Doc/Manual/Sections.html | 2 +- README | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ANNOUNCE b/ANNOUNCE index 6229edc4a..7c521e77b 100644 --- a/ANNOUNCE +++ b/ANNOUNCE @@ -1,4 +1,4 @@ -*** ANNOUNCE: SWIG 3.0.1 (in progress) *** +*** ANNOUNCE: SWIG 3.0.1 (27 May 2014) *** http://www.swig.org diff --git a/CHANGES.current b/CHANGES.current index 399a05415..4b95adfa8 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 3.0.1 (in progress) +Version 3.0.1 (27 May 2014) =========================== 2014-05-25: hfalcic diff --git a/Doc/Manual/Sections.html b/Doc/Manual/Sections.html index b616371df..0a61f074e 100644 --- a/Doc/Manual/Sections.html +++ b/Doc/Manual/Sections.html @@ -6,7 +6,7 @@

      SWIG-3.0 Documentation

      -Last update : SWIG-3.0.1 (in progress) +Last update : SWIG-3.0.1 (27 May 2014)

      Sections

      diff --git a/README b/README index 46497c148..e30441be7 100644 --- a/README +++ b/README @@ -1,6 +1,6 @@ SWIG (Simplified Wrapper and Interface Generator) -Version: 3.0.1 (in progress) +Version: 3.0.1 (27 May 2014) Tagline: SWIG is a compiler that integrates C and C++ with languages including Perl, Python, Tcl, Ruby, PHP, Java, C#, D, Go, Lua, From 18c9eca1827e009c66e5651145aff17745b76140 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Tue, 27 May 2014 19:58:36 +0100 Subject: [PATCH 1009/1048] Add Javascript to announcements --- ANNOUNCE | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/ANNOUNCE b/ANNOUNCE index 7c521e77b..2ec56266b 100644 --- a/ANNOUNCE +++ b/ANNOUNCE @@ -10,11 +10,11 @@ What is SWIG? SWIG is a software development tool that reads C/C++ header files and generates the wrapper code needed to make C and C++ code accessible from other programming languages including Perl, Python, Tcl, Ruby, -PHP, C#, Go, Java, Lua, Scheme (Guile, MzScheme, CHICKEN), D, Ocaml, -Pike, Modula-3, Octave, R, Common Lisp (CLISP, Allegro CL, CFFI, UFFI). -SWIG can also export its parse tree in the form of XML and Lisp -s-expressions. Major applications of SWIG include generation of -scripting language extension modules, rapid prototyping, testing, +PHP, C#, Go, Java, Javascript, Lua, Scheme (Guile, MzScheme, CHICKEN), +D, Ocaml, Pike, Modula-3, Octave, R, Common Lisp (CLISP, Allegro CL, +CFFI, UFFI). SWIG can also export its parse tree in the form of XML +and Lisp s-expressions. Major applications of SWIG include generation +of scripting language extension modules, rapid prototyping, testing, and user interface development for large C/C++ systems. Availability From 686d98672d97962e6ebeaf0e445ba069a8b999cd Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 28 May 2014 04:27:23 +0200 Subject: [PATCH 1010/1048] Javascript: fixed a missing link in documentation. --- Doc/Manual/Javascript.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Doc/Manual/Javascript.html b/Doc/Manual/Javascript.html index bfe91aa09..ef29ac63e 100644 --- a/Doc/Manual/Javascript.html +++ b/Doc/Manual/Javascript.html @@ -332,7 +332,7 @@ A simple example would have the following structure:

      The configuration file essentially conforms to node.js syntax. -It has some extras to configure node-webkit. See the Manifest specification for more details. +It has some extras to configure node-webkit. See the Manifest specification for more details.

      From 703862dc3a1ed01ad705e8884ef8963f8030cacb Mon Sep 17 00:00:00 2001 From: Olly Betts Date: Wed, 28 May 2014 23:04:06 +1200 Subject: [PATCH 1011/1048] Fix unused variable warning in Lua bindings --- Lib/lua/luarun.swg | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index 6f2068e7a..0728a0528 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -1514,7 +1514,6 @@ 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 new_metatable_index; const int SWIGUNUSED begin = lua_gettop(L); int i; /* if name already there (class is already registered) then do nothing */ @@ -1541,14 +1540,16 @@ 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 */ - new_metatable_index = lua_absindex(L,-1); - for(i=0;clss->bases[i];i++) { - int base_metatable; - SWIG_Lua_get_class_metatable(L,clss->bases[i]->fqname); - base_metatable = lua_absindex(L,-1); - SWIG_Lua_merge_tables_by_index(L,new_metatable_index, base_metatable); - lua_pop(L,1); + int new_metatable_index = lua_absindex(L,-1); + for(i=0;clss->bases[i];i++) + { + int base_metatable; + SWIG_Lua_get_class_metatable(L,clss->bases[i]->fqname); + base_metatable = lua_absindex(L,-1); + SWIG_Lua_merge_tables_by_index(L,new_metatable_index, base_metatable); + lua_pop(L,1); + } } /* And now we will overwrite all incorrectly set data */ #endif From 68347cb723afde8b7bbbbb4d0d8be0f5abae359d Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Wed, 28 May 2014 18:51:46 +0100 Subject: [PATCH 1012/1048] Bump version to 3.0.2 --- ANNOUNCE | 8 ++-- CHANGES | 84 ++++++++++++++++++++++++++++++++++++++++ CHANGES.current | 82 +-------------------------------------- Doc/Manual/Sections.html | 2 +- README | 2 +- configure.ac | 2 +- 6 files changed, 92 insertions(+), 88 deletions(-) diff --git a/ANNOUNCE b/ANNOUNCE index 2ec56266b..fc1160007 100644 --- a/ANNOUNCE +++ b/ANNOUNCE @@ -1,8 +1,8 @@ -*** ANNOUNCE: SWIG 3.0.1 (27 May 2014) *** +*** ANNOUNCE: SWIG 3.0.2 (in progress) *** http://www.swig.org -We're pleased to announce SWIG-3.0.1, the latest SWIG release. +We're pleased to announce SWIG-3.0.2, 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-3.0.1.tar.gz + http://prdownloads.sourceforge.net/swig/swig-3.0.2.tar.gz A Windows version is also available at - http://prdownloads.sourceforge.net/swig/swigwin-3.0.1.zip + http://prdownloads.sourceforge.net/swig/swigwin-3.0.2.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 821d76b2c..1cfedc31e 100644 --- a/CHANGES +++ b/CHANGES @@ -3,6 +3,90 @@ SWIG (Simplified Wrapper and Interface Generator) See the CHANGES.current file for changes in the current version. See the RELEASENOTES file for a summary of changes in each release. +Version 3.0.1 (27 May 2014) +=========================== + +2014-05-25: hfalcic + [Python] Python 3 byte string output: use errors="surrogateescape" + if available on the version of Python that's in use. This allows + obtaining the original byte string (and potentially trying a fallback + encoding) if the bytes can't be decoded as UTF-8. + + Previously, a UnicodeDecodeError would be raised with no way to treat + the data as bytes or try another codec. + +2014-05-18: vkalinin + Bug #175 - Restore %extend to work for unnamed nested structures by using a C + symbol comprising the outer structure name and unnamed variable instance name. + +2014-05-15: kwwette + Add #166 - 'make check' now works out of source. This required te examples to build + out of source. The main languages have been tested - C#, Go, Guile, Java, Javascript, + Lua, Octave, Perl, PHP, Python, Ruby and Tcl. + +2014-05-01: Oliver Buchtala + Javascript support added, see Javascript chapter in the documentation. + +2014-05-01: olly + [PHP] The generated __isset() method now returns true for read-only properties. + +2014-04-24: kwwette + [Go] Fix go ./configure parsing of gccgo --version, and + goruntime.swg typo in __GNUC_PATCHLEVEL__ (SF Bug #1298) + +2014-04-24: kwwette + Fix {python|perl5|ruby|tcl}/java examples + + In Lib/gcj/cni.i, for compatibility with newer gcj versions: + + - remove JvAllocObject() which gcj no longer defines, from gcj Changelog: + 2004-04-16 Bryce McKinlay + * gcj/cni.h (JvAllocObject): Remove these obsolete, + undocumented CNI calls. + + - change JvCreateJavaVM() argument from void* to JvVMInitArgs*, from gcj Changelog: + 2005-02-23 Thomas Fitzsimmons + PR libgcj/16923 + ... + (JvCreateJavaVM): Declare vm_args as JvVMInitArgs* rather than void*. + + *** POTENTIAL INCOMPATIBILITY *** + +2014-04-08: wsfulton + SF Bug #1366 - Remove duplicate declarations of strtoimax and strtoumax in inttypes.i + +2014-04-08: wsfulton + [Java C#] Enums which have been ignored via %ignore and are subsequently + used are handled slightly differently. Type wrapper classes are now generated + which are effectively a wrapper of an empty enum. Previously in Java uncompilable + code was generated and in C# an int was used. + +2014-04-04: wsfulton + Fix regression in 3.0.0 where legal code following an operator<< definition might + give a syntax error. SF Bug #1365. + +2014-04-03: olly + [PHP] Fix wrapping director constructors with default parameters + with a ZTS-enabled build of PHP. + +2014-04-02: olly + [PHP] Pass the ZTS context we already have to avoid needing to + call TSRMLS_FETCH, which is relatively expensive. + +2014-04-02: olly + [PHP] Pass ZTS context through to t_output_helper() so it works + with a ZTS-enabled build of PHP. Reported by Pierre Labastie in + github PR#155. + +2014-03-28: wsfulton + [Java C# D Go] Fixes for C enums used in an API and the definition of the enum + has not been parsed. For D, this fixes a segfault in SWIG. The other languages + now produce code that compiles, although the definition of the enum is needed + in order to use the enum properly from the target language. + +2014-03-23: v-for-vandal + [Lua] Fix for usage of snprintf in Lua runtime which Visual Studio does not have. + Version 3.0.0 (16 Mar 2014) =========================== diff --git a/CHANGES.current b/CHANGES.current index 4b95adfa8..8d715e730 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -2,86 +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 3.0.1 (27 May 2014) +Version 3.0.2 (in progress) =========================== -2014-05-25: hfalcic - [Python] Python 3 byte string output: use errors="surrogateescape" - if available on the version of Python that's in use. This allows - obtaining the original byte string (and potentially trying a fallback - encoding) if the bytes can't be decoded as UTF-8. - - Previously, a UnicodeDecodeError would be raised with no way to treat - the data as bytes or try another codec. - -2014-05-18: vkalinin - Bug #175 - Restore %extend to work for unnamed nested structures by using a C - symbol comprising the outer structure name and unnamed variable instance name. - -2014-05-15: kwwette - Add #166 - 'make check' now works out of source. This required te examples to build - out of source. The main languages have been tested - C#, Go, Guile, Java, Javascript, - Lua, Octave, Perl, PHP, Python, Ruby and Tcl. - -2014-05-01: Oliver Buchtala - Javascript support added, see Javascript chapter in the documentation. - -2014-05-01: olly - [PHP] The generated __isset() method now returns true for read-only properties. - -2014-04-24: kwwette - [Go] Fix go ./configure parsing of gccgo --version, and - goruntime.swg typo in __GNUC_PATCHLEVEL__ (SF Bug #1298) - -2014-04-24: kwwette - Fix {python|perl5|ruby|tcl}/java examples - - In Lib/gcj/cni.i, for compatibility with newer gcj versions: - - - remove JvAllocObject() which gcj no longer defines, from gcj Changelog: - 2004-04-16 Bryce McKinlay - * gcj/cni.h (JvAllocObject): Remove these obsolete, - undocumented CNI calls. - - - change JvCreateJavaVM() argument from void* to JvVMInitArgs*, from gcj Changelog: - 2005-02-23 Thomas Fitzsimmons - PR libgcj/16923 - ... - (JvCreateJavaVM): Declare vm_args as JvVMInitArgs* rather than void*. - - *** POTENTIAL INCOMPATIBILITY *** - -2014-04-08: wsfulton - SF Bug #1366 - Remove duplicate declarations of strtoimax and strtoumax in inttypes.i - -2014-04-08: wsfulton - [Java C#] Enums which have been ignored via %ignore and are subsequently - used are handled slightly differently. Type wrapper classes are now generated - which are effectively a wrapper of an empty enum. Previously in Java uncompilable - code was generated and in C# an int was used. - -2014-04-04: wsfulton - Fix regression in 3.0.0 where legal code following an operator<< definition might - give a syntax error. SF Bug #1365. - -2014-04-03: olly - [PHP] Fix wrapping director constructors with default parameters - with a ZTS-enabled build of PHP. - -2014-04-02: olly - [PHP] Pass the ZTS context we already have to avoid needing to - call TSRMLS_FETCH, which is relatively expensive. - -2014-04-02: olly - [PHP] Pass ZTS context through to t_output_helper() so it works - with a ZTS-enabled build of PHP. Reported by Pierre Labastie in - github PR#155. - -2014-03-28: wsfulton - [Java C# D Go] Fixes for C enums used in an API and the definition of the enum - has not been parsed. For D, this fixes a segfault in SWIG. The other languages - now produce code that compiles, although the definition of the enum is needed - in order to use the enum properly from the target language. - -2014-03-23: v-for-vandal - [Lua] Fix for usage of snprintf in Lua runtime which Visual Studio does not have. diff --git a/Doc/Manual/Sections.html b/Doc/Manual/Sections.html index 0a61f074e..33d76c239 100644 --- a/Doc/Manual/Sections.html +++ b/Doc/Manual/Sections.html @@ -6,7 +6,7 @@

      SWIG-3.0 Documentation

      -Last update : SWIG-3.0.1 (27 May 2014) +Last update : SWIG-3.0.2 (in progress)

      Sections

      diff --git a/README b/README index e30441be7..e4010bd80 100644 --- a/README +++ b/README @@ -1,6 +1,6 @@ SWIG (Simplified Wrapper and Interface Generator) -Version: 3.0.1 (27 May 2014) +Version: 3.0.2 (27 May 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 2ff5dc8db..8af45b69f 100644 --- a/configure.ac +++ b/configure.ac @@ -2,7 +2,7 @@ dnl Process this file with autoconf to produce a configure script. dnl The macros which aren't shipped with the autotools are stored in the dnl Tools/config directory in .m4 files. -AC_INIT([swig],[3.0.1],[http://www.swig.org]) +AC_INIT([swig],[3.0.2],[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 2b4c49d017f526f6622cd54547ab9fab31941176 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Fri, 16 May 2014 13:00:14 +0400 Subject: [PATCH 1013/1048] Add default __eq implementation * Renamed SWIG_Lua_equal to SWIG_Lua_class_equal * If class has no __eq implemented, then default __eq is provided. Default __eq compares actual pointers stored inside Lua userdata --- Examples/test-suite/lua/cpp_basic_runme.lua | 11 +++++ Lib/lua/luarun.swg | 46 +++++++++++++-------- Lib/lua/luaruntime.swg | 2 +- 3 files changed, 41 insertions(+), 18 deletions(-) diff --git a/Examples/test-suite/lua/cpp_basic_runme.lua b/Examples/test-suite/lua/cpp_basic_runme.lua index c7e0325c5..5a0e1c699 100644 --- a/Examples/test-suite/lua/cpp_basic_runme.lua +++ b/Examples/test-suite/lua/cpp_basic_runme.lua @@ -86,3 +86,14 @@ f4_name = tostring(f4) assert( f2_name == "Foo" ) assert( f3_name == "Foo" ) assert( f4_name == "FooSubSub" ) + +-- Test __eq implementation supplied by default + +-- eq_f1 and eq_f2 must be different userdata with same Foo* pointer. If eq_f1 and eq_f2 are the same userdata (e.g.) +-- > eq_f1 = smth +-- > eq_f2 = eq_f1 +-- then default Lua equality comparison kicks in and considers them equal. Access to global_fptr is actually a +-- function call (internally) and it returns new userdata each time. +eq_f1 = cb.Bar.global_fptr +eq_f2 = cb.Bar.global_fptr +assert( eq_f1 == eq_f2 ) diff --git a/Lib/lua/luarun.swg b/Lib/lua/luarun.swg index 0728a0528..756c38d01 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -1037,6 +1037,23 @@ SWIGINTERN int SWIG_Lua_class_disown(lua_State *L) return 0; } +/* 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_class_equal(lua_State *L) +{ + int result; + swig_lua_userdata *usr1,*usr2; + if (!lua_isuserdata(L,1) || !lua_isuserdata(L,2)) /* just in case */ + return 0; /* nil reply */ + usr1=(swig_lua_userdata*)lua_touserdata(L,1); /* get data */ + usr2=(swig_lua_userdata*)lua_touserdata(L,2); /* get data */ + /*result=(usr1->ptr==usr2->ptr && usr1->type==usr2->type); only works if type is the same*/ + result=(usr1->ptr==usr2->ptr); + lua_pushboolean(L,result); + return 1; +} + /* populate table at the top of the stack with metamethods that ought to be inherited */ SWIGINTERN void SWIG_Lua_populate_inheritable_metamethods(lua_State *L) { @@ -1471,6 +1488,18 @@ SWIGINTERN void SWIG_Lua_add_class_user_metamethods(lua_State *L, swig_lua_class lua_pop(L,1); /* remove copy of the key */ } + /* Special handling for __eq method */ + lua_pushstring(L, "__eq"); + lua_pushvalue(L,-1); + lua_rawget(L,metatable_index); + const int eq_undefined = lua_isnil(L,-1); + lua_pop(L,1); + if( eq_undefined ) { + lua_pushcfunction(L, SWIG_Lua_class_equal); + lua_rawset(L, metatable_index); + } else { + lua_pop(L,1); /* remove copy of the key */ + } /* Warning: __index and __newindex are SWIG-defined. For user-defined operator[] * a __getitem/__setitem method should be defined */ @@ -1788,23 +1817,6 @@ SWIGRUNTIME int SWIG_Lua_type(lua_State *L) return 1; } -/* 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) -{ - int result; - swig_lua_userdata *usr1,*usr2; - if (!lua_isuserdata(L,1) || !lua_isuserdata(L,2)) /* just in case */ - return 0; /* nil reply */ - usr1=(swig_lua_userdata*)lua_touserdata(L,1); /* get data */ - usr2=(swig_lua_userdata*)lua_touserdata(L,2); /* get data */ - /*result=(usr1->ptr==usr2->ptr && usr1->type==usr2->type); only works if type is the same*/ - result=(usr1->ptr==usr2->ptr); - lua_pushboolean(L,result); - return 1; -} - /* ----------------------------------------------------------------------------- * global variable support code: class/struct typemap functions * ----------------------------------------------------------------------------- */ diff --git a/Lib/lua/luaruntime.swg b/Lib/lua/luaruntime.swg index 89908044b..8df46e8cb 100644 --- a/Lib/lua/luaruntime.swg +++ b/Lib/lua/luaruntime.swg @@ -40,7 +40,7 @@ SWIGEXPORT int SWIG_init(lua_State* L) /* default Lua action */ #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); + SWIG_Lua_add_function(L,"swig_equals",SWIG_Lua_class_equal); #endif #if (SWIG_LUA_TARGET != SWIG_LUA_FLAVOR_ELUAC) From 4457d96e54b7dea20b4c7b43e5182fa564d5c0c9 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Fri, 23 May 2014 15:13:41 +0400 Subject: [PATCH 1014/1048] Moving variable declaration to the beginning of the block --- 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 756c38d01..8803c66f6 100644 --- a/Lib/lua/luarun.swg +++ b/Lib/lua/luarun.swg @@ -1456,6 +1456,7 @@ SWIGINTERN void SWIG_Lua_add_class_user_metamethods(lua_State *L, swig_lua_class int metatable_index; int metamethods_info_index; int tostring_undefined; + int eq_undefined = 0; SWIG_Lua_get_class_metatable(L, clss->fqname); metatable_index = lua_gettop(L); @@ -1492,7 +1493,7 @@ SWIGINTERN void SWIG_Lua_add_class_user_metamethods(lua_State *L, swig_lua_class lua_pushstring(L, "__eq"); lua_pushvalue(L,-1); lua_rawget(L,metatable_index); - const int eq_undefined = lua_isnil(L,-1); + eq_undefined = lua_isnil(L,-1); lua_pop(L,1); if( eq_undefined ) { lua_pushcfunction(L, SWIG_Lua_class_equal); From 46d7645c9ae1ecafd5447cb1f287c5f8d1dc5b4f Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Mon, 26 May 2014 23:27:29 +0400 Subject: [PATCH 1015/1048] More tests for equality operator overloading --- Examples/test-suite/common.mk | 1 + Examples/test-suite/equality.i | 67 ++++++++++++++++++++++ Examples/test-suite/lua/equality_runme.lua | 47 +++++++++++++++ 3 files changed, 115 insertions(+) create mode 100644 Examples/test-suite/equality.i create mode 100644 Examples/test-suite/lua/equality_runme.lua diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index bc1ca5cb8..485453b5a 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -210,6 +210,7 @@ CPP_TEST_CASES += \ enum_template \ enum_thorough \ enum_var \ + equality \ evil_diamond \ evil_diamond_ns \ evil_diamond_prop \ diff --git a/Examples/test-suite/equality.i b/Examples/test-suite/equality.i new file mode 100644 index 000000000..a1b70c299 --- /dev/null +++ b/Examples/test-suite/equality.i @@ -0,0 +1,67 @@ +/* File : equality.i */ +/* + Specific test for operator== overload. Partially overlaps with + operator_overload.i +*/ + +%module equality + +%inline %{ + +/* Point has no equality operator */ +typedef struct Point +{ + double x; + double y; +} Point; + +static const Point s_zeroPoint = { 0.0, 0.0 }; +/* stack version */ +Point MakePoint(double x, double y) + { Point new_point = {x, y}; return new_point; } + +const Point* GetZeroPointPtr() { return &s_zeroPoint; } +Point GetZeroPointCopy() { return s_zeroPoint; } + +/* EqualOpDefined has correct equality operator */ +class EqualOpDefined { +public: + EqualOpDefined(): + x(5) {} + EqualOpDefined(int val): + x(val) {} + + int x; +}; + +/* EqualOpWrong has logically incorrect equality operator */ +class EqualOpWrong { +public: + inline static const EqualOpWrong* GetStaticObject(); +}; + +static const EqualOpWrong s_wrongEqOp; + +const EqualOpWrong* EqualOpWrong::GetStaticObject() + { return &s_wrongEqOp; } + + +inline bool operator==( const EqualOpDefined& first, const EqualOpDefined& second ) + { return first.x == second.x; } + +inline bool operator==( const EqualOpWrong& first, const EqualOpWrong& second ) + { return false; } + +%} + +/* + in order to wrapper this correctly + we need to extend the class + to make the friends & non members part of the class +*/ +%extend EqualOpDefined { + bool operator==(const EqualOpDefined& b){return (*$self) == b;} +} +%extend EqualOpWrong { + bool operator==(const EqualOpWrong& b){return (*$self) == b;} +} diff --git a/Examples/test-suite/lua/equality_runme.lua b/Examples/test-suite/lua/equality_runme.lua new file mode 100644 index 000000000..cadbede0a --- /dev/null +++ b/Examples/test-suite/lua/equality_runme.lua @@ -0,0 +1,47 @@ +require("import") -- the import fn +import("equality") -- import code +eq=equality -- 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}) + +-- === No equality operator === + +-- logically same data without equality operator are not equal +p1 = eq.MakePoint(10,9); +p2 = eq.MakePoint(10,9); + +assert( p1 ~= p2 ); + +-- different wrappers for same Point* are equal +p3 = eq.GetZeroPointPtr() +p4 = eq.GetZeroPointPtr() + +assert( p3 == p4 ) + + +-- === Logically correct equality operator === + +ed1 = eq.EqualOpDefined(10) +ed2 = eq.EqualOpDefined(10) +ed3 = eq.EqualOpDefined(15) + +assert( ed1 == ed2 ) +assert( ed1 ~= ed3 ) + + +-- === Logically incorrect equality operator === + +ew1 = eq.EqualOpWrong() +ew2 = eq.EqualOpWrong() + +assert( ew1 ~= ew2 ); + +ew3 = eq.EqualOpWrong.GetStaticObject() +ew4 = eq.EqualOpWrong.GetStaticObject() + +-- Even though these are pointers to same object, operator== overload should +-- state that they are not equal +assert( ew3 ~= ew4 ) From 665c4f581be7aef1e37c40dee3fde00b2d1cdcfd Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Wed, 28 May 2014 22:15:50 +0400 Subject: [PATCH 1016/1048] %extend symbols for nested structs get into a wrong C symbol table --- Examples/test-suite/nested_extend_c.i | 7 +++++++ Source/Modules/nested.cxx | 14 ++++++++------ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/Examples/test-suite/nested_extend_c.i b/Examples/test-suite/nested_extend_c.i index 0e1495f86..fb3c053c4 100644 --- a/Examples/test-suite/nested_extend_c.i +++ b/Examples/test-suite/nested_extend_c.i @@ -10,6 +10,7 @@ char hi_extend() { return $self->c; } + static const long swig_size = sizeof(hiA); } %extend lowA { lowA() { @@ -21,6 +22,7 @@ int low_extend() { return $self->num; } + static const long swig_size = sizeof(lowA); } %extend hiB { @@ -32,6 +34,7 @@ char hi_extend() { return $self->c; } + static const long swig_size = sizeof(hiB); } %extend lowB { lowB() { @@ -43,6 +46,7 @@ int low_extend() { return $self->num; } + static const long swig_size = sizeof(lowB); } %extend FOO_bar { @@ -50,6 +54,9 @@ $self->d = 1; } }; +%extend NestedA { + static const long swig_size = sizeof(NestedA); +} #endif diff --git a/Source/Modules/nested.cxx b/Source/Modules/nested.cxx index 9ec52ead1..c4ab6a8ea 100644 --- a/Source/Modules/nested.cxx +++ b/Source/Modules/nested.cxx @@ -362,7 +362,15 @@ void Swig_nested_name_unnamed_c_structs(Node *n) { Delete(bases); } Setattr(classhash, name, c); + + // Merge the extension into the symbol table + if (Node *am = Getattr(Swig_extend_hash(), name)) { + Swig_extend_merge(c, am); + Swig_extend_append_previous(c, am); + Delattr(Swig_extend_hash(), name); + } Swig_symbol_popscope(); + // process declarations following this type (assign correct new type) SwigType *ty = Copy(name); Node *decl = nextSibling(c); @@ -376,12 +384,6 @@ void Swig_nested_name_unnamed_c_structs(Node *n) { decl = nextSibling(decl); } Delete(ty); - if (Node *am = Getattr(Swig_extend_hash(), name)) { - // Merge the extension into the symbol table - Swig_extend_merge(c, am); - Swig_extend_append_previous(c, am); - Delattr(Swig_extend_hash(), name); - } Swig_symbol_setscope(Swig_symbol_global_scope()); add_symbols_c(c); From 78719759d5572b6c80c6a7061e71f78bee49a5ea Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Wed, 28 May 2014 23:44:55 +0100 Subject: [PATCH 1017/1048] Test-suite makefile fixes for Windows Remove $(realpath ) which is no good for Windows executables running under Cygwin's make --- Examples/Makefile.in | 6 +++--- .../test-suite/java/preproc_line_file_runme.java | 16 ++++++++++++---- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index caf848596..1f3b07205 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -576,7 +576,7 @@ JAVAC = @JAVAC@ -d . # ---------------------------------------------------------------- java: $(SRCDIR_SRCS) - $(SWIG) -java $(SWIGOPT) -o $(ISRCS) $(realpath $(INTERFACEPATH)) + $(SWIG) -java $(SWIGOPT) -o $(ISRCS) $(INTERFACEPATH) $(CC) -c $(CCSHARED) $(CPPFLAGS) $(CFLAGS) $(JAVACFLAGS) $(SRCDIR_SRCS) $(ISRCS) $(INCLUDES) $(JAVA_INCLUDE) $(JAVALDSHARED) $(CFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JAVA_DLNK) $(LIBS) -o $(JAVA_LIBPREFIX)$(TARGET)$(JAVASO) @@ -585,7 +585,7 @@ java: $(SRCDIR_SRCS) # ---------------------------------------------------------------- java_cpp: $(SRCDIR_SRCS) - $(SWIG) -java -c++ $(SWIGOPT) -o $(ICXXSRCS) $(realpath $(INTERFACEPATH)) + $(SWIG) -java -c++ $(SWIGOPT) -o $(ICXXSRCS) $(INTERFACEPATH) $(CXX) -c $(CCSHARED) $(CPPFLAGS) $(CXXFLAGS) $(JAVACFLAGS) $(SRCDIR_SRCS) $(SRCDIR_CXXSRCS) $(ICXXSRCS) $(INCLUDES) $(JAVA_INCLUDE) $(JAVACXXSHARED) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(IOBJS) $(JAVA_DLNK) $(LIBS) $(CPP_DLLIBS) -o $(JAVA_LIBPREFIX)$(TARGET)$(JAVASO) @@ -1373,7 +1373,7 @@ csharp_cpp: $(SRCDIR_SRCS) # ---------------------------------------------------------------- ifneq (,$(SRCDIR)) -SRCDIR_CSHARPSRCS = $(wildcard $(addprefix $(SRCDIR),$(CSHARPSRCS))) +SRCDIR_CSHARPSRCS = $(addprefix $(SRCDIR),$(CSHARPSRCS)) else SRCDIR_CSHARPSRCS = endif diff --git a/Examples/test-suite/java/preproc_line_file_runme.java b/Examples/test-suite/java/preproc_line_file_runme.java index 123753fd9..7726b613b 100644 --- a/Examples/test-suite/java/preproc_line_file_runme.java +++ b/Examples/test-suite/java/preproc_line_file_runme.java @@ -13,13 +13,21 @@ public class preproc_line_file_runme { 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"; +// For swig-3.0.1 and earlier +// String FILENAME_WINDOWS = "Examples\\test-suite\\preproc_line_file.i"; +// String FILENAME_UNIX = "Examples/test-suite/preproc_line_file.i"; + + String FILENAME_WINDOWS2 = "Examples\\test-suite\\java\\..\\preproc_line_file.i"; + String FILENAME_UNIX2 = "Examples/test-suite/java/../preproc_line_file.i"; + + String FILENAME_WINDOWS3 = "..\\.\\..\\preproc_line_file.i"; + String FILENAME_UNIX3 = ".././../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); + if (!file.endsWith(FILENAME_UNIX2 + suffix) && !file.endsWith(FILENAME_WINDOWS2 + suffix) && + !file.endsWith(FILENAME_UNIX3 + suffix) && !file.endsWith(FILENAME_WINDOWS3 + suffix)) + throw new RuntimeException("file \"" + file + "\" doesn't end with " + FILENAME_UNIX2 + suffix + " or " + FILENAME_UNIX3 + suffix); } public static void main(String argv[]) throws Throwable From cc1ff55be458fba978cfb7f31f6966630f6b380e Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Wed, 28 May 2014 20:46:44 +0200 Subject: [PATCH 1018/1048] CCache: always generate docs in source directory --- .gitignore | 1 + CCache/Makefile.in | 18 +++++++++--------- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/.gitignore b/.gitignore index c7961efd7..e6c73c463 100644 --- a/.gitignore +++ b/.gitignore @@ -85,6 +85,7 @@ swig.spec .dirstamp CCache/ccache-swig CCache/ccache-swig.1 +CCache/web/ccache-man.html Lib/swigwarn.swg Source/CParse/parser.c Source/CParse/parser.h diff --git a/CCache/Makefile.in b/CCache/Makefile.in index 6703e2ac0..6cded08d4 100644 --- a/CCache/Makefile.in +++ b/CCache/Makefile.in @@ -32,27 +32,27 @@ Makefile: $(srcdir)/Makefile.in ./config.status $(SHELL) ./config.status # Note that HTML documentation is actually generated and used from the main SWIG documentation Makefile -docs: $(PACKAGE_NAME).1 web/ccache-man.html +docs: $(srcdir)/$(PACKAGE_NAME).1 $(srcdir)/web/ccache-man.html $(PACKAGE_NAME)$(EXEEXT): $(OBJS) $(HEADERS) $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(OBJS) $(LIBS) -$(PACKAGE_NAME).1: ccache.yo - -yodl2man -o $(PACKAGE_NAME).1 $(srcdir)/ccache.yo +$(srcdir)/$(PACKAGE_NAME).1: $(srcdir)/ccache.yo + -yodl2man -o $(srcdir)/$(PACKAGE_NAME).1 $(srcdir)/ccache.yo -web/ccache-man.html: ccache.yo - yodl2html -o web/ccache-man.html ccache.yo +$(srcdir)/web/ccache-man.html: $(srcdir)/ccache.yo + yodl2html -o $(srcdir)/web/ccache-man.html $(srcdir)/ccache.yo -install: $(PACKAGE_NAME)$(EXEEXT) $(PACKAGE_NAME).1 +install: $(PACKAGE_NAME)$(EXEEXT) $(srcdir)/$(PACKAGE_NAME).1 @echo "Installing $(PACKAGE_NAME)" @echo "Installing $(DESTDIR)${bindir}/`echo $(PACKAGE_NAME) | sed '$(transform)'`$(EXEEXT)" ${INSTALLCMD} -d $(DESTDIR)${bindir} ${INSTALLCMD} -m 755 $(PACKAGE_NAME)$(EXEEXT) $(DESTDIR)${bindir}/`echo $(PACKAGE_NAME) | sed '$(transform)'`$(EXEEXT) @echo "Installing $(DESTDIR)${mandir}/man1/`echo $(PACKAGE_NAME) | sed '$(transform)'`.1" ${INSTALLCMD} -d $(DESTDIR)${mandir}/man1 - ${INSTALLCMD} -m 644 $(PACKAGE_NAME).1 $(DESTDIR)${mandir}/man1/`echo $(PACKAGE_NAME) | sed '$(transform)'`.1 + ${INSTALLCMD} -m 644 $(srcdir)/$(PACKAGE_NAME).1 $(DESTDIR)${mandir}/man1/`echo $(PACKAGE_NAME) | sed '$(transform)'`.1 -uninstall: $(PACKAGE_NAME)$(EXEEXT) $(PACKAGE_NAME).1 +uninstall: $(PACKAGE_NAME)$(EXEEXT) $(srcdir)/$(PACKAGE_NAME).1 rm -f $(DESTDIR)${bindir}/`echo $(PACKAGE_NAME) | sed '$(transform)'`$(EXEEXT) rm -f $(DESTDIR)${mandir}/man1/`echo $(PACKAGE_NAME) | sed '$(transform)'`.1 @@ -69,7 +69,7 @@ distclean: clean /bin/rm -rf autom4te.cache maintainer-clean: distclean - /bin/rm -f $(PACKAGE_NAME).1 web/ccache-man.html + /bin/rm -f $(srcdir)/$(PACKAGE_NAME).1 $(srcdir)/web/ccache-man.html # FIXME: To fix this, test.sh needs to be able to take ccache from the From 46ce4d3ba9a1ae50706e828ab17c8bc6c2e50fe0 Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Wed, 28 May 2014 21:19:06 +0200 Subject: [PATCH 1019/1048] Distclean Tools/javascript --- Makefile.in | 6 +++++- Tools/javascript/Makefile.in | 3 +++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Makefile.in b/Makefile.in index a040d41a1..2b9cf3b32 100644 --- a/Makefile.in +++ b/Makefile.in @@ -403,7 +403,7 @@ clean-ccache: 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 +distclean-helper: distclean-test-suite distclean-examples distclean-tools distclean-dead distclean: distclean-source distclean-ccache distclean-helper @@ -429,6 +429,10 @@ distclean-examples: distclean-ccache: @test -z "$(ENABLE_CCACHE)" || (cd $(CCACHE) && $(MAKE) $(FLAGS) distclean) +distclean-tools: + @echo distcleaning Tools + @cd Tools/javascript && $(MAKE) $(FLAGS) distclean + distclean-dead: rm -f $(DISTCLEAN-DEAD) rm -rf autom4te.cache diff --git a/Tools/javascript/Makefile.in b/Tools/javascript/Makefile.in index 960c661b2..f65be2826 100644 --- a/Tools/javascript/Makefile.in +++ b/Tools/javascript/Makefile.in @@ -64,3 +64,6 @@ javascript: $(JS_INTERPRETER_OBJS) clean: rm -f *.o rm -f javascript + +distclean: clean + rm -f Makefile From 32212d5cc08d312f15e5f6d102610752b86e3f3c Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Wed, 28 May 2014 22:40:36 +0200 Subject: [PATCH 1020/1048] Fully clean Go test-suite --- Examples/test-suite/go/Makefile.in | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Examples/test-suite/go/Makefile.in b/Examples/test-suite/go/Makefile.in index 204cf8a12..5d8343be1 100644 --- a/Examples/test-suite/go/Makefile.in +++ b/Examples/test-suite/go/Makefile.in @@ -100,11 +100,12 @@ run_multi_testcase = \ @rm -f $*.go $*_gc.c $*_wrap.* $*_runme clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile go_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" go_clean rm -f mod_a.go mod_b.go imports_a.go imports_b.go rm -f clientdata_prop_a.go clientdata_prop_b.go rm -f multi_import_a.go multi_import_b.go rm -f packageoption_a.go packageoption_b.go packageoption_c.go + rm -f import_stl_a.go import_stl_b.go cvsignore: @echo '*_gc.c *_wrap.* *.so *.dll *.exp *.lib' From 74e17fdbf662d04f21b484616174ca7abdf1d30f Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Wed, 28 May 2014 23:39:10 +0200 Subject: [PATCH 1021/1048] Fix Javascript examples so that "make clean" works properly with node - Need to copy example.cxx to build directory so that build products end up in the right place; use a gyp command expansion to do so --- .gitignore | 1 + Examples/Makefile.in | 2 +- Examples/javascript/class/binding.gyp.in | 2 +- Examples/javascript/enum/binding.gyp.in | 2 +- Examples/javascript/exception/binding.gyp.in | 2 +- Examples/javascript/pointer/binding.gyp.in | 2 +- Examples/javascript/reference/binding.gyp.in | 2 +- Examples/javascript/simple/binding.gyp.in | 2 +- Examples/javascript/variables/binding.gyp.in | 2 +- 9 files changed, 9 insertions(+), 8 deletions(-) diff --git a/.gitignore b/.gitignore index e6c73c463..bce0812b7 100644 --- a/.gitignore +++ b/.gitignore @@ -124,6 +124,7 @@ Examples/test-suite/tcl/*/ Examples/test-suite/uffi/*/ *_wrap.c *_wrap.cxx +*-gypcopy.cxx # C# generated files *_runme.exe.mdb diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 1f3b07205..123a634d7 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -730,7 +730,7 @@ javascript_clean: rm -f *_wrap* $(RUNME) rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *@JSSO@ *.$(SO) - rm -f binding.gyp + rm -f binding.gyp example-gypcopy.cxx cd $(ROOT_DIR)/Tools/javascript && $(MAKE) -s clean ################################################################## diff --git a/Examples/javascript/class/binding.gyp.in b/Examples/javascript/class/binding.gyp.in index c56a650e9..cb2b45e8f 100644 --- a/Examples/javascript/class/binding.gyp.in +++ b/Examples/javascript/class/binding.gyp.in @@ -2,7 +2,7 @@ "targets": [ { "target_name": "example", - "sources": [ "$srcdir/example.cxx", "example_wrap.cxx" ], + "sources": [ " Date: Wed, 28 May 2014 23:55:08 +0200 Subject: [PATCH 1022/1048] Fully clean Javascript test-suite with jsc and v8 --- Examples/test-suite/javascript/Makefile.in | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index a54fcd7e7..b6e946de2 100644 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -107,7 +107,15 @@ endif %.clean: - rm -rf $* - rm -f $*_wrap.* - rm -f $*.so - rm -f $*.o + @rm -rf $* + @rm -f $*_wrap.* $*.so $*.o + +clean: + for ext in _wrap.cxx _wrap.o .so; do \ + rm -f clientdata_prop_a$${ext} clientdata_prop_b$${ext}; \ + rm -f imports_a$${ext} imports_b$${ext}; \ + rm -f import_stl_a$${ext} import_stl_b$${ext}; \ + rm -f mod_a$${ext} mod_b$${ext}; \ + rm -f multi_import_a$${ext} multi_import_b$${ext}; \ + rm -f packageoption_a$${ext} packageoption_b$${ext} packageoption_c$${ext}; \ + done From 7f48b2774b32d40c898d2a78d2fe4085aeb4dce9 Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Wed, 28 May 2014 23:55:19 +0200 Subject: [PATCH 1023/1048] Fully clean PHP test-suite --- Examples/test-suite/php/Makefile.in | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Examples/test-suite/php/Makefile.in b/Examples/test-suite/php/Makefile.in index 5f56760ea..00ccac325 100644 --- a/Examples/test-suite/php/Makefile.in +++ b/Examples/test-suite/php/Makefile.in @@ -65,7 +65,13 @@ run_testcase = \ # Clean: remove the generated .php file %.clean: - @rm -f $*.php; + @rm -f $*.php php_$*.h clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile php_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" php_clean + rm -f clientdata_prop_a.php clientdata_prop_b.php php_clientdata_prop_a.h php_clientdata_prop_b.h + rm -f import_stl_a.php import_stl_b.php php_import_stl_a.h php_import_stl_b.h + rm -f imports_a.php imports_b.php php_imports_a.h php_imports_b.h + rm -f mod_a.php mod_b.php php_mod_a.h php_mod_b.h + rm -f multi_import_a.php multi_import_b.php php_multi_import_a.h php_multi_import_b.h + rm -f packageoption_a.php packageoption_b.php packageoption_c.php php_packageoption_a.h php_packageoption_b.h php_packageoption_c.h From cc0738bbda7d962b3d72479ac866bca4ab8867e9 Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Wed, 28 May 2014 23:59:46 +0200 Subject: [PATCH 1024/1048] Fully clean Python examples and test-suite --- Examples/Makefile.in | 3 ++- Examples/python/import_packages/Makefile | 5 +++++ Examples/test-suite/python/Makefile.in | 7 +++---- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 123a634d7..b1b460c56 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -401,7 +401,8 @@ python_clean: rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *@SO@ *@PYTHON_SO@ rm -f $(TARGET).py - if [ -f $(RUNME).py ]; then rm -f $(RUNME)3.py $(RUNME)3.py.bak; fi + if test -f $(SRCDIR)$(RUNME).py; then rm -f $(RUNME)3.py $(RUNME)3.py.bak; fi + if test "x$(SRCDIR)" != x; then rm -f $(RUNME).py; fi ################################################################## diff --git a/Examples/python/import_packages/Makefile b/Examples/python/import_packages/Makefile index 2df2be101..d5054fd22 100644 --- a/Examples/python/import_packages/Makefile +++ b/Examples/python/import_packages/Makefile @@ -35,6 +35,11 @@ static: clean: $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' python_clean + if test "x$(SRCDIR)" != x; then \ + for file in `cd $(SRCDIR) && find . -type f -name __init__.py`; do \ + rm -f "$$file" || exit 1; \ + done; \ + fi; \ for s in $(import_packages_subdirs); do \ (cd $$s && $(MAKE) clean); \ done diff --git a/Examples/test-suite/python/Makefile.in b/Examples/test-suite/python/Makefile.in index 492396d15..87443cb57 100644 --- a/Examples/test-suite/python/Makefile.in +++ b/Examples/test-suite/python/Makefile.in @@ -160,12 +160,11 @@ endif # We only remove the _runme3.py if it is generated by 2to3 from a _runme.py. %.clean: @rm -f $*.py - @if [ -f $(srcdir)/$(py2_runme) ]; then \ - rm -f $(SCRIPTDIR)/$(py3_runme) $(SCRIPTDIR)/$(py3_runme).bak; \ - fi + @if test -f $(srcdir)/$(py2_runme); then rm -f $(SCRIPTDIR)/$(py3_runme) $(SCRIPTDIR)/$(py3_runme).bak; fi + @if test "x$(SRCDIR)" != x; then rm -f $(SCRIPTDIR)/$(py2_runme); fi clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile python_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" python_clean rm -f hugemod.h hugemod_a.i hugemod_b.i hugemod_a.py hugemod_b.py hugemod_runme.py rm -f clientdata_prop_a.py clientdata_prop_b.py import_stl_a.py import_stl_b.py rm -f imports_a.py imports_b.py mod_a.py mod_b.py multi_import_a.py From 3fe1eb705617c621f8f99d2f657cfe72a1049cce Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Thu, 29 May 2014 01:13:42 +0200 Subject: [PATCH 1025/1048] Set SRCDIR when calling test-suite clean targets, in case it's needed --- Examples/test-suite/allegrocl/Makefile.in | 2 +- Examples/test-suite/cffi/Makefile.in | 2 +- Examples/test-suite/chicken/Makefile.in | 2 +- Examples/test-suite/clisp/Makefile.in | 2 +- Examples/test-suite/errors/Makefile.in | 2 +- Examples/test-suite/guile/Makefile.in | 2 +- Examples/test-suite/lua/Makefile.in | 2 +- Examples/test-suite/mzscheme/Makefile.in | 2 +- Examples/test-suite/ocaml/Makefile.in | 2 +- Examples/test-suite/octave/Makefile.in | 2 +- Examples/test-suite/perl5/Makefile.in | 2 +- Examples/test-suite/pike/Makefile.in | 2 +- Examples/test-suite/r/Makefile.in | 2 +- Examples/test-suite/ruby/Makefile.in | 2 +- Examples/test-suite/tcl/Makefile.in | 2 +- Examples/test-suite/uffi/Makefile.in | 2 +- 16 files changed, 16 insertions(+), 16 deletions(-) diff --git a/Examples/test-suite/allegrocl/Makefile.in b/Examples/test-suite/allegrocl/Makefile.in index 8c253a7f2..02ef8e302 100644 --- a/Examples/test-suite/allegrocl/Makefile.in +++ b/Examples/test-suite/allegrocl/Makefile.in @@ -123,4 +123,4 @@ run_testcase = \ @rm -f $*.cl clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile allegrocl_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" allegrocl_clean diff --git a/Examples/test-suite/cffi/Makefile.in b/Examples/test-suite/cffi/Makefile.in index 6e657ba46..ee7e3f61e 100644 --- a/Examples/test-suite/cffi/Makefile.in +++ b/Examples/test-suite/cffi/Makefile.in @@ -48,4 +48,4 @@ run_testcase = \ @exit 0 clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile cffi_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" cffi_clean diff --git a/Examples/test-suite/chicken/Makefile.in b/Examples/test-suite/chicken/Makefile.in index 5a2ef3d8a..31ab311bb 100644 --- a/Examples/test-suite/chicken/Makefile.in +++ b/Examples/test-suite/chicken/Makefile.in @@ -97,5 +97,5 @@ run_testcase = \ @exit 0 clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile chicken_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" chicken_clean rm -f *.scm diff --git a/Examples/test-suite/clisp/Makefile.in b/Examples/test-suite/clisp/Makefile.in index 43f7159ff..6837ed60b 100644 --- a/Examples/test-suite/clisp/Makefile.in +++ b/Examples/test-suite/clisp/Makefile.in @@ -48,4 +48,4 @@ run_testcase = \ @exit 0 clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile clisp_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" clisp_clean diff --git a/Examples/test-suite/errors/Makefile.in b/Examples/test-suite/errors/Makefile.in index da67db8bd..3b165f9cd 100644 --- a/Examples/test-suite/errors/Makefile.in +++ b/Examples/test-suite/errors/Makefile.in @@ -53,5 +53,5 @@ include $(srcdir)/../common.mk @exit 0 clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile python_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" python_clean @rm -f *.$(ERROR_EXT) *.py diff --git a/Examples/test-suite/guile/Makefile.in b/Examples/test-suite/guile/Makefile.in index 6cbf3b9b1..9050d76f5 100644 --- a/Examples/test-suite/guile/Makefile.in +++ b/Examples/test-suite/guile/Makefile.in @@ -62,4 +62,4 @@ run_testcase = \ @rm -f $*-guile clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile guile_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" guile_clean diff --git a/Examples/test-suite/lua/Makefile.in b/Examples/test-suite/lua/Makefile.in index 00f940825..c562f09df 100644 --- a/Examples/test-suite/lua/Makefile.in +++ b/Examples/test-suite/lua/Makefile.in @@ -56,7 +56,7 @@ run_testcase = \ @exit 0 clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile lua_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" lua_clean cvsignore: @echo '*wrap* *.so *.dll *.exp *.lib' diff --git a/Examples/test-suite/mzscheme/Makefile.in b/Examples/test-suite/mzscheme/Makefile.in index 034e52131..da92f76fd 100644 --- a/Examples/test-suite/mzscheme/Makefile.in +++ b/Examples/test-suite/mzscheme/Makefile.in @@ -46,4 +46,4 @@ run_testcase = \ @exit 0 clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile mzscheme_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" mzscheme_clean diff --git a/Examples/test-suite/ocaml/Makefile.in b/Examples/test-suite/ocaml/Makefile.in index ee93d534c..9a4e008b9 100644 --- a/Examples/test-suite/ocaml/Makefile.in +++ b/Examples/test-suite/ocaml/Makefile.in @@ -81,4 +81,4 @@ include $(srcdir)/../common.mk @rm -f $*.ml $*.mli; clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile ocaml_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" ocaml_clean diff --git a/Examples/test-suite/octave/Makefile.in b/Examples/test-suite/octave/Makefile.in index 4f78371f4..fbffd240c 100644 --- a/Examples/test-suite/octave/Makefile.in +++ b/Examples/test-suite/octave/Makefile.in @@ -68,7 +68,7 @@ run_testcase = \ @rm -f $*.m; clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile octave_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" octave_clean cvsignore: @echo '*wrap* *.mc *.so *.dll *.exp *.lib' diff --git a/Examples/test-suite/perl5/Makefile.in b/Examples/test-suite/perl5/Makefile.in index 9d9d460d8..a4628ddcb 100644 --- a/Examples/test-suite/perl5/Makefile.in +++ b/Examples/test-suite/perl5/Makefile.in @@ -59,4 +59,4 @@ run_testcase = \ @rm -f $*.pm; clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile perl5_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" perl5_clean diff --git a/Examples/test-suite/pike/Makefile.in b/Examples/test-suite/pike/Makefile.in index 579c7e28f..92054dd9d 100644 --- a/Examples/test-suite/pike/Makefile.in +++ b/Examples/test-suite/pike/Makefile.in @@ -46,4 +46,4 @@ run_testcase = \ @rm -f $*.pike; clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile pike_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" pike_clean diff --git a/Examples/test-suite/r/Makefile.in b/Examples/test-suite/r/Makefile.in index 8ee73b279..d0489531f 100644 --- a/Examples/test-suite/r/Makefile.in +++ b/Examples/test-suite/r/Makefile.in @@ -66,7 +66,7 @@ run_multitestcase = \ done # Clean clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile r_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" r_clean %.clean: @rm -f $*.R $*_wrap.so $*_wrap.cpp $*_wrap.c $*_wrap.o $*_runme.Rout $*.Rout diff --git a/Examples/test-suite/ruby/Makefile.in b/Examples/test-suite/ruby/Makefile.in index 206617ecd..1a6875360 100644 --- a/Examples/test-suite/ruby/Makefile.in +++ b/Examples/test-suite/ruby/Makefile.in @@ -70,4 +70,4 @@ run_testcase = \ @exit 0 clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile ruby_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" ruby_clean diff --git a/Examples/test-suite/tcl/Makefile.in b/Examples/test-suite/tcl/Makefile.in index 32454b09c..82c59dee4 100644 --- a/Examples/test-suite/tcl/Makefile.in +++ b/Examples/test-suite/tcl/Makefile.in @@ -55,4 +55,4 @@ run_testcase = \ @exit 0 clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile tcl_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" tcl_clean diff --git a/Examples/test-suite/uffi/Makefile.in b/Examples/test-suite/uffi/Makefile.in index 59aa33c6a..275778c87 100644 --- a/Examples/test-suite/uffi/Makefile.in +++ b/Examples/test-suite/uffi/Makefile.in @@ -48,4 +48,4 @@ run_testcase = \ @exit 0 clean: - $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile uffi_clean + $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" uffi_clean From b51bc39cf7ad2eb9c037f735a2839283c19d1f03 Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Wed, 28 May 2014 21:18:41 +0200 Subject: [PATCH 1026/1048] Add check-maintainer-clean target: fails if files are missed by maintainer-clean --- .travis.yml | 2 +- Makefile.in | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 89bed90a1..08731ca62 100644 --- a/.travis.yml +++ b/.travis.yml @@ -113,7 +113,7 @@ script: - if test -n "$SWIGLANG"; then make -k $SWIGJOBS check-$SWIGLANG-examples CFLAGS="${CFLAGS_EXAMPLES[$SWIGLANG]}" CXXFLAGS="${CXXFLAGS_EXAMPLES[$SWIGLANG]}"; fi - if test -n "$SWIGLANG"; then make -k $SWIGJOBS check-$SWIGLANG-test-suite; fi - echo 'Cleaning...' && echo -en 'travis_fold:start:script.3\\r' - - make maintainer-clean && find . -type f | sed 's/^/File left after maintainer-clean - /' && ../../configure $CONFIGOPTS + - make check-maintainer-clean && ../../configure $CONFIGOPTS - echo -en 'travis_fold:end:script.3\\r' branches: only: diff --git a/Makefile.in b/Makefile.in index 2b9cf3b32..05c506559 100644 --- a/Makefile.in +++ b/Makefile.in @@ -455,6 +455,14 @@ maintainer-clean: @echo distcleaning @$(MAKE) $(FLAGS) distclean-helper +check-maintainer-clean: maintainer-clean + @if test "x$(srcdir)" != "x."; then \ + for file in `find . -type f`; do \ + echo "file missed by maintainer-clean: $$file"; \ + done; \ + fi; \ + test "x$$file" = x && echo "all files cleaned by maintainer-clean" + ##################################################################### # Update the Lib/swigwarn.swg file # Note: Generated into the source tree rather than build tree From 664c6cc81e88b300e21206623ae0053eec43e627 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 29 May 2014 07:50:21 +0100 Subject: [PATCH 1027/1048] Fix infinity testcase on windows --- Examples/test-suite/infinity.i | 27 ++++++++++++++----- .../test-suite/javascript/infinity_runme.js | 1 + 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/Examples/test-suite/infinity.i b/Examples/test-suite/infinity.i index 726150f02..4aa987c11 100644 --- a/Examples/test-suite/infinity.i +++ b/Examples/test-suite/infinity.i @@ -10,15 +10,16 @@ #include /* C99 math.h defines INFINITY. If not available, this is the fallback. */ -#ifndef INFINITY - #ifdef _MSC_VER +#if !defined(INFINITY) + #if defined(_MSC_VER) union MSVC_EVIL_FLOAT_HACK { unsigned __int8 Bytes[4]; float Value; }; - static union MSVC_EVIL_FLOAT_HACK INFINITY_HACK = {{0x00, 0x00, 0x80, 0x7F}}; + const union MSVC_EVIL_FLOAT_HACK INFINITY_HACK = {{0x00, 0x00, 0x80, 0x7F}}; #define INFINITY (INFINITY_HACK.Value) + #define INFINITY_NO_CONST #endif #ifdef __GNUC__ @@ -33,15 +34,27 @@ #define INFINITY (1e1000) #endif #endif -%} -%inline %{ -/* This will allow us to bind the real INFINITY value through SWIG via MYINFINITY. Use %rename to fix the name. */ +#ifdef INFINITY_NO_CONST +/* To void: error C2099: initializer is not a constant */ +double MYINFINITY = 0.0; +void initialise_MYINFINITY(void) { + MYINFINITY = INFINITY; +} +#else const double MYINFINITY = INFINITY; +void initialise_MYINFINITY(void) { +} +#endif -/* Use of float is intentional because the original bug was in the float conversion due to overflow checking. */ float use_infinity(float inf_val) { return inf_val; } %} + +/* This will allow us to bind the real INFINITY value through SWIG via MYINFINITY. Use %rename to fix the name. */ +const double MYINFINITY = INFINITY; +/* Use of float is intentional because the original bug was in the float conversion due to overflow checking. */ +float use_infinity(float inf_val); + diff --git a/Examples/test-suite/javascript/infinity_runme.js b/Examples/test-suite/javascript/infinity_runme.js index 050c391a7..8ebe496a6 100644 --- a/Examples/test-suite/javascript/infinity_runme.js +++ b/Examples/test-suite/javascript/infinity_runme.js @@ -1,4 +1,5 @@ var infinity = require("infinity"); +infinity.initialise_MYINFINITY(); var my_infinity = infinity.INFINITY; var ret_val = infinity.use_infinity(my_infinity); From 42938dc520d0c13c5d7e463298a2bd77f5ea9c82 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 29 May 2014 08:42:38 +0100 Subject: [PATCH 1028/1048] Correct infinity testcase --- Examples/test-suite/infinity.i | 1 + 1 file changed, 1 insertion(+) diff --git a/Examples/test-suite/infinity.i b/Examples/test-suite/infinity.i index 4aa987c11..e95bdf9cf 100644 --- a/Examples/test-suite/infinity.i +++ b/Examples/test-suite/infinity.i @@ -55,6 +55,7 @@ float use_infinity(float inf_val) /* This will allow us to bind the real INFINITY value through SWIG via MYINFINITY. Use %rename to fix the name. */ const double MYINFINITY = INFINITY; +void initialise_MYINFINITY(void); /* Use of float is intentional because the original bug was in the float conversion due to overflow checking. */ float use_infinity(float inf_val); From b71eb53baeb26f5052ed6da5064af6b10d0e6844 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 29 May 2014 08:44:19 +0100 Subject: [PATCH 1029/1048] Fix errors test-suite on windows --- Examples/test-suite/errors/Makefile.in | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/Examples/test-suite/errors/Makefile.in b/Examples/test-suite/errors/Makefile.in index 3b165f9cd..4c61001e7 100644 --- a/Examples/test-suite/errors/Makefile.in +++ b/Examples/test-suite/errors/Makefile.in @@ -15,18 +15,11 @@ LANGUAGE = errors ERROR_EXT = newerr -# Portable dos2unix / todos for stripping CR -TODOS = tr -d '\r' -#TODOS = sed -e 's/\r$$//' # On OSX behaves as if written 's/r$$//' srcdir = @srcdir@ top_srcdir = @top_srcdir@ top_builddir = @top_builddir@ -# strip source directory from output, so that diffs compare -srcdir_regexp = $(shell echo $(srcdir)/ | sed 's/\./[.]/g') -STRIP_SRCDIR = sed 's|^$(srcdir_regexp)||' - # 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,%, $(notdir $(wildcard $(srcdir)/*.i))) CPP_ERROR_TEST_CASES := $(filter cpp_%, $(ALL_ERROR_TEST_CASES)) @@ -37,17 +30,23 @@ ERROR_TEST_CASES := $(CPP_ERROR_TEST_CASES:=.cpptest) \ include $(srcdir)/../common.mk +# Portable dos2unix / todos for stripping CR +TODOS = tr -d '\r' +#TODOS = sed -e 's/\r$$//' # On OSX behaves as if written 's/r$$//' + +# strip source directory from output, so that diffs compare +STRIP_SRCDIR = sed -e 's|\\|/|g' -e 's|^$(SRCDIR)||' # Rules for the different types of tests %.cpptest: echo "$(ACTION)ing errors testcase $*" - -$(SWIG) -c++ -python -Wall -Fstandard $(SWIGOPT) $(srcdir)/$*.i 2>&1 | $(TODOS) | $(STRIP_SRCDIR) > $*.$(ERROR_EXT) - $(COMPILETOOL) diff -c $(srcdir)/$*.stderr $*.$(ERROR_EXT) + -$(SWIG) -c++ -python -Wall -Fstandard $(SWIGOPT) $(SRCDIR)$*.i 2>&1 | $(TODOS) | $(STRIP_SRCDIR) > $*.$(ERROR_EXT) + $(COMPILETOOL) diff -c $(SRCDIR)$*.stderr $*.$(ERROR_EXT) %.ctest: echo "$(ACTION)ing errors testcase $*" - -$(SWIG) -python -Wall -Fstandard $(SWIGOPT) $(srcdir)/$*.i 2>&1 | $(TODOS) | $(STRIP_SRCDIR) > $*.$(ERROR_EXT) - $(COMPILETOOL) diff -c $(srcdir)/$*.stderr $*.$(ERROR_EXT) + -$(SWIG) -python -Wall -Fstandard $(SWIGOPT) $(SRCDIR)$*.i 2>&1 | $(TODOS) | $(STRIP_SRCDIR) > $*.$(ERROR_EXT) + $(COMPILETOOL) diff -c $(SRCDIR)$*.stderr $*.$(ERROR_EXT) %.clean: @exit 0 From eb61c85e5f4c5a79dd8e01a36bddae9271612da2 Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Thu, 29 May 2014 14:26:02 +0200 Subject: [PATCH 1030/1048] check-maintainer-clean: print skipping message for in-source-tree builds --- Makefile.in | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Makefile.in b/Makefile.in index 05c506559..bb0845f37 100644 --- a/Makefile.in +++ b/Makefile.in @@ -456,11 +456,13 @@ maintainer-clean: @$(MAKE) $(FLAGS) distclean-helper check-maintainer-clean: maintainer-clean - @if test "x$(srcdir)" != "x."; then \ - for file in `find . -type f`; do \ - echo "file missed by maintainer-clean: $$file"; \ - done; \ + @if test "x$(srcdir)" = "x."; then \ + echo "skipping maintainer-clean check (in-source-tree build)"; \ + exit 0; \ fi; \ + for file in `find . -type f`; do \ + echo "file missed by maintainer-clean: $$file"; \ + done; \ test "x$$file" = x && echo "all files cleaned by maintainer-clean" ##################################################################### From b8026cc02f6b7639afd83cbd4e0419963d8c9428 Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Thu, 29 May 2014 14:35:23 +0200 Subject: [PATCH 1031/1048] Fix cleaning of Python runme.py scripts for in-source-tree builds --- Examples/Makefile.in | 2 +- Examples/test-suite/python/Makefile.in | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index b1b460c56..521df3a70 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -402,7 +402,7 @@ python_clean: rm -f *.@OBJEXT@ *@SO@ *@PYTHON_SO@ rm -f $(TARGET).py if test -f $(SRCDIR)$(RUNME).py; then rm -f $(RUNME)3.py $(RUNME)3.py.bak; fi - if test "x$(SRCDIR)" != x; then rm -f $(RUNME).py; fi + case "x$(SRCDIR)" in x|x./);; *) rm -f $(RUNME).py;; esac ################################################################## diff --git a/Examples/test-suite/python/Makefile.in b/Examples/test-suite/python/Makefile.in index 87443cb57..9673d7da1 100644 --- a/Examples/test-suite/python/Makefile.in +++ b/Examples/test-suite/python/Makefile.in @@ -161,7 +161,7 @@ endif %.clean: @rm -f $*.py @if test -f $(srcdir)/$(py2_runme); then rm -f $(SCRIPTDIR)/$(py3_runme) $(SCRIPTDIR)/$(py3_runme).bak; fi - @if test "x$(SRCDIR)" != x; then rm -f $(SCRIPTDIR)/$(py2_runme); fi + @if test "x$(SCRIPTDIR)" != "x$(srcdir)"; then rm -f $(SCRIPTDIR)/$(py2_runme); fi clean: $(MAKE) -f $(top_builddir)/$(EXAMPLES)/Makefile SRCDIR="$(SRCDIR)" python_clean From 79c91607369510a02788fb9e992f9de48118b835 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 29 May 2014 16:54:08 +0100 Subject: [PATCH 1032/1048] Search for 64bit webkit during configure For some Linux distributions (SUSE) --- configure.ac | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/configure.ac b/configure.ac index 8af45b69f..77b804ddd 100644 --- a/configure.ac +++ b/configure.ac @@ -1191,7 +1191,7 @@ else if test -z "$JSCORELIB"; then case $host in *-*-linux*) - dirs="/usr/lib/ /usr/local/lib/" + dirs="/usr/lib64/ /usr/local/lib64/ /usr/lib/ /usr/local/lib/" for i in $dirs ; do if test -r $i/libjavascriptcoregtk-1.0.so; then AC_MSG_RESULT($i) @@ -1259,7 +1259,7 @@ else AC_MSG_CHECKING(for V8 Javascript library) AC_ARG_WITH(jsv8lib,[ --with-v8lib=path Set location of V8 Javascript library directory],[JSV8LIBDIR="$withval"], [JSV8LIB=]) - v8libdirs="$JSV8LIBDIR /usr/lib*/ /usr/local/lib*/" + v8libdirs="$JSV8LIBDIR /usr/lib64/ /usr/local/lib64/ /usr/lib/ /usr/local/lib/" for d in $v8libdirs ; do if test -r $d/libv8.so; then JSV8LIBDIR=$d From 36a6a0cbe0654693f667fffc349dcb28d1549839 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 29 May 2014 19:54:13 +0100 Subject: [PATCH 1033/1048] Update AX_BOOST_BASE autoconf macro to serial 23 --- Tools/config/ax_boost_base.m4 | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/Tools/config/ax_boost_base.m4 b/Tools/config/ax_boost_base.m4 index 54a2a1bee..550b64138 100644 --- a/Tools/config/ax_boost_base.m4 +++ b/Tools/config/ax_boost_base.m4 @@ -33,7 +33,7 @@ # and this notice are preserved. This file is offered as-is, without any # warranty. -#serial 20 +#serial 23 AC_DEFUN([AX_BOOST_BASE], [ @@ -91,9 +91,23 @@ if test "x$want_boost" = "xyes"; then dnl are found, e.g. when only header-only libraries are installed! libsubdirs="lib" ax_arch=`uname -m` - if test $ax_arch = x86_64 -o $ax_arch = ppc64 -o $ax_arch = s390x -o $ax_arch = sparc64; then + case $ax_arch in + x86_64|ppc64|s390x|sparc64|aarch64) libsubdirs="lib64 lib lib64" - fi + ;; + esac + + dnl allow for real multi-arch paths e.g. /usr/lib/x86_64-linux-gnu. Give + dnl them priority over the other paths since, if libs are found there, they + dnl are almost assuredly the ones desired. + AC_REQUIRE([AC_CANONICAL_HOST]) + libsubdirs="lib/${host_cpu}-${host_os} $libsubdirs" + + case ${host_cpu} in + i?86) + libsubdirs="lib/i386-${host_os} $libsubdirs" + ;; + esac dnl first we check the system location for boost libraries dnl this location ist chosen if boost libraries are installed with the --layout=system option @@ -256,3 +270,4 @@ if test "x$want_boost" = "xyes"; then fi ]) + From cdd894d2af8eb2454006bf1a866b9bc59b70d3b5 Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Tue, 27 May 2014 01:15:10 +0200 Subject: [PATCH 1034/1048] .gitignore: add Source/TAGS --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index bce0812b7..b67e1d219 100644 --- a/.gitignore +++ b/.gitignore @@ -90,6 +90,7 @@ Lib/swigwarn.swg Source/CParse/parser.c Source/CParse/parser.h Source/eswig +Source/TAGS swig Tools/javascript/javascript From 603a73142ad9e97bc0435261f8f3067ad6653bbb Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Mon, 26 May 2014 20:39:04 +0200 Subject: [PATCH 1035/1048] Octave: ignore generated files --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index b67e1d219..28b44271f 100644 --- a/.gitignore +++ b/.gitignore @@ -134,6 +134,9 @@ Examples/test-suite/uffi/*/ # Javascript generated files *.gyp +# Octave generated files +swigexample*.oct + # Python generated files, based on: # https://github.com/github/gitignore/blob/master/Python.gitignore *.py[cod] From 5c5510842b5c443db0294ca924f13bd1f7ec7fa0 Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Mon, 26 May 2014 21:35:02 +0200 Subject: [PATCH 1036/1048] Octave: remove Python code from std_carray.i --- Lib/octave/std_carray.i | 56 ----------------------------------------- 1 file changed, 56 deletions(-) diff --git a/Lib/octave/std_carray.i b/Lib/octave/std_carray.i index 9e2338a61..e69de29bb 100644 --- a/Lib/octave/std_carray.i +++ b/Lib/octave/std_carray.i @@ -1,56 +0,0 @@ -%include - -/* -%fragment("StdCarrayTraits","header",fragment="StdSequenceTraits") -{ -namespace swig { - template - struct traits_asptr > { - static int asptr(PyObject *obj, std::carray **array) { - return traits_asptr_stdseq >::asptr(obj, array); - } - }; -} -} - -%warnfilter(SWIGWARN_IGNORE_OPERATOR_INDEX) std::carray::operator[]; - -%extend std::carray { - %fragment(SWIG_Traits_frag(std::carray<_Type, _Size >), "header", - fragment="SwigPyIterator_T", - fragment=SWIG_Traits_frag(_Type), - fragment="StdCarrayTraits") { - namespace swig { - template <> struct traits > { - typedef pointer_category category; - static const char* type_name() { - return "std::carray<" #_Type "," #_Size " >"; - } - }; - } - } - - %typemaps_asptr(SWIG_TYPECHECK_VECTOR, swig::asptr, - SWIG_Traits_frag(std::carray<_Type, _Size >), - std::carray<_Type, _Size >); - - %typemap(out,noblock=1) iterator, const_iterator { - $result = SWIG_NewPointerObj(swig::make_output_iterator((const $type &)$1), - swig::SwigPyIterator::descriptor(),SWIG_POINTER_OWN); - } - - inline size_t __len__() const { return self->size(); } - - inline const _Type& __getitem__(size_t i) const { return (*self)[i]; } - - inline void __setitem__(size_t i, const _Type& v) { (*self)[i] = v; } - - - swig::SwigPyIterator* __iter__(PyObject **PYTHON_SELF) { - return swig::make_output_iterator(self->begin(), self->begin(), self->end(), *PYTHON_SELF); - } -} - -%include -*/ - From ebe13380158ad5f552405463287d3cb4cdecc8bd Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Wed, 21 May 2014 22:31:36 +0200 Subject: [PATCH 1037/1048] Octave: whitespace/indentation cleanup of octave.cxx --- Source/Modules/octave.cxx | 658 +++++++++++++++++++------------------- 1 file changed, 329 insertions(+), 329 deletions(-) diff --git a/Source/Modules/octave.cxx b/Source/Modules/octave.cxx index 103b59194..1c8b639bb 100644 --- a/Source/Modules/octave.cxx +++ b/Source/Modules/octave.cxx @@ -1,5 +1,5 @@ /* ----------------------------------------------------------------------------- - * This file is part of SWIG, which is licensed as a whole under version 3 + * This file is part of SWIG, which is licensed as a whole under version 3 * (or any later version) of the GNU General Public License. Some additional * terms also apply to certain portions of SWIG. The full details of the SWIG * license and copyrights can be found in the LICENSE and COPYRIGHT files @@ -75,51 +75,51 @@ public: constructor_name(0), docs(0) { - /* Add code to manage protected constructors and directors */ - director_prot_ctor_code = NewString(""); - Printv(director_prot_ctor_code, - "if ( $comparison ) { /* subclassed */\n", - " $director_new \n", - "} else {\n", " error(\"accessing abstract class or protected constructor\"); \n", " SWIG_fail;\n", "}\n", NIL); + /* Add code to manage protected constructors and directors */ + director_prot_ctor_code = NewString(""); + Printv(director_prot_ctor_code, + "if ( $comparison ) { /* subclassed */\n", + " $director_new \n", + "} else {\n", " error(\"accessing abstract class or protected constructor\"); \n", " SWIG_fail;\n", "}\n", NIL); - enable_cplus_runtime_mode(); - allow_overloading(); - director_multiple_inheritance = 1; - director_language = 1; - docs = NewHash(); - } + enable_cplus_runtime_mode(); + allow_overloading(); + director_multiple_inheritance = 1; + director_language = 1; + docs = NewHash(); + } virtual void main(int argc, char *argv[]) { for (int i = 1; i < argc; i++) { if (argv[i]) { - if (strcmp(argv[i], "-help") == 0) { - fputs(usage, stdout); - } else if (strcmp(argv[i], "-global") == 0 || + if (strcmp(argv[i], "-help") == 0) { + fputs(usage, stdout); + } else if (strcmp(argv[i], "-global") == 0 || strcmp(argv[i], "-noglobal") == 0) { - Printv(stderr, + Printv(stderr, "*** -global/-noglobal are no longer supported\n" "*** global load behaviour is now determined at module load\n" "*** see the Perl section in the manual for details.\n", NIL); - SWIG_exit(EXIT_FAILURE); - } else if (strcmp(argv[i], "-globals") == 0) { - if (argv[i + 1]) { - global_name = NewString(argv[i + 1]); - Swig_mark_arg(i); - Swig_mark_arg(i + 1); - i++; - } else { - Swig_arg_error(); - } - } else if (strcmp(argv[i], "-opprefix") == 0) { - if (argv[i + 1]) { - op_prefix = NewString(argv[i + 1]); - Swig_mark_arg(i); - Swig_mark_arg(i + 1); - i++; - } else { - Swig_arg_error(); - } - } + SWIG_exit(EXIT_FAILURE); + } else if (strcmp(argv[i], "-globals") == 0) { + if (argv[i + 1]) { + global_name = NewString(argv[i + 1]); + Swig_mark_arg(i); + Swig_mark_arg(i + 1); + i++; + } else { + Swig_arg_error(); + } + } else if (strcmp(argv[i], "-opprefix") == 0) { + if (argv[i + 1]) { + op_prefix = NewString(argv[i + 1]); + Swig_mark_arg(i); + Swig_mark_arg(i + 1); + i++; + } else { + Swig_arg_error(); + } + } } } @@ -143,21 +143,21 @@ 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")) { - 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")) { + allow_directors(); + if (dirprot) + allow_dirprot(); + } + } } } @@ -202,8 +202,8 @@ public: Printf(f_runtime, "#define SWIG_DIRECTORS\n"); Swig_banner(f_directors_h); if (dirprot_mode()) { - // Printf(f_directors_h, "#include \n"); - // Printf(f_directors_h, "#include \n\n"); + // Printf(f_directors_h, "#include \n"); + // Printf(f_directors_h, "#include \n\n"); } } @@ -263,19 +263,19 @@ public: String *r = NewString(""); for (int j=0;s[j];++j) { if (s[j] == '\n') { - Append(r, "\\n\\\n"); + Append(r, "\\n\\\n"); } else if (s[j] == '\r') { - Append(r, "\\r"); + Append(r, "\\r"); } else if (s[j] == '\t') { - Append(r, "\\t"); + Append(r, "\\t"); } else if (s[j] == '\\') { - Append(r, "\\\\"); + Append(r, "\\\\"); } else if (s[j] == '\'') { - Append(r, "\\\'"); + Append(r, "\\\'"); } else if (s[j] == '\"') { - Append(r, "\\\""); + Append(r, "\\\""); } else - Putc(s[j], r); + Putc(s[j], r); } return r; } @@ -293,11 +293,11 @@ public: String *escaped_doc_str = texinfo_escape(doc_str); if (Len(doc_str)>0) { - Printf(f_doc,"static const char* %s_texinfo = ",wrap_name); - Printf(f_doc,"\"-*- texinfo -*-\\n\\\n%s", escaped_doc_str); - if (Len(decl_info)) - Printf(f_doc,"\\n\\\n@end deftypefn"); - Printf(f_doc,"\";\n"); + Printf(f_doc,"static const char* %s_texinfo = ",wrap_name); + Printf(f_doc,"\"-*- texinfo -*-\\n\\\n%s", escaped_doc_str); + if (Len(decl_info)) + Printf(f_doc,"\\n\\\n@end deftypefn"); + Printf(f_doc,"\";\n"); } Delete(escaped_doc_str); @@ -313,7 +313,7 @@ public: String *decl_info = Getattr(n, "decl_info"); String *cdecl_info = Getattr(n, "cdecl_info"); String *args_info = Getattr(n, "args_info"); - return !Len(synopsis) && !Len(decl_info) && + return !Len(synopsis) && !Len(decl_info) && !Len(cdecl_info) && !Len(args_info); } String *texinfo_name(Node* n, const char* defval = "0") { @@ -360,11 +360,11 @@ public: SwigType *type = Getattr(n, "type"); if (type && Strcmp(type, "void")) { - Node *nn = classLookup(Getattr(n, "type")); - String *type_str = nn ? Copy(Getattr(nn, "sym:name")) : SwigType_str(type, 0); - Append(decl_info, "@var{retval} = "); - Printf(args_str, "%s@var{retval} is of type %s. ", args_str, type_str); - Delete(type_str); + Node *nn = classLookup(Getattr(n, "type")); + String *type_str = nn ? Copy(Getattr(nn, "sym:name")) : SwigType_str(type, 0); + Append(decl_info, "@var{retval} = "); + Printf(args_str, "%s@var{retval} is of type %s. ", args_str, type_str); + Delete(type_str); } Append(decl_info, name); @@ -380,8 +380,8 @@ public: // strip off {} if necessary char *t = Char(str); if (*t == '{') { - Delitem(str, 0); - Delitem(str, DOH_END); + Delitem(str, 0); + Delitem(str, DOH_END); } // emit into synopsis section @@ -408,7 +408,7 @@ public: * addMissingParameterNames() * For functions that have not had nameless parameters set in the Language class. * - * Inputs: + * Inputs: * plist - entire parameter list * arg_offset - argument number for first parameter * Side effects: @@ -420,8 +420,8 @@ public: int i = arg_offset; while (p) { if (!Getattr(p, "lname")) { - String *pname = Swig_cparm_name(p, i); - Delete(pname); + String *pname = Swig_cparm_name(p, i); + Delete(pname); } i++; p = nextSibling(p); @@ -444,12 +444,12 @@ public: String *tm = Getattr(p, "tmap:in"); if (tm) { - pnext = Getattr(p, "tmap:in:next"); - if (checkAttribute(p, "tmap:in:numinputs", "0")) { - continue; - } + pnext = Getattr(p, "tmap:in:next"); + if (checkAttribute(p, "tmap:in:numinputs", "0")) { + continue; + } } else { - pnext = nextSibling(p); + pnext = nextSibling(p); } String *name = 0; @@ -457,9 +457,9 @@ public: String *value = 0; String *pdoc = Getattr(p, "tmap:doc"); if (pdoc) { - name = Getattr(p, "tmap:doc:name"); - type = Getattr(p, "tmap:doc:type"); - value = Getattr(p, "tmap:doc:value"); + name = Getattr(p, "tmap:doc:name"); + type = Getattr(p, "tmap:doc:type"); + value = Getattr(p, "tmap:doc:value"); } // Note: the generated name should be consistent with that in kwnames[] @@ -471,28 +471,28 @@ public: value = value ? value : Getattr(p, "value"); if (SwigType_isvarargs(type)) - break; + break; String *tex_name = NewString(""); if (name) - Printf(tex_name, "@var{%s}", name); + Printf(tex_name, "@var{%s}", name); else - Printf(tex_name, "@var{?}"); + Printf(tex_name, "@var{?}"); if (Len(decl_str)) - Append(decl_str, ", "); + Append(decl_str, ", "); Append(decl_str, tex_name); if (value) { - String *new_value = convertValue(value, Getattr(p, "type")); - if (new_value) { - value = new_value; - } else { - Node *lookup = Swig_symbol_clookup(value, 0); - if (lookup) - value = Getattr(lookup, "sym:name"); - } - Printf(decl_str, " = %s", value); + String *new_value = convertValue(value, Getattr(p, "type")); + if (new_value) { + value = new_value; + } else { + Node *lookup = Swig_symbol_clookup(value, 0); + if (lookup) + value = Getattr(lookup, "sym:name"); + } + Printf(decl_str, " = %s", value); } Node *nn = classLookup(Getattr(p, "type")); @@ -517,18 +517,18 @@ public: if (v && Len(v) > 0) { char fc = (Char(v))[0]; if (('0' <= fc && fc <= '9') || '\'' == fc || '"' == fc) { - /* number or string (or maybe NULL pointer) */ - if (SwigType_ispointer(t) && Strcmp(v, "0") == 0) - return NewString("None"); - else - return v; + /* number or string (or maybe NULL pointer) */ + if (SwigType_ispointer(t) && Strcmp(v, "0") == 0) + return NewString("None"); + else + return v; } if (Strcmp(v, "NULL") == 0 || Strcmp(v, "nullptr") == 0) - return SwigType_ispointer(t) ? NewString("nil") : NewString("0"); + return SwigType_ispointer(t) ? NewString("nil") : NewString("0"); if (Strcmp(v, "true") == 0 || Strcmp(v, "TRUE") == 0) - return NewString("true"); + return NewString("true"); if (Strcmp(v, "false") == 0 || Strcmp(v, "FALSE") == 0) - return NewString("false"); + return NewString("false"); } return 0; } @@ -572,89 +572,89 @@ public: int varargs = emit_isvarargs(l); char source[64]; - Printf(f->code, "if (!SWIG_check_num_args(\"%s\",args.length(),%i,%i,%i)) " - "{\n SWIG_fail;\n }\n", iname, num_arguments, num_required, varargs); + Printf(f->code, "if (!SWIG_check_num_args(\"%s\",args.length(),%i,%i,%i)) " + "{\n SWIG_fail;\n }\n", iname, num_arguments, num_required, varargs); if (constructor && num_arguments == 1 && num_required == 1) { if (Cmp(storage, "explicit") == 0) { - Node *parent = Swig_methodclass(n); - if (GetFlag(parent, "feature:implicitconv")) { - String *desc = NewStringf("SWIGTYPE%s", SwigType_manglestr(Getattr(n, "type"))); - Printf(f->code, "if (SWIG_CheckImplicit(%s)) SWIG_fail;\n", desc); - Delete(desc); - } + Node *parent = Swig_methodclass(n); + if (GetFlag(parent, "feature:implicitconv")) { + String *desc = NewStringf("SWIGTYPE%s", SwigType_manglestr(Getattr(n, "type"))); + Printf(f->code, "if (SWIG_CheckImplicit(%s)) SWIG_fail;\n", desc); + Delete(desc); + } } } for (j = 0, p = l; j < num_arguments; ++j) { while (checkAttribute(p, "tmap:in:numinputs", "0")) { - p = Getattr(p, "tmap:in:next"); + p = Getattr(p, "tmap:in:next"); } SwigType *pt = Getattr(p, "type"); String *tm = Getattr(p, "tmap:in"); if (tm) { - if (!tm || checkAttribute(p, "tmap:in:numinputs", "0")) { - p = nextSibling(p); - continue; - } + if (!tm || checkAttribute(p, "tmap:in:numinputs", "0")) { + p = nextSibling(p); + continue; + } - sprintf(source, "args(%d)", j); - Setattr(p, "emit:input", source); + sprintf(source, "args(%d)", j); + Setattr(p, "emit:input", source); - Replaceall(tm, "$source", Getattr(p, "emit:input")); - Replaceall(tm, "$input", Getattr(p, "emit:input")); - Replaceall(tm, "$target", Getattr(p, "lname")); + Replaceall(tm, "$source", Getattr(p, "emit:input")); + Replaceall(tm, "$input", Getattr(p, "emit:input")); + Replaceall(tm, "$target", Getattr(p, "lname")); - if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) { - Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); - } else { - Replaceall(tm, "$disown", "0"); - } + if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) { + Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); + } else { + Replaceall(tm, "$disown", "0"); + } - if (Getattr(p, "tmap:in:implicitconv")) { - const char *convflag = "0"; - if (!Getattr(p, "hidden")) { - SwigType *ptype = Getattr(p, "type"); - convflag = get_implicitconv_flag(classLookup(ptype)); - } - Replaceall(tm, "$implicitconv", convflag); - Setattr(p, "implicitconv", convflag); - } + if (Getattr(p, "tmap:in:implicitconv")) { + const char *convflag = "0"; + if (!Getattr(p, "hidden")) { + SwigType *ptype = Getattr(p, "type"); + convflag = get_implicitconv_flag(classLookup(ptype)); + } + Replaceall(tm, "$implicitconv", convflag); + Setattr(p, "implicitconv", convflag); + } - String *getargs = NewString(""); - if (j >= num_required) - Printf(getargs, "if (%dcode, getargs, "\n", NIL); - Delete(getargs); + String *getargs = NewString(""); + if (j >= num_required) + Printf(getargs, "if (%dcode, getargs, "\n", NIL); + Delete(getargs); - p = Getattr(p, "tmap:in:next"); - continue; + p = Getattr(p, "tmap:in:next"); + continue; } else { - Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0)); - break; + 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; } } // 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); } } @@ -662,23 +662,23 @@ public: String *cleanup = NewString(""); for (p = l; p;) { if ((tm = Getattr(p, "tmap:freearg"))) { - if (Getattr(p, "tmap:freearg:implicitconv")) { - const char *convflag = "0"; - if (!Getattr(p, "hidden")) { - SwigType *ptype = Getattr(p, "type"); - convflag = get_implicitconv_flag(classLookup(ptype)); - } - if (strcmp(convflag, "0") == 0) { - tm = 0; - } - } - if (tm && (Len(tm) != 0)) { - Replaceall(tm, "$source", Getattr(p, "lname")); - Printv(cleanup, tm, "\n", NIL); - } - p = Getattr(p, "tmap:freearg:next"); + if (Getattr(p, "tmap:freearg:implicitconv")) { + const char *convflag = "0"; + if (!Getattr(p, "hidden")) { + SwigType *ptype = Getattr(p, "type"); + convflag = get_implicitconv_flag(classLookup(ptype)); + } + if (strcmp(convflag, "0") == 0) { + tm = 0; + } + } + if (tm && (Len(tm) != 0)) { + Replaceall(tm, "$source", Getattr(p, "lname")); + Printv(cleanup, tm, "\n", NIL); + } + p = Getattr(p, "tmap:freearg:next"); } else { - p = nextSibling(p); + p = nextSibling(p); } } @@ -686,15 +686,15 @@ public: String *outarg = NewString(""); for (p = l; p;) { if ((tm = Getattr(p, "tmap:argout"))) { - Replaceall(tm, "$source", Getattr(p, "lname")); - Replaceall(tm, "$target", "_outp"); - Replaceall(tm, "$result", "_outp"); - Replaceall(tm, "$arg", Getattr(p, "emit:input")); - Replaceall(tm, "$input", Getattr(p, "emit:input")); - Printv(outarg, tm, "\n", NIL); - p = Getattr(p, "tmap:argout:next"); + Replaceall(tm, "$source", Getattr(p, "lname")); + Replaceall(tm, "$target", "_outp"); + Replaceall(tm, "$result", "_outp"); + Replaceall(tm, "$arg", Getattr(p, "emit:input")); + Replaceall(tm, "$input", Getattr(p, "emit:input")); + Printv(outarg, tm, "\n", NIL); + p = Getattr(p, "tmap:argout:next"); } else { - p = nextSibling(p); + p = nextSibling(p); } } @@ -720,9 +720,9 @@ public: Replaceall(tm, "$result", "_outv"); 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); Printf(f->code, "if (_outv.is_defined()) _outp = " "SWIG_Octave_AppendOutput(_outp, _outv);\n"); @@ -737,8 +737,8 @@ public: if (GetFlag(n, "feature:new")) { if ((tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0))) { - Replaceall(tm, "$source", Swig_cresult_name()); - Printf(f->code, "%s\n", tm); + Replaceall(tm, "$source", Swig_cresult_name()); + Printf(f->code, "%s\n", tm); } } @@ -830,16 +830,16 @@ public: if (is_assignable(n)) { Setattr(n, "wrap:name", setname); if ((tm = Swig_typemap_lookup("varin", n, name, 0))) { - Replaceall(tm, "$source", "args(0)"); - Replaceall(tm, "$target", name); - Replaceall(tm, "$input", "args(0)"); - if (Getattr(n, "tmap:varin:implicitconv")) { - Replaceall(tm, "$implicitconv", get_implicitconv_flag(n)); - } - emit_action_code(n, setf->code, tm); - Delete(tm); + Replaceall(tm, "$source", "args(0)"); + Replaceall(tm, "$target", name); + Replaceall(tm, "$input", "args(0)"); + if (Getattr(n, "tmap:varin:implicitconv")) { + Replaceall(tm, "$implicitconv", get_implicitconv_flag(n)); + } + emit_action_code(n, setf->code, tm); + Delete(tm); } else { - Swig_warning(WARN_TYPEMAP_VARIN_UNDEF, input_file, line_number, "Unable to set variable of type %s.\n", SwigType_str(t, 0)); + Swig_warning(WARN_TYPEMAP_VARIN_UNDEF, input_file, line_number, "Unable to set variable of type %s.\n", SwigType_str(t, 0)); } Append(setf->code, "fail:\n"); Printf(setf->code, "return octave_value_list();\n"); @@ -995,18 +995,18 @@ 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; - } + String *bname = Getattr(b.item, "name"); + if ((!bname) || GetFlag(b.item, "feature:ignore") || (!Getattr(b.item, "module"))) { + b = Next(b); + continue; + } - String *bname_mangled = SwigType_manglestr(SwigType_add_pointer(Copy(bname))); - Printf(base_class_names, "\"%s\",", bname_mangled); - Printf(base_class, "0,"); - b = Next(b); - index++; - Delete(bname_mangled); + String *bname_mangled = SwigType_manglestr(SwigType_add_pointer(Copy(bname))); + Printf(base_class_names, "\"%s\",", bname_mangled); + Printf(base_class, "0,"); + b = Next(b); + index++; + Delete(bname_mangled); } } @@ -1063,8 +1063,8 @@ public: bool overloaded = !!Getattr(n, "sym:overloaded"); if (overloaded) Delslice(rname, Len(rname) - Len(Getattr(n, "sym:overname")), DOH_END); - Printf(s_members_tab, "{\"%s\",%s,0,0,0,%s},\n", - realname, rname, tname); + Printf(s_members_tab, "{\"%s\",%s,0,0,0,%s},\n", + realname, rname, tname); Delete(rname); Delete(tname); } @@ -1112,7 +1112,7 @@ public: Delete(name); Setattr(self, "lname", "self_obj"); if (parms) - set_nextSibling(self, parms); + set_nextSibling(self, parms); Setattr(n, "parms", self); Setattr(n, "wrap:self", "1"); Setattr(n, "hidden", "1"); @@ -1144,12 +1144,12 @@ public: bool overloaded = !!Getattr(n, "sym:overloaded"); if (overloaded) Delslice(rname, Len(rname) - Len(Getattr(n, "sym:overname")), DOH_END); - Printf(s_members_tab, "{\"%s\",%s,0,0,1,%s},\n", - realname, rname, tname); + Printf(s_members_tab, "{\"%s\",%s,0,0,1,%s},\n", + realname, rname, tname); Delete(rname); Delete(tname); } - + return SWIG_OK; } @@ -1217,24 +1217,24 @@ public: 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," "\nSwig::Director(static_cast<%s*>(this)) { \n", classname, target, call, basetype); - Append(w->def, "}\n"); - Delete(target); - Wrapper_print(w, f_directors); - Delete(call); - DelWrapper(w); + 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," "\nSwig::Director(static_cast<%s*>(this)) { \n", classname, target, call, 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); + String *target = Swig_method_decl(0, decl, classname, parms, 0, 1); + Printf(f_directors_h, " %s;\n", target); + Delete(target); } } @@ -1250,7 +1250,7 @@ public: { Wrapper *w = NewWrapper(); Printf(w->def, "SwigDirector_%s::SwigDirector_%s(void* self) :" - "\nSwig::Director((octave_swig_type*)self,static_cast<%s*>(this)) { \n", classname, classname, classname); + "\nSwig::Director((octave_swig_type*)self,static_cast<%s*>(this)) { \n", classname, classname, classname); Append(w->def, "}\n"); Wrapper_print(w, f_directors); DelWrapper(w); @@ -1283,7 +1283,7 @@ public: if (Cmp(storage, "virtual") == 0) { if (Cmp(value, "0") == 0) { - pure_virtual = true; + pure_virtual = true; } } @@ -1317,18 +1317,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, ")"); @@ -1338,27 +1338,27 @@ public: Append(w->def, " {"); Append(declaration, ";\n"); - // declare method return value + // declare method return value // if the return value is a reference or const reference, a specialized typemap must // handle it, including declaration of c_result ($result). 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); } } 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++ -> Python) @@ -1374,50 +1374,50 @@ public: int outputs = 0; if (!is_void) - outputs++; + outputs++; // build argument list and type conversion string 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; + } - if (Getattr(p, "tmap:directorargout") != 0) - outputs++; + if (Getattr(p, "tmap:directorargout") != 0) + outputs++; - String *pname = Getattr(p, "name"); - String *ptype = Getattr(p, "type"); - Wrapper_add_local(w, "tmpv", "octave_value tmpv"); + String *pname = Getattr(p, "name"); + String *ptype = Getattr(p, "type"); + Wrapper_add_local(w, "tmpv", "octave_value tmpv"); - if ((tm = Getattr(p, "tmap:directorin")) != 0) { - String *parse = Getattr(p, "tmap:directorin:parse"); - if (!parse) { - Setattr(p, "emit:directorinput", "tmpv"); - Replaceall(tm, "$input", "tmpv"); - Replaceall(tm, "$owner", "0"); - Printv(wrap_args, tm, "\n", NIL); - Printf(wrap_args, "args.append(tmpv);\n"); - Putc('O', parse_args); - } else { - Append(parse_args, parse); - Setattr(p, "emit:directorinput", pname); - Replaceall(tm, "$input", pname); - Replaceall(tm, "$owner", "0"); - if (Len(tm) == 0) - Append(tm, pname); - } - p = Getattr(p, "tmap:directorin:next"); - continue; - } else if (Cmp(ptype, "void")) { - 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); + if ((tm = Getattr(p, "tmap:directorin")) != 0) { + String *parse = Getattr(p, "tmap:directorin:parse"); + if (!parse) { + Setattr(p, "emit:directorinput", "tmpv"); + Replaceall(tm, "$input", "tmpv"); + Replaceall(tm, "$owner", "0"); + Printv(wrap_args, tm, "\n", NIL); + Printf(wrap_args, "args.append(tmpv);\n"); + Putc('O', parse_args); + } else { + Append(parse_args, parse); + Setattr(p, "emit:directorinput", pname); + Replaceall(tm, "$input", pname); + Replaceall(tm, "$owner", "0"); + if (Len(tm) == 0) + Append(tm, pname); + } + p = Getattr(p, "tmap:directorin:next"); + continue; + } else if (Cmp(ptype, "void")) { + 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); } String *method_name = Getattr(n, "sym:name"); @@ -1438,45 +1438,45 @@ public: // marshal return value if (!is_void) { - Printf(w->code, "if (out.length()<%d) {\n", outputs); - Printf(w->code, "Swig::DirectorTypeMismatchException::raise(\"Octave " - "method %s.%s failed to return the required number " "of arguments.\");\n", classname, method_name); - Printf(w->code, "}\n"); + Printf(w->code, "if (out.length()<%d) {\n", outputs); + Printf(w->code, "Swig::DirectorTypeMismatchException::raise(\"Octave " + "method %s.%s failed to return the required number " "of arguments.\");\n", classname, method_name); + Printf(w->code, "}\n"); - tm = Swig_typemap_lookup("directorout", n, Swig_cresult_name(), w); - if (tm != 0) { - char temp[24]; - sprintf(temp, "out(%d)", idx); - Replaceall(tm, "$input", temp); - // Replaceall(tm, "$argnum", temp); - Replaceall(tm, "$disown", Getattr(n, "wrap:disown") ? "SWIG_POINTER_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; - } + tm = Swig_typemap_lookup("directorout", n, Swig_cresult_name(), w); + if (tm != 0) { + char temp[24]; + sprintf(temp, "out(%d)", idx); + Replaceall(tm, "$input", temp); + // Replaceall(tm, "$argnum", temp); + Replaceall(tm, "$disown", Getattr(n, "wrap:disown") ? "SWIG_POINTER_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; + } } idx++; // marshal outputs for (p = l; p;) { - if ((tm = Getattr(p, "tmap:directorargout")) != 0) { - char temp[24]; - sprintf(temp, "out(%d)", idx); - Replaceall(tm, "$result", temp); - 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) { + char temp[24]; + sprintf(temp, "out(%d)", idx); + Replaceall(tm, "$result", temp); + 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); @@ -1486,13 +1486,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); } } @@ -1506,7 +1506,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); @@ -1515,10 +1515,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); } } // clean up From b2d492c15a0240d8954d3702a87f90eb34fd49fb Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Mon, 26 May 2014 20:38:36 +0200 Subject: [PATCH 1038/1048] Octave: use common example.mk for examples, patterned after javascript --- Examples/octave/callback/Makefile | 18 ++-------------- Examples/octave/class/Makefile | 18 ++-------------- Examples/octave/constants/Makefile | 18 ++-------------- Examples/octave/contract/Makefile | 16 ++------------ Examples/octave/enum/Makefile | 18 ++-------------- Examples/octave/example.mk | 32 ++++++++++++++++++++++++++++ Examples/octave/extend/Makefile | 18 ++-------------- Examples/octave/funcptr/Makefile | 16 ++------------ Examples/octave/funcptr2/Makefile | 16 ++------------ Examples/octave/functor/Makefile | 18 ++-------------- Examples/octave/module_load/Makefile | 23 ++++++-------------- Examples/octave/operator/Makefile | 18 ++-------------- Examples/octave/pointer/Makefile | 16 ++------------ Examples/octave/reference/Makefile | 18 ++-------------- Examples/octave/simple/Makefile | 16 ++------------ Examples/octave/template/Makefile | 18 ++-------------- Examples/octave/variables/Makefile | 16 ++------------ 17 files changed, 68 insertions(+), 245 deletions(-) create mode 100644 Examples/octave/example.mk diff --git a/Examples/octave/callback/Makefile b/Examples/octave/callback/Makefile index 7855d0617..3b746de2f 100644 --- a/Examples/octave/callback/Makefile +++ b/Examples/octave/callback/Makefile @@ -1,17 +1,3 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cxx -TARGET = swigexample -INTERFACE = example.i -LIBS = -lm -SWIGOPT = +CXXSRCS = example.cxx -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean +include $(SRCDIR)../example.mk diff --git a/Examples/octave/class/Makefile b/Examples/octave/class/Makefile index 7855d0617..3b746de2f 100644 --- a/Examples/octave/class/Makefile +++ b/Examples/octave/class/Makefile @@ -1,17 +1,3 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cxx -TARGET = swigexample -INTERFACE = example.i -LIBS = -lm -SWIGOPT = +CXXSRCS = example.cxx -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean +include $(SRCDIR)../example.mk diff --git a/Examples/octave/constants/Makefile b/Examples/octave/constants/Makefile index eb05d1e7e..acf4d0575 100644 --- a/Examples/octave/constants/Makefile +++ b/Examples/octave/constants/Makefile @@ -1,17 +1,3 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = -TARGET = swigexample -INTERFACE = example.i -LIBS = -lm -SWIGOPT = +CXXSRCS = -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean +include $(SRCDIR)../example.mk diff --git a/Examples/octave/contract/Makefile b/Examples/octave/contract/Makefile index 2e0e82124..413b64bbd 100644 --- a/Examples/octave/contract/Makefile +++ b/Examples/octave/contract/Makefile @@ -1,15 +1,3 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -SRCS = example.c -TARGET = swigexample -INTERFACE = example.i +SRCS = example.c -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean +include $(SRCDIR)../example.mk diff --git a/Examples/octave/enum/Makefile b/Examples/octave/enum/Makefile index 7855d0617..3b746de2f 100644 --- a/Examples/octave/enum/Makefile +++ b/Examples/octave/enum/Makefile @@ -1,17 +1,3 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cxx -TARGET = swigexample -INTERFACE = example.i -LIBS = -lm -SWIGOPT = +CXXSRCS = example.cxx -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean +include $(SRCDIR)../example.mk diff --git a/Examples/octave/example.mk b/Examples/octave/example.mk new file mode 100644 index 000000000..e0b1e4efb --- /dev/null +++ b/Examples/octave/example.mk @@ -0,0 +1,32 @@ +# Note: as a convention an example must be in a child directory of this. +# These paths are relative to such an example directory + +TOP = ../.. +SWIG = $(TOP)/../preinst-swig +TARGET = swigexample +INTERFACE = example.i + +check: build + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run + +build: +ifneq (,$(SRCS)) + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave +else + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp +endif +ifneq (,$(TARGET2)$(SWIGOPT2)) +ifneq (,$(SRCS)) + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT2)' TARGET='$(TARGET2)' INTERFACE='$(INTERFACE)' octave +else + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT2)' TARGET='$(TARGET2)' INTERFACE='$(INTERFACE)' octave_cpp +endif +endif + + +clean: + $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean diff --git a/Examples/octave/extend/Makefile b/Examples/octave/extend/Makefile index 7855d0617..3b746de2f 100644 --- a/Examples/octave/extend/Makefile +++ b/Examples/octave/extend/Makefile @@ -1,17 +1,3 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cxx -TARGET = swigexample -INTERFACE = example.i -LIBS = -lm -SWIGOPT = +CXXSRCS = example.cxx -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean +include $(SRCDIR)../example.mk diff --git a/Examples/octave/funcptr/Makefile b/Examples/octave/funcptr/Makefile index 2e0e82124..413b64bbd 100644 --- a/Examples/octave/funcptr/Makefile +++ b/Examples/octave/funcptr/Makefile @@ -1,15 +1,3 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -SRCS = example.c -TARGET = swigexample -INTERFACE = example.i +SRCS = example.c -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean +include $(SRCDIR)../example.mk diff --git a/Examples/octave/funcptr2/Makefile b/Examples/octave/funcptr2/Makefile index 2e0e82124..413b64bbd 100644 --- a/Examples/octave/funcptr2/Makefile +++ b/Examples/octave/funcptr2/Makefile @@ -1,15 +1,3 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -SRCS = example.c -TARGET = swigexample -INTERFACE = example.i +SRCS = example.c -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean +include $(SRCDIR)../example.mk diff --git a/Examples/octave/functor/Makefile b/Examples/octave/functor/Makefile index 0fbc7586b..acf4d0575 100644 --- a/Examples/octave/functor/Makefile +++ b/Examples/octave/functor/Makefile @@ -1,17 +1,3 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = -TARGET = swigexample -INTERFACE = example.i -LIBS = -lm -SWIGOPT = +CXXSRCS = -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean +include $(SRCDIR)../example.mk diff --git a/Examples/octave/module_load/Makefile b/Examples/octave/module_load/Makefile index 7b24a8530..d2cd66e70 100644 --- a/Examples/octave/module_load/Makefile +++ b/Examples/octave/module_load/Makefile @@ -1,18 +1,7 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -SRCS = example.c -TARGET = swigexample -INTERFACE = example.i +SRCS = example.c +TARGET = swigexample +SWIGOPT = -module swigexample +TARGET2 = swigexample2 +SWIGOPT2 = -module swigexample2 -globals . -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ - TARGET='$(TARGET)' SWIGOPT='-module $$(TARGET)' INTERFACE='$(INTERFACE)' octave - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ - TARGET='$(TARGET)2' SWIGOPT='-module $$(TARGET) -globals .' INTERFACE='$(INTERFACE)' octave - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean - rm -f $(TARGET).m +include $(SRCDIR)../example.mk diff --git a/Examples/octave/operator/Makefile b/Examples/octave/operator/Makefile index 0fbc7586b..acf4d0575 100644 --- a/Examples/octave/operator/Makefile +++ b/Examples/octave/operator/Makefile @@ -1,17 +1,3 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = -TARGET = swigexample -INTERFACE = example.i -LIBS = -lm -SWIGOPT = +CXXSRCS = -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean +include $(SRCDIR)../example.mk diff --git a/Examples/octave/pointer/Makefile b/Examples/octave/pointer/Makefile index 2e0e82124..413b64bbd 100644 --- a/Examples/octave/pointer/Makefile +++ b/Examples/octave/pointer/Makefile @@ -1,15 +1,3 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -SRCS = example.c -TARGET = swigexample -INTERFACE = example.i +SRCS = example.c -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean +include $(SRCDIR)../example.mk diff --git a/Examples/octave/reference/Makefile b/Examples/octave/reference/Makefile index 7855d0617..3b746de2f 100644 --- a/Examples/octave/reference/Makefile +++ b/Examples/octave/reference/Makefile @@ -1,17 +1,3 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = example.cxx -TARGET = swigexample -INTERFACE = example.i -LIBS = -lm -SWIGOPT = +CXXSRCS = example.cxx -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' $(SWIGLIB) CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean +include $(SRCDIR)../example.mk diff --git a/Examples/octave/simple/Makefile b/Examples/octave/simple/Makefile index 2e0e82124..413b64bbd 100644 --- a/Examples/octave/simple/Makefile +++ b/Examples/octave/simple/Makefile @@ -1,15 +1,3 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -SRCS = example.c -TARGET = swigexample -INTERFACE = example.i +SRCS = example.c -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean +include $(SRCDIR)../example.mk diff --git a/Examples/octave/template/Makefile b/Examples/octave/template/Makefile index 0fbc7586b..acf4d0575 100644 --- a/Examples/octave/template/Makefile +++ b/Examples/octave/template/Makefile @@ -1,17 +1,3 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -CXXSRCS = -TARGET = swigexample -INTERFACE = example.i -LIBS = -lm -SWIGOPT = +CXXSRCS = -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \ - SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave_cpp - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean +include $(SRCDIR)../example.mk diff --git a/Examples/octave/variables/Makefile b/Examples/octave/variables/Makefile index 2e0e82124..413b64bbd 100644 --- a/Examples/octave/variables/Makefile +++ b/Examples/octave/variables/Makefile @@ -1,15 +1,3 @@ -TOP = ../.. -SWIG = $(TOP)/../preinst-swig -SRCS = example.c -TARGET = swigexample -INTERFACE = example.i +SRCS = example.c -check: build - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_run - -build: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' SRCS='$(SRCS)' SWIG='$(SWIG)' \ - TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' octave - -clean: - $(MAKE) -f $(TOP)/Makefile SRCDIR='$(SRCDIR)' octave_clean +include $(SRCDIR)../example.mk From ecf28da5a9c66904e57995cbd6cae35321ccece4 Mon Sep 17 00:00:00 2001 From: Karl Wette Date: Thu, 29 May 2014 23:42:22 +0200 Subject: [PATCH 1039/1048] Octave: remove deprecated -global/-noglobal command-line arguments --- CHANGES.current | 4 ++++ Source/Modules/octave.cxx | 7 ------- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/CHANGES.current b/CHANGES.current index 8d715e730..8e106f4b1 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,3 +5,7 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.2 (in progress) =========================== +2014-04-24: kwwette + [Octave] Remove deprecated -global/-noglobal command-line arguments + + *** POTENTIAL INCOMPATIBILITY *** diff --git a/Source/Modules/octave.cxx b/Source/Modules/octave.cxx index 1c8b639bb..12903166c 100644 --- a/Source/Modules/octave.cxx +++ b/Source/Modules/octave.cxx @@ -94,13 +94,6 @@ public: if (argv[i]) { if (strcmp(argv[i], "-help") == 0) { fputs(usage, stdout); - } else if (strcmp(argv[i], "-global") == 0 || - strcmp(argv[i], "-noglobal") == 0) { - Printv(stderr, - "*** -global/-noglobal are no longer supported\n" - "*** global load behaviour is now determined at module load\n" - "*** see the Perl section in the manual for details.\n", NIL); - SWIG_exit(EXIT_FAILURE); } else if (strcmp(argv[i], "-globals") == 0) { if (argv[i + 1]) { global_name = NewString(argv[i + 1]); From 84e1b553c4544d1c9a847c993931c412748c8b51 Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Sat, 31 May 2014 07:59:39 +0400 Subject: [PATCH 1040/1048] test fixed --- Examples/test-suite/nested_extend_c.i | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Examples/test-suite/nested_extend_c.i b/Examples/test-suite/nested_extend_c.i index fb3c053c4..64727b9ea 100644 --- a/Examples/test-suite/nested_extend_c.i +++ b/Examples/test-suite/nested_extend_c.i @@ -10,7 +10,7 @@ char hi_extend() { return $self->c; } - static const long swig_size = sizeof(hiA); + static const long swig_size = sizeof(union hiA); } %extend lowA { lowA() { @@ -22,7 +22,7 @@ int low_extend() { return $self->num; } - static const long swig_size = sizeof(lowA); + static const long swig_size = sizeof(struct lowA); } %extend hiB { @@ -34,7 +34,7 @@ char hi_extend() { return $self->c; } - static const long swig_size = sizeof(hiB); + static const long swig_size = sizeof(union hiB); } %extend lowB { lowB() { @@ -46,7 +46,7 @@ int low_extend() { return $self->num; } - static const long swig_size = sizeof(lowB); + static const long swig_size = sizeof(struct lowB); } %extend FOO_bar { @@ -55,7 +55,7 @@ } }; %extend NestedA { - static const long swig_size = sizeof(NestedA); + static const long swig_size = sizeof(struct NestedA); } #endif From 22be94d2070376237a2099788786b0cf7f8ab521 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 31 May 2014 19:58:42 +0100 Subject: [PATCH 1041/1048] Fix std::vector compile problems on OSX for Javascript --- Lib/javascript/jsc/std_vector.i | 2 +- Lib/javascript/v8/std_vector.i | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Lib/javascript/jsc/std_vector.i b/Lib/javascript/jsc/std_vector.i index 3f29b19c7..971b426a1 100644 --- a/Lib/javascript/jsc/std_vector.i +++ b/Lib/javascript/jsc/std_vector.i @@ -61,7 +61,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 && i Date: Sun, 1 Jun 2014 15:29:47 +0200 Subject: [PATCH 1042/1048] Fix bug in DohNewStringWithSize(): guarantee string is nul-terminated --- Source/DOH/string.c | 1 + 1 file changed, 1 insertion(+) diff --git a/Source/DOH/string.c b/Source/DOH/string.c index 50676c7c3..3e02e05d1 100644 --- a/Source/DOH/string.c +++ b/Source/DOH/string.c @@ -1114,6 +1114,7 @@ DOHString *DohNewStringWithSize(const DOHString_or_char *so, int len) { str->maxsize = max; if (s) { strncpy(str->str, s, len); + str->str[l] = 0; str->len = l; str->sp = l; } else { From 5f3ee109c8dd49fe7c6021c595a4afd648a129e6 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 2 Jun 2014 07:09:35 +0100 Subject: [PATCH 1043/1048] Add runtime test for %extend and nested union --- Examples/test-suite/java/nested_extend_c_runme.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Examples/test-suite/java/nested_extend_c_runme.java b/Examples/test-suite/java/nested_extend_c_runme.java index 9da093a09..5d9d861da 100644 --- a/Examples/test-suite/java/nested_extend_c_runme.java +++ b/Examples/test-suite/java/nested_extend_c_runme.java @@ -34,5 +34,12 @@ public class nested_extend_c_runme { if (low.low_extend() != 99) throw new RuntimeException("test failed"); } + { + FOO_bar foobar = new FOO_bar(); + foobar.setD(1234); + if (foobar.getD() != 1234) + throw new RuntimeException("test failed"); + foobar.bar_extend(); + } } } From 6d5444e58709a9d17a6f3a8bc47b80ce8ef28704 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 2 Jun 2014 07:23:14 +0100 Subject: [PATCH 1044/1048] CHANGES update --- CHANGES.current | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGES.current b/CHANGES.current index 8e106f4b1..73c028efd 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,7 +5,10 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.2 (in progress) =========================== -2014-04-24: kwwette +2014-06-02: vkalinin + Fix #183 - %extend and unnamed nested structs + +2014-05-24: kwwette [Octave] Remove deprecated -global/-noglobal command-line arguments *** POTENTIAL INCOMPATIBILITY *** From acd0ebc6605d42cfb931fe46a0aaab06e29fb847 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 2 Jun 2014 07:36:00 +0100 Subject: [PATCH 1045/1048] changes file updates --- CHANGES.current | 10 ++++++++++ README | 2 +- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/CHANGES.current b/CHANGES.current index 73c028efd..74730a89f 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,9 +5,19 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.2 (in progress) =========================== +2014-06-02: v-for-vandal + [Lua] Pull request #176: + If class has no __eq implemented, then default __eq is generated. + Default __eq compares actual pointers stored inside Lua userdata. + + 2014-06-02: vkalinin Fix #183 - %extend and unnamed nested structs +2014-05-28: kwwette + Fix install failure when using an 'out of source' build using the shipped + tarball - regression introduced in swig-3.0.1. + 2014-05-24: kwwette [Octave] Remove deprecated -global/-noglobal command-line arguments diff --git a/README b/README index e4010bd80..6cc847553 100644 --- a/README +++ b/README @@ -1,6 +1,6 @@ SWIG (Simplified Wrapper and Interface Generator) -Version: 3.0.2 (27 May 2014) +Version: 3.0.2 (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, From 37c09b01040d55eb9936a214c031e032c7bf80eb Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Wed, 4 Jun 2014 08:48:04 +0100 Subject: [PATCH 1046/1048] Add 3.0.2 release date --- ANNOUNCE | 2 +- CHANGES.current | 3 +-- Doc/Manual/Sections.html | 2 +- README | 2 +- RELEASENOTES | 3 +++ 5 files changed, 7 insertions(+), 5 deletions(-) diff --git a/ANNOUNCE b/ANNOUNCE index fc1160007..58de2fe10 100644 --- a/ANNOUNCE +++ b/ANNOUNCE @@ -1,4 +1,4 @@ -*** ANNOUNCE: SWIG 3.0.2 (in progress) *** +*** ANNOUNCE: SWIG 3.0.2 (4 Jun 2014) *** http://www.swig.org diff --git a/CHANGES.current b/CHANGES.current index 74730a89f..bb8bbdc41 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 3.0.2 (in progress) +Version 3.0.2 (4 Jun 2014) =========================== 2014-06-02: v-for-vandal @@ -10,7 +10,6 @@ Version 3.0.2 (in progress) If class has no __eq implemented, then default __eq is generated. Default __eq compares actual pointers stored inside Lua userdata. - 2014-06-02: vkalinin Fix #183 - %extend and unnamed nested structs diff --git a/Doc/Manual/Sections.html b/Doc/Manual/Sections.html index 33d76c239..bcae8139d 100644 --- a/Doc/Manual/Sections.html +++ b/Doc/Manual/Sections.html @@ -6,7 +6,7 @@

      SWIG-3.0 Documentation

      -Last update : SWIG-3.0.2 (in progress) +Last update : SWIG-3.0.2 (4 Jun 2014)

      Sections

      diff --git a/README b/README index 6cc847553..746bad7e1 100644 --- a/README +++ b/README @@ -1,6 +1,6 @@ SWIG (Simplified Wrapper and Interface Generator) -Version: 3.0.2 (in progress) +Version: 3.0.2 (4 Jun 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/RELEASENOTES b/RELEASENOTES index 542ff4b10..38fbe60e7 100644 --- a/RELEASENOTES +++ b/RELEASENOTES @@ -4,6 +4,9 @@ and CHANGES files. Release Notes ============= +SWIG-3.0.2 summary: +- Bug fix during install and a couple of other minor changes. + SWIG-3.0.1 summary: - Javascript module added. This supports JavascriptCore (Safari/Webkit), v8 (Chromium) and node.js currently. From 1949e2cc63abc3d8a361f37d2083774badd04bff Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Wed, 4 Jun 2014 12:21:09 +0100 Subject: [PATCH 1047/1048] Fix equality testcase --- Examples/test-suite/equality.i | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Examples/test-suite/equality.i b/Examples/test-suite/equality.i index a1b70c299..cdabc4892 100644 --- a/Examples/test-suite/equality.i +++ b/Examples/test-suite/equality.i @@ -6,6 +6,8 @@ %module equality +%warnfilter(SWIGWARN_LANG_IDENTIFIER) operator==; + %inline %{ /* Point has no equality operator */ @@ -40,7 +42,7 @@ public: inline static const EqualOpWrong* GetStaticObject(); }; -static const EqualOpWrong s_wrongEqOp; +static EqualOpWrong s_wrongEqOp; const EqualOpWrong* EqualOpWrong::GetStaticObject() { return &s_wrongEqOp; } From ef4cb2f57465025203961a484fd8f7a0a8c9faa7 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Wed, 4 Jun 2014 13:00:18 +0100 Subject: [PATCH 1048/1048] Fix example clean target in makefile for operating systems that don't use .so as shared library extension --- Examples/Makefile.in | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 521df3a70..50b7ead03 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -204,7 +204,7 @@ tcl_version: tcl_clean: rm -f *_wrap* *~ .~* mytclsh@EXEEXT@ rm -f core @EXTRA_CLEAN@ - rm -f *.@OBJEXT@ *@SO@ + rm -f *.@OBJEXT@ *$(TCL_SO) ################################################################## ##### PERL 5 ###### @@ -399,7 +399,7 @@ python_clean: rm -rf __pycache__ rm -f *_wrap* *~ .~* mypython@EXEEXT@ *.pyc rm -f core @EXTRA_CLEAN@ - rm -f *.@OBJEXT@ *@SO@ *@PYTHON_SO@ + rm -f *.@OBJEXT@ *@SO@ *$(PYTHON_SO) rm -f $(TARGET).py if test -f $(SRCDIR)$(RUNME).py; then rm -f $(RUNME)3.py $(RUNME)3.py.bak; fi case "x$(SRCDIR)" in x|x./);; *) rm -f $(RUNME).py;; esac @@ -461,7 +461,7 @@ octave_clean: rm -rf __pycache__ rm -f *_wrap* *~ .~* myoctave@EXEEXT@ *.pyc rm -f core @EXTRA_CLEAN@ - rm -f *.@OBJEXT@ *@SO@ *@OCTAVE_SO@ + rm -f *.@OBJEXT@ *@SO@ *$(OCTAVE_SO) ################################################################## ##### GUILE ###### @@ -551,7 +551,7 @@ guile_version: guile_clean: rm -f *_wrap* *~ .~* my-guile@EXEEXT@ $(TARGET)@EXEEXT@ rm -f core @EXTRA_CLEAN@ - rm -f *.@OBJEXT@ *@GUILE_SO@ + rm -f *.@OBJEXT@ *$(GUILE_SO) ################################################################## ##### JAVA ###### @@ -874,7 +874,7 @@ mzscheme_version: mzscheme_clean: rm -f *_wrap* *~ .~* rm -f core @EXTRA_CLEAN@ - rm -f *.@OBJEXT@ *@SO@ + rm -f *.@OBJEXT@ *$(MZSCHEME_SO) ################################################################## ##### Ocaml ##### @@ -1097,7 +1097,7 @@ ruby_version: ruby_clean: rm -f *_wrap* *~ .~* myruby@EXEEXT@ *.pm rm -f core @EXTRA_CLEAN@ - rm -f *.@OBJEXT@ *@SO@ + rm -f *.@OBJEXT@ *$(RUBY_SO) ################################################################## ##### PHP ###### @@ -1147,7 +1147,7 @@ php_version: php_clean: rm -f *_wrap* *~ .~* example.php php_example.h rm -f core @EXTRA_CLEAN@ - rm -f *.@OBJEXT@ *@SO@ + rm -f *.@OBJEXT@ *$(PHP_SO) ################################################################## ##### Pike ###### @@ -1480,7 +1480,7 @@ lua_version: lua_clean: rm -f *_wrap* *~ .~* mylua@EXEEXT@ rm -f core @EXTRA_CLEAN@ - rm -f *.@OBJEXT@ *@SO@ + rm -f *.@OBJEXT@ *$(LUA_SO) ################################################################## ##### ALLEGRO CL ######
  • 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 0427/1048] 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 0428/1048] 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 0429/1048] 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 0430/1048] 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 0431/1048] 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 0432/1048] 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 0433/1048] 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 0434/1048] 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 0435/1048] 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 0436/1048] 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 0437/1048] 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 0438/1048] [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 0439/1048] 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 0440/1048] 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 0441/1048] 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 0442/1048] 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 0443/1048] 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 0444/1048] 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 0445/1048] 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 0446/1048] 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 0447/1048] 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 0448/1048] 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 0449/1048] 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 0450/1048] 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 0451/1048] 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 0452/1048] 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 0453/1048] 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 0454/1048] 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 0455/1048] 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 0456/1048] 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 0457/1048] 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 0458/1048] 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 0459/1048] 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 0460/1048] [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 0461/1048] 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 0462/1048] 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 0463/1048] 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 0464/1048] 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 0465/1048] 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 0466/1048] 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 0467/1048] 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 0468/1048] 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 0469/1048] 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 0470/1048] 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 0471/1048] 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 0472/1048] 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 0473/1048] 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 0474/1048] 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 0475/1048] 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 0476/1048] 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 0477/1048] 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 0478/1048] 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 0479/1048] 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 0480/1048] 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 0481/1048] 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 0482/1048] 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 0483/1048] 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 0484/1048] 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 0485/1048] 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 0486/1048] 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 0487/1048] 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 0488/1048] 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 0489/1048] [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 0490/1048] 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 0491/1048] 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 0492/1048] %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 0493/1048] 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 0494/1048] 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 0495/1048] 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 0496/1048] 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 0497/1048] 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 0498/1048] 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 0499/1048] 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 0500/1048] 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 0501/1048] 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 0502/1048] 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 0503/1048] 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 0504/1048] 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 0505/1048] 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 0506/1048] 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 0507/1048] [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 0508/1048] [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 0509/1048] [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 0510/1048] 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 0511/1048] 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 0512/1048] 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 0513/1048] 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 0514/1048] 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 0515/1048] 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 0516/1048] %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 0517/1048] 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 0518/1048] 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 0519/1048] 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 0520/1048] 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 0521/1048] 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 0522/1048] 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 0523/1048] 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 0524/1048] 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 0525/1048] 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 0526/1048] 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 0527/1048] 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 0528/1048] 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 0529/1048] 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 0530/1048] 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 0531/1048] 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 0532/1048] 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 0533/1048] 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 0534/1048] 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 0535/1048] 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 0536/1048] 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 0537/1048] 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 0538/1048] 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 0539/1048] 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 0540/1048] 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 0541/1048] 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 0542/1048] 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 0543/1048] 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 0544/1048] 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 0545/1048] 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 0546/1048] 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 0547/1048] 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 0548/1048] 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 0549/1048] 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 0550/1048] 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 0551/1048] 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 0552/1048] 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 0553/1048] 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 0554/1048] 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 0555/1048] 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 0556/1048] 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 0557/1048] 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 1e34ecdc31c82d30141097f7744617361ebb748c Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Thu, 13 Feb 2014 19:25:16 +0100 Subject: [PATCH 0558/1048] Next iteration on creating a documentation for the Javascript module. --- .../Javascript/MappingC++ToJavascript.md | 220 --- .../V8_CodeGeneratorSpecification.md | 1063 -------------- Doc/Manual/Javascript.md | 1215 +++-------------- Source/Modules/javascript.cxx | 30 +- 4 files changed, 203 insertions(+), 2325 deletions(-) delete mode 100644 Doc/Devel/Javascript/MappingC++ToJavascript.md delete mode 100644 Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md diff --git a/Doc/Devel/Javascript/MappingC++ToJavascript.md b/Doc/Devel/Javascript/MappingC++ToJavascript.md deleted file mode 100644 index c77064933..000000000 --- a/Doc/Devel/Javascript/MappingC++ToJavascript.md +++ /dev/null @@ -1,220 +0,0 @@ -# Mapping C++ language features to Javascript - -## Namespaces - -A namespace is represented as a static instance (global variable) -containing other namespaces, global variables and functions -and class templates - -### Example: - -C++: - -~~~~c++ -namespace foo { - int x; - namespace bar { - double y; - } -} -~~~~ - -Javascript: - -~~~~javascript -var foo = new Object(); -foo.x = 0; -foo.bar = new Object(); -foo.bar.y = 0.0; -~~~~ - -## Global variables and functions - -Global variables and functions are properties of other context objects -(global or namespaces). - -### Example: - -C++: - -~~~~c++ -int x; -namespace foo { - void bar(); -} -~~~~ - -Javascript: - -~~~~javascript -var x = 0; -var foo = new Object(); -foo.bar = function() { - return undefined; -} -~~~~ - -## Classes - -Classes are defined as class templates and instantiated using the `new` -operator. -Class members are set in the constructor function using the `this` reference. -Private class members are set using the `var` keyword. - -### Example: - -C++: - -~~~~c++ -class Foo { - int bar(); - -private: - int x; -} -~~~~ - -Javascript: - -~~~~javascript -var Foo = function() { - var x = 42; - this.bar = function() { return x; }; -}; - -var foo = new Foo(); -foo.bar(); -~~~~ - -## Static class members and functions - -Static variables and functions should be added to the class template object. - -~~~~c++ -class Foo { - static std::string foo(); - std::string bar(); -} -~~~~ - -Javascript: - -~~~~javascript -var Foo = function() { - this.bar = function() { - return "bar"; - } -}; -Foo.foo = function() { - return "foo"; -}; - -var foo = new Foo(); -foo.foo() -> TypeError: Object [object Object] has no method 'foo' -Foo.foo() -> "foo" -foo.bar(); -> "bar" -~~~~ - -## Inheritance - -Javascript uses a prototype based inheritance mechanism. This limits -feature support to single inheritance. - -### Example: - -C++: - -~~~~c++ -class Foo { -public: - int foo(); - -private: - int x; -} - -class Bar: public Foo { -public: - int bar(); -} -~~~~ - -Javascript: - -~~~~javascript -var Foo = function() { - var x = 42; - this.foo = function() { return x; }; -}; - -var Bar = function() { - this.bar = function() { return 6; }; -} -Bar.prototype = new Foo(); -Bar.prototype.constructor = Bar; - -var foo = new Foo(); -var bar = new Bar(); - -foo.foo() -> 42 -foo.bar() -> TypeError: Object [object Object] has no method 'bar' -bar.foo() -> 42 -bar.bar() -> 6 -~~~~ - -## Virtual methods - -The prototype mechanism of Javascript allows method overriding which is -needed to map the concept of virtual functions. - -### Example: - -C++: - -~~~~c++ -class Foo { -public: - virtual int foo(); -} - -class Bar: public Foo { -public: - virtual int foo(); -} -~~~~ - -Javascript: - -~~~~javascript -var Foo = function() { - this.foo = function() { return 1; }; -}; - -var Bar = function() {} -Bar.prototype = new Foo(); -Bar.prototype.constructor = Bar; -Bar.prototype.foo = function() { return 42; }; - -var foo = new Foo(); -var bar = new Bar(); - -foo.foo() -> 1 -bar.foo() -> 42 -~~~~ - -## Overloading - -In Javascript like in other scripting languages method overloading is not -available. I.e., there can only be one function for one function name. -Therefore, it is necessary to implement a method dispatching mechanism -for these methods. - diff --git a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md b/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md deleted file mode 100644 index 63027b74d..000000000 --- a/Doc/Devel/Javascript/V8_CodeGeneratorSpecification.md +++ /dev/null @@ -1,1063 +0,0 @@ -Javascript: Specification of a Code Generator for V8 -==================================================== - -The aim of this is to evolve a specification for a code generator. - -## Top Level structure - -The generated code consists of the following blocks: - -~~~~ - - - - - - - - - - -~~~~ - -- `HELPER_FUNCTIONS`: static, from swg-file -- `INCLUDES`: static, module property -- `CLASS_TEMPLATES`: dynamically growing, on class declarations -- `FUNCTION_WRAPPERS`: dynamically growing, on method declarations -- `INITIALIZER`: dynamically growing, aggregates everything (to be specified in more detail) - -### INCLUDES - -~~~~ -#include - - -~~~~ - -`USER_DEFINED_INCLUDES`: a module property - -### CLASS_TEMPLATES - -Static references to class templates which are (should be) read-only and can be reused. - -~~~~ -v8::Persistent SWIGV8_${NAME_MANGLED}; -~~~~ - -Notes: - - it is very important to consider namespaces from the beginning. - `NAME_MANGLED` is the mangled qualified class name, e.g., `foo_bar_MyClass` for `foo::bar::MyClass`, - which is retrieved ny `Swig_string_mangle(Getattr(n, "name"))` - - namespaces do not need a function template, as they will not be - instantiated - -## FUNCTION_WRAPPERS - -There are different types of function wrappers: - - - Global Functions (global/namespace/class) - - Constructors / Destructors - - Getters / Settters - - Member Functions - -### Global Functions - -~~~~ -v8::Handle wrap_${NAME_MANGLED}(const v8::Arguments &args) { - v8::HandleScope scope; - v8::Handle ret; - ${LOCALS} - ${CODE} - return scope.Close(ret); -} -~~~~ - -- `LOCALS`: declarations for input and output arguments -- `CODE` contains input marshalling, the action, and output marshalling - -### Constructors - -~~~~ -v8::Handle ${NAME_MANGLED}_new(const v8::Arguments& args) { - v8::HandleScope scope; - v8::Handle self = args.Holder(); - ${LOCALS} - ${CODE} - self->SetInternalField(0, v8::External::New(ptr)); - return self; -} -~~~~ - -- `LOCALS`: declarations for input arguments -- `CODE` contains input marshalling, and the action - -### Destructors - -TODO: I haven't found out yet how a descrtuctor can be registered - -### Getters - -~~~~ -v8::Handle ${NAME_MANGLED}_get(v8::Local property, const v8::AccessorInfo& info) { - v8::HandleScope scope; - v8::Handle ret; - ${LOCALS} - ${CODE} - return scope.Close(ret); -} -~~~~ - -- `NAME_MANGLED`: the qualified mangled name of the variable, E.g., `foo::x -> foo_x`, `A.x -> A_x` -- `LOCALS`: declarations for output arguments -- `CODE` contains the action, and output marshalling - -### Setters - -~~~~ -void ${NAME_MANGLED}_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { - ${LOCALS} - ${CODE} -} -~~~~ -- `NAME_MANGLED`: the qualified mangled name of the variable, E.g., `foo::x -> foo_x`, `A.x -> A_x` -- `LOCALS`: declarations for input arguments -- `CODE` contains input marshalling, and the action - -### Functions - -~~~~ -v8::Handle ${NAME_MANGLED}(const Arguments &args) { - v8::HandleScope scope; - v8::Handle ret; - ${LOCALS} - ${CODE} - return scope.Close(ret); -} -~~~~ - -- `NAME_MANGLED`: the qualified mangled name of the variable, E.g., `foo::x -> foo_x`, `A.x -> A_x` -- `LOCALS`: declarations for input arguments -- `CODE` contains input marshalling, the action, and output marshalling - - -### Overloading - -TODO: if a function or a ctor is overloaded, a dispatcher function -must be generated which calls overloading wrappers depending on number -and type of input arguments. - - -## Initializer - -~~~~ -void ${MODULE}_Initialize(v8::Handle context) -{ - v8::HandleScope scope; - - // register the module in globale context - v8::Local global = context->Global(); - - ${PART_NAMESPACES} - - ${PART_CLASS_TEMPLATES} - - ${PART_WRAPPERS} - - ${PART_INHERITANCE} - - ${PART_REGISTER_CLASSES} - - ${PART_REGISTER_NS} -} -~~~~ - -### Namespaces - -Namespaces are objects without class templates. I.e., instances are created, -referenced locally, used as contexts for other registrations, and stored -in the according parent contexts. - -~~~~~ -v8::Handle ${NAME_MANGLED} = v8::ObjectTemplate::New(); -~~~~~ - -### Class Templates - -~~~~ -SWIGV8_${NAME_MANGLED} = SWIGV8_CreateClassTemplate("${NAME_UNQUALIFIED}" , ${NAME_MANGLED}_new); -~~~~ - -- `NAME_UNQUALIFIED`: the class name without context, i.e., namespaces - -### Inheritance - -~~~~ -SWIGV8_${NAME_MANGLED}->Inherit(SWIGV8_${BASE_CLASS}); -~~~~ - -- Note: multiple inheritance is not possible; thus we will always take the first parent class - -### Registration - -The registration part consists of registering classes at contexts (i.e., global or namespace), -methods and properties at classes or contexts, and namespaces as objects at -parent contexts. - -#### Global Variable - -~~~~ -${CONTEXT}->SetAccessor(v8::String::NewSymbol("${NAME_UNQUALIFIED}"), ${GETTER}, ${SETTER}); -~~~~ - -- `CONTEXT`: either global, or the according namespace template -- `${SETTER} = 0` for read-only variables - -#### Global Function - -~~~~ -SWIGV8_AddGlobalFunction(${CONTEXT}, "${NAME_UNQUALIFIED}", wrap_${NAME_QUALIFIED}); -~~~~ - -- `CONTEXT`: either global, or the according namespace template - -#### Class - -~~~~ -${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}", SWIGV8_${NAME_MANGLED}->GetFunction())); -~~~~ - -- Note: every class template has an associated ctor function wrapper, which is registered here -- `CONTEXT`: either global, or the according namespace instance - -#### Class method - -~~~~ -SWIGV8_AddClassMethod(SWIGV8_${CLASSNAME_MANGLED}, "${NAME_UNQUALIFIED}", wrap_${NAME_MANGLED}); -~~~~ - -Note: implemented in static helper function - -#### Class variable - -~~~~ -SWIGV8_AddProperty(SWIGV8_${CLASSNAME_MANGLED}, "${NAME_UNQUALIFIED}", ${GETTER}, ${SETTER}); -~~~~ - -- `GETTER`: the name of the generated wrapper for the property getter -- `SETTER`: the name of the generated wrapper for property setter; optional (i.e., maybe `NULL`) - -### Namespace - -~~~~ -${CONTEXT}->Set(v8::String::NewSymbol("${NAME_UNQUALIFIED}", ${NAME_MANGLED}->NewInstance())); -~~~~ - -Note: it is important to register the namespace objects in reverse order, -e.g., - -~~~~ -namespace foo { - namespace bar {} -} -~~~~ - -would be registered in this order: - -~~~~ -foo->Set(v8::String::NewSymbol("bar", bar->NewInstance())); -global->Set(v8::String::NewSymbol("foo", foo->NewInstance())); -~~~~ - -## HELPER_FUNCTIONS - -A lot of boiler-plate code can be shifted into static helper functions: - -~~~~ - -/** - * Creates a class template for a class without extra initialization function. - */ -v8::Persistent SWIGV8_CreateClassTemplate(const char* symbol, v8::InvocationCallback func) -{ - v8::Local class_templ = v8::FunctionTemplate::New(func); - class_templ->SetClassName(v8::String::NewSymbol(symbol)); - - v8::Handle inst_templ = class_templ->InstanceTemplate(); - inst_templ->SetInternalFieldCount(1); - - return v8::Persistent::New(class_templ); -} - -/** - * Registers a class method with given name for a given class template. - */ -void SWIGV8_AddMemberFunction(v8::Handle class_templ, - const char* symbol, - v8::InvocationCallback func) -{ - v8::Handle proto_templ = class_templ->PrototypeTemplate(); - proto_templ->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(func)); -} - -/** - * Registers a class property with given name for a given class template. - */ -void SWIGV8_AddMemberVariable(v8::Handle class_templ, - const char* varname, - v8::AccessorGetter getter, - v8::AccessorSetter setter) -{ - v8::Handle proto_templ = class_templ->InstanceTemplate(); - proto_templ->SetAccessor(v8::String::New(varname), getter, setter); -} - - -/** - * Adds a property with given name to a given context. - */ -void SWIGV8_AddGlobalVariable(v8::Handle context, - const char* varname, - v8::AccessorGetter getter, - v8::AccessorSetter setter) -{ - context->SetAccessor(v8::String::NewSymbol(varname), getter, setter); -} - -/** - * Adds a function with given name to a given context. - */ -void SWIGV8_AddGlobalFunction(v8::Handle context, - const char* symbol, - v8::InvocationCallback func) -{ - context->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(func)->GetFunction()); -} - -template -static T* SWIGV8_UnwrapThisPointer (v8::Handle handle) -{ - // assert(!handle.IsEmpty()); - // assert(handle->InternalFieldCount() > 0); - v8::Local wrap = v8::Local::Cast(handle->GetInternalField(0)); - return static_cast(wrap->Value()); -} - -~~~~ - -------------------------- - -Examples -======== - -In this chapter manually coded wrappers are presented. -This has been useful for studying the addressed code generation on basis -of examples. - -## Global variable - -~~~~~ -static double Foo = 42.0; - -void Foo_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { - v8::HandleScope scope; - double arg1 ; - arg1 = value->NumberValue(); - Foo = arg1; -} - -v8::Handle Foo_get(v8::Local property, const v8::AccessorInfo& info) { - v8::HandleScope scope; - v8::Handle ret; - double result; - - result = Foo; - - ret = v8::Number::New(result); - return scope.Close(ret); -} - -int GlobalVar_Initialize(v8::Handle context) { - - v8::Local global = context->Global(); - global->SetAccessor(v8::String::New("Foo"), Foo_get, Foo_set); - - return 0; -} -~~~~~ - -## Global functions - -~~~~~ - -static double foo(int bla) { - return (bla * 2.1); -} - -v8::Handle wrap_foo(const v8::Arguments &args) { - v8::HandleScope scope; - v8::Handle ret; - - int arg1 ; - double result; - - arg1 = args[0]->Int32Value(); - - result = foo(arg1); - - ret = v8::Number::New(result); - - return scope.Close(ret); -} - -int GlobalFunc_Initialize(v8::Handle context) { - - v8::Local global = context->Global(); - - global->Set(v8::String::NewSymbol("foo"), v8::FunctionTemplate::New(wrap_foo)->GetFunction()); - - return 0; -} -~~~~~ - - -## Namespaces - -~~~~~ - -namespace foo { - static double bar = 42.0; -} - -void foo_bar_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { - v8::HandleScope scope; - - double arg1 ; - arg1 = value->NumberValue(); - foo::bar = arg1; - -} - -v8::Handle foo_bar_get(v8::Local property, const v8::AccessorInfo& info) { - v8::HandleScope scope; - v8::Handle ret; - double result; - - result = foo::bar; - - ret = v8::Number::New(result); - return scope.Close(ret); -} - -int Namespace_Initialize(v8::Handle context) { - - v8::Local global = context->Global(); - - v8::Handle foo = v8::ObjectTemplate::New(); - - foo->SetAccessor(v8::String::New("bar"), foo_bar_get, foo_bar_set); - - global->Set(v8::String::New("foo"), foo->NewInstance()); - return 0; -} - -~~~~~ - -## Class - -~~~~~ - -class A { -public: - A() { - x = 42; - } - - ~A() {} - - double foo(bool a) { - if(a) - return 11.11; - else - return 22.22; - } - - int x; -}; - -v8::Handle A_new(const v8::Arguments& args) { - v8::HandleScope scope; - v8::Handle self = args.Holder(); - A *result; - result = new A(); - self->SetInternalField(0, v8::External::New(result)); - return self; -} - -void A_x_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { - v8::HandleScope scope; - A *arg1; - int arg2; - - arg1 = SWIGV8_UnwrapThisPointer(info.Holder()); - arg2 = value->Int32Value(); - - arg1->x = arg2; - -} - -v8::Handle A_x_get(v8::Local property, const v8::AccessorInfo& info) { - v8::HandleScope scope; - v8::Handle jsresult; - A *arg1; - int result; - - arg1 = SWIGV8_UnwrapThisPointer(info.Holder()); - result = arg1->x; - - jsresult = v8::Int32::New(result); - return scope.Close(jsresult); -} - -v8::Handle wrap_A_foo(const v8::Arguments& args) -{ - v8::HandleScope scope; - v8::Handle jsresult; - A *arg1; - double arg2; - double result; - - arg1 = SWIGV8_UnwrapThisPointer(args.Holder()); - arg2 = args[0]->NumberValue(); - - result = arg1->foo(arg2); - - jsresult = v8::Number::New(result); - return scope.Close(jsresult); -} - -int Class_Initialize(v8::Handle context) { - - v8::Local global = context->Global(); - - v8::Persistent class_A = SWIGV8_CreateClassTemplate("A", A_new); - SWIGV8_AddMemberVariable(class_A, "x", A_x_get, A_x_set); - SWIGV8_AddMemberFunction(class_A, "foo", wrap_A_foo); - - global->Set(v8::String::NewSymbol("A"), class_A->GetFunction()); - - return 0; -} - -~~~~~ - -## Static variables and functions - -Static variables and functions are implemented similar to global ones. -They are added to the class object instead of the class template. -Therefore, these are only accessible via the class object and not via -instances of this class. - -~~~~~ - -class A { -public: - A() { - x = 7; - } - - ~A() {} - - static int foo() { - return 42; - } - - static int x; -}; - -int A::x = 7; - -v8::Handle A_new(const v8::Arguments& args) { - v8::HandleScope scope; - v8::Handle self = args.Holder(); - A *result; - result = new A(); - self->SetInternalField(0, v8::External::New(result)); - return self; -} - -void A_x_set(v8::Local property, v8::Local value, const v8::AccessorInfo& info) { - v8::HandleScope scope; - int arg1; - - arg1 = value->Int32Value(); - - A::x = arg1; - -} - -v8::Handle A_x_get(v8::Local property, const v8::AccessorInfo& info) { - v8::HandleScope scope; - v8::Handle jsresult; - int result; - - result = A::x; - - jsresult = v8::Int32::New(result); - return scope.Close(jsresult); -} - -v8::Handle wrap_A_foo(const v8::Arguments& args) -{ - v8::HandleScope scope; - v8::Handle jsresult; - int result; - - result = A::foo(); - - jsresult = v8::Number::New(result); - return scope.Close(jsresult); -} - -int Class_Initialize(v8::Handle context) { - - v8::Local global = context->Global(); - - v8::Persistent classtempl_A = SWIGV8_CreateClassTemplate("A", A_new); - - v8::Handle class_A = classtempl_A->GetFunction(); - - SWIGV8_AddGlobalVariable(class_A, "x", A_x_get, A_x_set); - SWIGV8_AddGlobalFunction(class_A, "foo", wrap_A_foo); - - global->Set(v8::String::NewSymbol("A"), class_A); - - return 0; -} - -~~~~~ - -## Inheritance - -~~~~~ -class A { -public: - A() {} - - ~A() {} - - double foo() { - return 11.11; - } -}; - -class B: public A { -public: - B() {} - ~B() {} - - int bar() { - return 7; - } -}; - -... (left out function wrappers) ... - -int Class_Initialize(v8::Handle context) { - - v8::Local global = context->Global(); - - v8::Persistent class_A = SWIGV8_CreateClassTemplate("A", A_new); - v8::Persistent class_B = SWIGV8_CreateClassTemplate("B", B_new); - - SWIGV8_AddMemberFunction(class_A, "foo", wrap_A_foo); - SWIGV8_AddMemberFunction(class_B, "bar", wrap_B_bar); - - class_B->Inherit(class_A); - - global->Set(v8::String::NewSymbol("A"), class_A->GetFunction()); - global->Set(v8::String::NewSymbol("B"), class_B->GetFunction()); - - return 0; -} -~~~~~ - -## String arguments - -At a first stage all strings are treated as Utf8. -For proper handling strings as return values I have to study -other modules. - -~~~~~ -int my_strlen(const char* s) { - return strlen(s); -} - -// creates a new string -const char* foo(int a) { - char* result = new char[a+1]; - result[a] = 0; - memset(result, 'a', a); - return result; -} - -v8::Handle wrap_my_strlen(const v8::Arguments& args) -{ - v8::HandleScope scope; - v8::Handle jsresult; - const char* arg1; - int result; - - v8::String::Utf8Value utf8(args[0]); - - result = my_strlen(*utf8); - - jsresult = v8::Number::New(result); - return scope.Close(jsresult); -} - -v8::Handle wrap_foo(const v8::Arguments& args) -{ - v8::HandleScope scope; - v8::Handle jsresult; - int arg1; - const char* result; - - arg1 = args[0]->Int32Value(); - result = foo(arg1); - - jsresult = v8::String::New(result); - - return scope.Close(jsresult); -} - -int Strings_Initialize(v8::Handle context) { - - v8::Local global = context->Global(); - - SWIGV8_AddGlobalFunction(global, "strlen", wrap_my_strlen); - SWIGV8_AddGlobalFunction(global, "foo", wrap_foo); - - return 0; -} -~~~~~ - -------------------------- - -Control flow analysis -===================== - -## Global variables - -### Example: -~~~~ -int x; - -namespace foo { - double y; -} -~~~~ - -### Control flow: -Command: -~~~~ -swig -analyze -c++ functionWrapper +before globalvariableHandler +before example.i -~~~~ - -~~~~ -enter top() of example -enter variableHandler() of x -enter globalvariableHandler() of x - | sym:name - "x" - | name - "x" - | type - "int" - - enter variableWrapper() of x - - enter functionWrapper() of x - | name - "x" - | sym:name - "x_set" - | parms - int - | wrap:action - "x = arg1;" - | type - "void" - exit functionWrapper() of x - - enter functionWrapper() of x - | name - "x" - | sym:name - "x_get" - | type - "int" - exit functionWrapper() of x - exit variableWrapper() of x -exit globalvariableHandler() of x -exit variableHandler() of x - -enter variableHandler() of foo::y -enter globalvariableHandler() of foo::y - | sym:name - "y" - | name - "foo::y" - | type - "double" - - enter variableWrapper() of foo::y - enter functionWrapper() of foo::y - | name - "foo::y" - | sym:name - "y_set" - | parms - double - | wrap:action - "foo::y = arg1;" - | type - "void" - exit functionWrapper() of foo::y - - enter functionWrapper() of foo::y - | name - "foo::y" - | sym:name - "y_get" - | wrap:action - "result = (double)foo::y;" - | type - "double" - exit functionWrapper() of foo::y - exit variableWrapper() of foo::y -exit globalvariableHandler() of foo::y -exit variableHandler() of foo::y -exit top() of example - -~~~~ - -## Simple class - -### Example: - -~~~~ -class A { -public: - A(); - ~A(); -}; - -namespace foo { - class B { - }; -} -~~~~ - -### Control flow: - -~~~~ -enter top() of example - enter classHandler() of A - enter constructorHandler() of A - enter functionWrapper() of A - | name - "A" - | sym:name - "new_A" - | access - "public" - | wrap:action - "result = (A *)new A();" - | type - "p.A" - exit functionWrapper() of A - exit constructorHandler() of A - enter destructorHandler() of ~A - enter functionWrapper() of ~A - | name - "~A" - | sym:name - "delete_A" - | parms - A * - | wrap:action - "delete arg1;" - exit functionWrapper() of ~A - exit destructorHandler() of ~A -exit classHandler() of A -enter classHandler() of foo::B - enter constructorHandler() of foo::B::B - enter functionWrapper() of foo::B::B - | name - "foo::B::B" - | sym:name - "new_B" - | access - "public" - | wrap:action - "result = (foo::B *)new foo::B();" - | type - "p.foo::B" - exit functionWrapper() of foo::B::B - exit constructorHandler() of foo::B::B - enter destructorHandler() of foo::B::~B - enter functionWrapper() of foo::B::~B - | name - "foo::B::~B" - | sym:name - "delete_B" - | parms - foo::B * - | wrap:action - "delete arg1;" - | type - "void" - exit functionWrapper() of foo::B::~B - exit destructorHandler() of foo::B::~B -exit classHandler() of foo::B -exit top() of example - -~~~~ - -### Example - -~~~~ -class A { -public: - int x; -}; -~~~~ - - -### Control flow - -~~~~ -enter top() of example -enter classHandler() of A - enter variableHandler() of x - enter membervariableHandler() of x - enter functionWrapper() of x - | name - "x" - | sym:name - "A_x_set" - | access - "public" - | parms - A *,int - | wrap:action - "if (arg1) (arg1)->x = arg2;" - | type - "void" - | memberset - "1" - exit functionWrapper() of x - enter functionWrapper() of x - | name - "x" - | sym:name - "A_x_get" - | access - "public" - | parms - A * - | wrap:action - "result = (int) ((arg1)->x);" - | type - "int" - | memberset - "1" - | memberget - "1" - exit functionWrapper() of x - exit membervariableHandler() of x - exit variableHandler() of x - enter constructorHandler() of A::A - enter functionWrapper() of A::A - exit functionWrapper() of A::A - exit constructorHandler() of A::A - enter destructorHandler() of A::~A - enter functionWrapper() of A::~A - exit functionWrapper() of A::~A - exit destructorHandler() of A::~A -exit classHandler() of A -exit top() of example -~~~~ - -## Class method - -### Example - -~~~~ -class A { -public: - void foo(int x, double y); -private: - void bar(); -}; -~~~~ - -### Control flow - -~~~~ -enter top() of example -enter classHandler() of A - enter functionHandler() of foo - enter memberfunctionHandler() of foo - enter functionWrapper() of foo - | name - "foo" - | sym:name - "A_foo" - | access - "public" - | parms - A *,int,double - | wrap:action - "(arg1)->foo(arg2,arg3);" - | type - "void" - exit functionWrapper() of foo - exit memberfunctionHandler() of foo - exit functionHandler() of foo -... -exit classHandler() of A -exit top() of example -~~~~ - -## Static class variable and method - -### Example - -~~~~ -class A { -public: - static int x; - - static void foo(); -}; -~~~~ - -### Control flow - -~~~~ -enter top() of example -enter classHandler() of A - enter variableHandler() of x - enter staticmembervariableHandler() of x - enter variableWrapper() of A::x - enter functionWrapper() of A::x - | name - "A::x" - | sym:name - "A_x_set" - | parms - int - | wrap:action - "A::x = arg1;" - | type - "void" - exit functionWrapper() of A::x - enter functionWrapper() of A::x - +++ cdecl ---------------------------------------- - | name - "A::x" - | ismember - "1" - | sym:name - "A_x_get" - | variableWrapper:sym:name - "A_x" - | wrap:action - "result = (int)A::x;" - | type - "int" - exit functionWrapper() of A::x - exit variableWrapper() of A::x - exit staticmembervariableHandler() of x - exit variableHandler() of x - enter functionHandler() of foo - enter staticmemberfunctionHandler() of foo - enter globalfunctionHandler() of A::foo - enter functionWrapper() of A::foo - | name - "A::foo" - | sym:name - "A_foo" - | wrap:action - "A::foo();" - | type - "void" - exit functionWrapper() of A::foo - exit globalfunctionHandler() of A::foo - exit staticmemberfunctionHandler() of foo - exit functionHandler() of foo - enter constructorHandler() of A::A - exit constructorHandler() of A::A - enter destructorHandler() of A::~A - exit destructorHandler() of A::~A -exit classHandler() of A -exit top() of example -~~~~ - -## Inheritance - -### Example - -~~~~ -class A { -}; - -class B: public A { -}; -~~~~ - -### Control flow - -~~~~ -enter top() of example -enter classHandler() of A - +++ class ---------------------------------------- - | name - "A" - | sym:name - "A" -... -exit classHandler() of A -enter classHandler() of B - | name - "B" - | sym:name - "B" - | privatebaselist - 0xf1238f10 - | protectedbaselist - 0xf1238ef0 - | baselist - 0xf1238ed0 - | bases - 0xf1239830 - | allbases - 0xf1239c30 -... -exit classHandler() of B -exit top() of example -~~~~ diff --git a/Doc/Manual/Javascript.md b/Doc/Manual/Javascript.md index a01c630d8..77b7e086b 100644 --- a/Doc/Manual/Javascript.md +++ b/Doc/Manual/Javascript.md @@ -1,1103 +1,264 @@ -% SWIG AND JAVASCRIPT - +% SWIG and Javascript + +This chapter describes SWIG's support of Javascript. + + # Overview -This chapter describes SWIG support for Javascript. -The module is designed to support JavascriptCore and V8 as target engine. -Currently only JavascriptCore support is implemented. -JavaScriptCore is the built-in JavaScript engine for WebKit, whereas V8 is the engine used by Chromium. +JavaScript is a prototype-based scripting language that is dynamic, weakly typed +and has first-class functions. Its arguably the most popular language for web development. +Beyond of being a browser-based scripting language, with [node.js](http://nodejs.org) +Javascript has found its way to a backend development language, too. -JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. Its arguably the most popular language for web development. C++, on the other hand, is statically typed, compiled, general purpose programming language. -The approach I followed here is "Test driven" where I have written the examples/test-cases to be supported for Javascript one-by-one and implemented the required module files in parallel. -The support for Javascript would be added similar to other supported target languages in swig. Swig comes with an "Examples" directory for Javascript like other supported language. The directory contains examples for every supported feature of the target language. There is also a test-suite directory for javascript which contains additional tests. +Native Javascript extensions can be used for applications that embed a web-browser view or +that embed a Javascript engine (such as *node.js*). +Extending a general purpose web-browser is not possible as this would be severe security issue. + +With [WebKit](http://www.webkit.org/) there is an modern and open-source browser +implementations available which can be embedded into an application. +At the moment, [Chromium Embedded Framework](http://code.google.com/p/chromiumembedded/) +can not extended as CEF does not provide access to the V8 engine, but instead comes with +its own extension mechanism. + +SWIG Javasript currently supports **JavascriptCore**, the Javascript engine used by `Safari`, +and **v8**, which is used by `Chromium` and `node.js`. # Preliminaries -In order to use this module, you will need to have installed javascriptcore and you can install it by installing package libwebkit-dev -You can find out some necessary compiler/linker flag by +# Running SWIG - pkg-config javascriptcoregtk-1.0 --cflags --libs +Suppose that you defined a SWIG module such as the following: -## Using the module - -To generate an extension for JavascriptCore one would call swig as follows - -~~~~ - -swig -c++ -javascript -jsc example.i - -~~~~ - -This generates a C++ source file containing the wrapper. - -## How does Javascript talk to C++? - -JavascriptCore provides a C-API which allows to extend a Javascript interpreter with native methods and structures. Normally, this is used to implement the builtin features of the language. However, by extending the interpreter, it is also possible to add your own commands and variables. A reference manual of this API can be found -[here](http://developer.apple.com/library/mac/#documentation/Carbon/Reference/WebKit_JavaScriptCore_Ref/_index.html). - -Typically, when you add a new command to the javascript interpreter you need to do two things: first you need to write a special "wrapper" function that serves as the glue between the interpreter and the underlying C function. Then you need to give the interpreter information about the wrapper by providing details about the name of the function, arguments, and so forth. The next few sections illustrate the process. - -## Wrapper functions - -Suppose you have an ordinary C function like this : - -~~~~ - -int fact(int n) { - if (n <= 1) return 1; - else return n*fact(n-1); -} - -~~~~ - -In order to access this function from a scripting language, it is necessary to write a special "wrapper" function that serves as the glue between the scripting language and the underlying C function. A wrapper function must do three things : - - - Gather function arguments and make sure they are valid. - - Call the C function. - - Convert the return value into a form recognized by the javascript. - -As an example, the javascript wrapper function for the fact() function above example might look like the following : - -~~~~ - -JSValueRef wrap_fact(JSContextRef context, JSObjectRef function, JSObjectRef globalobj, size_t argc, const JSValueRef argv[], JSValueRef* exception) -{ - int arg1 = (int)JSValueToNumber(context, argv[0], NULL); - int arg2 = (int)JSValueToNumber(context, argv[1], NULL); - int result = (int)fact(arg1,arg2); - JSValueRef jsresult = JSValueMakeNumber(context, result); - return jsresult; -} - -~~~~ - -Once you have created a wrapper function, the final step is to tell the javascript about the new function. This is done by register function called by the javascript when the module is loaded. For example, adding the above function to the javascript interpreter requires code like the following : - -~~~~ - -bool jsc_registerFunction(JSGlobalContextRef context, JSObjectRef object, - const char* functionName, JSObjectCallAsFunctionCallback callback) -{ - JSStringRef js_globalvarsclassname = JSStringCreateWithUTF8CString(globalvarsclassname); - JSObjectSetProperty(context,js_globalvarsclassname,JSObjectMakeFunctionWithCallback(context, - js_globalvarsclassname, callback), kJSPropertyAttributeNone,NULL); - JSStringRelease(jsstring); - return true; -} - -int example_init(JSContextRef context) { - JSObjectRef global; - ... - jsc_registerFunction(context, global, "fact", wrap_fact); - ... -} - -~~~~ - -When executed, javascript will now have a new command called "fact" that you can use like any other Javascript command. -Although the process of adding a new function to javascript has been illustrated, the procedure is almost identical for Perl and Python. Both require special wrappers to be written and both need additional initialization code. - -## Variable Linking - -Variable linking refers to the problem of mapping a C/C++ global variable to a variable in the scripting language interpreter. For example, suppose you had the following variable: - -~~~~ - -double Foo = 3.5; - -~~~~ - -To provide such access, variables are commonly manipulated using a pair of get/set functions. For example, whenever the value of a variable is read, a "get" function is invoked. Similarly, whenever the value of a variable is changed, a "set" function is called. - -~~~~ - -bool Foo_set(JSContextRef context, JSObjectRef globalobj, JSStringRef propertyName, JSValueRef value, - JSValueRef* exception) -{ - JSValueRef jsresult; - double arg1 = (double)JSValueToNumber(context, value, NULL); - Foo = arg1; - jscresult = JSValueMakeUndefined(context); - return jsresult; -} - -JSValueRef Foo_get(JSContextRef context, JSObjectRef globalobj, JSStringRef propertyName, JSValueRef* exception) -{ - JSValueRef jsresult; - double result = (double)Foo; - jsresult = JSValueMakeNumber(context, result); - return jsresult; -} - -~~~~ - -In many languages, calls to the get/set functions can be attached to evaluation and assignment operators. Therefore, evaluating a variable such as Foo might implicitly call the get function. Similarly, typing Foo = 4 would call the underlying set function to change the value. - -# A tour of basic C/C++ wrapping - -By default, SWIG tries to build a very natural javascript interface to your C/C++ code. Functions are wrapped as functions, classes are wrapped as classes, and so forth. This section briefly covers the essential aspects of this wrapping. - -## Modules - -The SWIG %module directive specifies the name of the Javascript module. If you specify `%module example`, then everything is wrapped into a Javascript 'example' module. Underneath the covers, this module consists of a cpp source file example.cpp. When choosing a module name, make sure you don't use the same name as a built-in Javascript command or standard module name. - -## Global variables - -C/C++ global variables are fully supported by SWIG. However, the underlying mechanism is somewhat different than you might expect due to the way that javascript works. - -~~~~ - -// SWIG interface file with global variables +```code %module example -... -%inline %{ +%{ +#include "example.h" +%} +int gcd(int x, int y); extern double Foo; -extern int gcd(int x, int y); -%} +``` + +To build a Javascript module, run SWIG using the `-javascript` option +and a desired target engine `-jsc` or `-v8`. + +```shell +$ swig -javascript -jsc example.i +``` + +If building a C++ extension, add the -c++ option: + +```shell +$ swig -c++ -javascript -jsc example.i +``` + +This creates a C/C++ source file example_wrap.c or example_wrap.cxx. The generated C source file contains the low-level wrappers that need to be compiled and linked with the rest of your C/C++ application to create an extension module. + +The name of the wrapper file is derived from the name of the input file. +For example, if the input file is example.i, the name of the wrapper file is example_wrap.c. +To change this, you can use the -o option. +The wrapped module will export one function which must be called to register the module with the Javascript interpreter. +For example, if your module is named `example` the corresponding initializer for JavascriptCore would be + +```code +bool example_initialize(JSGlobalContextRef context, JSObjectRef *exports) +``` + +and for v8: + +```code +void example_initialize (v8::Handle exports) +``` + +# Compilation and Linking + +## Installation + + + +## Dealing with `v8` version incompatibilities + +Unfortunately, v8 does not provide pre-processor macros do detect which version you link to. +Therefore, you have to provide this information manually. + + +# Integration + +This should give a short overview how to integrate your module in different environments: as a `node.js` module, and as an extension for an embedded Chromium. + +## Creating `node.js` Extensions + +As `v8` is written in C++ and comes as a C++ library it is crucial to compile your module using the +same compiler flags as used for building v8. To make things easier, `node.js` provides a build tool called `node-gyp`. + +This expects configuration file named `binding.gyp` which is basically in JSON format and +conforms to the same format that is used with Google's build-tool `gyp`. + +`binding.gyp`: +```code +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} +``` + +First you would create the wrapper using SWIG: + +```shell + +``` + +## Embedded Webkit + + +# Implementation + +The Javascript Module implementation has take a very different approach than other modules +to be able to generate code for different Javascript interpreters. + + +## Module Source Code + +The Javascript module is implemented in `Source/Modules/javascript.cxx`. It contains a SWIG Language class which does represents the module's entry point to the swig engine. +It implements the `Language` interface and dispatches the code generation to a `JSEmitter` instance, `V8Emitter` or `JSCEmitter`. Additionally there are some helpers: `Template`, for templated code generation, and `JSEmitterState`, which is used to manage state information during AST traversal. To find your way through this huge source file, here is a rough map: + +```code +// module wide defines + +#define NAME "name" + ... -~~~~ +// Helper class declarations +class JSEmitterState { ... }; -Now look at the javascript: +class Template { ... }; -~~~~ -print("Global variable Foo=" + example.Foo); -example.Foo = 3.1415926; -print("Variable Foo changed to=" + example.Foo); -print("GCD of x and y is=" + example.gcd(x,y)); +// JSEmitter declaration -~~~~ +class JSEmitter { ... }; -## Constants and enums -C/C++ constants are installed as javascript objects containing the appropriate value. To create a constant, use #define, enum, or the %constant directive. For example: +// Emitter factory declarations -~~~~ +JSEmitter *swig_javascript_create_JSCEmitter(); +JSEmitter *swig_javascript_create_V8Emitter(); -#define ICONST 42 -#define FCONST 2.1828 -%constant int iconst = 37; -~~~~ +// Javascript module class declaration -In javascript they are treated as: +class JAVASCRIPT:public Language { ... }; -~~~~ -print("ICONST = " + example.ICONST + " (should be 42)\n"); -print("FCONST = " + example.FCONST + " (should be 2.1828)\n"); -print("iconst = " + example.iconst + " (should be 37)\n"); +// Javascript module function definitions -~~~~ +int JAVASCRIPT::functionWrapper(Node *n) { ... } -For enums, make sure that the definition of the enumeration actually appears in a header file or in the wrapper file somehow---if you just stick an enum in a SWIG interface without also telling the C compiler about it, the wrapper code won't compile. -Enums are treated as constants.So if we have enums in c++ as: - -~~~~ - -void enum_test(color c, Foo::speed s); - -~~~~ - -In javascript they are treated as: - -~~~~ - -example.enum_test(example.RED, example.Foo.IMPULSE); -example.enum_test(example.BLUE, example.Foo.WARP); -example.enum_test(example.GREEN, example.Foo.LUDICROUS); - -~~~~ - -### Inside the class -For class enums as below: - -~~~~ - -class Foo { -public: -Foo() { } -enum speed { IMPULSE, WARP, LUDICROUS }; -} - -~~~~ - -In javascript they are treated as: - -~~~~ - -print(" Foo_IMPULSE =" + example.Foo.IMPULSE); -print(" Foo_WARP =" + example.Foo.WARP); -print(" Foo_LUDICROUS =" + example.Foo.LUDICROUS); - -~~~~ - -## Pointers - -C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Here is a rather simple interface - -~~~~ - -/* File : example.i */ -%module example -%{ -extern void add(int *, int *, int *); -%} - -~~~~ - -When wrapped, you will be able to use the functions in a natural way from javascript. For example: - -~~~~ - -// Call the add() function with some pointers -example.add(a, b, c); - -~~~~ - -// In javascript the code look like as: - -~~~~ - -a = example.new_intp(); -example.intp_assign(a,37); - -~~~~ - -- The first one creates an int-pointer instance. -- The second one assigns it the value 37. - -### C++ classes - -C++ classes are wrapped by javascript classes as well. For example, if you have this class, - -~~~~ - -class Circle -{ -public: - Circle(); - Circle(double r); - double area(); - double radius; -}; - -~~~~ - -you can use it in javascript like this: - -~~~~ - -print("Creating some objects:"); -c = new example.Circle(10); -print("area = " + c.area()); - -~~~~ - -Class data members are accessed in the same manner as C structures. - -Static class members and functions are mapped to javascript in a straight-forward manner: - -~~~~ - -class Spam { -public: - static void foo(); - static int bar; -}; - -~~~~ - -In javascript, the static member can be access in this way: - -~~~~ - -// ----- Access a static member ----- -print("\nA access of static member is" + example.Spam.Foo); // access static member as properties of the class object. - -~~~~ - -## C++ inheritance - -SWIG is fully aware of issues related to C++ inheritance. Therefore, if you have classes like this - -~~~~ - -class A { -public: - void foo(); - virtual void bar(); -}; -class B: public A { -public: - virtual void bar(); -}; - -~~~~ - -Those classes are wrapped into a hierarchy of javascript classes that reflect the same inheritance structure. All of the usual javascript utility functions work normally: - -~~~~ - -var a = new example.A(); -a.foo(); -a.bar(); -var b = new example.B(); -b.foo(); -b.bar(); -print("b.cPtr = " + b.getCPtr()); - -~~~~ - -## C++ overloaded functions - -C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example, if you have two functions like this: - -~~~~ - -void f(int val) { - std::cout << "Called f(int)." << std::endl; -} -void f(int val1, int val2) { - std::cout << "Called f(int, int)." << std::endl; -} -void f(const char* s) { - std::cout << "Called f(const char*)." << std::endl; -} - -~~~~ - -You can use them in javascript in a straightforward manner: - -~~~~ - -example.f(1); -example.f(1, 2); -example.f("bla"); - -~~~~ - -## C++ operators - -Certain C++ overloaded operators can be handled automatically by SWIG. Though, in javascript operator overloading is not possible. Instead one has to make use of the `%rename` feature. - -For example, consider a class like this: - -~~~~ - -/* File : example.h */ -#include -class Complex { -private: - double rpart, ipart; -public: - Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { } - Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { } - Complex &operator=(const Complex &c) { - rpart = c.rpart; - ipart = c.ipart; - return *this; - } - Complex operator+(const Complex &c) const { - return Complex(rpart+c.rpart, ipart+c.ipart); - } - Complex operator-(const Complex &c) const { - return Complex(rpart-c.rpart, ipart-c.ipart); - } - Complex operator*(const Complex &c) const { - return Complex(rpart*c.rpart - ipart*c.ipart, - rpart*c.ipart + c.rpart*ipart); - } - Complex operator-() const { - return Complex(-rpart, -ipart); - } - - double re() const { return rpart; } - double im() const { return ipart; } -}; - -~~~~ - -When wrapped, it works like you expect: - -~~~~ - -a = new example.Complex(2,3); -b = new example.Complex(-5,10); - -print ("a =" + a); -print ("b =" + b); - -c = a.plus(b); - -print("c =" + c); -print("a*b =" + a.times(b)); -print("a-c =" + a.minus(c)); - -e = example.Complex.copy(a.minus(c)); -print("e =" + e); - -// Big expression -f = a.plus(b).times(c.plus(b.times(e))).plus(a.uminus()); -print("f =" + f); - -~~~~ - -One restriction with operator overloading support is that SWIG is not able to fully handle operators that aren't defined as part of the class. For example, if you had code like this - -~~~~ - -class Complex { -... -friend Complex operator+(double, const Complex &c); -... -}; - -~~~~ - -then SWIG ignores it and issues a warning. You can still wrap the operator, but you may have to encapsulate it in a special function. For example: - -%rename(Complex_add_dc) operator+(double, const Complex &); - -There are ways to make this operator appear as part of the class using the %extend directive. - -## C++ namespaces: - -SWIG is aware of C++ namespaces, but namespace names do not appear in the module nor do namespaces result in a module that is broken up into submodules or packages. For example, if you have a file like this, - -~~~~ - -%module example -namespace nspace { -extern int gcd(int x, int y); -extern double Foo; -class Circle -{ -public: - Circle(); - Circle(double r); - double area(); - double radius; - }; -} - -~~~~ - -for namespaces, you use the %feature directive in interface file. %feature attaches a new attribute to any parse tree node that matches given prototype. - -~~~~ - -/* File : example.i */ -%module example -%{ -#include "example.h" -%} -%feature("nspace", 1); -%include "example.h" - -~~~~ - -it works in javascript as follows: - -~~~~ - -print("Global variable Foo=" + example.nspace.Foo); -example.nspace.Foo = 5; -print("Variable Foo changed to " + example.nspace.Foo); -print("GCD of number 6,18 is " + example.nspace.gcd(6,18)); -print("Creating some objects:"); -c = new example.nspace.Circle(10); -print("area = " + c.area()); - -~~~~ - -If your program has more than one namespace, name conflicts (if any) can be resolved using %rename For example: - -~~~~ - -%rename(Bar_spam) Bar::spam; -namespace Foo { - int spam(); -} -namespace Bar { - int spam(); -} - -~~~~ - -If you have more than one namespace and your want to keep their symbols separate, consider wrapping them as separate SWIG modules. For example, make the module name the same as the namespace and create extension modules for each namespace separately. If your program utilizes thousands of small deeply nested namespaces each with identical symbol names, well, then you get what you deserve. -SWIG resolves overloaded functions and methods using a disambiguation scheme that ranks and sorts declarations according to a set of type-precedence rules. The order in which declarations appear in the input does not matter except in situations where ambiguity arises--in this case, the first declaration takes precedence. - -## C++ templates - -C++ templates don't present a huge problem for SWIG. However, in order to create wrappers, you have to tell SWIG to create wrappers for a particular template instantiation. To do this, you use the %template directive. For example: - -~~~~ - -/* File : example.i */ -%module example -%{ -#include "example.h" -%} -/* Let's just grab the original header file here */ -%include "example.h" - -/* Now instantiate some specific template declarations */ -%template(maxint) max; -%template(maxdouble) max; -%template(vecint) vector; -%template(vecdouble) vector; - -~~~~ - -In javascript: - -~~~~ - -//Call some templated functions -print(example.maxint(3,7)); -print(example.maxdouble(3.14,2.18)); - -// Create some class - -iv = new example.vecint(100); -dv = new example.vecdouble(1000); - -for(i=0;i<=100;i++) - iv.setitem(i,2*i); - -for(i=0;i<=1000;i++) - dv.setitem(i, 1.0/(i+1)); - -sum = 0; -for(i=0;i<=100;i++) - sum = sum + iv.getitem(i); - -print(sum); - -sum = 0.0; -for(i=0;i<=1000;i++) - sum = sum + dv.getitem(i); -print(sum); - -~~~~ - -## Exception handling - -The SWIG %exception directive can be used to create a user-definable exception handler for converting exceptions in your C/C++ program into javascript exceptions. The chapter on customization features contains more details, but suppose you have a C++ class like the following: - -Since several methods in this class can throw an exception for an out-of-bounds access, you might want to catch this in the javascript extension by writing the following in an interface file: - -~~~~ - -/* File : example.i */ -%module example -%{ -#include "example.h" -%} -%include "std_string.i" - -/* Let's just grab the original header file here */ -%include "example.h" - -~~~~ - -Actually in JS there is no support for typed exceptions.For now there is support for integer and string -exception. Example for integer exception - -~~~~ - -JSValueRef jsc_gcd(JSContextRef context, JSObjectRef function, JSObjectRef globalobj, size_t argc, const JSValueRef argv[], JSValueRef* exception) -{ -int arg1 = (int)JSValueToNumber(context, argv[0], NULL); -int arg2 = (int)JSValueToNumber(context, argv[1], NULL); -*exception = JSValueMakeNumber(context, 13); -int result = (int)gcd(arg1,arg2); -JSValueRef jsresult = JSValueMakeNumber(context, result); - -~~~~ - -and for string exception: - -~~~~ - -JSValueRef wrap_gcd(JSContextRef context, JSObjectRef function, JSObjectRef globalobj, size_t argc, const JSValueRef argv[], JSValueRef* exception) -{ -int arg1 = (int)JSValueToNumber(context, argv[0], NULL); -int arg2 = (int)JSValueToNumber(context, argv[1], NULL); -JSStringRef message = JSStringCreateWithUTF8CString("This is a test error."); -*exception = JSValueMakeString(context, message); -JSStringRelease(message); -int result = (int)gcd(arg1,arg2); -JSValueRef jscresult = JSValueMakeNumber(context, result); -return jsresult; -} - -~~~~ - -## How to use generated modules? - -Basically there is no standard extension mechanism in Javascript. We provided a custom interpreter with extension abilities. If JSC is embedded into a custom application, one has to make use of a generated module initializer function that allows easy extension of interpreter. -The basic approach is as follows: - -### Basic Mechanism -- Creating the context -- Calling module initializer -- Evaluate Javascript - -#### Creating the context - -~~~~ - -JSGlobalContextRef context = JSGlobalContextCreate(NULL); -JSObjectRef globalObject = JSContextGetGlobalObject(context); ... -~~~~ -### Calling module initializer +// Module factory implementations -~~~~ +static Language *new_swig_javascript() { ... } - extern int example_init(JSGlobalContextRef context); - ... - example_init(context); - ... +extern "C" Language *swig_javascript(void) { ... } -~~~~ -### Evaluate Javascript +// JSEmitter implementation -~~~~ +JSEmitter::JSEmitter() { ... } -// Evaluate the javascript -char* scriptContent = jsccreateStringWithContentsOfFile(scriptPath.c_str()); -JSStringRef jsScript; -if(!scriptContent) { - printf("FAIL: runme script could not be loaded.\n"); - failed = 1; - } - else { - JSValueRef ex; - jsScript = JSStringCreateWithUTF8CString(scriptContent); - JSValueRef jsResult = JSEvaluateScript(context, jsScript, 0, 0, 0, &ex); - if (!jsResult && ex) { - jsc_printError(context, ex, scriptPath); - failed = 1; - } - } - if (scriptContent != NULL) { - free(scriptContent); - } - JSStringRelease(jsScript); - JSGlobalContextRelease(context); - globalObject = 0; - for(std::vector::iterator it = loaded_modules.begin(); - it != loaded_modules.end(); ++it) { - HANDLE handle = *it; - dlclose(handle); - } - if (failed) { - printf("FAIL: Some tests failed.\n"); - return 1; - } -} +Template JSEmitter::getTemplate(const String *name) { ... } -~~~~ +... -## Typemaps -A typemap is nothing more than a code generation rule that is attached to a specific C datatype. For example, to convert integers from javascript to C, you might define a typemap like this: +// JSCEmitter declaration -~~~~ +class JSCEmitter: public JSEmitter { ... }; -%typemap(in) int { - $1 = ($1_ltype)JSValueToNumber(context, $input, NULL); %} - printf("Received an integer : %d\n",$1); -} -~~~~ +// JSCEmitter implementation -Typemaps are always associated with some specific aspect of code generation. In this case, the "in" method refers to the conversion of input arguments to C/C++. The datatype int is the datatype to which the typemap will be applied. The supplied C code is used to convert values. In this code a number of special variable prefaced by a $ are used. The $1 variable is placeholder for a local variable of type int. +JSCEmitter::JSCEmitter() { ... } -## Javascript typemaps +void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) { ... } -The previous section illustrated an "in" typemap for converting javascript objects to C. A variety of different typemap methods are defined by the javascript module. For example, to convert a C integer back into a javascript object, you might define an "out" typemap like this: +... -~~~~ -%typemap(out) int { - $result = JSValueMakeNumber(context, $1); -} +// JSCEmitter factory -~~~~ +JSEmitter *swig_javascript_create_JSCEmitter() { ... } -The Javascript module makes use of Swig's unified template library. -## Typemap variables +// V8Emitter declaration -Within typemap code, a number of special variables prefaced with a $ may appear. A full list of variables can be found in the "Typemaps" chapter. This is a list of the most common variables: +class V8Emitter: public JSEmitter { ... }; -`$1`: -A C local variable corresponding to the actual type specified in the %typemap directive. For input values, this is a C local variable that's supposed to hold an argument value. For output values, this is the raw result that's supposed to be returned to Javascript. -`$input`: -A javascript Object * holding a raw javascript object with an argument or variable value. +// V8Emitter implementation -`$result`: -A javascript Object * that holds the result to be returned to javascript. +V8Emitter::V8Emitter() { ... } -`$1_name`: -The parameter name that was matched. +int V8Emitter::initialize(Node *n) { ... } -`$1_type`: -The actual C datatype matched by the typemap. -`$1_ltype`: -An assignable version of the datatype matched by the typemap (a type that can appear on the left-hand-side of a C assignment operation). This type is stripped of qualifiers and may be an altered version of `$1_type`. All arguments and local variables in wrapper functions are declared using this type so that their values can be properly assigned. +// V8Emitter factory -`$symname`: -The javascript name of the wrapper function being created. +JSEmitter *swig_javascript_create_V8Emitter() { ... } -# Javascript: Specification of a Code Generator for JSC -The module implementation tries to accomplish a separation of logic and code generation by making -use of code templates. In the following, the templates are explained. +// Helper implementation (JSEmitterState, Template) -# Top Level structure +JSEmitterState::JSEmitterState() { ... } -The generated code consists of the following blocks: +... -~~~~ +Template::Template(const String *code_) { ... } - - - - - +``` -~~~~ +## Code Templates -- `RUNTIME`: runtime code generated by swig -- `HELPER_FUNCTIONS`: static, from swg-file -- `INCLUDES`: static, module property -- `FUNCTION_WRAPPERS`: dynamically growing, on method declarations -- `INITIALIZER`: dynamically growing, aggregates everything +All generated code is created on the basis of code templates. +The templates for *JavascriptCore* can be found in `Lib/javascript/jsc/javascriptcode.swg`, +for *v8* in `Lib/javascript/v8/javascriptcode.swg`. -## INCLUDES +To track the originating code template for generated code you can run -~~~~ +```shell +swig -javascript -jsc -debug-codetemplates +``` -#include - +which wraps generated code with a descriptive comment -~~~~ +```code +/* begin fragment("temlate_name") */ -`USER_DEFINED_INCLUDES`: a module property +...generated code ... -## `HELPER_FUNCTIONS` +/* end fragment("temlate_name") */ +``` -A lot of boiler-plate code can be shifted into static helper functions: +The Template class is used like this: -~~~~ +```code + Template t_register = getTemplate("jsv8_register_static_variable"); + t_register.replace("$jsparent", state.clazz(NAME_MANGLED)) + .replace("$jsname", state.variable(NAME)) + .replace("$jsgetter", state.variable(GETTER)) + .replace("$jssetter", state.variable(SETTER)) + .trim(). + print(f_init_static_wrappers); +``` -bool JS_registerClass(JSGlobalContextRef& context, JSObjectRef& parentObject,const char* className, - JSClassDefinition* definition) { - JSStringRef js_className = JSStringCreateWithUTF8CString(className); - JSObjectRef classObject = JSObjectMake(context, JSClassCreate(definition), NULL); - JSObjectSetProperty(context, parentObject,js_className, classObject,kJSPropertyAttributeNone, NULL); - JSStringRelease(js_className); - return true; -} +The code template is registered to the *JSEmitter* via +`Template::replace` does simple -bool JS_registerNamespace(JSGlobalContextRef& context,JSObjectRef& namespaceObj,JSObjectRef& parentNamespace,const char* name) -{ - JSStringRef js_name = JSStringCreateWithUTF8CString(name); - JSObjectSetProperty(context, parentNamespace,js_name, namespaceObj,kJSPropertyAttributeNone, NULL); - JSStringRelease(js_name); - return true; -} - -bool JS_registerFunction(JSGlobalContextRef context, JSObjectRef object, const char* functionName, JSObjectCallAsFunctionCallback callback) -{ - JSStringRef js_functionName = JSStringCreateWithUTF8CString(functionName); - JSObjectSetProperty(context,object,js_functionName,JSObjectMakeFunctionWithCallback(context, - js_functionName, callback), kJSPropertyAttributeNone, NULL); - JSStringRelease(js_functionName); - return true; -} -bool JS_veto_set_variable(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) -{ - char buffer[256]; - char msg[512]; - int res; - JSStringGetUTF8CString(propertyName, buffer, 256); - res = sprintf(msg, "Tried to write read-only variable: %s.", buffer); - if(res<0) { - SWIG_exception(SWIG_ERROR, "Tried to write read-only variable."); - } else { - SWIG_exception(SWIG_ERROR, msg); - } - return false; -} - -JSValueRef JS_CharPtrToJSValue(JSContextRef context, char* cstr) { - JSValueRef val; - JSStringRef jsstring = JSStringCreateWithUTF8CString((char*) cstr); - val = JSValueMakeString(context, jsstring); - JSStringRelease(jsstring); - return val; -} - -~~~~ - -## `FUNCTION_WRAPPERS` - -There are different types of function wrappers: -- Member Functions -- Getproperty / Setproperty -- Global Functions (global/namespace/class) -- Constructors / Destructors - - -## Member Functions - -~~~~ - -JSValueRef ${functionname}(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) -{ - ${LOCALS} - ${CODE} - return jsresult; - - goto fail; - fail: - return NULL; -} - -~~~~ - -- `functionname`: the name of generated wrapper for function -- `LOCALS`: declarations for input arguments -- `CODE`: contains input marshalling, the action, and output marshalling - -## Setproperty - -~~~~ - -bool ${setname}(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) -{ - ${LOCALS} - ${CODE} - return jsresult; - - goto fail; - fail: - return NULL; -} - -~~~~ - -- `setname`: the name of the generated wrapper for setproperty. -- `LOCALS`: declarations for input arguments -- `CODE`: contains input marshalling, and the action - -## Getproperty - -~~~~ - -JSValueRef ${getname}(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) -{ - ${LOCALS} - ${CODE} - return jsresult; - - goto fail; - fail: - return NULL; -} - -~~~~ - -- `getname`: the name of the generated wrapper for the getproperty -- `LOCALS`: declarations for output arguments -- `CODE`: contains the action, and output marshalling - - -## Global Functions - -~~~~ - -JSStaticValue ${namespace}_values[] = { - ${jsglobalvariables} - { 0, 0, 0, 0 } -}; -JSStaticFunction ${namespace}_functions[] = { - ${jsglobalfunctions} - { 0, 0, 0 } -}; -JSClassDefinition ${namespace}_classDefinition; - -~~~~ - -## Variable declaration - -~~~~ - -{"${propertyname}",${getname}, ${setname}, kJSPropertyAttributeNone} - -~~~~ - -This is used to fill variable definition tables. -`kJSPropertyAttributeNone` is JSC specific and means that the variable has a getter and setter. -Even for read-only variables a setter is used which throws an exception. - -## Constructor - -~~~~ - -JSObjectRef _wrap_create_${classname_mangled}${overloadext}(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) -{ - ${LOCALS} - ${CODE} - return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_${type_mangled}, SWIG_POINTER_OWN); - - goto fail; - fail: - return NULL; -} - -~~~~ -- `classname_mangled` is the mangled qualified class name, e.g., `foo::A -> foo_A` -- `LOCALS`: declarations for input arguments -- `CODE`: contains input marshalling, and the action - -## Destructors - -~~~~ - -void _wrap_${classname_mangled}_finalize(JSObjectRef thisObject) -{ - SWIG_PRV_DATA* t = (SWIG_PRV_DATA*)JSObjectGetPrivate(thisObject); - if(t && t->swigCMemOwn) delete (${type}*)(t->swigCObject); - if(t) delete t; -} - -~~~~ - -- `classname_mangled` is the mangled qualified class name, e.g., `foo::A -> foo_A` - -## Initializer - -~~~~ - -bool ${modulename}_initialize(JSGlobalContextRef context) { - SWIG_InitializeModule(0); - - JSObjectRef global_object = JSContextGetGlobalObject(context); - - /* Initialize the base swig type object */ - _SwigObject_objectDefinition.staticFunctions = _SwigObject_functions; - _SwigObject_objectDefinition.staticValues = _SwigObject_values; - _SwigObject_classRef = JSClassCreate(&_SwigObject_objectDefinition); - - /* Create objects for namespaces */ - ${create_namespaces} - - /* Create classes */ - ${initializercode} - - /* Register namespaces */ - ${register_namespaces} - - return true; -} - -~~~~ - -## Class template defintions - -A class is specified by a static part (`*_classDefinition`) and a dynamic part (`*_objectDefinition`). - -~~~~ - -${classname_mangled}_classDefinition.staticFunctions = ${classname_mangled}_staticFunctions; - ${classname_mangled}_classDefinition.staticValues = ${classname_mangled}_staticValues; - ${classname_mangled}_classDefinition.callAsConstructor = _wrap_create_${classname_mangled}; - ${classname_mangled}_objectDefinition.staticValues = ${classname_mangled}_values; - ${classname_mangled}_objectDefinition.staticFunctions = ${classname_mangled}_functions; - ${classname_mangled}_objectDefinition.parentClass = ${base_classname}_classRef; - JSClassRef ${classname_mangled}_classRef = JSClassCreate(&${classname_mangled}_objectDefinition); - SWIGTYPE_${classtype_mangled}->clientdata = ${classname_mangled}_classRef;%} - -~~~~ - -Notes: -- `classname_mangled` is the mangled qualified class name, e.g., `foo::A -> foo_A` - which is retrieved by `Swig_name_mangle(Getattr(n, "name"))` -- ClassDefinitions are built using the staticValues array and the staticFunction array. The staticValues and staticFunctions arrays are the simplest and most efficient means for vending custom properties to the class object. - -## Inheritance - -~~~~ - -{${classname_mangled}_objectDefinition.parentClass = ${base_classname}_classRef}; - -~~~~ - -- `classname_mangled` is the mangled qualified class name, e.g., `foo::A -> foo_A` -- Note: multiple inheritance is not possible; thus we will always take the first parent class - -## Namespaces - -Namespaces are objects without class templates. i.e., instances are created, referenced locally, used as contexts for other registrations, and stored in the according parent contexts. - -~~~~ - - ${namespace}_classDefinition.staticFunctions = ${namespace}_functions; - ${namespace}_classDefinition.staticValues = ${namespace}_values; - JSObjectRef ${namespace}_object = JSObjectMake(context, JSClassCreate(&${namespace}_classDefinition), NULL); - -~~~~ - -## Registration - -The registration part consists of registering classes at contexts (i.e., global or namespace), methods and properties at classes or contexts, and namespaces as objects at parent contexts. - -* Global functions - -~~~~ - -JS_registerFunction(${context}, ${context_object}, "${functionname}", ${functionwrapper} - -~~~~ - -* Classes - -~~~~ - -JS_registerClass(context, ${namespace}_object, "${classname}", &${classname_mangled}_classDefinition) - -~~~~ - -Note: every class template has an associated constructor function wrapper, which is registered here - -* Namespaces - -~~~~ - -${namespace}_classDefinition.staticFunctions = ${namespace}_functions; -${namespace}_classDefinition.staticValues = ${namespace}_values; -JSObjectRef ${namespace}_object = JSObjectMake(context, JSClassCreate(&${namespace}_classDefinition), NULL); - -~~~~ - -Namespaces are registered using: - -~~~~ - -JS_registerNamespace(context, ${namespace}_object, ${parent_namespace}_object, "${namespace}"); - -~~~~ +## Emitter diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 70bb12f68..b8d36e21f 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -23,6 +23,17 @@ bool js_template_enable_debug = false; #define DTOR "dtor" #define ARGCOUNT "wrap:argc" +// keys for global state variables +#define CREATE_NAMESPACES "create_namespaces" +#define REGISTER_NAMESPACES "register_namespaces" +#define INITIALIZER "initializer" + +// keys for class scoped state variables +#define MEMBER_VARIABLES "member_variables" +#define MEMBER_FUNCTIONS "member_functions" +#define STATIC_FUNCTIONS "static_functions" +#define STATIC_VARIABLES "static_variables" + /** * A convenience class to manage state variables for emitters. * The implementation delegates to swig Hash DOHs and provides @@ -274,15 +285,15 @@ protected: File *f_wrappers; }; -/********************************************************************** - * JAVASCRIPT: swig module implementation - **********************************************************************/ - /* factory methods for concrete JSEmitters: */ JSEmitter *swig_javascript_create_JSCEmitter(); JSEmitter *swig_javascript_create_V8Emitter(); +/********************************************************************** + * JAVASCRIPT: swig module implementation + **********************************************************************/ + class JAVASCRIPT:public Language { public: @@ -1411,17 +1422,6 @@ private: }; -// keys for global state variables -#define CREATE_NAMESPACES "create_namespaces" -#define REGISTER_NAMESPACES "register_namespaces" -#define INITIALIZER "initializer" - -// keys for class scoped state variables -#define MEMBER_VARIABLES "member_variables" -#define MEMBER_FUNCTIONS "member_functions" -#define STATIC_FUNCTIONS "static_functions" -#define STATIC_VARIABLES "static_variables" - JSCEmitter::JSCEmitter() : JSEmitter(), NULL_STR(NewString("NULL")), From 02c55fc52fb30da3cec7188b64d456c7dcf8fc9f Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Thu, 13 Feb 2014 21:18:06 +0100 Subject: [PATCH 0559/1048] Next iteration on creating a documentation for the Javascript module. --- Doc/Manual/Javascript.md | 202 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 196 insertions(+), 6 deletions(-) diff --git a/Doc/Manual/Javascript.md b/Doc/Manual/Javascript.md index 77b7e086b..e1622aa88 100644 --- a/Doc/Manual/Javascript.md +++ b/Doc/Manual/Javascript.md @@ -1,7 +1,7 @@ % SWIG and Javascript This chapter describes SWIG's support of Javascript. - +It does not cover SWIG basics only information that is specific to this module. # Overview @@ -17,7 +17,7 @@ Extending a general purpose web-browser is not possible as this would be severe With [WebKit](http://www.webkit.org/) there is an modern and open-source browser implementations available which can be embedded into an application. At the moment, [Chromium Embedded Framework](http://code.google.com/p/chromiumembedded/) -can not extended as CEF does not provide access to the V8 engine, but instead comes with +can not be extended as CEF does not provide access to the V8 engine, but instead comes with its own extension mechanism. SWIG Javasript currently supports **JavascriptCore**, the Javascript engine used by `Safari`, @@ -69,6 +69,15 @@ and for v8: void example_initialize (v8::Handle exports) ``` +## Missing features + +The Javascript module is not yet as mature as other modules and some things are still missing. +As it makes use of Swigs Unified typemap library (UTL), many typemaps are inherited. + +- Director support +- TODO: there is more + + # Compilation and Linking ## Installation @@ -113,6 +122,7 @@ First you would create the wrapper using SWIG: ## Embedded Webkit +TODO: Here a minimal example of how to implement # Implementation @@ -122,8 +132,9 @@ to be able to generate code for different Javascript interpreters. ## Module Source Code -The Javascript module is implemented in `Source/Modules/javascript.cxx`. It contains a SWIG Language class which does represents the module's entry point to the swig engine. -It implements the `Language` interface and dispatches the code generation to a `JSEmitter` instance, `V8Emitter` or `JSCEmitter`. Additionally there are some helpers: `Template`, for templated code generation, and `JSEmitterState`, which is used to manage state information during AST traversal. To find your way through this huge source file, here is a rough map: +The Javascript module is implemented in `Source/Modules/javascript.cxx`. +It dispatches the code generation to a `JSEmitter` instance, `V8Emitter` or `JSCEmitter`. Additionally there are some helpers: `Template`, for templated code generation, and `JSEmitterState`, which is used to manage state information during AST traversal. +This is a rough map shall make it easier to find a way through this huge source file: ```code // module wide defines @@ -257,8 +268,187 @@ The Template class is used like this: print(f_init_static_wrappers); ``` -The code template is registered to the *JSEmitter* via -`Template::replace` does simple +A code template is registered with the *JSEmitter* via `fragment(name, "template")`, e.g., + +```code +%fragment ("jsc_variable_declaration", "templates") +%{ + {"$jsname", $jsgetter, $jssetter, kJSPropertyAttributeNone}, +%} +``` + +`Template` creates a copy of that string and `Template::replace` uses Swig's `Replaceall` +to replace variables in the template. `Template::trim` can be used to eliminate +leading and trailing whitespaces. `Template::print` is used to write the final template string +to a Swig `DOH` (based on `Printv`). All methods allow chaining. ## Emitter + +The Javascript module delegates code generation to a `JSEmitter` instance. +The following extract shows the essential interface: + +```code +class JSEmitter { + ... + + /** + * Opens output files and temporary output DOHs. + */ + virtual int initialize(Node *n); + + /** + * Writes all collected code into the output file(s). + */ + virtual int dump(Node *n) = 0; + + /** + * Cleans up all open output DOHs. + */ + virtual int close() = 0; + + ... + + /** + * Invoked at the beginning of the classHandler. + */ + virtual int enterClass(Node *); + + /** + * Invoked at the end of the classHandler. + */ + virtual int exitClass(Node *) { + return SWIG_OK; + }; + + /** + * Invoked at the beginning of the variableHandler. + */ + virtual int enterVariable(Node *); + + /** + * Invoked at the end of the variableHandler. + */ + virtual int exitVariable(Node *) { + return SWIG_OK; + }; + + /** + * Invoked at the beginning of the functionHandler. + */ + virtual int enterFunction(Node *); + + /** + * Invoked at the end of the functionHandler. + */ + virtual int exitFunction(Node *) { + return SWIG_OK; + }; + + /** + * Invoked by functionWrapper callback after call to Language::functionWrapper. + */ + virtual int emitWrapperFunction(Node *n); + + /** + * Invoked from constantWrapper after call to Language::constantWrapper. + **/ + virtual int emitConstant(Node *n); + + /** + * Registers a given code snippet for a given key name. + * + * This method is called by the fragmentDirective handler + * of the JAVASCRIPT language module. + **/ + int registerTemplate(const String *name, const String *code); + + /** + * Retrieve the code template registered for a given name. + */ + Template getTemplate(const String *name); + + State &getState(); + + ... + +} +``` + +The module calls `initialize`, `dump`, and `close` from within the `top` method: + +```code +int JAVASCRIPT::top(Node *n) { + emitter->initialize(n); + + Language::top(n); + + emitter->dump(n); + emitter->close(); + + return SWIG_OK; +} +``` + +The methods `enterClass` and `exitClass` are called from within the `classHandler` method: + +```code +int JAVASCRIPT::classHandler(Node *n) { + + emitter->enterClass(n); + Language::classHandler(n); + emitter->exitClass(n); + + return SWIG_OK; +} +``` + +In `enterClass` the emitter stores state information that is necessary when processing class members. In `exitClass` the wrapper code for the whole class is generated. + + +## Emitter states + +For storing information during the AST traversal the emitter provides a `JSEmitterState` with +different slots to store data representing the scopes global, class, function, and variable. + +```code +class JSEmitterState { + +public: + + JSEmitterState(); + + ~JSEmitterState(); + + DOH *global(); + + DOH *global(const char* key, DOH *initial = 0); + + DOH *clazz(bool reset = false); + + DOH *clazz(const char* key, DOH *initial = 0); + + DOH *function(bool reset = false); + + DOH *function(const char* key, DOH *initial = 0); + + DOH *variable(bool reset = false); + + DOH *variable(const char* key, DOH *initial = 0); + + static int IsSet(DOH *val); + + ... +}; +``` + +When entering a scope, such as in `enterClass`, the corresponding state is reset and new data +is stored: + +```code + state.clazz(RESET); + state.clazz(NAME, Getattr(n, "sym:name")); +``` + +State information can be retrieved using `state.clazz(NAME)` or +with `Getattr` on `state.clazz()` which actually returns a `Hash` instance. From b83d285793be072a6e6088a5c16f59b24cd68d5d Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 13 Feb 2014 22:05:10 +0000 Subject: [PATCH 0560/1048] 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 fa8b350cd67a8850a866ee52250a6955ef17699f Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 14 Feb 2014 00:00:12 +0100 Subject: [PATCH 0561/1048] More Javascript module documentation. --- Doc/Manual/Javascript.md | 425 ++++++++++++++++++--------------------- 1 file changed, 193 insertions(+), 232 deletions(-) diff --git a/Doc/Manual/Javascript.md b/Doc/Manual/Javascript.md index e1622aa88..b571e05c3 100644 --- a/Doc/Manual/Javascript.md +++ b/Doc/Manual/Javascript.md @@ -1,9 +1,9 @@ -% SWIG and Javascript +# SWIG and Javascript This chapter describes SWIG's support of Javascript. It does not cover SWIG basics only information that is specific to this module. -# Overview +## Overview JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. Its arguably the most popular language for web development. @@ -14,42 +14,36 @@ Native Javascript extensions can be used for applications that embed a web-brows that embed a Javascript engine (such as *node.js*). Extending a general purpose web-browser is not possible as this would be severe security issue. -With [WebKit](http://www.webkit.org/) there is an modern and open-source browser -implementations available which can be embedded into an application. -At the moment, [Chromium Embedded Framework](http://code.google.com/p/chromiumembedded/) -can not be extended as CEF does not provide access to the V8 engine, but instead comes with -its own extension mechanism. - SWIG Javasript currently supports **JavascriptCore**, the Javascript engine used by `Safari`, and **v8**, which is used by `Chromium` and `node.js`. -# Preliminaries +With [WebKit](http://www.webkit.org/) there is a modern browser +implementation available as open-source which can be embedded into an application. +Unfortunately, [Chromium Embedded Framework](http://code.google.com/p/chromiumembedded/) +does not provide access to the native V8 engine, making it impossible to extend the engine +using the Javascript module. -# Running SWIG +## Preliminaries + +### Running SWIG Suppose that you defined a SWIG module such as the following: -```code -%module example -%{ -#include "example.h" -%} -int gcd(int x, int y); -extern double Foo; -``` + %module example + %{ + #include "example.h" + %} + int gcd(int x, int y); + extern double Foo; To build a Javascript module, run SWIG using the `-javascript` option and a desired target engine `-jsc` or `-v8`. -```shell -$ swig -javascript -jsc example.i -``` + $ swig -javascript -jsc example.i If building a C++ extension, add the -c++ option: -```shell -$ swig -c++ -javascript -jsc example.i -``` + $ swig -c++ -javascript -jsc example.i This creates a C/C++ source file example_wrap.c or example_wrap.cxx. The generated C source file contains the low-level wrappers that need to be compiled and linked with the rest of your C/C++ application to create an extension module. @@ -59,15 +53,11 @@ To change this, you can use the -o option. The wrapped module will export one function which must be called to register the module with the Javascript interpreter. For example, if your module is named `example` the corresponding initializer for JavascriptCore would be -```code -bool example_initialize(JSGlobalContextRef context, JSObjectRef *exports) -``` + bool example_initialize(JSGlobalContextRef context, JSObjectRef *exports) and for v8: -```code -void example_initialize (v8::Handle exports) -``` + void example_initialize (v8::Handle exports) ## Missing features @@ -75,26 +65,22 @@ The Javascript module is not yet as mature as other modules and some things are As it makes use of Swigs Unified typemap library (UTL), many typemaps are inherited. - Director support -- TODO: there is more +- TODO: hmpf... I suppose there is more +## Compilation and Linking -# Compilation and Linking +### Installation -## Installation - - - -## Dealing with `v8` version incompatibilities +### Dealing with `v8` version incompatibilities Unfortunately, v8 does not provide pre-processor macros do detect which version you link to. Therefore, you have to provide this information manually. - -# Integration +## Integration This should give a short overview how to integrate your module in different environments: as a `node.js` module, and as an extension for an embedded Chromium. -## Creating `node.js` Extensions +### Creating `node.js` Extensions As `v8` is written in C++ and comes as a C++ library it is crucial to compile your module using the same compiler flags as used for building v8. To make things easier, `node.js` provides a build tool called `node-gyp`. @@ -103,138 +89,132 @@ This expects configuration file named `binding.gyp` which is basically in JSON f conforms to the same format that is used with Google's build-tool `gyp`. `binding.gyp`: -```code -{ - "targets": [ + { - "target_name": "example", - "sources": [ "example.cxx", "example_wrap.cxx" ] + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] } - ] -} -``` First you would create the wrapper using SWIG: -```shell -``` - -## Embedded Webkit +### Embedded Webkit TODO: Here a minimal example of how to implement -# Implementation +## Implementation The Javascript Module implementation has take a very different approach than other modules to be able to generate code for different Javascript interpreters. -## Module Source Code +### Module Source Code The Javascript module is implemented in `Source/Modules/javascript.cxx`. It dispatches the code generation to a `JSEmitter` instance, `V8Emitter` or `JSCEmitter`. Additionally there are some helpers: `Template`, for templated code generation, and `JSEmitterState`, which is used to manage state information during AST traversal. This is a rough map shall make it easier to find a way through this huge source file: -```code -// module wide defines + // module wide defines -#define NAME "name" + #define NAME "name" -... + ... -// Helper class declarations -class JSEmitterState { ... }; + // Helper class declarations + class JSEmitterState { ... }; -class Template { ... }; + class Template { ... }; -// JSEmitter declaration + // JSEmitter declaration -class JSEmitter { ... }; + class JSEmitter { ... }; -// Emitter factory declarations + // Emitter factory declarations -JSEmitter *swig_javascript_create_JSCEmitter(); -JSEmitter *swig_javascript_create_V8Emitter(); + JSEmitter *swig_javascript_create_JSCEmitter(); + JSEmitter *swig_javascript_create_V8Emitter(); -// Javascript module class declaration + // Javascript module class declaration -class JAVASCRIPT:public Language { ... }; + class JAVASCRIPT:public Language { ... }; -// Javascript module function definitions + // Javascript module function definitions -int JAVASCRIPT::functionWrapper(Node *n) { ... } + int JAVASCRIPT::functionWrapper(Node *n) { ... } -... + ... -// Module factory implementations + // Module factory implementations -static Language *new_swig_javascript() { ... } + static Language *new_swig_javascript() { ... } -extern "C" Language *swig_javascript(void) { ... } + extern "C" Language *swig_javascript(void) { ... } -// JSEmitter implementation + // JSEmitter implementation -JSEmitter::JSEmitter() { ... } + JSEmitter::JSEmitter() { ... } -Template JSEmitter::getTemplate(const String *name) { ... } + Template JSEmitter::getTemplate(const String *name) { ... } -... + ... -// JSCEmitter declaration + // JSCEmitter declaration -class JSCEmitter: public JSEmitter { ... }; + class JSCEmitter: public JSEmitter { ... }; -// JSCEmitter implementation + // JSCEmitter implementation -JSCEmitter::JSCEmitter() { ... } + JSCEmitter::JSCEmitter() { ... } -void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) { ... } + void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) { ... } -... + ... -// JSCEmitter factory + // JSCEmitter factory -JSEmitter *swig_javascript_create_JSCEmitter() { ... } + JSEmitter *swig_javascript_create_JSCEmitter() { ... } -// V8Emitter declaration + // V8Emitter declaration -class V8Emitter: public JSEmitter { ... }; + class V8Emitter: public JSEmitter { ... }; -// V8Emitter implementation + // V8Emitter implementation -V8Emitter::V8Emitter() { ... } + V8Emitter::V8Emitter() { ... } -int V8Emitter::initialize(Node *n) { ... } + int V8Emitter::initialize(Node *n) { ... } -// V8Emitter factory + // V8Emitter factory -JSEmitter *swig_javascript_create_V8Emitter() { ... } + JSEmitter *swig_javascript_create_V8Emitter() { ... } -// Helper implementation (JSEmitterState, Template) + // Helper implementation (JSEmitterState, Template) -JSEmitterState::JSEmitterState() { ... } + JSEmitterState::JSEmitterState() { ... } -... + ... -Template::Template(const String *code_) { ... } + Template::Template(const String *code_) { ... } -``` -## Code Templates +### Code Templates All generated code is created on the basis of code templates. The templates for *JavascriptCore* can be found in `Lib/javascript/jsc/javascriptcode.swg`, @@ -242,213 +222,194 @@ for *v8* in `Lib/javascript/v8/javascriptcode.swg`. To track the originating code template for generated code you can run -```shell -swig -javascript -jsc -debug-codetemplates -``` + $ swig -javascript -jsc -debug-codetemplates which wraps generated code with a descriptive comment -```code -/* begin fragment("temlate_name") */ + /* begin fragment("temlate_name") */ -...generated code ... + ...generated code ... -/* end fragment("temlate_name") */ -``` + /* end fragment("temlate_name") */ The Template class is used like this: -```code - Template t_register = getTemplate("jsv8_register_static_variable"); - t_register.replace("$jsparent", state.clazz(NAME_MANGLED)) - .replace("$jsname", state.variable(NAME)) - .replace("$jsgetter", state.variable(GETTER)) - .replace("$jssetter", state.variable(SETTER)) - .trim(). - print(f_init_static_wrappers); -``` + Template t_register = getTemplate("jsv8_register_static_variable"); + t_register.replace("$jsparent", state.clazz(NAME_MANGLED)) + .replace("$jsname", state.variable(NAME)) + .replace("$jsgetter", state.variable(GETTER)) + .replace("$jssetter", state.variable(SETTER)) + .trim(). + print(f_init_static_wrappers); A code template is registered with the *JSEmitter* via `fragment(name, "template")`, e.g., -```code -%fragment ("jsc_variable_declaration", "templates") -%{ - {"$jsname", $jsgetter, $jssetter, kJSPropertyAttributeNone}, -%} -``` + %fragment ("jsc_variable_declaration", "templates") + %{ + {"$jsname", $jsgetter, $jssetter, kJSPropertyAttributeNone}, + %} `Template` creates a copy of that string and `Template::replace` uses Swig's `Replaceall` to replace variables in the template. `Template::trim` can be used to eliminate leading and trailing whitespaces. `Template::print` is used to write the final template string to a Swig `DOH` (based on `Printv`). All methods allow chaining. - -## Emitter +### Emitter The Javascript module delegates code generation to a `JSEmitter` instance. The following extract shows the essential interface: -```code -class JSEmitter { - ... + class JSEmitter { + ... - /** - * Opens output files and temporary output DOHs. - */ - virtual int initialize(Node *n); + /** + * Opens output files and temporary output DOHs. + */ + virtual int initialize(Node *n); - /** - * Writes all collected code into the output file(s). - */ - virtual int dump(Node *n) = 0; + /** + * Writes all collected code into the output file(s). + */ + virtual int dump(Node *n) = 0; - /** - * Cleans up all open output DOHs. - */ - virtual int close() = 0; + /** + * Cleans up all open output DOHs. + */ + virtual int close() = 0; - ... + ... - /** - * Invoked at the beginning of the classHandler. - */ - virtual int enterClass(Node *); + /** + * Invoked at the beginning of the classHandler. + */ + virtual int enterClass(Node *); - /** - * Invoked at the end of the classHandler. - */ - virtual int exitClass(Node *) { - return SWIG_OK; - }; + /** + * Invoked at the end of the classHandler. + */ + virtual int exitClass(Node *) { + return SWIG_OK; + }; - /** - * Invoked at the beginning of the variableHandler. - */ - virtual int enterVariable(Node *); + /** + * Invoked at the beginning of the variableHandler. + */ + virtual int enterVariable(Node *); - /** - * Invoked at the end of the variableHandler. - */ - virtual int exitVariable(Node *) { - return SWIG_OK; - }; + /** + * Invoked at the end of the variableHandler. + */ + virtual int exitVariable(Node *) { + return SWIG_OK; + }; - /** - * Invoked at the beginning of the functionHandler. - */ - virtual int enterFunction(Node *); + /** + * Invoked at the beginning of the functionHandler. + */ + virtual int enterFunction(Node *); - /** - * Invoked at the end of the functionHandler. - */ - virtual int exitFunction(Node *) { - return SWIG_OK; - }; + /** + * Invoked at the end of the functionHandler. + */ + virtual int exitFunction(Node *) { + return SWIG_OK; + }; - /** - * Invoked by functionWrapper callback after call to Language::functionWrapper. - */ - virtual int emitWrapperFunction(Node *n); + /** + * Invoked by functionWrapper callback after call to Language::functionWrapper. + */ + virtual int emitWrapperFunction(Node *n); - /** - * Invoked from constantWrapper after call to Language::constantWrapper. - **/ - virtual int emitConstant(Node *n); + /** + * Invoked from constantWrapper after call to Language::constantWrapper. + **/ + virtual int emitConstant(Node *n); - /** - * Registers a given code snippet for a given key name. - * - * This method is called by the fragmentDirective handler - * of the JAVASCRIPT language module. - **/ - int registerTemplate(const String *name, const String *code); + /** + * Registers a given code snippet for a given key name. + * + * This method is called by the fragmentDirective handler + * of the JAVASCRIPT language module. + **/ + int registerTemplate(const String *name, const String *code); - /** - * Retrieve the code template registered for a given name. - */ - Template getTemplate(const String *name); + /** + * Retrieve the code template registered for a given name. + */ + Template getTemplate(const String *name); - State &getState(); + State &getState(); - ... + ... -} -``` + } The module calls `initialize`, `dump`, and `close` from within the `top` method: -```code -int JAVASCRIPT::top(Node *n) { - emitter->initialize(n); + int JAVASCRIPT::top(Node *n) { + emitter->initialize(n); - Language::top(n); + Language::top(n); - emitter->dump(n); - emitter->close(); + emitter->dump(n); + emitter->close(); - return SWIG_OK; -} -``` + return SWIG_OK; + } The methods `enterClass` and `exitClass` are called from within the `classHandler` method: -```code -int JAVASCRIPT::classHandler(Node *n) { + int JAVASCRIPT::classHandler(Node *n) { - emitter->enterClass(n); - Language::classHandler(n); - emitter->exitClass(n); + emitter->enterClass(n); + Language::classHandler(n); + emitter->exitClass(n); - return SWIG_OK; -} -``` + return SWIG_OK; + } In `enterClass` the emitter stores state information that is necessary when processing class members. In `exitClass` the wrapper code for the whole class is generated. -## Emitter states +### Emitter states For storing information during the AST traversal the emitter provides a `JSEmitterState` with different slots to store data representing the scopes global, class, function, and variable. -```code -class JSEmitterState { + class JSEmitterState { -public: + public: - JSEmitterState(); + JSEmitterState(); - ~JSEmitterState(); + ~JSEmitterState(); - DOH *global(); + DOH *global(); - DOH *global(const char* key, DOH *initial = 0); + DOH *global(const char* key, DOH *initial = 0); - DOH *clazz(bool reset = false); + DOH *clazz(bool reset = false); - DOH *clazz(const char* key, DOH *initial = 0); + DOH *clazz(const char* key, DOH *initial = 0); - DOH *function(bool reset = false); + DOH *function(bool reset = false); - DOH *function(const char* key, DOH *initial = 0); + DOH *function(const char* key, DOH *initial = 0); - DOH *variable(bool reset = false); + DOH *variable(bool reset = false); - DOH *variable(const char* key, DOH *initial = 0); + DOH *variable(const char* key, DOH *initial = 0); - static int IsSet(DOH *val); + static int IsSet(DOH *val); - ... -}; -``` + ... + }; When entering a scope, such as in `enterClass`, the corresponding state is reset and new data is stored: -```code - state.clazz(RESET); - state.clazz(NAME, Getattr(n, "sym:name")); -``` + state.clazz(RESET); + state.clazz(NAME, Getattr(n, "sym:name")); State information can be retrieved using `state.clazz(NAME)` or with `Getattr` on `state.clazz()` which actually returns a `Hash` instance. From e829ea601f573b96efdf0e1ed602d90a7d39e29f Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 14 Feb 2014 00:00:37 +0100 Subject: [PATCH 0562/1048] Add Javascript to chapters. --- Doc/Manual/chapters | 1 + 1 file changed, 1 insertion(+) diff --git a/Doc/Manual/chapters b/Doc/Manual/chapters index 40e227164..427ec4fa7 100644 --- a/Doc/Manual/chapters +++ b/Doc/Manual/chapters @@ -22,6 +22,7 @@ D.html Go.html Guile.html Java.html +Javascript.html Lisp.html Lua.html Modula3.html From 8148b017f879f272616c8bb36b6bcd60232f9c4f Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 14 Feb 2014 00:01:15 +0100 Subject: [PATCH 0563/1048] Add a pandoc filter to create compatible html. --- Doc/Manual/pandoc_filter.py | 59 +++++++++++++++++++++++++++++++++ Doc/Manual/pandoc_template.html | 54 +++--------------------------- 2 files changed, 63 insertions(+), 50 deletions(-) create mode 100755 Doc/Manual/pandoc_filter.py diff --git a/Doc/Manual/pandoc_filter.py b/Doc/Manual/pandoc_filter.py new file mode 100755 index 000000000..81b259936 --- /dev/null +++ b/Doc/Manual/pandoc_filter.py @@ -0,0 +1,59 @@ +#!/usr/bin/env python + +""" +Pandoc filter that changes pandoc default HTML output for codeblocks +to match SWIG's format: + +
      +
      ...
      +
      + +""" + +from pandocfilters import toJSONFilter, stringify, walk, RawBlock, Div, Str +import sys +import json +import re + +global the_title + +def html(x): + return RawBlock('html', x) + +SHELL = re.compile(r"\s*[$]") + +def codeblocks(key, value, format, meta): + if key == 'CodeBlock': + [[id, classes, kvs], contents] = value + if format == "html" or format == "html5": + newcontents = [html('
      \n' + contents + '
      ')] + + if contents.startswith("$"): + classes.append("shell") + + if len(classes) == 0: + classes.append("code") + + return Div([id, classes, kvs], newcontents) + if key == 'Header': + if value[0] == 1: + global the_title + the_title = stringify(value) + value[1][0] = "" + +def set_title(unMeta): + global the_title + unMeta["title"] = {"t": "MetaInlines", "c": [Str(the_title)]} + +def __toJSONFilter(action): + doc = json.loads(sys.stdin.read()) + if len(sys.argv) > 1: + format = sys.argv[1] + else: + format = "" + altered = walk(doc, action, format, doc[0]['unMeta']) + set_title(altered[0]['unMeta']) + json.dump(altered, sys.stdout) + +if __name__ == "__main__": + __toJSONFilter(codeblocks) diff --git a/Doc/Manual/pandoc_template.html b/Doc/Manual/pandoc_template.html index 390bfc51c..d8cbc12ad 100644 --- a/Doc/Manual/pandoc_template.html +++ b/Doc/Manual/pandoc_template.html @@ -1,56 +1,10 @@ - - + + - - - -$for(author-meta)$ - -$endfor$ -$if(date-meta)$ - -$endif$ - $if(title-prefix)$$title-prefix$ - $endif$$if(pagetitle)$$pagetitle$$endif$ -$if(highlighting-css)$ - -$endif$ -$for(css)$ - -$endfor$ -$if(math)$ - $math$ -$endif$ -$for(header-includes)$ - $header-includes$ -$endfor$ + + $pagetitle$ -$for(include-before)$ -$include-before$ -$endfor$ -$if(title)$ -
      -

      $title$

      -$for(author)$ -

      $author$

      -$endfor$ -$if(date)$ -

      $date$

      -$endif$ -
      -$endif$ -$if(toc)$ -
      -$toc$ -
      -$endif$ -
      $body$ -
      -$for(include-after)$ -$include-after$ -$endfor$ From 915b7094331bf99f5cf6ed31d5747d10ae1bebb9 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 14 Feb 2014 00:02:05 +0100 Subject: [PATCH 0564/1048] Not a real change. Using a macro to reset JSEmitterStates for the sake of readability. --- Source/Modules/javascript.cxx | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index b8d36e21f..63994c029 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -34,6 +34,8 @@ bool js_template_enable_debug = false; #define STATIC_FUNCTIONS "static_functions" #define STATIC_VARIABLES "static_variables" +#define RESET true + /** * A convenience class to manage state variables for emitters. * The implementation delegates to swig Hash DOHs and provides @@ -723,7 +725,7 @@ int JSEmitter::emitWrapperFunction(Node *n) { } int JSEmitter::enterClass(Node *n) { - state.clazz(true); + state.clazz(RESET); state.clazz(NAME, Getattr(n, "sym:name")); state.clazz("nspace", current_namespace); @@ -755,7 +757,7 @@ int JSEmitter::enterClass(Node *n) { } int JSEmitter::enterFunction(Node *n) { - state.function(true); + state.function(RESET); state.function(NAME, Getattr(n, "sym:name")); if(Equal(Getattr(n, "storage"), "static")) { SetFlag(state.function(), IS_STATIC); @@ -765,7 +767,7 @@ int JSEmitter::enterFunction(Node *n) { int JSEmitter::enterVariable(Node *n) { // reset the state information for variables. - state.variable(true); + state.variable(RESET); // Retrieve a pure symbol name. Using 'sym:name' as a basis, as it considers %renamings. if (Equal(Getattr(n, "view"), "memberconstantHandler")) { From 1fca61c59ad7a825725b76d394de688774f296e8 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 14 Feb 2014 09:00:04 +0100 Subject: [PATCH 0565/1048] Conitnued documenting the Javascript module. --- Doc/Manual/Javascript.md | 109 +++++++++++++++++++++++---------------- 1 file changed, 65 insertions(+), 44 deletions(-) diff --git a/Doc/Manual/Javascript.md b/Doc/Manual/Javascript.md index b571e05c3..3525df5fe 100644 --- a/Doc/Manual/Javascript.md +++ b/Doc/Manual/Javascript.md @@ -14,14 +14,10 @@ Native Javascript extensions can be used for applications that embed a web-brows that embed a Javascript engine (such as *node.js*). Extending a general purpose web-browser is not possible as this would be severe security issue. -SWIG Javasript currently supports **JavascriptCore**, the Javascript engine used by `Safari`, -and **v8**, which is used by `Chromium` and `node.js`. +SWIG Javasript currently supports **JavascriptCore**, the Javascript engine used by `Safari/Webkit`, and **v8**, which is used by `Chromium` and `node.js`. -With [WebKit](http://www.webkit.org/) there is a modern browser +[WebKit](http://www.webkit.org/) is a modern browser implementation available as open-source which can be embedded into an application. -Unfortunately, [Chromium Embedded Framework](http://code.google.com/p/chromiumembedded/) -does not provide access to the native V8 engine, making it impossible to extend the engine -using the Javascript module. ## Preliminaries @@ -59,33 +55,42 @@ and for v8: void example_initialize (v8::Handle exports) -## Missing features +### Future work The Javascript module is not yet as mature as other modules and some things are still missing. As it makes use of Swigs Unified typemap library (UTL), many typemaps are inherited. +We could work on that if requested: -- Director support -- TODO: hmpf... I suppose there is more +- More typemaps: compared to other modules there are only a few typemaps implemented. + For instance a lot of the `std_*.i` typemaps are missing, such as `std_iostream`, for instance. -## Compilation and Linking +- Director support: this would allow to extend a C++ abstract base class in Javascript. + A pragmatic intermediate step for the most important usecase + would be to support Javascript callbacks as arguments. -### Installation +- We will try to find a way into + [Chromium Embedded Framework (CEF)](http://code.google.com/p/chromiumembedded/). + CEF is also open-source and available for all platforms. + However, at the moment it does not provide access to the native V8 engine, + making it impossible to extend the engine using the extensions created with this module. -### Dealing with `v8` version incompatibilities - -Unfortunately, v8 does not provide pre-processor macros do detect which version you link to. -Therefore, you have to provide this information manually. ## Integration -This should give a short overview how to integrate your module in different environments: as a `node.js` module, and as an extension for an embedded Chromium. +This should give a short overview how to integrate your module in different environments: as a `node.js` module, and as an extension for an embedded Webkit. ### Creating `node.js` Extensions -As `v8` is written in C++ and comes as a C++ library it is crucial to compile your module using the -same compiler flags as used for building v8. To make things easier, `node.js` provides a build tool called `node-gyp`. +To install `node.js` you can download an installer from their +[web-site](https://launchpad.net/~chris-lea/+archive/node.js) for all platforms. -This expects configuration file named `binding.gyp` which is basically in JSON format and +For Ubuntu there is also a [PPA](https://launchpad.net/~chris-lea/+archive/node.js/) available. + +As `v8` is written in C++ and comes as a C++ library it is crucial to compile your module +using the same compiler flags as used for building v8. +To make things easier, `node.js` provides a build tool called `node-gyp`. + +This expects a configuration file named `binding.gyp` which is basically in JSON format and conforms to the same format that is used with Google's build-tool `gyp`. `binding.gyp`: @@ -99,12 +104,29 @@ conforms to the same format that is used with Google's build-tool `gyp`. ] } -First you would create the wrapper using SWIG: +First create the wrapper using SWIG: + $ swig -javascript -node -c++ example.cxx + +Then run `node-gyp` + + $ node-gyp + +This will create a `build` folder containing the native module. +To use the extension you have to require it in your javascript source file. + + require("./build/Release/example") ### Embedded Webkit -TODO: Here a minimal example of how to implement +Webkit is built-in OSX and available as library for GTK. + +#### OSX + + +#### GTK + + ## Implementation @@ -112,106 +134,105 @@ The Javascript Module implementation has take a very different approach than oth to be able to generate code for different Javascript interpreters. -### Module Source Code +### Source Code The Javascript module is implemented in `Source/Modules/javascript.cxx`. It dispatches the code generation to a `JSEmitter` instance, `V8Emitter` or `JSCEmitter`. Additionally there are some helpers: `Template`, for templated code generation, and `JSEmitterState`, which is used to manage state information during AST traversal. -This is a rough map shall make it easier to find a way through this huge source file: +This rough map shall make it easier to find a way through this huge source file: // module wide defines #define NAME "name" - ... - // Helper class declarations + // ############################### + // # Helper class declarations + class JSEmitterState { ... }; class Template { ... }; - - // JSEmitter declaration + // ############################### + // # JSEmitter declaration class JSEmitter { ... }; - // Emitter factory declarations JSEmitter *swig_javascript_create_JSCEmitter(); JSEmitter *swig_javascript_create_V8Emitter(); + // ############################### + // # Javascript module - // Javascript module class declaration + // Javascript module declaration class JAVASCRIPT:public Language { ... }; - - // Javascript module function definitions + // Javascript module implementation int JAVASCRIPT::functionWrapper(Node *n) { ... } - ... - - // Module factory implementations + // Module factory implementation static Language *new_swig_javascript() { ... } extern "C" Language *swig_javascript(void) { ... } - - // JSEmitter implementation + // ############################### + // # JSEmitter base implementation JSEmitter::JSEmitter() { ... } Template JSEmitter::getTemplate(const String *name) { ... } - ... + // ############################### + // # JSCEmitter // JSCEmitter declaration class JSCEmitter: public JSEmitter { ... }; - // JSCEmitter implementation JSCEmitter::JSCEmitter() { ... } void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) { ... } - ... - // JSCEmitter factory JSEmitter *swig_javascript_create_JSCEmitter() { ... } + // ############################### + // # V8Emitter + // V8Emitter declaration class V8Emitter: public JSEmitter { ... }; - // V8Emitter implementation V8Emitter::V8Emitter() { ... } int V8Emitter::initialize(Node *n) { ... } - // V8Emitter factory JSEmitter *swig_javascript_create_V8Emitter() { ... } - // Helper implementation (JSEmitterState, Template) + // ############################### + // # Helper implementation (JSEmitterState, Template) JSEmitterState::JSEmitterState() { ... } - ... Template::Template(const String *code_) { ... } + ... ### Code Templates From 68472802721264ec8adee4f80ce7576eb3dd1a3e Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 14 Feb 2014 09:02:37 +0100 Subject: [PATCH 0566/1048] Pandoc filter detects shell blocks when not explicitely given. Considered as shell if the first character is '$', as in $ swig -javascript Alternatively you can specify the class explicitely: ```shell swig -javascript ``` --- Doc/Manual/pandoc_filter.py | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/Doc/Manual/pandoc_filter.py b/Doc/Manual/pandoc_filter.py index 81b259936..f1e84904a 100755 --- a/Doc/Manual/pandoc_filter.py +++ b/Doc/Manual/pandoc_filter.py @@ -15,12 +15,11 @@ import sys import json import re -global the_title - def html(x): return RawBlock('html', x) SHELL = re.compile(r"\s*[$]") +the_title = "" def codeblocks(key, value, format, meta): if key == 'CodeBlock': @@ -28,21 +27,19 @@ def codeblocks(key, value, format, meta): if format == "html" or format == "html5": newcontents = [html('
      \n' + contents + '
      ')] - if contents.startswith("$"): - classes.append("shell") - if len(classes) == 0: - classes.append("code") + if contents.startswith("$"): + classes.append("shell") + else: + classes.append("code") return Div([id, classes, kvs], newcontents) if key == 'Header': if value[0] == 1: - global the_title the_title = stringify(value) value[1][0] = "" def set_title(unMeta): - global the_title unMeta["title"] = {"t": "MetaInlines", "c": [Str(the_title)]} def __toJSONFilter(action): From 05146e2aed5b8e9df390acdd12b6e5cda2ed2e00 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 14 Feb 2014 13:04:21 +0100 Subject: [PATCH 0567/1048] Documented extending Node.js and Webkit's Javascript engine. --- Doc/Manual/Javascript.md | 78 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 75 insertions(+), 3 deletions(-) diff --git a/Doc/Manual/Javascript.md b/Doc/Manual/Javascript.md index 3525df5fe..11c9f7333 100644 --- a/Doc/Manual/Javascript.md +++ b/Doc/Manual/Javascript.md @@ -77,7 +77,7 @@ We could work on that if requested: ## Integration -This should give a short overview how to integrate your module in different environments: as a `node.js` module, and as an extension for an embedded Webkit. +This should give a short introduction to integrating your module in different environments: as a `node.js` module, and as an extension for an embedded Webkit. ### Creating `node.js` Extensions @@ -117,15 +117,88 @@ To use the extension you have to require it in your javascript source file. require("./build/Release/example") + ### Embedded Webkit -Webkit is built-in OSX and available as library for GTK. +Webkit is built-in for OSX and available as library for GTK. + #### OSX +There is general information about programming with WebKit on +[Apple Developer Documentation](https://developer.apple.com/library/mac/documentation/cocoa/conceptual/DisplayWebContent/DisplayWebContent.html). +Details about `Cocoa` programming are not covered here. + +An integration of a native extension 'example' would look like this: + + #import "appDelegate.h" + + extern bool example_initialize(JSGlobalContextRef context); + + + @implementation ExampleAppDelegate + + @synthesize webView; + + + - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { + + // Start a webview with the bundled index.html file + NSString *path = [[NSBundle mainBundle] bundlePath]; + NSString *url = [NSString stringWithFormat: @"file://%@/Contents/Assets/index.html", path]; + + WebFrame *webframe = [webView mainFrame]; + JSGlobalContextRef context = [webframe globalContext]; + + example_initialize(context); + + [ [webView mainFrame] loadRequest: + [NSURLRequest requestWithURL: [NSURL URLWithString:url] ] + ]; + } + + @end #### GTK +There is general information about programming GTK on the +[GTK documentation](https://developer.gnome.org/gtk2/), in the +[GTK tutorial](https://developer.gnome.org/gtk-tutorial), +and for Webkit there is a [Webkit GTK+ API Reference](http://webkitgtk.org/reference/webkitgtk/stable/index.html). + +An integration of a native extension 'example' would look like this: + + #include + #include + + extern bool example_initialize(JSGlobalContextRef context); + + int main(int argc, char* argv[]) + { + // Initialize GTK+ + gtk_init(&argc, &argv); + + ... + + // Create a browser instance + WebKitWebView *webView = WEBKIT_WEB_VIEW(webkit_web_view_new()); + WebFrame *webframe = webkit_web_view_get_main_frame(webView); + JSGlobalContextRef context = webkit_web_frame_get_global_context(webFrame); + example_initialize(context); + + ... + + // Load a web page into the browser instance + webkit_web_view_load_uri(webView, "http://www.webkitgtk.org/"); + + ... + + // Run the main GTK+ event loop + gtk_main(); + + return 0; + } + ## Implementation @@ -133,7 +206,6 @@ Webkit is built-in OSX and available as library for GTK. The Javascript Module implementation has take a very different approach than other modules to be able to generate code for different Javascript interpreters. - ### Source Code The Javascript module is implemented in `Source/Modules/javascript.cxx`. From 8df34d54d0957552a53fe5f1e6598849c4ac9f81 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 14 Feb 2014 13:21:52 +0100 Subject: [PATCH 0568/1048] Beginning to document v8 integration. --- Doc/Manual/Javascript.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Doc/Manual/Javascript.md b/Doc/Manual/Javascript.md index 11c9f7333..275557ccc 100644 --- a/Doc/Manual/Javascript.md +++ b/Doc/Manual/Javascript.md @@ -200,6 +200,15 @@ An integration of a native extension 'example' would look like this: } +### Embedded V8 + +It is possible to create a custom application like `node.js` embedding a v8 engine. + +TODO: +- how to install v8 +- v8 version issues: command-line switch, pre-processor macro +- sample integration code + ## Implementation From ead4d695f007fd6835d2f5d62e8c28ddfc1f7d29 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 13 Feb 2014 23:56:01 +0000 Subject: [PATCH 0569/1048] 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 0570/1048] 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 0571/1048] 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 0572/1048] 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 0573/1048] 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 0574/1048] 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 0575/1048] 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 0576/1048] 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 0577/1048] 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 0578/1048] 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 0579/1048] 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 0580/1048] 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 0581/1048] 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 0582/1048] 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 0583/1048] 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 0584/1048] 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 0585/1048] 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 0586/1048] 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 0587/1048] 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 0588/1048] 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 0589/1048] 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 0590/1048] 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 0591/1048] 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 0592/1048] 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 0593/1048] "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 0594/1048] 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 0595/1048] 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 0596/1048] 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 0597/1048] 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 0598/1048] 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 0599/1048] 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 0600/1048] 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 0601/1048] [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 0602/1048] 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 0603/1048] 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 0604/1048] 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 0605/1048] 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 0606/1048] -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 0607/1048] 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 0608/1048] 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 0609/1048] 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 0610/1048] 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 0611/1048] 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 0612/1048] 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 0613/1048] 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 0614/1048] 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 0615/1048] 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 0616/1048] 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 0617/1048] 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 0618/1048] 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 0619/1048] 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 0620/1048] 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 0621/1048] 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 0622/1048] 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 0623/1048] 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 0624/1048] 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 0625/1048] 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 0626/1048] 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 0627/1048] 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 0628/1048] 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 0629/1048] 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 0630/1048] 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 0631/1048] 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 0632/1048] 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 0633/1048] 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 0634/1048] 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 0635/1048] 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 0636/1048] 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 0637/1048] 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 0638/1048] 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 0639/1048] 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 0640/1048] 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 0641/1048] 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 0642/1048] 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 0643/1048] [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 0644/1048] 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 0645/1048] 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 0646/1048] 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 0647/1048] 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 77ead7017caca778eb3143fa487856ee8dcd4b7b Mon Sep 17 00:00:00 2001
      From: Oliver Buchtala 
      Date: Thu, 20 Feb 2014 11:13:57 +0100
      Subject: [PATCH 0648/1048] Refactored configuration for javascript examples.
      
      ---
       Examples/Makefile.in                   | 37 +++++++++++++--
       Examples/javascript/class/Makefile     | 22 +--------
       Examples/javascript/constant/Makefile  | 22 +--------
       Examples/javascript/enum/Makefile      | 22 +--------
       Examples/javascript/exception/Makefile | 22 +--------
       Examples/javascript/functor/Makefile   | 22 +--------
       Examples/javascript/js_example.mk      | 63 ++++++++++++++++++++++++++
       Examples/javascript/namespace/Makefile | 22 +--------
       Examples/javascript/operator/Makefile  | 22 +--------
       Examples/javascript/overload/Makefile  | 22 +--------
       Examples/javascript/pointer/Makefile   | 22 +--------
       Examples/javascript/reference/Makefile | 22 +--------
       Examples/javascript/simple/Makefile    | 22 +--------
       Examples/javascript/template/Makefile  | 22 +--------
       Examples/javascript/variables/Makefile | 22 +--------
       15 files changed, 121 insertions(+), 265 deletions(-)
       create mode 100644 Examples/javascript/js_example.mk
      
      diff --git a/Examples/Makefile.in b/Examples/Makefile.in
      index a2a211cbd..17e66acce 100644
      --- a/Examples/Makefile.in
      +++ b/Examples/Makefile.in
      @@ -668,6 +668,11 @@ android_clean:
       #####                       JAVASCRIPT                      ######
       ##################################################################
       
      +# Note: These targets are used from withing Makefiles in the Example directories.
      +# There is a common makefile, 'Examples/javascript/js_example.mk' to simplify
      +# create a configuration for a new example.
      +
      +
       ROOT_DIR = @ROOT_DIR@
       JSCFLAGS = @JSCFLAGS@
       JSCXXFLAGS = @JSCXXFLAGS@
      @@ -689,6 +694,7 @@ JSCXXSHARED = @JSCXXSHARED@
       #		environment.
       #   For testing native v8 and jsc extensions we provide our own
       #		interpreter (see 'Tools/javascript').
      +#
       # ----------------------------------------------------------------
       
       JS_INTERPRETER_SRC_DIR = $(ROOT_DIR)/Tools/javascript
      @@ -717,19 +723,38 @@ javascript_exe: $(SRCS)
       SWIGJS   = $(SWIG) -javascript
       
       # ----------------------------------------------------------------
      -# Run the javascript executable
      +# Creating and building Javascript wrappers
       # ----------------------------------------------------------------
       
      -javascript: $(SRCS)
      +javascript_wrapper:
       	$(SWIGJS) $(SWIGOPT) $(INTERFACEPATH)
      +
      +javascript_wrapper_cpp: $(SRCS)
      +	$(SWIGJS) -c++ $(SWIGOPT) $(INTERFACEPATH)
      +
      +javascript_build: $(SRCS)
       	$(CC) -c $(CCSHARED) $(CFLAGS) $(JSCFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) $(JSINCLUDES)
       	$(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO)
       
      -javascript_cpp: $(SRCS)
      -	$(SWIGJS) -c++ $(SWIGOPT) $(INTERFACEPATH)
      +javascript_build_cpp:: $(SRCS)
       	$(CXX) -c $(CCSHARED) $(CFLAGS) $(JSCFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(JSINCLUDES)
       	$(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO)
       
      +# TODO: make node-gyp configurable and detected via ./configure
      +javascript_build_node: $(SRCS)
      +	node-gyp --loglevel=silent configure build 1>>/dev/null
      +
      +# -----------------------------------------------------------------
      +# Running a javascript example
      +# -----------------------------------------------------------------
      +
      +javascript_run:
      +	$(JS_INTERPRETER_SRC_DIR)/javascript -$(JSENGINE) runme.js
      +
      +# TODO: make node configurable and detected via ./configure
      +javascript_run_node:
      +	node runme.js
      +
       # -----------------------------------------------------------------
       # Cleaning the javascript examples
       # -----------------------------------------------------------------
      @@ -740,6 +765,8 @@ javascript_clean:
       	rm -f core @EXTRA_CLEAN@
       	rm -f *.@OBJEXT@ *@JSSO@
       
      +
      +
       ##################################################################
       #####                      MODULA3                          ######
       ##################################################################
      @@ -1604,7 +1631,7 @@ R_SCRIPT=$(RUNME).R
       r: $(SRCS)
       	$(SWIG) -r $(SWIGOPT) $(INTERFACEPATH)
       ifneq ($(SRCS),)
      -	$(CC) -g -c $(CFLAGS) $(R_CFLAGS) $(SRCS) $(INCLUDES) 
      +	$(CC) -g -c $(CFLAGS) $(R_CFLAGS) $(SRCS) $(INCLUDES)
       endif
       	+( PKG_CPPFLAGS="$(INCLUDES)" $(COMPILETOOL) $(R) CMD SHLIB -o $(LIBPREFIX)$(TARGET)$(SO) $(ISRCS) $(OBJS) > /dev/null )
       
      diff --git a/Examples/javascript/class/Makefile b/Examples/javascript/class/Makefile
      index 99a9e9e86..b0934786a 100755
      --- a/Examples/javascript/class/Makefile
      +++ b/Examples/javascript/class/Makefile
      @@ -1,21 +1,3 @@
      -TOP = ../..
      -SWIG = $(TOP)/../preinst-swig
      -CXXSRCS    = example.cxx
      -JS_SCRIPT = runme.js
      -TARGET = example
      -INTERFACE = example.i
      +SRCS = example.cxx
       
      -wrapper::
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp
      -
      -build:: wrapper
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build
      -
      -clean::
      -	$(MAKE) -f $(TOP)/Makefile javascript_clean
      -
      -check:: build
      -	$(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \
      -		TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run
      +include ../js_example.mk
      diff --git a/Examples/javascript/constant/Makefile b/Examples/javascript/constant/Makefile
      index 99a9e9e86..b0934786a 100755
      --- a/Examples/javascript/constant/Makefile
      +++ b/Examples/javascript/constant/Makefile
      @@ -1,21 +1,3 @@
      -TOP = ../..
      -SWIG = $(TOP)/../preinst-swig
      -CXXSRCS    = example.cxx
      -JS_SCRIPT = runme.js
      -TARGET = example
      -INTERFACE = example.i
      +SRCS = example.cxx
       
      -wrapper::
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp
      -
      -build:: wrapper
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build
      -
      -clean::
      -	$(MAKE) -f $(TOP)/Makefile javascript_clean
      -
      -check:: build
      -	$(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \
      -		TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run
      +include ../js_example.mk
      diff --git a/Examples/javascript/enum/Makefile b/Examples/javascript/enum/Makefile
      index 99a9e9e86..b0934786a 100755
      --- a/Examples/javascript/enum/Makefile
      +++ b/Examples/javascript/enum/Makefile
      @@ -1,21 +1,3 @@
      -TOP = ../..
      -SWIG = $(TOP)/../preinst-swig
      -CXXSRCS    = example.cxx
      -JS_SCRIPT = runme.js
      -TARGET = example
      -INTERFACE = example.i
      +SRCS = example.cxx
       
      -wrapper::
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp
      -
      -build:: wrapper
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build
      -
      -clean::
      -	$(MAKE) -f $(TOP)/Makefile javascript_clean
      -
      -check:: build
      -	$(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \
      -		TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run
      +include ../js_example.mk
      diff --git a/Examples/javascript/exception/Makefile b/Examples/javascript/exception/Makefile
      index 99a9e9e86..b0934786a 100755
      --- a/Examples/javascript/exception/Makefile
      +++ b/Examples/javascript/exception/Makefile
      @@ -1,21 +1,3 @@
      -TOP = ../..
      -SWIG = $(TOP)/../preinst-swig
      -CXXSRCS    = example.cxx
      -JS_SCRIPT = runme.js
      -TARGET = example
      -INTERFACE = example.i
      +SRCS = example.cxx
       
      -wrapper::
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp
      -
      -build:: wrapper
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build
      -
      -clean::
      -	$(MAKE) -f $(TOP)/Makefile javascript_clean
      -
      -check:: build
      -	$(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \
      -		TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run
      +include ../js_example.mk
      diff --git a/Examples/javascript/functor/Makefile b/Examples/javascript/functor/Makefile
      index 99a9e9e86..b0934786a 100755
      --- a/Examples/javascript/functor/Makefile
      +++ b/Examples/javascript/functor/Makefile
      @@ -1,21 +1,3 @@
      -TOP = ../..
      -SWIG = $(TOP)/../preinst-swig
      -CXXSRCS    = example.cxx
      -JS_SCRIPT = runme.js
      -TARGET = example
      -INTERFACE = example.i
      +SRCS = example.cxx
       
      -wrapper::
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp
      -
      -build:: wrapper
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build
      -
      -clean::
      -	$(MAKE) -f $(TOP)/Makefile javascript_clean
      -
      -check:: build
      -	$(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \
      -		TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run
      +include ../js_example.mk
      diff --git a/Examples/javascript/js_example.mk b/Examples/javascript/js_example.mk
      new file mode 100644
      index 000000000..c2e9c6dcf
      --- /dev/null
      +++ b/Examples/javascript/js_example.mk
      @@ -0,0 +1,63 @@
      +# Note: as a convention an example must be in a child directory of this.
      +# These paths are relative to such an example directory
      +EXAMPLES_TOP=../..
      +SWIG_TOP=../../..
      +
      +SWIG = $(SWIG_TOP)/preinst-swig
      +
      +# TODO: we could only set these only if not yet set...
      +JS_SCRIPT = runme.js
      +TARGET = example
      +INTERFACE = example.i
      +
      +ifneq (, $(ENGINE))
      +	JSENGINE=$(ENGINE)
      +else
      +	JSENGINE=node
      +endif
      +
      +ifeq (node,$(JSENGINE))
      +  SWIGOPT=-v8 -DBUILDING_NODE_EXTENSION=1
      +endif
      +
      +ifeq (v8,$(JSENGINE))
      +  SWIGOPT=-v8
      +endif
      +
      +ifeq (jsc,$(JSENGINE))
      +  SWIGOPT=-jsc
      +endif
      +
      +
      +ifeq (node,$(JSENGINE))
      +
      +build: wrapper
      +	$(MAKE) -f $(EXAMPLES_TOP)/Makefile CXXSRCS='$(SRCS)' SWIG='$(SWIG)' \
      +	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' JSENGINE='$(JSENGINE)' javascript_build_node
      +
      +else
      +
      +build: wrapper
      +	$(MAKE) -f $(EXAMPLES_TOP)/Makefile CXXSRCS='$(SRCS)' SWIG='$(SWIG)' \
      +	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' JSENGINE='$(JSENGINE)' javascript_build_cpp
      +
      +endif
      +
      +wrapper:
      +	$(MAKE) -f $(EXAMPLES_TOP)/Makefile CXXSRCS='$(SRCS)' SWIG='$(SWIG)' \
      +	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp
      +
      +ifeq (node,$(JSENGINE))
      +
      +check: build
      +	$(MAKE) -f $(EXAMPLES_TOP)/Makefile JSENGINE='$(JSENGINE)' javascript_run_node
      +
      +else
      +
      +check: build
      +	$(MAKE) -f $(EXAMPLES_TOP)/Makefile JSENGINE='$(JSENGINE)' javascript_run
      +
      +endif
      +
      +clean:
      +	$(MAKE) -f $(EXAMPLES_TOP)/Makefile javascript_clean
      diff --git a/Examples/javascript/namespace/Makefile b/Examples/javascript/namespace/Makefile
      index 99a9e9e86..b0934786a 100755
      --- a/Examples/javascript/namespace/Makefile
      +++ b/Examples/javascript/namespace/Makefile
      @@ -1,21 +1,3 @@
      -TOP = ../..
      -SWIG = $(TOP)/../preinst-swig
      -CXXSRCS    = example.cxx
      -JS_SCRIPT = runme.js
      -TARGET = example
      -INTERFACE = example.i
      +SRCS = example.cxx
       
      -wrapper::
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp
      -
      -build:: wrapper
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build
      -
      -clean::
      -	$(MAKE) -f $(TOP)/Makefile javascript_clean
      -
      -check:: build
      -	$(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \
      -		TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run
      +include ../js_example.mk
      diff --git a/Examples/javascript/operator/Makefile b/Examples/javascript/operator/Makefile
      index 99a9e9e86..b0934786a 100755
      --- a/Examples/javascript/operator/Makefile
      +++ b/Examples/javascript/operator/Makefile
      @@ -1,21 +1,3 @@
      -TOP = ../..
      -SWIG = $(TOP)/../preinst-swig
      -CXXSRCS    = example.cxx
      -JS_SCRIPT = runme.js
      -TARGET = example
      -INTERFACE = example.i
      +SRCS = example.cxx
       
      -wrapper::
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp
      -
      -build:: wrapper
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build
      -
      -clean::
      -	$(MAKE) -f $(TOP)/Makefile javascript_clean
      -
      -check:: build
      -	$(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \
      -		TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run
      +include ../js_example.mk
      diff --git a/Examples/javascript/overload/Makefile b/Examples/javascript/overload/Makefile
      index 99a9e9e86..b0934786a 100755
      --- a/Examples/javascript/overload/Makefile
      +++ b/Examples/javascript/overload/Makefile
      @@ -1,21 +1,3 @@
      -TOP = ../..
      -SWIG = $(TOP)/../preinst-swig
      -CXXSRCS    = example.cxx
      -JS_SCRIPT = runme.js
      -TARGET = example
      -INTERFACE = example.i
      +SRCS = example.cxx
       
      -wrapper::
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp
      -
      -build:: wrapper
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build
      -
      -clean::
      -	$(MAKE) -f $(TOP)/Makefile javascript_clean
      -
      -check:: build
      -	$(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \
      -		TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run
      +include ../js_example.mk
      diff --git a/Examples/javascript/pointer/Makefile b/Examples/javascript/pointer/Makefile
      index 99a9e9e86..b0934786a 100755
      --- a/Examples/javascript/pointer/Makefile
      +++ b/Examples/javascript/pointer/Makefile
      @@ -1,21 +1,3 @@
      -TOP = ../..
      -SWIG = $(TOP)/../preinst-swig
      -CXXSRCS    = example.cxx
      -JS_SCRIPT = runme.js
      -TARGET = example
      -INTERFACE = example.i
      +SRCS = example.cxx
       
      -wrapper::
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp
      -
      -build:: wrapper
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build
      -
      -clean::
      -	$(MAKE) -f $(TOP)/Makefile javascript_clean
      -
      -check:: build
      -	$(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \
      -		TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run
      +include ../js_example.mk
      diff --git a/Examples/javascript/reference/Makefile b/Examples/javascript/reference/Makefile
      index 99a9e9e86..b0934786a 100755
      --- a/Examples/javascript/reference/Makefile
      +++ b/Examples/javascript/reference/Makefile
      @@ -1,21 +1,3 @@
      -TOP = ../..
      -SWIG = $(TOP)/../preinst-swig
      -CXXSRCS    = example.cxx
      -JS_SCRIPT = runme.js
      -TARGET = example
      -INTERFACE = example.i
      +SRCS = example.cxx
       
      -wrapper::
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp
      -
      -build:: wrapper
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build
      -
      -clean::
      -	$(MAKE) -f $(TOP)/Makefile javascript_clean
      -
      -check:: build
      -	$(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \
      -		TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run
      +include ../js_example.mk
      diff --git a/Examples/javascript/simple/Makefile b/Examples/javascript/simple/Makefile
      index 99a9e9e86..b0934786a 100755
      --- a/Examples/javascript/simple/Makefile
      +++ b/Examples/javascript/simple/Makefile
      @@ -1,21 +1,3 @@
      -TOP = ../..
      -SWIG = $(TOP)/../preinst-swig
      -CXXSRCS    = example.cxx
      -JS_SCRIPT = runme.js
      -TARGET = example
      -INTERFACE = example.i
      +SRCS = example.cxx
       
      -wrapper::
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp
      -
      -build:: wrapper
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build
      -
      -clean::
      -	$(MAKE) -f $(TOP)/Makefile javascript_clean
      -
      -check:: build
      -	$(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \
      -		TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run
      +include ../js_example.mk
      diff --git a/Examples/javascript/template/Makefile b/Examples/javascript/template/Makefile
      index 99a9e9e86..b0934786a 100755
      --- a/Examples/javascript/template/Makefile
      +++ b/Examples/javascript/template/Makefile
      @@ -1,21 +1,3 @@
      -TOP = ../..
      -SWIG = $(TOP)/../preinst-swig
      -CXXSRCS    = example.cxx
      -JS_SCRIPT = runme.js
      -TARGET = example
      -INTERFACE = example.i
      +SRCS = example.cxx
       
      -wrapper::
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp
      -
      -build:: wrapper
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build
      -
      -clean::
      -	$(MAKE) -f $(TOP)/Makefile javascript_clean
      -
      -check:: build
      -	$(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \
      -		TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run
      +include ../js_example.mk
      diff --git a/Examples/javascript/variables/Makefile b/Examples/javascript/variables/Makefile
      index 99a9e9e86..b0934786a 100755
      --- a/Examples/javascript/variables/Makefile
      +++ b/Examples/javascript/variables/Makefile
      @@ -1,21 +1,3 @@
      -TOP = ../..
      -SWIG = $(TOP)/../preinst-swig
      -CXXSRCS    = example.cxx
      -JS_SCRIPT = runme.js
      -TARGET = example
      -INTERFACE = example.i
      +SRCS = example.cxx
       
      -wrapper::
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp
      -
      -build:: wrapper
      -	$(MAKE) -f $(TOP)/Makefile CXXSRCS='$(CXXSRCS)' SWIG='$(SWIG)' \
      -	SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_build
      -
      -clean::
      -	$(MAKE) -f $(TOP)/Makefile javascript_clean
      -
      -check:: build
      -	$(MAKE) -f $(TOP)/Makefile JSCXXSRCS='$(JSCXXSRCS)' TARGET='$(TARGET)' \
      -		TOP='$(TOP)' JS_SCRIPT='$(JS_SCRIPT)' javascript_run
      +include ../js_example.mk
      
      From fd0e75843d3ec7816c85a5d1ab84bd9319c9b27e Mon Sep 17 00:00:00 2001
      From: Oliver Buchtala 
      Date: Thu, 20 Feb 2014 11:14:48 +0100
      Subject: [PATCH 0649/1048] Deactivated broken JS examples.
      
      ---
       Examples/javascript/check.list | 6 +++---
       1 file changed, 3 insertions(+), 3 deletions(-)
      
      diff --git a/Examples/javascript/check.list b/Examples/javascript/check.list
      index 146f1800f..040267812 100644
      --- a/Examples/javascript/check.list
      +++ b/Examples/javascript/check.list
      @@ -1,13 +1,13 @@
       class
       constant
       enum
      -exception
      +#exception
       functor
      -namespace
      +#namespace
       operator
       overload
       pointer
      -reference
      +#reference
       simple
       template
       variables
      
      From 48e7df8eb2f7cb87e57dd7a890fbaa9ec8598ac7 Mon Sep 17 00:00:00 2001
      From: Oliver Buchtala 
      Date: Thu, 20 Feb 2014 11:15:18 +0100
      Subject: [PATCH 0650/1048] Better error message when no Javascript emitter is
       specified.
      
      ---
       Source/Modules/javascript.cxx | 2 +-
       1 file changed, 1 insertion(+), 1 deletion(-)
      
      diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx
      index 63994c029..496114c01 100644
      --- a/Source/Modules/javascript.cxx
      +++ b/Source/Modules/javascript.cxx
      @@ -533,7 +533,7 @@ void JAVASCRIPT::main(int argc, char *argv[]) {
           }
         default:
           {
      -      Printf(stderr, "Unknown emitter type.");
      +      Printf(stderr, "SWIG Javascript: Unknown emitter type.\n");
             SWIG_exit(-1);
             break;
           }
      
      From 7c1f66c29e4d0fd72e656b4bd27b2010c053b2c7 Mon Sep 17 00:00:00 2001
      From: Oliver Buchtala 
      Date: Thu, 20 Feb 2014 11:15:46 +0100
      Subject: [PATCH 0651/1048] Add more notes about how to install node.
      
      ---
       Doc/Manual/Javascript.md | 28 ++++++++++++++++++++++++----
       1 file changed, 24 insertions(+), 4 deletions(-)
      
      diff --git a/Doc/Manual/Javascript.md b/Doc/Manual/Javascript.md
      index 275557ccc..33f65e864 100644
      --- a/Doc/Manual/Javascript.md
      +++ b/Doc/Manual/Javascript.md
      @@ -79,19 +79,30 @@ We could work on that if requested:
       
       This should give a short introduction to integrating your module in different environments: as a `node.js` module, and as an extension for an embedded Webkit.
       
      +
       ### Creating `node.js` Extensions
       
       To install `node.js` you can download an installer from their
      -[web-site](https://launchpad.net/~chris-lea/+archive/node.js) for all platforms.
      +[web-site](https://launchpad.net/~chris-lea/+archive/node.js) for OSX and Windows.
      +For Linux you can either build the source yourself and to a `sudo checkinstall`
      +or stick to the (probably stone-age) packaged version.
      +For Ubuntu there is a [PPA](https://launchpad.net/~chris-lea/+archive/node.js/) available.
       
      -For Ubuntu there is also a [PPA](https://launchpad.net/~chris-lea/+archive/node.js/) available.
      +    $ sudo add-apt-repository ppa:chris-lea/node.js
      +    $ sudo apt-get update
      +    $ sudo apt-get install nodejs
       
       As `v8` is written in C++ and comes as a C++ library it is crucial to compile your module
       using the same compiler flags as used for building v8.
       To make things easier, `node.js` provides a build tool called `node-gyp`.
       
      -This expects a configuration file named `binding.gyp` which is basically in JSON format and
      -conforms to the same format that is used with Google's build-tool `gyp`.
      +You have to install it using `npm`:
      +
      +    $ npm install -g node-gyp
      +
      +
      +`node-gyp` expects a configuration file named `binding.gyp` which is basically in JSON
      +format and conforms to the same format that is used with Google's build-tool `gyp`.
       
       `binding.gyp`:
       
      @@ -117,6 +128,15 @@ To use the extension you have to require it in your javascript source file.
       
           require("./build/Release/example")
       
      +#### Troubleshooting
      +
      +- *'module' object has no attribute 'script_main'*
      +
      +  This happened when `gyp` was installed as distribution package.
      +  It seems to be outdated. Removing it resolves the problem.
      +
      +    $ sudo apt-get remove gyp
      +
       
       ### Embedded Webkit
       
      
      From 8e65414a764f390e0db4f8ded0031ecdef16d896 Mon Sep 17 00:00:00 2001
      From: Oliver Buchtala 
      Date: Thu, 20 Feb 2014 11:37:15 +0100
      Subject: [PATCH 0652/1048] Add an extra argument for enabling nodejs support.
      
      This is essentially using the v8 emitter plus setting a #define.
      ---
       Source/Modules/javascript.cxx | 5 +++++
       1 file changed, 5 insertions(+)
      
      diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx
      index 496114c01..fc0006225 100644
      --- a/Source/Modules/javascript.cxx
      +++ b/Source/Modules/javascript.cxx
      @@ -511,6 +511,11 @@ void JAVASCRIPT::main(int argc, char *argv[]) {
               Swig_mark_arg(i);
               mode = JSEmitter::JavascriptCore;
               SWIG_library_directory("javascript/jsc");
      +      } else if (strcmp(argv[i], "-node") == 0) {
      +        Swig_mark_arg(i);
      +        mode = JSEmitter::V8;
      +        SWIG_library_directory("javascript/v8");
      +        Preprocessor_define("BUILDING_NODE_EXTENSION 1", 0);
             } else if (strcmp(argv[i], "-debug-codetemplates") == 0) {
               Swig_mark_arg(i);
               js_template_enable_debug = true;
      
      From 3f22a3d639a2884b8cd50d57fc22b6df49a85cdf Mon Sep 17 00:00:00 2001
      From: Oliver Buchtala 
      Date: Thu, 20 Feb 2014 11:37:40 +0100
      Subject: [PATCH 0653/1048] Simplification in common javascript example
       Makefile.
      
      ---
       Examples/javascript/js_example.mk | 13 +------------
       1 file changed, 1 insertion(+), 12 deletions(-)
      
      diff --git a/Examples/javascript/js_example.mk b/Examples/javascript/js_example.mk
      index c2e9c6dcf..7cecd184a 100644
      --- a/Examples/javascript/js_example.mk
      +++ b/Examples/javascript/js_example.mk
      @@ -16,18 +16,7 @@ else
       	JSENGINE=node
       endif
       
      -ifeq (node,$(JSENGINE))
      -  SWIGOPT=-v8 -DBUILDING_NODE_EXTENSION=1
      -endif
      -
      -ifeq (v8,$(JSENGINE))
      -  SWIGOPT=-v8
      -endif
      -
      -ifeq (jsc,$(JSENGINE))
      -  SWIGOPT=-jsc
      -endif
      -
      +SWIGOPT=-$(JSENGINE)
       
       ifeq (node,$(JSENGINE))
       
      
      From 462674ea11fc227501a485a878efd1ae9e111126 Mon Sep 17 00:00:00 2001
      From: Oliver Buchtala 
      Date: Thu, 20 Feb 2014 12:28:06 +0100
      Subject: [PATCH 0654/1048] Added examples to Javascript module documentation.
      
      ---
       Doc/Manual/Javascript.md | 183 +++++++++++++++++++++++++++++++++++++++
       1 file changed, 183 insertions(+)
      
      diff --git a/Doc/Manual/Javascript.md b/Doc/Manual/Javascript.md
      index 33f65e864..f2289757a 100644
      --- a/Doc/Manual/Javascript.md
      +++ b/Doc/Manual/Javascript.md
      @@ -128,6 +128,10 @@ To use the extension you have to require it in your javascript source file.
       
           require("./build/Release/example")
       
      +
      +A more detailed exlanation is given in section `Examples`.
      +
      +
       #### Troubleshooting
       
       - *'module' object has no attribute 'script_main'*
      @@ -230,6 +234,185 @@ TODO:
       - sample integration code
       
       
      +## Examples
      +
      +Some basic examples are shown here in more detail.
      +
      +### Simple
      +
      +The common example `simple` looks like this:
      +
      +    /* File : example.i */
      +    %module example
      +
      +    %inline %{
      +    extern int    gcd(int x, int y);
      +    extern double Foo;
      +    %}
      +
      +To make this available as node extension a `binding.gyp` has to be created:
      +
      +    {
      +      "targets": [
      +        {
      +          "target_name": "example",
      +          "sources": [ "example.cxx", "example_wrap.cxx" ]
      +        }
      +      ]
      +    }
      +
      +Then `node-gyp` is used to build the extension:
      +
      +    $ node-gyp configure build
      +
      +
      +From a 'nodejs` application this would be used this way:
      +
      +    // import the extension via require
      +    var example = require("./build/Release/example");
      +
      +    // calling the global method
      +    var x = 42;
      +    var y = 105;
      +    var g = example.gcd(x,y);
      +
      +    // Accessing the globak variable
      +    var f = example.Foo;
      +    example.Foo = 3.1415926;
      +
      +First the module `example` is loaded from the previously built extension.
      +Global methods and variables are available in the scope of the module.
      +
      +> Note: ECMAScript 5, the currently implemented Javascript standard, does not have modules.
      +> `node.js` and other implementations provide this mechanism defined by the
      +> [CommonJS](http://wiki.commonjs.org/wiki/CommonJS) group.
      +> For browsers this is provided by [Browserify](http://browserify.org), for instance.
      +
      +### Class
      +
      +The common example `class` looks defines three classes, `Shape`, `Circle`, and `Square`:
      +
      +    class Shape {
      +    public:
      +      Shape() {
      +        nshapes++;
      +      }
      +      virtual ~Shape() {
      +        nshapes--;
      +      };
      +      double  x, y;
      +      void    move(double dx, double dy);
      +      virtual double area(void) = 0;
      +      virtual double perimeter(void) = 0;
      +      static  int nshapes;
      +    };
      +
      +    class Circle : public Shape {
      +    private:
      +      double radius;
      +    public:
      +      Circle(double r) : radius(r) { };
      +      virtual double area(void);
      +      virtual double perimeter(void);
      +    };
      +
      +    class Square : public Shape {
      +    private:
      +      double width;
      +    public:
      +      Square(double w) : width(w) { };
      +      virtual double area(void);
      +      virtual double perimeter(void);
      +    };
      +
      +`Circle` and `Square` inherit from `Shape`. `Shape` has a static variable a function `move`
      +that can't be overridden (non-virtual) and two abstract functions `area` and `perimeter` (pure virtual) that must be overridden by the sub-classes.
      +
      +A `nodejs` extension is built the same way as for the `simple` example.
      +
      +From Javascript this extension can be used this way:
      +
      +
      +    var example = require("./build/Release/example");
      +
      +    // local aliases for convenience
      +    var Shape = example.Shape;
      +    var Circle = example.Circle;
      +    var Square = example.Square;
      +
      +    // Creating new instances using the 'new' operator
      +    var c = new Circle(10);
      +    var s = new Square(10);
      +
      +    // Accessing a static member
      +    var nshapes = Shape.nshapes;
      +
      +    // Accessing member variables
      +    c.x = 20;
      +    c.y = 30;
      +    s.x = -10;
      +    s.y = 5;
      +
      +    // Calling some methods -----
      +    c.area();
      +    c.perimeter();
      +    s.area();
      +    s.perimeter();
      +
      +
      +Running these commands in an interactive node shell result in this output:
      +
      +    $ node -i
      +    > var example = require("./build/Release/example");
      +    undefined
      +    > var Shape = example.Shape;
      +    undefined
      +    > var Circle = example.Circle;
      +    undefined
      +    > var Square = example.Square;
      +    undefined
      +    > var c = new Circle(10);
      +    undefined
      +    > var s = new Square(10);
      +    undefined
      +    > var nshapes = Shape.nshapes;
      +    undefined
      +    > Shape.nshapes;
      +    2
      +    > c.x = 20;
      +    20
      +    > c.y = 30;
      +    30
      +    > s.x = -10;
      +    -10
      +    > s.y = 5;
      +    5
      +    > c.area();
      +    314.1592653589793
      +    > c.perimeter();
      +    62.83185307179586
      +    > s.area();
      +    100
      +    > s.perimeter();
      +    40
      +    > c.move(40, 40)
      +    undefined
      +    > c.x
      +    60
      +    > c.y
      +    70
      +    >
      +
      +> Note: In ECMAScript 5 there is no concept for classes.
      +  Instead each function can be used as a constructor function which is executed by the 'new'
      +  operator. Furthermore, during construction the key property `prototype` of the constructor function is used to attach a prototype instance to the created object.
      +  A prototype is essentially an object itself that is the first-class delegate of a class
      +  used whenever the access to a property of an object fails.
      +  The very same prototype instance is shared among all instances of one type.
      +  Prototypal inheritance is explained in more detail on in
      +  [Inheritance and the prototype chain](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain), for instance.
      +
      +
       ## Implementation
       
       The Javascript Module implementation has take a very different approach than other modules
      
      From 1ffacaab5b7635da623de6c49c22684a1c46d549 Mon Sep 17 00:00:00 2001
      From: Oliver Buchtala 
      Date: Thu, 20 Feb 2014 12:30:57 +0100
      Subject: [PATCH 0655/1048] Add note about '-node' command line flag for
       Node.js code generation.
      
      ---
       Doc/Manual/Javascript.md | 4 +++-
       1 file changed, 3 insertions(+), 1 deletion(-)
      
      diff --git a/Doc/Manual/Javascript.md b/Doc/Manual/Javascript.md
      index f2289757a..2690cb5db 100644
      --- a/Doc/Manual/Javascript.md
      +++ b/Doc/Manual/Javascript.md
      @@ -33,7 +33,9 @@ Suppose that you defined a SWIG module such as the following:
           extern double Foo;
       
       To build a Javascript module, run SWIG using the `-javascript` option
      -and a desired target engine `-jsc` or `-v8`.
      +and a desired target engine `-jsc`, `-v8`, or `-node`.
      +The generator for `node` is essentially delegating to the `v8` generator and adds
      +some necessary preprocessor definitions.
       
           $ swig -javascript -jsc example.i
       
      
      From 84ba91dc63d817376486cecfd7188f56303e6e3b Mon Sep 17 00:00:00 2001
      From: Oliver Buchtala 
      Date: Thu, 20 Feb 2014 12:38:53 +0100
      Subject: [PATCH 0656/1048] Some fixes in example section of Javascript
       documentation.
      
      ---
       Doc/Manual/Javascript.md | 40 +++++++++++++++++++++++++++-------------
       1 file changed, 27 insertions(+), 13 deletions(-)
      
      diff --git a/Doc/Manual/Javascript.md b/Doc/Manual/Javascript.md
      index 2690cb5db..044343588 100644
      --- a/Doc/Manual/Javascript.md
      +++ b/Doc/Manual/Javascript.md
      @@ -292,7 +292,7 @@ Global methods and variables are available in the scope of the module.
       
       ### Class
       
      -The common example `class` looks defines three classes, `Shape`, `Circle`, and `Square`:
      +The common example `class` defines three classes, `Shape`, `Circle`, and `Square`:
       
           class Shape {
           public:
      @@ -327,12 +327,14 @@ The common example `class` looks defines three classes, `Shape`, `Circle`, and `
             virtual double perimeter(void);
           };
       
      -`Circle` and `Square` inherit from `Shape`. `Shape` has a static variable a function `move`
      -that can't be overridden (non-virtual) and two abstract functions `area` and `perimeter` (pure virtual) that must be overridden by the sub-classes.
      +`Circle` and `Square` inherit from `Shape`. `Shape` has a static variable `nshapes`,
      +a function `move` that can't be overridden (non-virtual),
      +and two abstract functions `area` and `perimeter` (pure virtual) that must be
      +overridden by the sub-classes.
       
       A `nodejs` extension is built the same way as for the `simple` example.
       
      -From Javascript this extension can be used this way:
      +In javascript it can be used this way:
       
       
           var example = require("./build/Release/example");
      @@ -342,27 +344,29 @@ From Javascript this extension can be used this way:
           var Circle = example.Circle;
           var Square = example.Square;
       
      -    // Creating new instances using the 'new' operator
      +    // creating new instances using the 'new' operator
           var c = new Circle(10);
           var s = new Square(10);
       
      -    // Accessing a static member
      -    var nshapes = Shape.nshapes;
      +    // accessing a static member
      +    Shape.nshapes;
       
      -    // Accessing member variables
      +    // accessing member variables
           c.x = 20;
           c.y = 30;
           s.x = -10;
           s.y = 5;
       
      -    // Calling some methods -----
      +    // calling some methods
           c.area();
           c.perimeter();
           s.area();
           s.perimeter();
       
      +    // instantiation of Shape is not permitted
      +    new Shape();
       
      -Running these commands in an interactive node shell result in this output:
      +Running these commands in an interactive node shell results in the following output:
       
           $ node -i
           > var example = require("./build/Release/example");
      @@ -377,8 +381,6 @@ Running these commands in an interactive node shell result in this output:
           undefined
           > var s = new Square(10);
           undefined
      -    > var nshapes = Shape.nshapes;
      -    undefined
           > Shape.nshapes;
           2
           > c.x = 20;
      @@ -403,7 +405,19 @@ Running these commands in an interactive node shell result in this output:
           60
           > c.y
           70
      -    >
      +    > new Shape()
      +    Error: Class Shape can not be instantiated
      +    at repl:1:2
      +    at REPLServer.self.eval (repl.js:110:21)
      +    at Interface. (repl.js:239:12)
      +    at Interface.EventEmitter.emit (events.js:95:17)
      +    at Interface._onLine (readline.js:202:10)
      +    at Interface._line (readline.js:531:8)
      +    at Interface._ttyWrite (readline.js:760:14)
      +    at ReadStream.onkeypress (readline.js:99:10)
      +    at ReadStream.EventEmitter.emit (events.js:98:17)
      +    at emitKey (readline.js:1095:12)
      +
       
       > Note: In ECMAScript 5 there is no concept for classes.
         Instead each function can be used as a constructor function which is executed by the 'new'
      
      From de7ed84f77d2e27b5fdea1ad0774994df2720caa Mon Sep 17 00:00:00 2001
      From: Olly Betts 
      Date: Fri, 21 Feb 2014 08:09:58 +1300
      Subject: [PATCH 0657/1048] 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 0658/1048] 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 0659/1048] 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 0660/1048] 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 0661/1048] 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 0662/1048] 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 0663/1048] 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 0664/1048] 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 0665/1048] 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 0666/1048] 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 0667/1048] 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 0668/1048] 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 0669/1048] 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 0670/1048] 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 0671/1048] 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 0672/1048] 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 0673/1048] 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 0674/1048] 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 0675/1048] 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 0676/1048] 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 0677/1048] 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 0678/1048] 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 0679/1048] 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 0680/1048] 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 0681/1048] 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 0682/1048] 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 0683/1048] 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 0684/1048] 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 0685/1048] 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 15550dab450f003c0b42d6a3353b137435793999 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 25 Feb 2014 20:16:15 +0100 Subject: [PATCH 0686/1048] Fix issue with strange constants under OSX. Receiving strange constant nodes before the real tree under OSX 10.8. Not so under Ubuntu 12.04. --- Source/Modules/javascript.cxx | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index fc0006225..b20de6202 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -33,6 +33,7 @@ bool js_template_enable_debug = false; #define MEMBER_FUNCTIONS "member_functions" #define STATIC_FUNCTIONS "static_functions" #define STATIC_VARIABLES "static_variables" +#define HAS_TEMPLATES "has_templates" #define RESET true @@ -600,6 +601,9 @@ JSEmitter::~JSEmitter() { * ----------------------------------------------------------------------------- */ int JSEmitter::registerTemplate(const String *name, const String *code) { + if (!State::IsSet(state.global(HAS_TEMPLATES))) { + SetFlag(state.global(), HAS_TEMPLATES); + } return Setattr(templates, name, code); } @@ -1067,6 +1071,13 @@ int JSEmitter::emitSetter(Node *n, bool is_member, bool is_static) { * ----------------------------------------------------------------------------- */ int JSEmitter::emitConstant(Node *n) { + // HACK: somehow it happened under OSX that before everything started + // a lot of SWIG internal constants were emitted + // This didn't happen on Ubuntu Precise... + // so we + if (!State::IsSet(state.global(HAS_TEMPLATES))) { + return SWIG_ERROR; + } Wrapper *wrapper = NewWrapper(); SwigType *type = Getattr(n, "type"); From 3aa689d276158fc89921d98ee928cfb68465b943 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Wed, 26 Feb 2014 00:13:18 +0000 Subject: [PATCH 0687/1048] 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 e62c6126e9d6645eaff2b96d7847d4a8c681bb84 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 26 Feb 2014 10:47:48 +0100 Subject: [PATCH 0688/1048] Fix regressions in Javascript example configuration. --- Examples/Makefile.in | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 17e66acce..fe0e42fdc 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -717,7 +717,7 @@ JS_INTERPRETER_SRC = \ # TODO: improve: # - exe suffix # - '-ldl' should come from configure -javascript_exe: $(SRCS) +javascript_custom_interpreter: $(JS_INTERPRETER_SRC) $(CXX) $(CXXFLAGS) $(JS_INTERPRETER_CXXFLAGS) $(JSINCLUDES) $(JS_INTERPRETER_SRC) -ldl $(LIBS) $(JSDYNAMICLINKING) -o $(JS_INTERPRETER_SRC_DIR)/javascript SWIGJS = $(SWIG) -javascript @@ -744,11 +744,23 @@ javascript_build_cpp:: $(SRCS) javascript_build_node: $(SRCS) node-gyp --loglevel=silent configure build 1>>/dev/null +# These targets are used by the test-suite: + +javascript: $(SRCS) javascript_custom_interpreter + $(SWIGJS) $(SWIGOPT) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CFLAGS) $(JSCFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) $(JSINCLUDES) + $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + +javascript_cpp: $(SRCS) javascript_custom_interpreter + $(SWIGJS) -c++ $(SWIGOPT) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CFLAGS) $(JSCFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(JSINCLUDES) + $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + # ----------------------------------------------------------------- # Running a javascript example # ----------------------------------------------------------------- -javascript_run: +javascript_run: $(JS_INTERPRETER_SRC_DIR)/javascript $(JS_INTERPRETER_SRC_DIR)/javascript -$(JSENGINE) runme.js # TODO: make node configurable and detected via ./configure @@ -764,6 +776,7 @@ javascript_clean: rm -f *_wrap* runme rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *@JSSO@ + rm -f $(JS_INTERPRETER_SRC_DIR)/javascript From 16a702c0aac717462b1eb94fc4640446943d9396 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 26 Feb 2014 10:48:38 +0100 Subject: [PATCH 0689/1048] Added a comment. --- Source/Modules/javascript.cxx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index b20de6202..7b153c66c 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -1073,8 +1073,8 @@ int JSEmitter::emitSetter(Node *n, bool is_member, bool is_static) { int JSEmitter::emitConstant(Node *n) { // HACK: somehow it happened under OSX that before everything started // a lot of SWIG internal constants were emitted - // This didn't happen on Ubuntu Precise... - // so we + // This didn't happen on other platforms yet... + // we ignore those premature definitions if (!State::IsSet(state.global(HAS_TEMPLATES))) { return SWIG_ERROR; } From bf1606c0f9261dcb4ae8d5c24aebc987a67e7510 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 26 Feb 2014 11:10:09 +0100 Subject: [PATCH 0690/1048] Fix travis configuration. --- .travis.yml | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/.travis.yml b/.travis.yml index 3b8500aee..2664890d4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,17 +1,16 @@ language: c compiler: - gcc -node_js: - -0.10.12 before_script: - "sudo apt-get install rlwrap" - - "wget https://launchpad.net/~chris-lea/+archive/node.js/+build/4936691/+files/nodejs_0.10.18-1chl1~precise1_amd64.deb" - - "sudo dpkg -i nodejs_0.10.18-1chl1~precise1_amd64.deb" + - "sudo apt-get install python-software-properties" + - "echo 'yes' | sudo add-apt-repository ppa:chris-lea/node.js" + - "sudo apt-get update" + - "sudo apt-get install nodejs" - "sudo npm install -g node-gyp" - - "sudo apt-get install libv8-3.7.12.22 libv8-dev" + - "sudo apt-get install libv8-dev" - "sudo apt-get install libwebkitgtk-dev" - "./autogen.sh && ./configure && make" - - "cd Examples && make javascript_exe && cd .." script: - "make SMOKE=1 check-javascript-test-suite" - "make SMOKE=1 ENGINE=jsc check-javascript-test-suite" From b216a739c45cfb595a5b70da7e811b6130148a63 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 26 Feb 2014 20:51:38 +0100 Subject: [PATCH 0691/1048] Introduced an extra Makefile for the custom javascript interpreter. --- Examples/Makefile.in | 49 +------ Tools/javascript/Makefile.in | 56 ++++++++ Tools/javascript/javascript.cxx | 5 + Tools/javascript/js_shell.cxx | 4 +- Tools/javascript/jsc_shell.cxx | 4 + configure.ac | 6 + swig-v8/swig-v8.xcodeproj/project.pbxproj | 153 ++++++++++++++++++++++ 7 files changed, 233 insertions(+), 44 deletions(-) create mode 100644 Tools/javascript/Makefile.in create mode 100644 swig-v8/swig-v8.xcodeproj/project.pbxproj diff --git a/Examples/Makefile.in b/Examples/Makefile.in index fe0e42fdc..b3292810a 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -683,43 +683,6 @@ JSSO =@JSSO@ JSLDSHARED = @JSLDSHARED@ JSCXXSHARED = @JSCXXSHARED@ -# ---------------------------------------------------------------- -# Compile a custom javascript interpreter -# ---------------------------------------------------------------- -# -# Note: -# There is no common CLI Javascript interpreter. -# V8 comes with one 'd8' which however does not provide a means -# to load extensions. Therefore, by default we use nodejs as -# environment. -# For testing native v8 and jsc extensions we provide our own -# interpreter (see 'Tools/javascript'). -# -# ---------------------------------------------------------------- - -JS_INTERPRETER_SRC_DIR = $(ROOT_DIR)/Tools/javascript - -# These settings are provided by 'configure' (see '/configure.in') -ifeq (1, @JSV8ENABLED@) - JS_INTERPRETER_SRC_V8 = $(JS_INTERPRETER_SRC_DIR)/v8_shell.cxx - JS_INTERPRETER_CXXFLAGS_V8 = -DENABLE_V8 -endif - -ifeq (1, @JSCENABLED@) - JS_INTERPRETER_SRC_JSC = $(JS_INTERPRETER_SRC_DIR)/jsc_shell.cxx - JS_INTERPRETER_CXXFLAGS_JSC = -DENABLE_JSC -endif - -JS_INTERPRETER_CXXFLAGS = $(JS_INTERPRETER_CXXFLAGS_JSC) $(JS_INTERPRETER_CXXFLAGS_V8) -JS_INTERPRETER_SRC = \ - $(JS_INTERPRETER_SRC_DIR)/javascript.cxx $(JS_INTERPRETER_SRC_DIR)/js_shell.cxx $(JS_INTERPRETER_SRC_JSC) $(JS_INTERPRETER_SRC_V8) - -# TODO: improve: -# - exe suffix -# - '-ldl' should come from configure -javascript_custom_interpreter: $(JS_INTERPRETER_SRC) - $(CXX) $(CXXFLAGS) $(JS_INTERPRETER_CXXFLAGS) $(JSINCLUDES) $(JS_INTERPRETER_SRC) -ldl $(LIBS) $(JSDYNAMICLINKING) -o $(JS_INTERPRETER_SRC_DIR)/javascript - SWIGJS = $(SWIG) -javascript # ---------------------------------------------------------------- @@ -760,8 +723,11 @@ javascript_cpp: $(SRCS) javascript_custom_interpreter # Running a javascript example # ----------------------------------------------------------------- -javascript_run: $(JS_INTERPRETER_SRC_DIR)/javascript - $(JS_INTERPRETER_SRC_DIR)/javascript -$(JSENGINE) runme.js +javascript_custom_interpreter: + (cd $(ROOT_DIR)/Tools/javascript && $(MAKE) JSENGINE='$(JSENGINE)') + +javascript_run: javascript_custom_interpreter + $(ROOT_DIR)/Tools/javascript/javascript -$(JSENGINE) runme.js # TODO: make node configurable and detected via ./configure javascript_run_node: @@ -775,9 +741,8 @@ javascript_clean: rm -rf build rm -f *_wrap* runme rm -f core @EXTRA_CLEAN@ - rm -f *.@OBJEXT@ *@JSSO@ - rm -f $(JS_INTERPRETER_SRC_DIR)/javascript - + rm -f *.@OBJEXT@ *@JSSO@ *.bundle + (cd $(ROOT_DIR)/Tools/javascript && $(MAKE) -s clean) ################################################################## diff --git a/Tools/javascript/Makefile.in b/Tools/javascript/Makefile.in new file mode 100644 index 000000000..57e63e88d --- /dev/null +++ b/Tools/javascript/Makefile.in @@ -0,0 +1,56 @@ +# ---------------------------------------------------------------- +# Compile a custom javascript interpreter +# ---------------------------------------------------------------- +# +# Note: +# There is no common CLI Javascript interpreter. +# V8 comes with one 'd8' which however does not provide a means +# to load extensions. Therefore, by default we use nodejs as +# environment. +# For testing native v8 and jsc extensions we provide our own +# interpreter (see 'Tools/javascript'). +# +# ---------------------------------------------------------------- +CC = @CC@ +# HACK: under OSX a g++ compiled interpreter is seg-faulting when loading module libraries +# with 'c++' it works... probably some missing flags? +CXX = @JSINTERPRETERCXX@ +CFLAGS = @BOOST_CPPFLAGS@ @PLATFLAGS@ + +ROOT_DIR = @ROOT_DIR@ +JSCFLAGS = @JSCFLAGS@ +JSCXXFLAGS = @JSCXXFLAGS@ +JSINCLUDES = @JSCOREINC@ @JSV8INC@ +JSDYNAMICLINKING = @JSCOREDYNAMICLINKING@ @JSV8DYNAMICLINKING@ +JSLIBRARYPREFIX = @JSLIBRARYPREFIX@ +JSSO =@JSSO@ +JSLDSHARED = @JSLDSHARED@ +JSCXXSHARED = @JSCXXSHARED@ +JSV8ENABLED = @JSV8ENABLED@ +JSCENABLED = @JSCENABLED@ + +# These settings are provided by 'configure' (see '/configure.in') +ifeq (1, $(JSV8ENABLED)) + JS_INTERPRETER_SRC_V8 = v8_shell.cxx + JS_INTERPRETER_CXXFLAGS_V8 = -DENABLE_V8 +endif + +ifeq (1, $(JSCENABLED)) + JS_INTERPRETER_SRC_JSC = jsc_shell.cxx + JS_INTERPRETER_CXXFLAGS_JSC = -DENABLE_JSC +endif + +JS_INTERPRETER_CXXFLAGS = $(JS_INTERPRETER_CXXFLAGS_JSC) $(JS_INTERPRETER_CXXFLAGS_V8) +JS_INTERPRETER_SRC = javascript.cxx js_shell.cxx $(JS_INTERPRETER_SRC_JSC) $(JS_INTERPRETER_SRC_V8) + +JS_INTERPRETER_OBJS = $(JS_INTERPRETER_SRC:.cxx=.o) + +%.o: %.cxx + $(CXX) $(JS_INTERPRETER_CXXFLAGS) -g $(JSINCLUDES) -o $@ -c $< + +javascript: $(JS_INTERPRETER_OBJS) + $(CXX) -g -Wl,-search_paths_first -Wl,-headerpad_max_install_names $^ $(CFLAGS) -o javascript $(JSDYNAMICLINKING) + +clean: + rm -f *.o + rm -f javascript diff --git a/Tools/javascript/javascript.cxx b/Tools/javascript/javascript.cxx index ec4ac4e3f..e5cb0a47e 100644 --- a/Tools/javascript/javascript.cxx +++ b/Tools/javascript/javascript.cxx @@ -13,6 +13,11 @@ void print_usage() { int main(int argc, char* argv[]) { +#if defined(JAVASCRIPT_INTERPRETER_STOP) + std::cout << "Attach your Debugger and press any key to continue" << std::endl; + std::cin.get(); +#endif + std::string scriptPath = ""; bool interactive = false; diff --git a/Tools/javascript/js_shell.cxx b/Tools/javascript/js_shell.cxx index ca5ca7ecd..c0ac3da58 100644 --- a/Tools/javascript/js_shell.cxx +++ b/Tools/javascript/js_shell.cxx @@ -7,7 +7,7 @@ #ifdef __GNUC__ #ifdef __APPLE__ -#define LIBRARY_EXT ".dylib" +#define LIBRARY_EXT ".bundle" #else #define LIBRARY_EXT ".so" #endif @@ -52,7 +52,7 @@ std::string JSShell::LoadModule(const std::string& name, HANDLE* library) { HANDLE handle = LOAD_LIBRARY(lib_name.c_str()); if(handle == 0) { - std::cout << "Could not load library " << lib_name << ":" + std::cerr << "Could not load library " << lib_name << ":" << std::endl << LIBRARY_ERROR() << std::endl; return 0; } diff --git a/Tools/javascript/jsc_shell.cxx b/Tools/javascript/jsc_shell.cxx index e4e8cdd96..cf30d7bd7 100644 --- a/Tools/javascript/jsc_shell.cxx +++ b/Tools/javascript/jsc_shell.cxx @@ -70,6 +70,10 @@ bool JSCShell::InitializeEngine() { JSClassRef __shell_class__ = JSClassCreate(&__shell_classdef__); JSObjectRef __shell__ = JSObjectMake(context, __shell_class__, 0); bool success = JSObjectSetPrivate(__shell__, (void*) (long) this); + if (!success) { + std::cerr << "Could not register the shell in the Javascript context" << std::endl; + return false; + } JSStringRef shellKey = JSStringCreateWithUTF8CString("__shell__"); JSObjectSetProperty(context, globalObject, shellKey, __shell__, kJSPropertyAttributeReadOnly, NULL); JSStringRelease(shellKey); diff --git a/configure.ac b/configure.ac index 72b507662..09bb65f25 100644 --- a/configure.ac +++ b/configure.ac @@ -1135,11 +1135,14 @@ else JSSO=".dylib" JSLDSHARED='$(CC) -dynamiclib' JSCXXSHARED='$(CXX) -dynamiclib' + # HACK: didn't manage to get dynamic module loading working with a g++ compiled interpreter + JSINTERPRETERCXX='c++' ;; *) JSSO=$SO JSLDSHARED='$(LDSHARED)' JSCXXSHARED='$(CXXSHARED)' + JSINTERPRETERCXX='$(CXX)' ;; esac @@ -1219,6 +1222,7 @@ else ;; *-*-darwin*) JSCOREDYNAMICLINKING="-framework JavaScriptCore" + JSCENABLED=1 ;; *) ;; @@ -1305,6 +1309,7 @@ AC_SUBST(JSLIBRARYPREFIX) AC_SUBST(JSSO) AC_SUBST(JSLDSHARED) AC_SUBST(JSCXXSHARED) +AC_SUBST(JSINTERPRETERCXX) AC_SUBST(JSCOREINC) AC_SUBST(JSCOREDYNAMICLINKING) @@ -2650,6 +2655,7 @@ AC_CONFIG_FILES([ \ Examples/test-suite/r/Makefile \ Examples/test-suite/go/Makefile \ Examples/test-suite/javascript/Makefile \ + Tools/javascript/Makefile \ Lib/ocaml/swigp4.ml ]) AC_CONFIG_FILES([preinst-swig], [chmod +x preinst-swig]) diff --git a/swig-v8/swig-v8.xcodeproj/project.pbxproj b/swig-v8/swig-v8.xcodeproj/project.pbxproj new file mode 100644 index 000000000..d6fcad63b --- /dev/null +++ b/swig-v8/swig-v8.xcodeproj/project.pbxproj @@ -0,0 +1,153 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXGroup section */ + A7E4F27918BDF64900ED77C7 = { + isa = PBXGroup; + children = ( + ); + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXLegacyTarget section */ + A7E4F28018BDF64900ED77C7 /* swig-v8 */ = { + isa = PBXLegacyTarget; + buildArgumentsString = "$(ACTION)"; + buildConfigurationList = A7E4F28318BDF64900ED77C7 /* Build configuration list for PBXLegacyTarget "swig-v8" */; + buildPhases = ( + ); + buildToolPath = /usr/bin/make; + dependencies = ( + ); + name = "swig-v8"; + passBuildSettingsInEnvironment = 1; + productName = "swig-v8"; + }; +/* End PBXLegacyTarget section */ + +/* Begin PBXProject section */ + A7E4F27B18BDF64900ED77C7 /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 0450; + ORGANIZATIONNAME = "Oliver Buchtala"; + }; + buildConfigurationList = A7E4F27E18BDF64900ED77C7 /* Build configuration list for PBXProject "swig-v8" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = A7E4F27918BDF64900ED77C7; + projectDirPath = ""; + projectRoot = ""; + targets = ( + A7E4F28018BDF64900ED77C7 /* swig-v8 */, + ); + }; +/* End PBXProject section */ + +/* Begin XCBuildConfiguration section */ + A7E4F28118BDF64900ED77C7 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ARCHS = "$(ARCHS_STANDARD_64_BIT)"; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_ENABLE_OBJC_EXCEPTIONS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.8; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + }; + name = Debug; + }; + A7E4F28218BDF64900ED77C7 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ARCHS = "$(ARCHS_STANDARD_64_BIT)"; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_ENABLE_OBJC_EXCEPTIONS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.8; + SDKROOT = macosx; + }; + name = Release; + }; + A7E4F28418BDF64900ED77C7 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + DEBUGGING_SYMBOLS = YES; + GCC_GENERATE_DEBUGGING_SYMBOLS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + OTHER_CFLAGS = ""; + OTHER_LDFLAGS = ""; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + A7E4F28518BDF64900ED77C7 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + OTHER_CFLAGS = ""; + OTHER_LDFLAGS = ""; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + A7E4F27E18BDF64900ED77C7 /* Build configuration list for PBXProject "swig-v8" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A7E4F28118BDF64900ED77C7 /* Debug */, + A7E4F28218BDF64900ED77C7 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A7E4F28318BDF64900ED77C7 /* Build configuration list for PBXLegacyTarget "swig-v8" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A7E4F28418BDF64900ED77C7 /* Debug */, + A7E4F28518BDF64900ED77C7 /* Release */, + ); + defaultConfigurationIsVisible = 0; + }; +/* End XCConfigurationList section */ + }; + rootObject = A7E4F27B18BDF64900ED77C7 /* Project object */; +} From 15f12d9b59b9e8522853f010f9d443164774a6a6 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 26 Feb 2014 22:44:37 +0100 Subject: [PATCH 0692/1048] Make examples work with node.js and the custom interpreter. --- Examples/javascript/class/example.js | 1 + Examples/javascript/class/runme.js | 2 +- Examples/javascript/constant/example.js | 1 + Examples/javascript/constant/runme.js | 2 +- Examples/javascript/enum/example.js | 1 + Examples/javascript/enum/runme.js | 2 +- Examples/javascript/exception/example.js | 1 + Examples/javascript/exception/runme.js | 2 +- Examples/javascript/functor/example.js | 1 + Examples/javascript/functor/runme.js | 2 +- Examples/javascript/namespace/example.js | 1 + Examples/javascript/namespace/runme.js | 2 +- Examples/javascript/operator/example.js | 1 + Examples/javascript/operator/runme.js | 2 +- Examples/javascript/overload/example.js | 1 + Examples/javascript/overload/runme.js | 2 +- Examples/javascript/overload/swig_gdb.log | 0 Examples/javascript/pointer/example.js | 1 + Examples/javascript/pointer/runme.js | 2 +- Examples/javascript/reference/example.js | 1 + Examples/javascript/reference/runme.js | 2 +- Examples/javascript/simple/example.js | 1 + Examples/javascript/simple/runme.js | 2 +- Examples/javascript/template/example.js | 1 + Examples/javascript/template/runme.js | 2 +- Examples/javascript/variables/example.js | 1 + Examples/javascript/variables/runme.js | 2 +- 27 files changed, 26 insertions(+), 13 deletions(-) create mode 100644 Examples/javascript/class/example.js create mode 100644 Examples/javascript/constant/example.js create mode 100644 Examples/javascript/enum/example.js create mode 100644 Examples/javascript/exception/example.js create mode 100644 Examples/javascript/functor/example.js create mode 100644 Examples/javascript/namespace/example.js create mode 100644 Examples/javascript/operator/example.js create mode 100644 Examples/javascript/overload/example.js delete mode 100644 Examples/javascript/overload/swig_gdb.log create mode 100644 Examples/javascript/pointer/example.js create mode 100644 Examples/javascript/reference/example.js create mode 100644 Examples/javascript/simple/example.js create mode 100644 Examples/javascript/template/example.js create mode 100644 Examples/javascript/variables/example.js diff --git a/Examples/javascript/class/example.js b/Examples/javascript/class/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/class/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/class/runme.js b/Examples/javascript/class/runme.js index 5bb62ecd4..e1d5d9797 100755 --- a/Examples/javascript/class/runme.js +++ b/Examples/javascript/class/runme.js @@ -1,4 +1,4 @@ -var example = require("./build/Release/example"); +var example = require("./example"); // ----- Object creation ----- diff --git a/Examples/javascript/constant/example.js b/Examples/javascript/constant/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/constant/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/constant/runme.js b/Examples/javascript/constant/runme.js index b11c08c98..2188bf099 100755 --- a/Examples/javascript/constant/runme.js +++ b/Examples/javascript/constant/runme.js @@ -1,4 +1,4 @@ -var example = require("./build/Release/example"); +var example = require("./example"); console.log("ICONST = " + example.ICONST + " (should be 42)\n"); console.log("FCONST = " + example.FCONST + " (should be 2.1828)\n"); diff --git a/Examples/javascript/enum/example.js b/Examples/javascript/enum/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/enum/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/enum/runme.js b/Examples/javascript/enum/runme.js index 9d3accd1d..d4e89e8c8 100755 --- a/Examples/javascript/enum/runme.js +++ b/Examples/javascript/enum/runme.js @@ -1,4 +1,4 @@ -var example = require("./build/Release/example"); +var example = require("./example"); // ----- Object creation ----- diff --git a/Examples/javascript/exception/example.js b/Examples/javascript/exception/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/exception/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/exception/runme.js b/Examples/javascript/exception/runme.js index f7041f028..977f51ebc 100644 --- a/Examples/javascript/exception/runme.js +++ b/Examples/javascript/exception/runme.js @@ -1,4 +1,4 @@ -var example = require("./build/Release/example"); +var example = require("./example"); console.log("Trying to catch some exceptions."); t = new example.Test(); diff --git a/Examples/javascript/functor/example.js b/Examples/javascript/functor/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/functor/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/functor/runme.js b/Examples/javascript/functor/runme.js index f7be78286..dc12470f4 100644 --- a/Examples/javascript/functor/runme.js +++ b/Examples/javascript/functor/runme.js @@ -1,4 +1,4 @@ -var example = require("./build/Release/example"); +var example = require("./example"); a = new example.intSum(0); b = new example.doubleSum(100.0); diff --git a/Examples/javascript/namespace/example.js b/Examples/javascript/namespace/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/namespace/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/namespace/runme.js b/Examples/javascript/namespace/runme.js index 9a9d6744d..08e0d3769 100644 --- a/Examples/javascript/namespace/runme.js +++ b/Examples/javascript/namespace/runme.js @@ -1,4 +1,4 @@ -var example = require("./build/Release/example"); +var example = require("./example"); console.log("Global variable Foo=" + example.nspace.Foo); example.nspace.Foo = 5; diff --git a/Examples/javascript/operator/example.js b/Examples/javascript/operator/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/operator/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/operator/runme.js b/Examples/javascript/operator/runme.js index 9dba4b7f9..a700918d6 100644 --- a/Examples/javascript/operator/runme.js +++ b/Examples/javascript/operator/runme.js @@ -1,4 +1,4 @@ -var example = require("./build/Release/example"); +var example = require("./example"); a = new example.Complex(2,3); b = new example.Complex(-5,10); diff --git a/Examples/javascript/overload/example.js b/Examples/javascript/overload/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/overload/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/overload/runme.js b/Examples/javascript/overload/runme.js index 5ff5d01be..1e6c861a6 100644 --- a/Examples/javascript/overload/runme.js +++ b/Examples/javascript/overload/runme.js @@ -1,4 +1,4 @@ -var example = require("./build/Release/example"); +var example = require("./example"); example.f(); example.f(1); diff --git a/Examples/javascript/overload/swig_gdb.log b/Examples/javascript/overload/swig_gdb.log deleted file mode 100644 index e69de29bb..000000000 diff --git a/Examples/javascript/pointer/example.js b/Examples/javascript/pointer/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/pointer/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/pointer/runme.js b/Examples/javascript/pointer/runme.js index 00778dfbc..7f1e51c9e 100755 --- a/Examples/javascript/pointer/runme.js +++ b/Examples/javascript/pointer/runme.js @@ -1,4 +1,4 @@ -var example = require("./build/Release/example"); +var example = require("./example"); // First create some objects using the pointer library. console.log("Testing the pointer library\n"); diff --git a/Examples/javascript/reference/example.js b/Examples/javascript/reference/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/reference/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/reference/runme.js b/Examples/javascript/reference/runme.js index ee5737076..935d2b948 100755 --- a/Examples/javascript/reference/runme.js +++ b/Examples/javascript/reference/runme.js @@ -1,5 +1,5 @@ // This file illustrates the manipulation of C++ references in Javascript. -var example = require("./build/Release/example"); +var example = require("./example"); // ----- Object creation ----- diff --git a/Examples/javascript/simple/example.js b/Examples/javascript/simple/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/simple/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/simple/runme.js b/Examples/javascript/simple/runme.js index d970dcb7c..be2c18669 100755 --- a/Examples/javascript/simple/runme.js +++ b/Examples/javascript/simple/runme.js @@ -1,4 +1,4 @@ -var example = require("./build/Release/example"); +var example = require("./example"); /* Call our gcd() function */ diff --git a/Examples/javascript/template/example.js b/Examples/javascript/template/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/template/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/template/runme.js b/Examples/javascript/template/runme.js index 551475c72..55894dfd5 100644 --- a/Examples/javascript/template/runme.js +++ b/Examples/javascript/template/runme.js @@ -1,4 +1,4 @@ -var example = require("./build/Release/example"); +var example = require("./example"); //Call some templated functions console.log(example.maxint(3,7)); diff --git a/Examples/javascript/variables/example.js b/Examples/javascript/variables/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/variables/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/variables/runme.js b/Examples/javascript/variables/runme.js index 22d208480..d07861713 100755 --- a/Examples/javascript/variables/runme.js +++ b/Examples/javascript/variables/runme.js @@ -1,4 +1,4 @@ -var example = require("./build/Release/example"); +var example = require("./example"); // Try to set the values of some global variables example.ivar = 42; From 424e3f47123f8a7746d12d02204b896e55b8444d Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 26 Feb 2014 22:46:24 +0100 Subject: [PATCH 0693/1048] Fix custom javascript interpreter configuration for OSX. --- Examples/Makefile.in | 10 +++++----- Examples/javascript/js_example.mk | 2 +- Tools/javascript/Makefile.in | 11 ++++++----- Tools/javascript/javascript.cxx | 11 +++++++++-- Tools/javascript/js_shell.cxx | 14 ++++++++++++-- Tools/javascript/js_shell.h | 5 +++++ configure.ac | 4 ++++ 7 files changed, 42 insertions(+), 15 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index b3292810a..6769fda0b 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -668,7 +668,7 @@ android_clean: ##### JAVASCRIPT ###### ################################################################## -# Note: These targets are used from withing Makefiles in the Example directories. +# Note: These targets are also from within Makefiles in the Example directories. # There is a common makefile, 'Examples/javascript/js_example.mk' to simplify # create a configuration for a new example. @@ -690,10 +690,10 @@ SWIGJS = $(SWIG) -javascript # ---------------------------------------------------------------- javascript_wrapper: - $(SWIGJS) $(SWIGOPT) $(INTERFACEPATH) + $(SWIGJS) $(SWIGOPT) -o $(INTERFACEDIR)$(TARGET)_wrap.c $(INTERFACEPATH) javascript_wrapper_cpp: $(SRCS) - $(SWIGJS) -c++ $(SWIGOPT) $(INTERFACEPATH) + $(SWIGJS) -c++ $(SWIGOPT) -o $(INTERFACEDIR)$(TARGET)_wrap.cxx $(INTERFACEPATH) javascript_build: $(SRCS) $(CC) -c $(CCSHARED) $(CFLAGS) $(JSCFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) $(JSINCLUDES) @@ -727,7 +727,7 @@ javascript_custom_interpreter: (cd $(ROOT_DIR)/Tools/javascript && $(MAKE) JSENGINE='$(JSENGINE)') javascript_run: javascript_custom_interpreter - $(ROOT_DIR)/Tools/javascript/javascript -$(JSENGINE) runme.js + $(ROOT_DIR)/Tools/javascript/javascript -$(JSENGINE) -L $(TARGET) runme.js # TODO: make node configurable and detected via ./configure javascript_run_node: @@ -741,7 +741,7 @@ javascript_clean: rm -rf build rm -f *_wrap* runme rm -f core @EXTRA_CLEAN@ - rm -f *.@OBJEXT@ *@JSSO@ *.bundle + rm -f *.@OBJEXT@ *@JSSO@ *.$(SO) (cd $(ROOT_DIR)/Tools/javascript && $(MAKE) -s clean) diff --git a/Examples/javascript/js_example.mk b/Examples/javascript/js_example.mk index 7cecd184a..6cb6eb113 100644 --- a/Examples/javascript/js_example.mk +++ b/Examples/javascript/js_example.mk @@ -44,7 +44,7 @@ check: build else check: build - $(MAKE) -f $(EXAMPLES_TOP)/Makefile JSENGINE='$(JSENGINE)' javascript_run + $(MAKE) -f $(EXAMPLES_TOP)/Makefile JSENGINE='$(JSENGINE)' TARGET='$(TARGET)' javascript_run endif diff --git a/Tools/javascript/Makefile.in b/Tools/javascript/Makefile.in index 57e63e88d..32744333f 100644 --- a/Tools/javascript/Makefile.in +++ b/Tools/javascript/Makefile.in @@ -16,6 +16,7 @@ CC = @CC@ # with 'c++' it works... probably some missing flags? CXX = @JSINTERPRETERCXX@ CFLAGS = @BOOST_CPPFLAGS@ @PLATFLAGS@ +LINKFLAGS = @JSINTERPRETERLINKFLAGS@ ROOT_DIR = @ROOT_DIR@ JSCFLAGS = @JSCFLAGS@ @@ -32,24 +33,24 @@ JSCENABLED = @JSCENABLED@ # These settings are provided by 'configure' (see '/configure.in') ifeq (1, $(JSV8ENABLED)) JS_INTERPRETER_SRC_V8 = v8_shell.cxx - JS_INTERPRETER_CXXFLAGS_V8 = -DENABLE_V8 + JS_INTERPRETER_ENABLE_V8 = -DENABLE_V8 endif ifeq (1, $(JSCENABLED)) JS_INTERPRETER_SRC_JSC = jsc_shell.cxx - JS_INTERPRETER_CXXFLAGS_JSC = -DENABLE_JSC + JS_INTERPRETER_ENABLE_JSC = -DENABLE_JSC endif -JS_INTERPRETER_CXXFLAGS = $(JS_INTERPRETER_CXXFLAGS_JSC) $(JS_INTERPRETER_CXXFLAGS_V8) +JS_INTERPRETER_DEFINES = $(JS_INTERPRETER_ENABLE_JSC) $(JS_INTERPRETER_ENABLE_V8) JS_INTERPRETER_SRC = javascript.cxx js_shell.cxx $(JS_INTERPRETER_SRC_JSC) $(JS_INTERPRETER_SRC_V8) JS_INTERPRETER_OBJS = $(JS_INTERPRETER_SRC:.cxx=.o) %.o: %.cxx - $(CXX) $(JS_INTERPRETER_CXXFLAGS) -g $(JSINCLUDES) -o $@ -c $< + $(CXX) $(JS_INTERPRETER_DEFINES) -g $(JSINCLUDES) -o $@ -c $< javascript: $(JS_INTERPRETER_OBJS) - $(CXX) -g -Wl,-search_paths_first -Wl,-headerpad_max_install_names $^ $(CFLAGS) -o javascript $(JSDYNAMICLINKING) + $(CXX) $(LINKFLAGS) $^ $(CFLAGS) -o javascript $(JSDYNAMICLINKING) clean: rm -f *.o diff --git a/Tools/javascript/javascript.cxx b/Tools/javascript/javascript.cxx index e5cb0a47e..5e7cc0b20 100644 --- a/Tools/javascript/javascript.cxx +++ b/Tools/javascript/javascript.cxx @@ -23,13 +23,18 @@ int main(int argc, char* argv[]) { bool interactive = false; JSShell* shell = 0; + std::vector modulePath; + modulePath.push_back("."); + for (int idx = 1; idx < argc; ++idx) { if(strcmp(argv[idx], "-v8") == 0) { - shell = JSShell::Create(JSShell::V8); + shell = JSShell::Create(JSShell::V8); } else if(strcmp(argv[idx], "-jsc") == 0) { - shell = JSShell::Create(JSShell::JSC); + shell = JSShell::Create(JSShell::JSC); } else if(strcmp(argv[idx], "-i") == 0) { interactive = true; + } else if(strcmp(argv[idx], "-L") == 0) { + modulePath.push_back(argv[++idx]); } else { scriptPath = argv[idx]; } @@ -39,6 +44,8 @@ int main(int argc, char* argv[]) { shell = JSShell::Create(); } + shell->setModulePath(modulePath); + bool failed = false; if(interactive) { diff --git a/Tools/javascript/js_shell.cxx b/Tools/javascript/js_shell.cxx index c0ac3da58..5890c922c 100644 --- a/Tools/javascript/js_shell.cxx +++ b/Tools/javascript/js_shell.cxx @@ -41,6 +41,7 @@ std::string JSShell::LoadModule(const std::string& name, HANDLE* library) { std::string lib_name; std::string module_name; + if (pathIdx == std::string::npos) { module_name = name; lib_name = std::string(name).append(LIBRARY_EXT); @@ -50,9 +51,18 @@ std::string JSShell::LoadModule(const std::string& name, HANDLE* library) { lib_name = path.append(module_name).append(LIBRARY_EXT); } - HANDLE handle = LOAD_LIBRARY(lib_name.c_str()); + std::string lib_path; + HANDLE handle = 0; + + for (int i = 0; i < module_path.size(); ++i) { + lib_path = module_path[i] + "/" + lib_name; + if (access( lib_path.c_str(), F_OK ) != -1) { + handle = LOAD_LIBRARY(lib_path.c_str()); + } + } + if(handle == 0) { - std::cerr << "Could not load library " << lib_name << ":" + std::cerr << "Could not find module " << lib_path << ":" << std::endl << LIBRARY_ERROR() << std::endl; return 0; } diff --git a/Tools/javascript/js_shell.h b/Tools/javascript/js_shell.h index 84a8534d6..1e2466b96 100644 --- a/Tools/javascript/js_shell.h +++ b/Tools/javascript/js_shell.h @@ -29,6 +29,10 @@ public: virtual bool RunShell(); + void setModulePath(const std::vector& modulePath) { + module_path = modulePath; + } + protected: virtual bool InitializeEngine() = 0; @@ -42,6 +46,7 @@ protected: protected: std::vector loaded_modules; + std::vector module_path; }; diff --git a/configure.ac b/configure.ac index 09bb65f25..720aebd04 100644 --- a/configure.ac +++ b/configure.ac @@ -1137,12 +1137,14 @@ else JSCXXSHARED='$(CXX) -dynamiclib' # HACK: didn't manage to get dynamic module loading working with a g++ compiled interpreter JSINTERPRETERCXX='c++' + JSINTERPRETERLINKFLAGS='-g -Wl,-search_paths_first -Wl,-headerpad_max_install_names' ;; *) JSSO=$SO JSLDSHARED='$(LDSHARED)' JSCXXSHARED='$(CXXSHARED)' JSINTERPRETERCXX='$(CXX)' + JSINTERPRETERLINKFLAGS='-ldl' ;; esac @@ -1309,7 +1311,9 @@ AC_SUBST(JSLIBRARYPREFIX) AC_SUBST(JSSO) AC_SUBST(JSLDSHARED) AC_SUBST(JSCXXSHARED) + AC_SUBST(JSINTERPRETERCXX) +AC_SUBST(JSINTERPRETERLINKFLAGS) AC_SUBST(JSCOREINC) AC_SUBST(JSCOREDYNAMICLINKING) From 94869c922861adc007e1cfffde279f2c4e554311 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 26 Feb 2014 22:47:29 +0100 Subject: [PATCH 0694/1048] More gitignores filtering Javascript related files. --- .gitignore | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.gitignore b/.gitignore index eb3aa012c..25cac8fec 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,8 @@ # Editor files and various other junk *.sw? *.bak +*.log +.DS_Store # Local PCRE pcre @@ -23,6 +25,7 @@ pcre *.so *.so.* *.dylib +*.bundle # C/C++ static libraries, based on: # https://github.com/github/gitignore/blob/master/C.gitignore @@ -72,6 +75,7 @@ Lib/ocaml/swigp4.ml Source/Include/stamp-h1 Source/Include/swigconfig.h Source/Makefile +Tools/javascript/Makefile .deps config.log config.status @@ -86,6 +90,7 @@ Source/CParse/parser.c Source/CParse/parser.h Source/eswig swig +Tools/javascript/javascript # Generated documentation Doc/Manual/CCache.html @@ -103,6 +108,7 @@ Examples/test-suite/d/*/ Examples/test-suite/go/*/ Examples/test-suite/guile/*/ Examples/test-suite/java/*/ +Examples/test-suite/javascript/*/ Examples/test-suite/lua/*/ Examples/test-suite/mzscheme/*/ Examples/test-suite/ocaml/*/ @@ -115,6 +121,8 @@ Examples/test-suite/r/*/ Examples/test-suite/ruby/*/ Examples/test-suite/tcl/*/ Examples/test-suite/uffi/*/ +*_wrap.c +*_wrap.cxx # Python generated files, based on: # https://github.com/github/gitignore/blob/master/Python.gitignore From 348cb2026e2edad29003281ed9b0a2f43c10aa54 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 26 Feb 2014 22:56:31 +0100 Subject: [PATCH 0695/1048] Fix regressions in configuration of some Javascript examples. --- Examples/javascript/constant/Makefile | 2 +- Examples/javascript/operator/Makefile | 2 +- Examples/javascript/overload/Makefile | 2 +- Examples/javascript/template/Makefile | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Examples/javascript/constant/Makefile b/Examples/javascript/constant/Makefile index b0934786a..a2570636e 100755 --- a/Examples/javascript/constant/Makefile +++ b/Examples/javascript/constant/Makefile @@ -1,3 +1,3 @@ -SRCS = example.cxx +SRCS = include ../js_example.mk diff --git a/Examples/javascript/operator/Makefile b/Examples/javascript/operator/Makefile index b0934786a..a2570636e 100755 --- a/Examples/javascript/operator/Makefile +++ b/Examples/javascript/operator/Makefile @@ -1,3 +1,3 @@ -SRCS = example.cxx +SRCS = include ../js_example.mk diff --git a/Examples/javascript/overload/Makefile b/Examples/javascript/overload/Makefile index b0934786a..a2570636e 100755 --- a/Examples/javascript/overload/Makefile +++ b/Examples/javascript/overload/Makefile @@ -1,3 +1,3 @@ -SRCS = example.cxx +SRCS = include ../js_example.mk diff --git a/Examples/javascript/template/Makefile b/Examples/javascript/template/Makefile index b0934786a..a2570636e 100755 --- a/Examples/javascript/template/Makefile +++ b/Examples/javascript/template/Makefile @@ -1,3 +1,3 @@ -SRCS = example.cxx +SRCS = include ../js_example.mk From 7e015e4acf3cb6644f2002d4457a589f1d76f69d Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 26 Feb 2014 23:26:19 +0100 Subject: [PATCH 0696/1048] Fix regression in Javascript configuration. --- Tools/javascript/Makefile.in | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Tools/javascript/Makefile.in b/Tools/javascript/Makefile.in index 32744333f..d1a5e1c98 100644 --- a/Tools/javascript/Makefile.in +++ b/Tools/javascript/Makefile.in @@ -14,7 +14,7 @@ CC = @CC@ # HACK: under OSX a g++ compiled interpreter is seg-faulting when loading module libraries # with 'c++' it works... probably some missing flags? -CXX = @JSINTERPRETERCXX@ +JSCXX = @JSINTERPRETERCXX@ CFLAGS = @BOOST_CPPFLAGS@ @PLATFLAGS@ LINKFLAGS = @JSINTERPRETERLINKFLAGS@ @@ -47,10 +47,10 @@ JS_INTERPRETER_SRC = javascript.cxx js_shell.cxx $(JS_INTERPRETER_SRC_JSC) $(JS_ JS_INTERPRETER_OBJS = $(JS_INTERPRETER_SRC:.cxx=.o) %.o: %.cxx - $(CXX) $(JS_INTERPRETER_DEFINES) -g $(JSINCLUDES) -o $@ -c $< + $(JSCXX) $(JS_INTERPRETER_DEFINES) -g $(JSINCLUDES) -o $@ -c $< javascript: $(JS_INTERPRETER_OBJS) - $(CXX) $(LINKFLAGS) $^ $(CFLAGS) -o javascript $(JSDYNAMICLINKING) + $(JSCXX) $^ $(CFLAGS) -o javascript $(JSDYNAMICLINKING) $(LINKFLAGS) clean: rm -f *.o From b20b0f4e4b1626030c4155f22313af3ee0fd4e00 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Thu, 27 Feb 2014 01:02:06 +0100 Subject: [PATCH 0697/1048] Removed CMake. Started a separate project which acts as a CMake shell around SWIG. --- CMakeLists.txt | 173 ------------------------------------------------- 1 file changed, 173 deletions(-) delete mode 100644 CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt deleted file mode 100644 index 1bf7a2c76..000000000 --- a/CMakeLists.txt +++ /dev/null @@ -1,173 +0,0 @@ -project(swig) -cmake_minimum_required(VERSION 2.8) - -# Project wide configuration variables -# ------------------------------------ - -set(SWIG_VERSION 2.0.6) -set(SWIG_SOURCE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/Source" CACHE INTERNAL "Path of swig sources" FORCE) - -# Configure -# --------- - -include(CheckIncludeFiles) -include(CheckIncludeFile) -include(CheckTypeSize) -include(CheckSymbolExists) -include(CheckLibraryExists) -include(CheckCSourceCompiles) - -# HACK: didn't get the bool check working for Visual Studio 2008 -if(MSVC) -set(HAVE_BOOL 1) -else() -set(CMAKE_EXTRA_INCLUDE_FILES stdbool.h) -check_type_size("bool" HAVE_BOOL) -set(CMAKE_EXTRA_INCLUDE_FILES) -endif() - -check_include_file("inttypes.h" HAVE_INTTYPES_H) -check_include_file("memory.h" HAVE_MEMORY_H) -check_include_file("stddef.h" HAVE_STDDEF_H) -check_include_file("stdint.h" HAVE_STDINT_H) -check_include_file("stdlib.h" HAVE_STDLIB_H) -check_include_file("string.h" HAVE_STRING_H) -check_include_file("strings.h" HAVE_STRINGS_H) -check_include_file("sys/stat.h" HAVE_SYS_STAT_H) -check_include_file("sys/types.h" HAVE_SYS_TYPES_H) -check_include_file("unistd.h" HAVE_UNISTD_H) -check_include_files( "stdlib.h;stdarg.h;string.h;float.h" HAVE_STDC_HEADERS ) - -check_library_exists(dl dlopen "" HAVE_LIBDL) - -configure_file(${CMAKE_CURRENT_SOURCE_DIR}/Tools/swigconfig.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/Source/Include/swigconfig.h) - -# Compiler flags -# -------------- - -include_directories("${SWIG_SOURCE_DIR}/CParse" - "${SWIG_SOURCE_DIR}/Include" - "${SWIG_SOURCE_DIR}/DOH" - "${SWIG_SOURCE_DIR}/Swig" - "${SWIG_SOURCE_DIR}/Preprocessor" - "${SWIG_SOURCE_DIR}/Modules" - "${PROJECT_BINARY_DIR}/Source/Include" -) - -# Pre-Build -# --------- - -# Copy Lib directory into the build dist folder -file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/Dist) -file(COPY ${PROJECT_SOURCE_DIR}/Lib DESTINATION ${PROJECT_BINARY_DIR}/Dist) - -# add the command to generate the source code (depends on bison) -file(MAKE_DIRECTORY ${PROJECT_BINARY_DIR}/Source/CParse) -add_custom_command ( - OUTPUT ${PROJECT_BINARY_DIR}/Source/CParse/parser.c - DEPENDS ${SWIG_SOURCE_DIR}/CParse/parser.y - COMMAND bison -o ${PROJECT_BINARY_DIR}/Source/CParse/parser.c --defines=${PROJECT_BINARY_DIR}/Source/Include/parser.h ${SWIG_SOURCE_DIR}/CParse/parser.y -) -set_property(SOURCE ${PROJECT_BINARY_DIR}/Source/CParse/parser.c PROPERTY GENERATED 1) -set_property(SOURCE ${PROJECT_BINARY_DIR}/Source/CParse/parser.h PROPERTY GENERATED 1) - -# generate swigwarn.swg -file(READ ${SWIG_SOURCE_DIR}/Include/swigwarn.h SWIG_WARN_H) -string(REGEX REPLACE "#define WARN([^ \\t]*)[ \\t]*([0-9]+)" "%define SWIGWARN\\1 \\2 %enddef" SWIG_WARN_SWG ${SWIG_WARN_H}) -file(WRITE ${PROJECT_BINARY_DIR}/Dist/Lib/swigwarn.swg ${SWIG_WARN_SWG}) -set_property(SOURCE ${PROJECT_BINARY_DIR}/Dist/Lib/swigwarn.swg PROPERTY GENERATED 1) - -# Libraries -# --------- - -add_library(cparse "${SWIG_SOURCE_DIR}/CParse/cscanner.c" - "${SWIG_SOURCE_DIR}/CParse/templ.c" - "${SWIG_SOURCE_DIR}/CParse/util.c" - "${PROJECT_BINARY_DIR}/Source/CParse/parser.c" - "${PROJECT_BINARY_DIR}/Source/CParse/parser.h" -) - -add_library(preprocessor "${SWIG_SOURCE_DIR}/Preprocessor/cpp.c" - "${SWIG_SOURCE_DIR}/Preprocessor/expr.c" -) - -add_library(doh "${SWIG_SOURCE_DIR}/DOH/base.c" - "${SWIG_SOURCE_DIR}/DOH/file.c" - "${SWIG_SOURCE_DIR}/DOH/fio.c" - "${SWIG_SOURCE_DIR}/DOH/hash.c" - "${SWIG_SOURCE_DIR}/DOH/list.c" - "${SWIG_SOURCE_DIR}/DOH/memory.c" - "${SWIG_SOURCE_DIR}/DOH/string.c" - "${SWIG_SOURCE_DIR}/DOH/void.c" -) - -add_library(core "${SWIG_SOURCE_DIR}/Swig/cwrap.c" - "${SWIG_SOURCE_DIR}/Swig/deprecate.c" - "${SWIG_SOURCE_DIR}/Swig/error.c" - "${SWIG_SOURCE_DIR}/Swig/fragment.c" - "${SWIG_SOURCE_DIR}/Swig/getopt.c" - "${SWIG_SOURCE_DIR}/Swig/include.c" - "${SWIG_SOURCE_DIR}/Swig/misc.c" - "${SWIG_SOURCE_DIR}/Swig/naming.c" - "${SWIG_SOURCE_DIR}/Swig/parms.c" - "${SWIG_SOURCE_DIR}/Swig/scanner.c" - "${SWIG_SOURCE_DIR}/Swig/stype.c" - "${SWIG_SOURCE_DIR}/Swig/symbol.c" - "${SWIG_SOURCE_DIR}/Swig/tree.c" - "${SWIG_SOURCE_DIR}/Swig/typemap.c" - "${SWIG_SOURCE_DIR}/Swig/typeobj.c" - "${SWIG_SOURCE_DIR}/Swig/typesys.c" - "${SWIG_SOURCE_DIR}/Swig/wrapfunc.c" -) - -add_library(modules "${SWIG_SOURCE_DIR}/Modules/allegrocl.cxx" - "${SWIG_SOURCE_DIR}/Modules/allocate.cxx" - "${SWIG_SOURCE_DIR}/Modules/browser.cxx" - "${SWIG_SOURCE_DIR}/Modules/cffi.cxx" - "${SWIG_SOURCE_DIR}/Modules/chicken.cxx" - "${SWIG_SOURCE_DIR}/Modules/clisp.cxx" - "${SWIG_SOURCE_DIR}/Modules/contract.cxx" - "${SWIG_SOURCE_DIR}/Modules/csharp.cxx" - "${SWIG_SOURCE_DIR}/Modules/d.cxx" - "${SWIG_SOURCE_DIR}/Modules/directors.cxx" - "${SWIG_SOURCE_DIR}/Modules/emit.cxx" - "${SWIG_SOURCE_DIR}/Modules/go.cxx" - "${SWIG_SOURCE_DIR}/Modules/guile.cxx" - "${SWIG_SOURCE_DIR}/Modules/java.cxx" - "${SWIG_SOURCE_DIR}/Modules/javascript.cxx" - "${SWIG_SOURCE_DIR}/Modules/lang.cxx" - "${SWIG_SOURCE_DIR}/Modules/lua.cxx" - "${SWIG_SOURCE_DIR}/Modules/modula3.cxx" - "${SWIG_SOURCE_DIR}/Modules/module.cxx" - "${SWIG_SOURCE_DIR}/Modules/mzscheme.cxx" - "${SWIG_SOURCE_DIR}/Modules/ocaml.cxx" - "${SWIG_SOURCE_DIR}/Modules/octave.cxx" - "${SWIG_SOURCE_DIR}/Modules/overload.cxx" - "${SWIG_SOURCE_DIR}/Modules/perl5.cxx" - "${SWIG_SOURCE_DIR}/Modules/php.cxx" - "${SWIG_SOURCE_DIR}/Modules/pike.cxx" - "${SWIG_SOURCE_DIR}/Modules/python.cxx" - "${SWIG_SOURCE_DIR}/Modules/r.cxx" - "${SWIG_SOURCE_DIR}/Modules/ruby.cxx" - "${SWIG_SOURCE_DIR}/Modules/s-exp.cxx" - "${SWIG_SOURCE_DIR}/Modules/tcl8.cxx" - "${SWIG_SOURCE_DIR}/Modules/typepass.cxx" - "${SWIG_SOURCE_DIR}/Modules/uffi.cxx" - "${SWIG_SOURCE_DIR}/Modules/utils.cxx" - "${SWIG_SOURCE_DIR}/Modules/xml.cxx" - "${PROJECT_BINARY_DIR}/Source/Include/swigconfig.h" - "${SWIG_SOURCE_DIR}/Include/swigwarn.h" -) - -add_executable(swig - "${SWIG_SOURCE_DIR}/Modules/main.cxx" - "${SWIG_SOURCE_DIR}/Modules/swigmain.cxx" -) - -target_link_libraries(swig cparse preprocessor doh core modules) - -# copy binary into Dist folder -get_property(SWIG_EXECUTABLE TARGET swig PROPERTY LOCATION) -add_custom_command(TARGET swig POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy ${SWIG_EXECUTABLE} ${PROJECT_BINARY_DIR}/Dist -) From c36800713bf3803c335af15550fdcfd21fc77224 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 27 Feb 2014 20:12:53 +0000 Subject: [PATCH 0698/1048] 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 0699/1048] 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 70385842df0c68c4e7e7eeb4531f703330edb831 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Fri, 28 Feb 2014 10:40:41 +0100 Subject: [PATCH 0700/1048] Add missing copy ctor for Javascript Code Template class. --- Source/Modules/javascript.cxx | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 7b153c66c..748043619 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -86,6 +86,8 @@ public: Template(const String *code, const String *templateName); + Template(const Template& other); + ~Template(); String *str(); @@ -620,7 +622,6 @@ Template JSEmitter::getTemplate(const String *name) { } Template t(templ, name); - return t; } @@ -2441,6 +2442,11 @@ Template& Template::pretty_print(DOH *doh) { return *this; } +Template::Template(const Template& t) { + code = NewString(t.code); + templateName = NewString(t.templateName); +} + void Template::operator=(const Template& t) { Delete(code); Delete(templateName); From e208f85beaac946c5e8536e088b148a880856f37 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 28 Feb 2014 07:49:11 +0000 Subject: [PATCH 0701/1048] 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 0702/1048] 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 0703/1048] 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 0704/1048] 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 0705/1048] 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 0706/1048] 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 0707/1048] 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 0708/1048] 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 0709/1048] 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 0710/1048] 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 0711/1048] 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 0712/1048] 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 0713/1048] '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 0714/1048] 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 0715/1048] 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 0716/1048] 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 0717/1048] 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 0718/1048] __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 0719/1048] 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 0720/1048] 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 0721/1048] 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 0722/1048] 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 ) + From dbd61e40e1c92aa02c3ce5170534687f7ae8d42f Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 4 Mar 2014 10:41:35 +0100 Subject: [PATCH 0723/1048] Fix issues that were observed with newer JavascriptCore. --- Tools/javascript/Makefile.in | 2 +- Tools/javascript/js_shell.cxx | 1 + Tools/javascript/jsc_shell.cxx | 4 ++-- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Tools/javascript/Makefile.in b/Tools/javascript/Makefile.in index d1a5e1c98..f18cfa65d 100644 --- a/Tools/javascript/Makefile.in +++ b/Tools/javascript/Makefile.in @@ -47,7 +47,7 @@ JS_INTERPRETER_SRC = javascript.cxx js_shell.cxx $(JS_INTERPRETER_SRC_JSC) $(JS_ JS_INTERPRETER_OBJS = $(JS_INTERPRETER_SRC:.cxx=.o) %.o: %.cxx - $(JSCXX) $(JS_INTERPRETER_DEFINES) -g $(JSINCLUDES) -o $@ -c $< + $(JSCXX) $(JS_INTERPRETER_DEFINES) $(CFLAGS) $(JSINCLUDES) -o $@ -c $< javascript: $(JS_INTERPRETER_OBJS) $(JSCXX) $^ $(CFLAGS) -o javascript $(JSDYNAMICLINKING) $(LINKFLAGS) diff --git a/Tools/javascript/js_shell.cxx b/Tools/javascript/js_shell.cxx index 5890c922c..539b83d65 100644 --- a/Tools/javascript/js_shell.cxx +++ b/Tools/javascript/js_shell.cxx @@ -4,6 +4,7 @@ #include #include #include +#include #ifdef __GNUC__ #ifdef __APPLE__ diff --git a/Tools/javascript/jsc_shell.cxx b/Tools/javascript/jsc_shell.cxx index cf30d7bd7..292c4042b 100644 --- a/Tools/javascript/jsc_shell.cxx +++ b/Tools/javascript/jsc_shell.cxx @@ -64,9 +64,9 @@ bool JSCShell::InitializeEngine() { if(context == 0) return false; JSObjectRef globalObject = JSContextGetGlobalObject(context); - // store this for later use - JSClassDefinition __shell_classdef__; + JSClassDefinition __shell_classdef__ = JSClassDefinition(); + JSClassRef __shell_class__ = JSClassCreate(&__shell_classdef__); JSObjectRef __shell__ = JSObjectMake(context, __shell_class__, 0); bool success = JSObjectSetPrivate(__shell__, (void*) (long) this); From e48dee81eaa1db588ba5c1818eeca1f7982930ae Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Tue, 4 Mar 2014 13:54:38 +0400 Subject: [PATCH 0724/1048] Disable old-names generation for enums in class in namespace --- Source/Modules/lua.cxx | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 2f06b8668..4a9676611 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -1166,9 +1166,15 @@ public: virtual int enumDeclaration(Node *n) { current[STATIC_CONST] = true; current[ENUM_CONST] = true; + // Drop v2_compatibility if NSpace is given + int old_v2_compatibility = v2_compatibility; + if (getNSpace()) { + v2_compatibility = 0; + } int result = Language::enumDeclaration(n); current[STATIC_CONST] = false; current[ENUM_CONST] = false; + v2_compatibility = old_v2_compatibility; return result; } From a9b8b85c1c1b2bfe5b9b389e6f9406258371d512 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 4 Mar 2014 11:00:26 +0100 Subject: [PATCH 0725/1048] Minor change in Javascript configuration. --- configure.ac | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/configure.ac b/configure.ac index 720aebd04..c7527a87f 100644 --- a/configure.ac +++ b/configure.ac @@ -1195,12 +1195,6 @@ else *-*-linux*) dirs="/usr/lib/ /usr/local/lib/" for i in $dirs ; do - if test -r $i/libwebkit-1.0.la; then - AC_MSG_RESULT($i) - JSCORELIB="-L$i -lwebkit-1.0" - break - fi - if test -r $i/libjavascriptcoregtk-1.0.so; then AC_MSG_RESULT($i) JSCORELIB="-L$i -ljavascriptcoregtk-1.0" @@ -1212,6 +1206,12 @@ else JSCORELIB="-L$i -lwebkitgtk-1.0" break fi + + if test -r $i/libwebkit-1.0.la; then + AC_MSG_RESULT($i) + JSCORELIB="-L$i -lwebkit-1.0" + break + fi done if test -z "$JSCORELIB"; then From 869de3e7614814bcbf827d6796ef44d4c7047855 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Tue, 4 Mar 2014 14:30:10 +0400 Subject: [PATCH 0726/1048] Getattribute->GetFlag --- Source/Modules/lua.cxx | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 4a9676611..0a5a00515 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -1285,7 +1285,7 @@ public: // * consider effect on template_specialization_defarg static Hash *emitted = NewHash(); - if (Getattr(emitted, mangled_fr_t)) { + if (GetFlag(emitted, mangled_fr_t)) { full_proxy_class_name = 0; proxy_class_name = 0; return SWIG_NOWRAP; @@ -1901,7 +1901,7 @@ public: Setattr(scope, "lua:cdata", carrays_hash); assert(rawGetCArraysHash(nspace)); - if (reg && nspace != 0 && Len(nspace) != 0 && Getattr(carrays_hash, "lua:no_reg") == 0) { + if (reg && nspace != 0 && Len(nspace) != 0 && GetFlag(carrays_hash, "lua:no_reg") == 0) { // Split names into components List *components = Split(nspace, '.', -1); String *parent_path = NewString(""); @@ -1947,7 +1947,7 @@ public: void closeCArraysHash(String *nspace, File *output) { Hash *carrays_hash = rawGetCArraysHash(nspace); assert(carrays_hash); - assert(Getattr(carrays_hash, "lua:closed") == 0); + assert(GetFlag(carrays_hash, "lua:closed") == 0); SetFlag(carrays_hash, "lua:closed"); @@ -1982,13 +1982,13 @@ public: Printf(methods_tab, " {0,0}\n};\n"); Printv(output, methods_tab, NIL); - if (!Getattr(carrays_hash, "lua:no_classes")) { + if (!GetFlag(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(carrays_hash, "lua:no_namespaces")) { + if (!GetFlag(carrays_hash, "lua:no_namespaces")) { String *namespaces_tab = Getattr(carrays_hash, "namespaces"); Printf(namespaces_tab, " 0\n};\n"); Printv(output, namespaces_tab, NIL); @@ -2009,7 +2009,7 @@ public: String *get_tab_name = Getattr(carrays_hash, "get:name"); String *set_tab_name = Getattr(carrays_hash, "set:name"); - if (Getattr(carrays_hash, "lua:class_instance")) { + if (GetFlag(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 { @@ -2022,7 +2022,7 @@ public: Printv(metatable_tab, tab4, "{LSTRKEY(\".set\"), LROVAL(", set_tab_name, ")},\n", NIL); Printv(metatable_tab, tab4, "{LSTRKEY(\".fn\"), LROVAL(", Getattr(carrays_hash, "methods:name"), ")},\n", NIL); - if (Getattr(carrays_hash, "lua:class_instance")) { + if (GetFlag(carrays_hash, "lua:class_instance")) { String *static_cls = Getattr(carrays_hash, "lua:class_instance:static_hash"); assert(static_cls); // static_cls is swig_lua_namespace. This structure can't be use with eLua(LTR) @@ -2032,7 +2032,7 @@ 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(carrays_hash, "lua:class_static")) { + } else if (GetFlag(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"); @@ -2080,7 +2080,7 @@ public: // 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) + if (GetFlag(carrays_hash, "lua:closed") == 0) Append(to_close, ki.key); } ki = Next(ki); @@ -2125,8 +2125,8 @@ public: 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; + bool has_classes = GetFlag(carrays_hash, "lua:no_classes") == 0; + bool has_namespaces = GetFlag(carrays_hash, "lua:no_namespaces") == 0; Printv(output, "{\n", tab4, "\"", name, "\",\n", From 1a7e12911ac96e8b788686076f35771ac248220d Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 4 Mar 2014 12:00:13 +0100 Subject: [PATCH 0727/1048] Adding a chapter about Javascript tests and examples. --- Doc/Manual/Javascript.md | 50 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) diff --git a/Doc/Manual/Javascript.md b/Doc/Manual/Javascript.md index 044343588..0394ccfde 100644 --- a/Doc/Manual/Javascript.md +++ b/Doc/Manual/Javascript.md @@ -57,6 +57,54 @@ and for v8: void example_initialize (v8::Handle exports) +### Running Tests and Examples + +The configuration for tests and examples currently supports Linux and Mac only, MinGW not yet. + +The default interpreter is `node.js` as it is available on all platforms and convenient to use. + +Running the examples with JavascriptCore requires `libjavascriptcoregtk-1.0` to be installed, e.g., under Ubuntu with + + $ sudo apt-get install libjavascriptcoregtk-1.0-dev + +Running with `V8` requires `libv8`: + + $ sudo apt-get install libv8-dev + +Examples can be run using + + $ make ENGINE=jsc check-javascript-examples + +`ENGINE` can be `node`, `jsc`, or `v8`. + +The test-suite can be run using + + $ make ENGINE=jsc check-javascript-test-suite + +A smaller, manually selected set of tests can be run using + + $ make SMOKE=1 ENGINE=jsc check-javascript-test-suite + + +Tests should run without any problems, i.e., have been tried out, on the following platforms/interpreters: + +- Ubuntu Precise 12.04 64bit + - JavascriptCore (GTK) 1.0 + - Node.js (0.10.26) + - v8 (3.7.12) +- Ubuntu Saucy 13.10 64bit + - JavascriptCore (GTK) 1.0 + 3.0 + - Node.js + - v8 (3.14.5) +- Mac OSX Mountain Lion 10.8 + - JavascriptCore (built-in) + - Node.js +- Windows 7 64bit (VS 2010) + - Node.js + +Note: a `CMake` based configuration can be found in the `cmake` branch on + [](https://github.com/oliver----/swig-v8) which can be used to generate a Visual Studio solution. It is rather limited building only the SWIG executable and Javascript examples. + ### Future work The Javascript module is not yet as mature as other modules and some things are still missing. @@ -79,7 +127,7 @@ We could work on that if requested: ## Integration -This should give a short introduction to integrating your module in different environments: as a `node.js` module, and as an extension for an embedded Webkit. +This chapter gives a short introduction how to use a native Javascript extension: as a `node.js` module, and as an extension for an embedded Webkit. ### Creating `node.js` Extensions From 6b82dff8f35d9ca743670a6131a87d493514c6b6 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 4 Mar 2014 22:50:23 +0100 Subject: [PATCH 0728/1048] Minor tweaks in Javascript documentation. --- Doc/Manual/Javascript.md | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/Doc/Manual/Javascript.md b/Doc/Manual/Javascript.md index 0394ccfde..73f17eabb 100644 --- a/Doc/Manual/Javascript.md +++ b/Doc/Manual/Javascript.md @@ -1,7 +1,7 @@ # SWIG and Javascript This chapter describes SWIG's support of Javascript. -It does not cover SWIG basics only information that is specific to this module. +It does not cover SWIG basics, but only information that is specific to this module. ## Overview @@ -88,19 +88,19 @@ A smaller, manually selected set of tests can be run using Tests should run without any problems, i.e., have been tried out, on the following platforms/interpreters: -- Ubuntu Precise 12.04 64bit - - JavascriptCore (GTK) 1.0 - - Node.js (0.10.26) - - v8 (3.7.12) -- Ubuntu Saucy 13.10 64bit - - JavascriptCore (GTK) 1.0 + 3.0 - - Node.js - - v8 (3.14.5) -- Mac OSX Mountain Lion 10.8 - - JavascriptCore (built-in) - - Node.js -- Windows 7 64bit (VS 2010) - - Node.js + - Ubuntu Precise 12.04 64bit + - JavascriptCore (Webkit 1.8.3) + - Node.js (0.10.26) + - v8 (3.7.12) + - Ubuntu Saucy 13.10 64bit + - JavascriptCore (Webkit 1.10.2) + - Node.js + - v8 (3.14.5) + - Mac OSX Mountain Lion 10.8 + - JavascriptCore (built-in) + - Node.js + - Windows 7 64bit (VS 2010) + - Node.js Note: a `CMake` based configuration can be found in the `cmake` branch on [](https://github.com/oliver----/swig-v8) which can be used to generate a Visual Studio solution. It is rather limited building only the SWIG executable and Javascript examples. From 924f373a2f6a58c4a8d40e6f61434a6e3f6df50b Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 4 Mar 2014 22:51:19 +0100 Subject: [PATCH 0729/1048] Fix pandoc filter. And add a script that helps to run pandoc with appropriate command line flags. --- Doc/Manual/markdown_to_html.sh | 9 +++++++++ Doc/Manual/pandoc_filter.py | 18 +++++++++--------- 2 files changed, 18 insertions(+), 9 deletions(-) create mode 100755 Doc/Manual/markdown_to_html.sh diff --git a/Doc/Manual/markdown_to_html.sh b/Doc/Manual/markdown_to_html.sh new file mode 100755 index 000000000..925f62a64 --- /dev/null +++ b/Doc/Manual/markdown_to_html.sh @@ -0,0 +1,9 @@ +#!/bin/bash + +if [ "$1" == "" ]; then + echo "Usage: markdown_to_html " + echo "-- Example: markdown_to_html Javascript" +else + pandoc -f markdown -t json $1.md | ./pandoc_filter.py | pandoc -f json -t html -s --template pandoc_template.html -o $1.html +fi + diff --git a/Doc/Manual/pandoc_filter.py b/Doc/Manual/pandoc_filter.py index f1e84904a..33ac3ffd6 100755 --- a/Doc/Manual/pandoc_filter.py +++ b/Doc/Manual/pandoc_filter.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python +#!/usr/bin/python """ Pandoc filter that changes pandoc default HTML output for codeblocks @@ -24,16 +24,16 @@ the_title = "" def codeblocks(key, value, format, meta): if key == 'CodeBlock': [[id, classes, kvs], contents] = value - if format == "html" or format == "html5": - newcontents = [html('
        \n' + contents + '
        ')] - if len(classes) == 0: - if contents.startswith("$"): - classes.append("shell") - else: - classes.append("code") + newcontents = [html('
        \n' + contents + '
        ')] - return Div([id, classes, kvs], newcontents) + if len(classes) == 0: + if contents.startswith("$"): + classes.append("shell") + else: + classes.append("code") + + return Div([id, classes, kvs], newcontents) if key == 'Header': if value[0] == 1: the_title = stringify(value) From 8c05fe37afcbcd6a2fc2a7d8bbe028e6d8f59239 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Tue, 4 Mar 2014 22:55:32 +0100 Subject: [PATCH 0730/1048] Removed obsolete paragraph from Javascript documentation. --- Doc/Manual/Javascript.md | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/Doc/Manual/Javascript.md b/Doc/Manual/Javascript.md index 73f17eabb..36dfa7c2f 100644 --- a/Doc/Manual/Javascript.md +++ b/Doc/Manual/Javascript.md @@ -273,17 +273,6 @@ An integration of a native extension 'example' would look like this: return 0; } - -### Embedded V8 - -It is possible to create a custom application like `node.js` embedding a v8 engine. - -TODO: -- how to install v8 -- v8 version issues: command-line switch, pre-processor macro -- sample integration code - - ## Examples Some basic examples are shown here in more detail. From b5bc87667d62fa05a31ab85ba0b7894f83d7cdce Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 5 Mar 2014 01:10:55 +0100 Subject: [PATCH 0731/1048] Fix regressions. - Adapted to changes in UTL - Fixed detection of setters and getters. --- Lib/javascript/jsc/javascriptstrings.swg | 2 ++ Source/Modules/javascript.cxx | 23 +++++++++++++++++++---- Tools/javascript/Makefile.in | 7 ++++--- 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/Lib/javascript/jsc/javascriptstrings.swg b/Lib/javascript/jsc/javascriptstrings.swg index 26908d9da..0581c1920 100644 --- a/Lib/javascript/jsc/javascriptstrings.swg +++ b/Lib/javascript/jsc/javascriptstrings.swg @@ -78,6 +78,7 @@ SWIG_JSC_FromCharPtrAndSize(JSContextRef context, const char* carray, size_t siz SWIG_AsCharPtrAndSize, SWIG_FromCharPtrAndSize, SWIG_CharPtrLen, + SWIG_CharBufLen, SWIG_NewCopyCharArray, SWIG_DeleteCharArray, FragLimits, CHAR_MIN, CHAR_MAX) @@ -167,6 +168,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, diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 748043619..53af47665 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -492,6 +492,14 @@ int JAVASCRIPT::top(Node *n) { return SWIG_OK; } +static const char *usage = (char *) "\ +Javascript Options (available with -javascript)\n\ + -jsc - creates a JavascriptCore extension \n\ + -v8 - creates a v8 extension \n\ + -node - creates a node.js extension \n\ + -debug-codetemplates - generates information about the origin of code templates.\n"; + + /* --------------------------------------------------------------------- * main() * @@ -522,6 +530,9 @@ void JAVASCRIPT::main(int argc, char *argv[]) { } else if (strcmp(argv[i], "-debug-codetemplates") == 0) { Swig_mark_arg(i); js_template_enable_debug = true; + } else if (strcmp(argv[i], "-help") == 0) { + fputs(usage, stdout); + return; } } } @@ -704,14 +715,18 @@ int JSEmitter::emitWrapperFunction(Node *n) { if (GetFlag(n, "allocate:smartpointeraccess")) { is_static = false; } - bool is_setter = GetFlag(n, "wrap:issetter"); + + bool is_member = GetFlag(n, "ismember"); + bool is_setter = GetFlag(n, "memberset") || GetFlag(n, "varset"); + bool is_getter = GetFlag(n, "memberget") || GetFlag(n, "varget"); if (is_setter) { - bool is_member = GetFlag(n, "memberset"); ret = emitSetter(n, is_member, is_static); - } else { - bool is_member = GetFlag(n, "memberget"); + } else if (is_getter) { ret = emitGetter(n, is_member, is_static); + } else { + Swig_print_node(n); } + } else { Printf(stderr, "Warning: unsupported wrapper function type\n"); Swig_print_node(n); diff --git a/Tools/javascript/Makefile.in b/Tools/javascript/Makefile.in index f18cfa65d..d58412b50 100644 --- a/Tools/javascript/Makefile.in +++ b/Tools/javascript/Makefile.in @@ -15,7 +15,8 @@ CC = @CC@ # HACK: under OSX a g++ compiled interpreter is seg-faulting when loading module libraries # with 'c++' it works... probably some missing flags? JSCXX = @JSINTERPRETERCXX@ -CFLAGS = @BOOST_CPPFLAGS@ @PLATFLAGS@ +CFLAGS = @PLATCFLAGS@ +CXXFLAGS = @BOOST_CPPFLAGS@ @PLATCXXFLAGS@ LINKFLAGS = @JSINTERPRETERLINKFLAGS@ ROOT_DIR = @ROOT_DIR@ @@ -47,10 +48,10 @@ JS_INTERPRETER_SRC = javascript.cxx js_shell.cxx $(JS_INTERPRETER_SRC_JSC) $(JS_ JS_INTERPRETER_OBJS = $(JS_INTERPRETER_SRC:.cxx=.o) %.o: %.cxx - $(JSCXX) $(JS_INTERPRETER_DEFINES) $(CFLAGS) $(JSINCLUDES) -o $@ -c $< + $(JSCXX) $(JS_INTERPRETER_DEFINES) $(CXXFLAGS) $(JSINCLUDES) -o $@ -c $< javascript: $(JS_INTERPRETER_OBJS) - $(JSCXX) $^ $(CFLAGS) -o javascript $(JSDYNAMICLINKING) $(LINKFLAGS) + $(JSCXX) $^ $(CXXFLAGS) -o javascript $(JSDYNAMICLINKING) $(LINKFLAGS) clean: rm -f *.o From 89610e984ea3732a7da7bfc6bea1ffed2039201e Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 5 Mar 2014 01:39:26 +0100 Subject: [PATCH 0732/1048] Beautified Javascript module. --- Source/Modules/javascript.cxx | 574 ++++++++++++++++------------------ 1 file changed, 266 insertions(+), 308 deletions(-) diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx index 53af47665..eae594727 100644 --- a/Source/Modules/javascript.cxx +++ b/Source/Modules/javascript.cxx @@ -50,27 +50,27 @@ public: ~JSEmitterState(); - DOH *global(); + DOH *global (); - DOH *global(const char* key, DOH *initial = 0); + DOH *global (const char *key, DOH *initial = 0); DOH *clazz(bool reset = false); - DOH *clazz(const char* key, DOH *initial = 0); + DOH *clazz(const char *key, DOH *initial = 0); DOH *function(bool reset = false); - DOH *function(const char* key, DOH *initial = 0); + DOH *function(const char *key, DOH *initial = 0); DOH *variable(bool reset = false); - DOH *variable(const char* key, DOH *initial = 0); + DOH *variable(const char *key, DOH *initial = 0); static int IsSet(DOH *val); private: - DOH *getState(const char* key, bool reset = false); + DOH *getState(const char *key, bool reset = false); Hash *_global; }; @@ -84,23 +84,23 @@ class Template { public: Template(const String *code); - Template(const String *code, const String *templateName); + Template(const String *code, const String *templateName); - Template(const Template& other); + Template(const Template & other); ~Template(); String *str(); - Template& replace(const String *pattern, const String *repl); + Template & replace(const String *pattern, const String *repl); - Template& print(DOH *doh); + Template & print(DOH *doh); - Template& pretty_print(DOH *doh); + Template & pretty_print(DOH *doh); - void operator=(const Template& t); + void operator=(const Template & t); - Template& trim(); + Template & trim(); private: @@ -133,9 +133,9 @@ public: V8 }; - JSEmitter(); + JSEmitter(); - virtual ~JSEmitter(); + virtual ~ JSEmitter(); /** * Opens output files and temporary output DOHs. @@ -220,7 +220,7 @@ public: */ Template getTemplate(const String *name); - State &getState(); + State & getState(); protected: @@ -255,7 +255,7 @@ protected: virtual String *emitInputTypemap(Node *n, Parm *params, Wrapper *wrapper, String *arg); - virtual void marshalOutput(Node *n, ParmList *params, Wrapper *wrapper, String *actioncode, const String *cresult=0, bool emitReturnVariable = true); + virtual void marshalOutput(Node *n, ParmList *params, Wrapper *wrapper, String *actioncode, const String *cresult = 0, bool emitReturnVariable = true); virtual void emitCleanupCode(Node *n, Wrapper *wrapper, ParmList *params); @@ -303,9 +303,8 @@ class JAVASCRIPT:public Language { public: - JAVASCRIPT(): emitter(NULL) {} - - ~JAVASCRIPT() { + JAVASCRIPT():emitter(NULL) { + } ~JAVASCRIPT() { delete emitter; } @@ -327,7 +326,7 @@ public: private: - JSEmitter *emitter; + JSEmitter * emitter; }; /* --------------------------------------------------------------------- @@ -515,24 +514,24 @@ void JAVASCRIPT::main(int argc, char *argv[]) { for (int i = 1; i < argc; i++) { if (argv[i]) { if (strcmp(argv[i], "-v8") == 0) { - Swig_mark_arg(i); - mode = JSEmitter::V8; - SWIG_library_directory("javascript/v8"); + Swig_mark_arg(i); + mode = JSEmitter::V8; + SWIG_library_directory("javascript/v8"); } else if (strcmp(argv[i], "-jsc") == 0) { - Swig_mark_arg(i); - mode = JSEmitter::JavascriptCore; - SWIG_library_directory("javascript/jsc"); + Swig_mark_arg(i); + mode = JSEmitter::JavascriptCore; + SWIG_library_directory("javascript/jsc"); } else if (strcmp(argv[i], "-node") == 0) { - Swig_mark_arg(i); - mode = JSEmitter::V8; - SWIG_library_directory("javascript/v8"); - Preprocessor_define("BUILDING_NODE_EXTENSION 1", 0); + Swig_mark_arg(i); + mode = JSEmitter::V8; + SWIG_library_directory("javascript/v8"); + Preprocessor_define("BUILDING_NODE_EXTENSION 1", 0); } else if (strcmp(argv[i], "-debug-codetemplates") == 0) { - Swig_mark_arg(i); - js_template_enable_debug = true; + Swig_mark_arg(i); + js_template_enable_debug = true; } else if (strcmp(argv[i], "-help") == 0) { - fputs(usage, stdout); - return; + fputs(usage, stdout); + return; } } } @@ -591,12 +590,7 @@ extern "C" Language *swig_javascript(void) { * ----------------------------------------------------------------------------- */ JSEmitter::JSEmitter() -: templates(NewHash()), - namespaces(NULL), - current_namespace(NULL), - defaultResultName(NewString("result")), - f_wrappers(NULL) -{ +: templates(NewHash()), namespaces(NULL), current_namespace(NULL), defaultResultName(NewString("result")), f_wrappers(NULL) { } /* ----------------------------------------------------------------------------- @@ -614,8 +608,8 @@ JSEmitter::~JSEmitter() { * ----------------------------------------------------------------------------- */ int JSEmitter::registerTemplate(const String *name, const String *code) { - if (!State::IsSet(state.global(HAS_TEMPLATES))) { - SetFlag(state.global(), HAS_TEMPLATES); + if (!State::IsSet(state.global (HAS_TEMPLATES))) { + SetFlag(state.global (), HAS_TEMPLATES); } return Setattr(templates, name, code); } @@ -636,13 +630,13 @@ Template JSEmitter::getTemplate(const String *name) { return t; } -JSEmitterState &JSEmitter::getState() { +JSEmitterState & JSEmitter::getState() { return state; } -int JSEmitter::initialize(Node * /*n*/) { +int JSEmitter::initialize(Node * /*n */ ) { - if(namespaces != NULL) { + if (namespaces != NULL) { Delete(namespaces); } namespaces = NewHash(); @@ -702,10 +696,10 @@ int JSEmitter::emitWrapperFunction(Node *n) { if (kind) { if (Equal(kind, "function") - // HACK: sneaky.ctest revealed that typedef'd (global) functions must be - // detected via the 'view' attribute. - || (Equal(kind, "variable") && Equal(Getattr(n, "view"), "globalfunctionHandler")) - ) { + // HACK: sneaky.ctest revealed that typedef'd (global) functions must be + // detected via the 'view' attribute. + || (Equal(kind, "variable") && Equal(Getattr(n, "view"), "globalfunctionHandler")) + ) { bool is_member = GetFlag(n, "ismember") | GetFlag(n, "feature:extend"); bool is_static = GetFlag(state.function(), IS_STATIC); ret = emitFunction(n, is_member, is_static); @@ -713,18 +707,18 @@ int JSEmitter::emitWrapperFunction(Node *n) { bool is_static = GetFlag(state.variable(), IS_STATIC); // HACK: smartpointeraccessed static variables are not treated as statics if (GetFlag(n, "allocate:smartpointeraccess")) { - is_static = false; + is_static = false; } bool is_member = GetFlag(n, "ismember"); bool is_setter = GetFlag(n, "memberset") || GetFlag(n, "varset"); bool is_getter = GetFlag(n, "memberget") || GetFlag(n, "varget"); if (is_setter) { - ret = emitSetter(n, is_member, is_static); + ret = emitSetter(n, is_member, is_static); } else if (is_getter) { - ret = emitGetter(n, is_member, is_static); + ret = emitGetter(n, is_member, is_static); } else { - Swig_print_node(n); + Swig_print_node(n); } } else { @@ -784,7 +778,7 @@ int JSEmitter::enterClass(Node *n) { int JSEmitter::enterFunction(Node *n) { state.function(RESET); state.function(NAME, Getattr(n, "sym:name")); - if(Equal(Getattr(n, "storage"), "static")) { + if (Equal(Getattr(n, "storage"), "static")) { SetFlag(state.function(), IS_STATIC); } return SWIG_OK; @@ -803,14 +797,13 @@ int JSEmitter::enterVariable(Node *n) { state.variable(NAME, Swig_scopename_last(Getattr(n, "sym:name"))); } - if(Equal(Getattr(n, "storage"), "static")) { + if (Equal(Getattr(n, "storage"), "static")) { SetFlag(state.variable(), IS_STATIC); } if (!Language::instance()->is_assignable(n)) { SetFlag(state.variable(), IS_IMMUTABLE); } - // FIXME: test "arrays_global" does not compile with that as it is not allowed to assign to char[] if (Equal(Getattr(n, "type"), "a().char")) { SetFlag(state.variable(), IS_IMMUTABLE); @@ -829,7 +822,7 @@ int JSEmitter::emitCtor(Node *n) { //String *mangled_name = SwigType_manglestr(Getattr(n, "name")); String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); - if(is_overloaded) { + if (is_overloaded) { t_ctor = getTemplate("js_overloaded_ctor"); Append(wrap_name, Getattr(n, "sym:overname")); } @@ -869,14 +862,14 @@ int JSEmitter::emitCtor(Node *n) { DelWrapper(wrapper); // create a dispatching ctor - if(is_overloaded) { + if (is_overloaded) { if (!Getattr(n, "sym:nextSibling")) { String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); Template t_mainctor(getTemplate("js_ctor_dispatcher")); t_mainctor.replace("$jswrapper", wrap_name) - .replace("$jsmangledname", state.clazz(NAME_MANGLED)) - .replace("$jsdispatchcases", state.clazz(CTOR_DISPATCHERS)) - .pretty_print(f_wrappers); + .replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsdispatchcases", state.clazz(CTOR_DISPATCHERS)) + .pretty_print(f_wrappers); state.clazz(CTOR, wrap_name); } } else { @@ -895,37 +888,37 @@ int JSEmitter::emitDtor(Node *n) { String *ctype = SwigType_lstr(p_classtype, ""); String *free = NewString(""); - // (Taken from JSCore implementation.) + // (Taken from JSCore implementation.) /* The if (Extend) block was taken from the Ruby implementation. * The problem is that in the case of an %extend to create a destructor for a struct to coordinate automatic memory cleanup with the Javascript collector, * the swig function was not being generated. More specifically: - struct MyData { - %extend { - ~MyData() { - FreeData($self); - } - } - }; - %newobject CreateData; - struct MyData* CreateData(void); - %delobject FreeData; - void FreeData(struct MyData* the_data); + struct MyData { + %extend { + ~MyData() { + FreeData($self); + } + } + }; + %newobject CreateData; + struct MyData* CreateData(void); + %delobject FreeData; + void FreeData(struct MyData* the_data); - where the use case is something like: - var my_data = example.CreateData(); - my_data = null; + where the use case is something like: + var my_data = example.CreateData(); + my_data = null; - This function was not being generated: - SWIGINTERN void delete_MyData(struct MyData *self){ - FreeData(self); - } + This function was not being generated: + SWIGINTERN void delete_MyData(struct MyData *self){ + FreeData(self); + } - I don't understand fully why it wasn't being generated. It just seems to happen in the Lua generator. - There is a comment about staticmemberfunctionHandler having an inconsistency and I tracked down dome of the SWIGINTERN void delete_* - code to that function in the Language base class. - The Ruby implementation seems to have an explicit check for if(Extend) and explicitly generates the code, so that's what I'm doing here. - The Ruby implementation does other stuff which I omit. - */ + I don't understand fully why it wasn't being generated. It just seems to happen in the Lua generator. + There is a comment about staticmemberfunctionHandler having an inconsistency and I tracked down dome of the SWIGINTERN void delete_* + code to that function in the Language base class. + The Ruby implementation seems to have an explicit check for if(Extend) and explicitly generates the code, so that's what I'm doing here. + The Ruby implementation does other stuff which I omit. + */ if (Extend) { String *wrap = Getattr(n, "wrap:code"); if (wrap) { @@ -933,77 +926,75 @@ int JSEmitter::emitDtor(Node *n) { } } - // HACK: this is only for the v8 emitter. maybe set an attribute wrap:action of node // TODO: generate dtors more similar to other wrappers // EW: I think this is wrong. delete should only be used when new was used to create. If malloc was used, free needs to be used. - if(SwigType_isarray(type)) { + if (SwigType_isarray(type)) { Printf(free, "delete [] (%s)", ctype); } else { Printf(free, "delete (%s)", ctype); } - String* destructor_action = Getattr(n, "wrap:action"); + String *destructor_action = Getattr(n, "wrap:action"); // Adapted from the JSCore implementation. /* The next challenge is to generate the correct finalize function for JavaScriptCore to call. Originally, it would use this fragment from javascriptcode.swg - %fragment ("JS_destructordefn", "templates") + %fragment ("JS_destructordefn", "templates") %{ void _wrap_${classname_mangled}_finalize(JSObjectRef thisObject) { - SWIG_PRV_DATA* t = (SWIG_PRV_DATA*)JSObjectGetPrivate(thisObject); - if(t && t->swigCMemOwn) free ((${type}*)t->swigCObject); - if(t) free(t); + SWIG_PRV_DATA* t = (SWIG_PRV_DATA*)JSObjectGetPrivate(thisObject); + if(t && t->swigCMemOwn) free ((${type}*)t->swigCObject); + if(t) free(t); } %} But for the above example case of %extend to define a destructor on a struct, we need to override the system to not call free ((${type}*)t->swigCObject); - and substitute it with what the user has provided. + and substitute it with what the user has provided. To solve this, I created a variation fragment called JS_destructoroverridedefn: SWIG_PRV_DATA* t = (SWIG_PRV_DATA*)JSObjectGetPrivate(thisObject); if(t && t->swigCMemOwn) { - ${type}* arg1 = (${type}*)t->swigCObject; - ${destructor_action} + ${type}* arg1 = (${type}*)t->swigCObject; + ${destructor_action} } if(t) free(t); - Based on what I saw in the Lua and Ruby modules, I use Getattr(n, "wrap:action") - to decide if the user has a preferred destructor action. - Based on that, I decide which fragment to use. - And in the case of the custom action, I substitute that action in. - I noticed that destructor_action has the form - delete_MyData(arg1); + Based on what I saw in the Lua and Ruby modules, I use Getattr(n, "wrap:action") + to decide if the user has a preferred destructor action. + Based on that, I decide which fragment to use. + And in the case of the custom action, I substitute that action in. + I noticed that destructor_action has the form + delete_MyData(arg1); The explicit arg1 is a little funny, so I structured the fragment to create a temporary variable called arg1 to make the generation easier. This might suggest this solution misunderstands a more complex case. - Also, there is a problem where destructor_action is always true for me, even when not requesting %extend as above. - So this code doesn't actually quite work as I expect. The end result is that the code still works because - destructor_action calls free like the original template. The one caveat is the string in destructor_action casts to char* which is wierd. - I think there is a deeper underlying SWIG issue because I don't think it should be char*. However, it doesn't really matter for free. + Also, there is a problem where destructor_action is always true for me, even when not requesting %extend as above. + So this code doesn't actually quite work as I expect. The end result is that the code still works because + destructor_action calls free like the original template. The one caveat is the string in destructor_action casts to char* which is wierd. + I think there is a deeper underlying SWIG issue because I don't think it should be char*. However, it doesn't really matter for free. - Maybe the fix for the destructor_action always true problem is that this is supposed to be embedded in the if(Extend) block above. - But I don't fully understand the conditions of any of these things, and since it works for the moment, I don't want to break more stuff. - */ - if(destructor_action) { + Maybe the fix for the destructor_action always true problem is that this is supposed to be embedded in the if(Extend) block above. + But I don't fully understand the conditions of any of these things, and since it works for the moment, I don't want to break more stuff. + */ + if (destructor_action) { Template t_dtor = getTemplate("js_dtoroverride"); state.clazz(DTOR, wrap_name); t_dtor.replace("${classname_mangled}", state.clazz(NAME_MANGLED)) - .replace("$jswrapper", wrap_name) - .replace("$jsfree", free) - .replace("$jstype", ctype); + .replace("$jswrapper", wrap_name) + .replace("$jsfree", free) + .replace("$jstype", ctype); t_dtor.replace("${destructor_action}", destructor_action); Wrapper_pretty_print(t_dtor.str(), f_wrappers); - } - else { + } else { Template t_dtor = getTemplate("js_dtor"); state.clazz(DTOR, wrap_name); t_dtor.replace("$jsmangledname", state.clazz(NAME_MANGLED)) - .replace("$jswrapper", wrap_name) - .replace("$jsfree", free) - .replace("$jstype", ctype) - .pretty_print(f_wrappers); + .replace("$jswrapper", wrap_name) + .replace("$jsfree", free) + .replace("$jstype", ctype) + .pretty_print(f_wrappers); } Delete(p_classtype); @@ -1091,7 +1082,7 @@ int JSEmitter::emitConstant(Node *n) { // a lot of SWIG internal constants were emitted // This didn't happen on other platforms yet... // we ignore those premature definitions - if (!State::IsSet(state.global(HAS_TEMPLATES))) { + if (!State::IsSet(state.global (HAS_TEMPLATES))) { return SWIG_ERROR; } @@ -1197,12 +1188,11 @@ int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { do { String *siblname = Getattr(sibl, "wrap:name"); - if (siblname) - { + if (siblname) { // handle function overloading Template t_dispatch_case = getTemplate("js_function_dispatch_case"); t_dispatch_case.replace("$jswrapper", siblname) - .replace("$jsargcount", Getattr(sibl, ARGCOUNT)); + .replace("$jsargcount", Getattr(sibl, ARGCOUNT)); Append(wrapper->code, t_dispatch_case.str()); } @@ -1219,7 +1209,7 @@ int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { String *overname = Getattr(n, "sym:overname"); int l1 = Len(wrap_name); int l2 = Len(overname); - Delslice(wrap_name, l1-l2, l1); + Delslice(wrap_name, l1 - l2, l1); Setattr(n, "wrap:name", wrap_name); state.function(WRAPPER_NAME, wrap_name); @@ -1267,9 +1257,11 @@ void JSEmitter::marshalOutput(Node *n, ParmList *params, Wrapper *wrapper, Strin Parm *p; // adds a declaration for the result variable - if(emitReturnVariable) emit_return_variable(n, type, wrapper); + if (emitReturnVariable) + emit_return_variable(n, type, wrapper); // if not given, use default result identifier ('result') for output typemap - if(cresult == 0) cresult = defaultResultName; + if (cresult == 0) + cresult = defaultResultName; tm = Swig_typemap_lookup_out("out", n, cresult, wrapper, actioncode); bool should_own = GetFlag(n, "feature:new"); @@ -1294,11 +1286,11 @@ void JSEmitter::marshalOutput(Node *n, ParmList *params, Wrapper *wrapper, Strin if (params) { for (p = params; p;) { if ((tm = Getattr(p, "tmap:argout"))) { - Replaceall(tm, "$input", Getattr(p, "emit:input")); - Printv(wrapper->code, tm, "\n", NIL); - p = Getattr(p, "tmap:argout:next"); + Replaceall(tm, "$input", Getattr(p, "emit:input")); + Printv(wrapper->code, tm, "\n", NIL); + p = Getattr(p, "tmap:argout:next"); } else { - p = nextSibling(p); + p = nextSibling(p); } } } @@ -1348,7 +1340,7 @@ int JSEmitter::switchNamespace(Node *n) { if (nspace == NULL) { // enums and constants do not have 'sym:nspace' set // so we try to get the namespace from the qualified name - if(Equal(Getattr(n, "nodeType"), "enumitem")) { + if (Equal(Getattr(n, "nodeType"), "enumitem")) { nspace = Swig_scopename_prefix(Getattr(n, "name")); } } @@ -1457,14 +1449,7 @@ private: }; JSCEmitter::JSCEmitter() -: JSEmitter(), - NULL_STR(NewString("NULL")), - VETO_SET(NewString("JS_veto_set_variable")), - f_wrap_cpp(NULL), - f_runtime(NULL), - f_header(NULL), - f_init(NULL) -{ +: JSEmitter(), NULL_STR(NewString("NULL")), VETO_SET(NewString("JS_veto_set_variable")), f_wrap_cpp(NULL), f_runtime(NULL), f_header(NULL), f_init(NULL) { } JSCEmitter::~JSCEmitter() { @@ -1488,10 +1473,9 @@ void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Ma // determine an offset index, as members have an extra 'this' argument // except: static members and ctors. int startIdx = 0; - if (is_member && !is_static && mode!=Ctor) { + if (is_member && !is_static && mode != Ctor) { startIdx = 1; } - // store number of arguments for argument checks int num_args = emit_num_arguments(parms) - startIdx; String *argcount = NewString(""); @@ -1512,16 +1496,16 @@ void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Ma case Getter: case Function: if (is_member && !is_static && i == 0) { - Printv(arg, "thisObject", 0); + Printv(arg, "thisObject", 0); } else { - Printf(arg, "argv[%d]", i - startIdx); + Printf(arg, "argv[%d]", i - startIdx); } break; case Setter: if (is_member && !is_static && i == 0) { - Printv(arg, "thisObject", 0); + Printv(arg, "thisObject", 0); } else { - Printv(arg, "value", 0); + Printv(arg, "value", 0); } break; case Ctor: @@ -1559,9 +1543,9 @@ int JSCEmitter::initialize(Node *n) { f_init = NewString(""); f_header = NewString(""); - state.global(CREATE_NAMESPACES, NewString("")); - state.global(REGISTER_NAMESPACES, NewString("")); - state.global(INITIALIZER, NewString("")); + state.global (CREATE_NAMESPACES, NewString("")); + state.global (REGISTER_NAMESPACES, NewString("")); + state.global (INITIALIZER, NewString("")); /* Register file targets with the SWIG file handler */ Swig_register_filebyname("begin", f_wrap_cpp); @@ -1594,10 +1578,10 @@ int JSCEmitter::dump(Node *n) { // compose the initializer function using a template Template initializer(getTemplate("js_initializer")); initializer.replace("$jsname", module) - .replace("$jsregisterclasses", state.global(INITIALIZER)) - .replace("$jscreatenamespaces", state.global(CREATE_NAMESPACES)) - .replace("$jsregisternamespaces", state.global(REGISTER_NAMESPACES)) - .pretty_print(f_init); + .replace("$jsregisterclasses", state.global (INITIALIZER)) + .replace("$jscreatenamespaces", state.global (CREATE_NAMESPACES)) + .replace("$jsregisternamespaces", state.global (REGISTER_NAMESPACES)) + .pretty_print(f_init); Printv(f_wrap_cpp, f_init, 0); @@ -1671,7 +1655,7 @@ int JSCEmitter::exitVariable(Node *n) { if (GetFlag(n, "ismember")) { if (GetFlag(state.variable(), IS_STATIC) - || Equal(Getattr(n, "nodeType"), "enumitem")) { + || Equal(Getattr(n, "nodeType"), "enumitem")) { Append(state.clazz(STATIC_VARIABLES), t_variable.str()); } else { Append(state.clazz(MEMBER_VARIABLES), t_variable.str()); @@ -1711,11 +1695,11 @@ int JSCEmitter::exitClass(Node *n) { //Append(f_wrappers, state.clazz(CTOR_WRAPPERS)); // for abstract classes add a vetoing ctor - if(GetFlag(state.clazz(), IS_ABSTRACT)) { + if (GetFlag(state.clazz(), IS_ABSTRACT)) { Template t_veto_ctor(getTemplate("js_veto_ctor")); t_veto_ctor.replace("$jswrapper", state.clazz(CTOR)) - .replace("$jsname", state.clazz(NAME)) - .pretty_print(f_wrappers); + .replace("$jsname", state.clazz(NAME)) + .pretty_print(f_wrappers); } /* adds a class template statement to initializer function */ @@ -1727,12 +1711,12 @@ int JSCEmitter::exitClass(Node *n) { if (base_class != NULL) { Template t_inherit(getTemplate("jsc_class_inherit")); t_inherit.replace("$jsmangledname", state.clazz(NAME_MANGLED)) - .replace("$jsbaseclassmangled", SwigType_manglestr(Getattr(base_class, "name"))) - .pretty_print(jsclass_inheritance); + .replace("$jsbaseclassmangled", SwigType_manglestr(Getattr(base_class, "name"))) + .pretty_print(jsclass_inheritance); } else { Template t_inherit(getTemplate("jsc_class_noinherit")); t_inherit.replace("$jsmangledname", state.clazz(NAME_MANGLED)) - .pretty_print(jsclass_inheritance); + .pretty_print(jsclass_inheritance); } t_classtemplate.replace("$jsmangledname", state.clazz(NAME_MANGLED)) @@ -1740,7 +1724,7 @@ int JSCEmitter::exitClass(Node *n) { .replace("$jsclass_inheritance", jsclass_inheritance) .replace("$jsctor", state.clazz(CTOR)) .replace("$jsdtor", state.clazz(DTOR)) - .pretty_print(state.global(INITIALIZER)); + .pretty_print(state.global (INITIALIZER)); Delete(jsclass_inheritance); /* Note: this makes sure that there is a swig_type added for this class */ @@ -1750,8 +1734,8 @@ int JSCEmitter::exitClass(Node *n) { Template t_registerclass(getTemplate("jsc_class_registration")); t_registerclass.replace("$jsname", state.clazz(NAME)) .replace("$jsmangledname", state.clazz(NAME_MANGLED)) - .replace("$jsnspace", Getattr(state.clazz("nspace"),NAME_MANGLED)) - .pretty_print(state.global(INITIALIZER)); + .replace("$jsnspace", Getattr(state.clazz("nspace"), NAME_MANGLED)) + .pretty_print(state.global (INITIALIZER)); return SWIG_OK; } @@ -1778,21 +1762,21 @@ int JSCEmitter::emitNamespaces() { Template namespace_definition(getTemplate("jsc_nspace_declaration")); namespace_definition.replace("$jsglobalvariables", variables) - .replace("$jsglobalfunctions", functions) - .replace("$jsnspace", name_mangled) - .pretty_print(f_wrap_cpp); + .replace("$jsglobalfunctions", functions) + .replace("$jsnspace", name_mangled) + .pretty_print(f_wrap_cpp); Template t_createNamespace(getTemplate("jsc_nspace_definition")); t_createNamespace.replace("$jsmangledname", name_mangled); - Append(state.global(CREATE_NAMESPACES), t_createNamespace.str()); + Append(state.global (CREATE_NAMESPACES), t_createNamespace.str()); // Don't register 'exports' as namespace. It is return to the application. if (!Equal("exports", name)) { Template t_registerNamespace(getTemplate("jsc_nspace_registration")); t_registerNamespace.replace("$jsmangledname", name_mangled) - .replace("$jsname", name) - .replace("$jsparent", parent_mangled); - Append(state.global(REGISTER_NAMESPACES), t_registerNamespace.str()); + .replace("$jsname", name) + .replace("$jsparent", parent_mangled); + Append(state.global (REGISTER_NAMESPACES), t_registerNamespace.str()); } } @@ -1808,13 +1792,13 @@ JSEmitter *swig_javascript_create_JSCEmitter() { * V8: JSEmitter implementation for V8 engine **********************************************************************/ -class V8Emitter: public JSEmitter { +class V8Emitter:public JSEmitter { public: V8Emitter(); - virtual ~V8Emitter(); + virtual ~ V8Emitter(); virtual int initialize(Node *n); virtual int dump(Node *n); virtual int close(); @@ -1853,37 +1837,32 @@ private: // the output cpp file File *f_wrap_cpp; - String* NULL_STR; + String *NULL_STR; String *VETO_SET; String *moduleName; }; V8Emitter::V8Emitter() -: JSEmitter(), - NULL_STR(NewString("0")), - VETO_SET(NewString("JS_veto_set_variable")) -{ +: JSEmitter(), NULL_STR(NewString("0")), VETO_SET(NewString("JS_veto_set_variable")) { } -V8Emitter::~V8Emitter() -{ +V8Emitter::~V8Emitter() { Delete(NULL_STR); Delete(VETO_SET); } -int V8Emitter::initialize(Node *n) -{ +int V8Emitter::initialize(Node *n) { JSEmitter::initialize(n); - moduleName = Getattr(n,"name"); + moduleName = Getattr(n, "name"); // Get the output file name - String *outfile = Getattr(n,"outfile"); + String *outfile = Getattr(n, "outfile"); f_wrap_cpp = NewFile(outfile, "w", SWIG_output_files()); if (!f_wrap_cpp) { - FileErrorDisplay(outfile); - SWIG_exit(EXIT_FAILURE); + FileErrorDisplay(outfile); + SWIG_exit(EXIT_FAILURE); } f_runtime = NewString(""); @@ -1912,12 +1891,11 @@ int V8Emitter::initialize(Node *n) return SWIG_OK; } -int V8Emitter::dump(Node *n) -{ +int V8Emitter::dump(Node *n) { /* Get the module name */ String *module = Getattr(n, "name"); - // write the swig banner + // write the swig banner Swig_banner(f_wrap_cpp); Template initializer_define(getTemplate("js_initializer_define")); @@ -1936,14 +1914,14 @@ int V8Emitter::dump(Node *n) // filled with sub-parts Template initializer(getTemplate("js_initializer")); initializer.replace("$jsname", moduleName) - .replace("$jsv8nspaces", f_init_namespaces) - .replace("$jsv8classtemplates", f_init_class_templates) - .replace("$jsv8wrappers", f_init_wrappers) - .replace("$jsv8inheritance", f_init_inheritance) - .replace("$jsv8classinstances", f_init_class_instances) - .replace("$jsv8staticwrappers", f_init_static_wrappers) - .replace("$jsv8registerclasses", f_init_register_classes) - .replace("$jsv8registernspaces", f_init_register_namespaces); + .replace("$jsv8nspaces", f_init_namespaces) + .replace("$jsv8classtemplates", f_init_class_templates) + .replace("$jsv8wrappers", f_init_wrappers) + .replace("$jsv8inheritance", f_init_inheritance) + .replace("$jsv8classinstances", f_init_class_instances) + .replace("$jsv8staticwrappers", f_init_static_wrappers) + .replace("$jsv8registerclasses", f_init_register_classes) + .replace("$jsv8registernspaces", f_init_register_namespaces); Printv(f_init, initializer.str(), 0); Printv(f_wrap_cpp, f_init, 0); @@ -1953,8 +1931,7 @@ int V8Emitter::dump(Node *n) return SWIG_OK; } -int V8Emitter::close() -{ +int V8Emitter::close() { Delete(f_runtime); Delete(f_header); Delete(f_class_templates); @@ -1972,8 +1949,7 @@ int V8Emitter::close() return SWIG_OK; } -int V8Emitter::enterClass(Node *n) -{ +int V8Emitter::enterClass(Node *n) { JSEmitter::enterClass(n); // emit declaration of a v8 class template @@ -1985,13 +1961,12 @@ int V8Emitter::enterClass(Node *n) return SWIG_OK; } -int V8Emitter::exitClass(Node *n) -{ - if(GetFlag(state.clazz(), IS_ABSTRACT)) { +int V8Emitter::exitClass(Node *n) { + if (GetFlag(state.clazz(), IS_ABSTRACT)) { Template t_veto_ctor(getTemplate("js_veto_ctor")); t_veto_ctor.replace("$jswrapper", state.clazz(CTOR)) - .replace("$jsname", state.clazz(NAME)) - .pretty_print(f_wrappers); + .replace("$jsname", state.clazz(NAME)) + .pretty_print(f_wrappers); } /* Note: this makes sure that there is a swig_type added for this class */ @@ -2018,33 +1993,31 @@ int V8Emitter::exitClass(Node *n) .pretty_print(f_init_class_instances); // emit inheritance setup - Node* baseClass = getBaseClass(n); - if(baseClass) { + Node *baseClass = getBaseClass(n); + if (baseClass) { String *base_name = Getattr(baseClass, "name"); Template t_inherit = getTemplate("jsv8_inherit"); String *base_name_mangled = SwigType_manglestr(base_name); - t_inherit.replace("$jsmangledname", state.clazz(NAME_MANGLED)) - .replace("$jsbaseclass", base_name_mangled) - .trim() - .pretty_print(f_init_inheritance); + t_inherit.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsbaseclass", base_name_mangled) + .trim() + .pretty_print(f_init_inheritance); Delete(base_name_mangled); } - // emit registeration of class template Template t_register = getTemplate("jsv8_register_class"); t_register.replace("$jsmangledname", state.clazz(NAME_MANGLED)) - .replace("$jsname", state.clazz(NAME)) - .replace("$jsparent", Getattr(state.clazz("nspace"),NAME_MANGLED)) + .replace("$jsname", state.clazz(NAME)) + .replace("$jsparent", Getattr(state.clazz("nspace"), NAME_MANGLED)) .trim() .pretty_print(f_init_register_classes); return SWIG_OK; } -int V8Emitter::enterVariable(Node* n) -{ +int V8Emitter::enterVariable(Node *n) { JSEmitter::enterVariable(n); state.variable(GETTER, NULL_STR); @@ -2053,43 +2026,40 @@ int V8Emitter::enterVariable(Node* n) return SWIG_OK; } -int V8Emitter::exitVariable(Node* n) -{ - if(GetFlag(n, "ismember")) { - if(GetFlag(state.variable(), IS_STATIC) || Equal(Getattr(n, "nodeType"), "enumitem") ) { +int V8Emitter::exitVariable(Node *n) { + if (GetFlag(n, "ismember")) { + if (GetFlag(state.variable(), IS_STATIC) || Equal(Getattr(n, "nodeType"), "enumitem")) { Template t_register = getTemplate("jsv8_register_static_variable"); t_register.replace("$jsparent", state.clazz(NAME_MANGLED)) - .replace("$jsname", state.variable(NAME)) - .replace("$jsgetter", state.variable(GETTER)) - .replace("$jssetter", state.variable(SETTER)) - .trim(). - print(f_init_static_wrappers); + .replace("$jsname", state.variable(NAME)) + .replace("$jsgetter", state.variable(GETTER)) + .replace("$jssetter", state.variable(SETTER)) + .trim().print(f_init_static_wrappers); } else { Template t_register = getTemplate("jsv8_register_member_variable"); t_register.replace("$jsmangledname", state.clazz(NAME_MANGLED)) - .replace("$jsname", state.variable(NAME)) - .replace("$jsgetter", state.variable(GETTER)) - .replace("$jssetter", state.variable(SETTER)) - .trim() - .print(f_init_wrappers); + .replace("$jsname", state.variable(NAME)) + .replace("$jsgetter", state.variable(GETTER)) + .replace("$jssetter", state.variable(SETTER)) + .trim() + .print(f_init_wrappers); } } else { // Note: a global variable is treated like a static variable // with the parent being a nspace object (instead of class object) Template t_register = getTemplate("jsv8_register_static_variable"); t_register.replace("$jsparent", Getattr(current_namespace, NAME_MANGLED)) - .replace("$jsname", state.variable(NAME)) - .replace("$jsgetter", state.variable(GETTER)) - .replace("$jssetter", state.variable(SETTER)) - .trim() - .print(f_init_wrappers); + .replace("$jsname", state.variable(NAME)) + .replace("$jsgetter", state.variable(GETTER)) + .replace("$jssetter", state.variable(SETTER)) + .trim() + .print(f_init_wrappers); } return SWIG_OK; } -int V8Emitter::exitFunction(Node* n) -{ +int V8Emitter::exitFunction(Node *n) { bool is_member = GetFlag(n, "ismember") | GetFlag(n, "feature:extend"); // create a dispatcher for overloaded functions @@ -2103,33 +2073,32 @@ int V8Emitter::exitFunction(Node* n) return SWIG_OK; } } - // register the function at the specific context - if(is_member) { - if(GetFlag(state.function(), IS_STATIC)) { + if (is_member) { + if (GetFlag(state.function(), IS_STATIC)) { Template t_register = getTemplate("jsv8_register_static_function"); t_register.replace("$jsparent", state.clazz(NAME_MANGLED)) - .replace("$jsname", state.function(NAME)) - .replace("$jswrapper", state.function(WRAPPER_NAME)) - .trim() - .print(f_init_static_wrappers); + .replace("$jsname", state.function(NAME)) + .replace("$jswrapper", state.function(WRAPPER_NAME)) + .trim() + .print(f_init_static_wrappers); } else { Template t_register = getTemplate("jsv8_register_member_function"); t_register.replace("$jsmangledname", state.clazz(NAME_MANGLED)) - .replace("$jsname", state.function(NAME)) - .replace("$jswrapper", state.function(WRAPPER_NAME)) - .trim() - .print(f_init_wrappers); + .replace("$jsname", state.function(NAME)) + .replace("$jswrapper", state.function(WRAPPER_NAME)) + .trim() + .print(f_init_wrappers); } } else { // Note: a global function is treated like a static function // with the parent being a nspace object instead of class object Template t_register = getTemplate("jsv8_register_static_function"); t_register.replace("$jsparent", Getattr(current_namespace, NAME)) - .replace("$jsname", state.function(NAME)) - .replace("$jswrapper", state.function(WRAPPER_NAME)) - .trim() - .pretty_print(f_init_static_wrappers); + .replace("$jsname", state.function(NAME)) + .replace("$jswrapper", state.function(WRAPPER_NAME)) + .trim() + .pretty_print(f_init_static_wrappers); } return SWIG_OK; @@ -2140,10 +2109,9 @@ void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Mar String *tm; int startIdx = 0; - if (is_member && !is_static && mode!=Ctor) { + if (is_member && !is_static && mode != Ctor) { startIdx = 1; } - // store number of arguments for argument checks int num_args = emit_num_arguments(parms) - startIdx; String *argcount = NewString(""); @@ -2162,23 +2130,23 @@ void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, Mar switch (mode) { case Getter: if (is_member && !is_static && i == 0) { - Printv(arg, "info.Holder()", 0); + Printv(arg, "info.Holder()", 0); } else { - Printf(arg, "args[%d]", i - startIdx); + Printf(arg, "args[%d]", i - startIdx); } break; case Function: if (is_member && !is_static && i == 0) { - Printv(arg, "args.Holder()", 0); + Printv(arg, "args.Holder()", 0); } else { - Printf(arg, "args[%d]", i - startIdx); + Printf(arg, "args[%d]", i - startIdx); } break; case Setter: if (is_member && !is_static && i == 0) { - Printv(arg, "info.Holder()", 0); + Printv(arg, "info.Holder()", 0); } else { - Printv(arg, "value", 0); + Printv(arg, "value", 0); } break; case Ctor: @@ -2214,7 +2182,6 @@ int V8Emitter::emitNamespaces() { if (Equal(parent, "")) { do_register = false; } - // Note: 'exports' is by convention the name of the object where // globals are stored into if (Equal(name, "exports")) { @@ -2225,16 +2192,16 @@ int V8Emitter::emitNamespaces() { // create namespace object and register it to the parent scope Template t_create_ns = getTemplate("jsv8_create_namespace"); t_create_ns.replace("$jsmangledname", name_mangled) - .trim() - .pretty_print(f_init_namespaces); + .trim() + .pretty_print(f_init_namespaces); } if (do_register) { Template t_register_ns = getTemplate("jsv8_register_namespace"); t_register_ns.replace("$jsmangledname", name_mangled) - .replace("$jsname", name) - .replace("$jsparent", parent_mangled) - .trim(); + .replace("$jsname", name) + .replace("$jsparent", parent_mangled) + .trim(); // prepend in order to achieve reversed order of registration statements Insert(f_init_register_namespaces, 0, t_register_ns.str()); @@ -2254,21 +2221,18 @@ JSEmitter *swig_javascript_create_V8Emitter() { **********************************************************************/ JSEmitterState::JSEmitterState() - : _global(NewHash()) -{ +: _global(NewHash()) { // initialize sub-hashes Setattr(_global, "class", NewHash()); Setattr(_global, "function", NewHash()); Setattr(_global, "variable", NewHash()); } -JSEmitterState::~JSEmitterState() -{ +JSEmitterState::~JSEmitterState() { Delete(_global); } -DOH *JSEmitterState::getState(const char* key, bool _new) -{ +DOH *JSEmitterState::getState(const char *key, bool _new) { if (_new) { Hash *hash = NewHash(); Setattr(_global, key, hash); @@ -2276,63 +2240,55 @@ DOH *JSEmitterState::getState(const char* key, bool _new) return Getattr(_global, key); } -DOH *JSEmitterState::global() { +DOH *JSEmitterState::global () { return _global; } -DOH *JSEmitterState::global(const char* key, DOH *initial) -{ - if(initial != 0) { +DOH *JSEmitterState::global (const char *key, DOH *initial) { + if (initial != 0) { Setattr(_global, key, initial); } return Getattr(_global, key); } -DOH *JSEmitterState::clazz(bool _new) -{ +DOH *JSEmitterState::clazz(bool _new) { return getState("class", _new); } -DOH *JSEmitterState::clazz(const char* key, DOH *initial) -{ +DOH *JSEmitterState::clazz(const char *key, DOH *initial) { DOH *c = clazz(); - if(initial != 0) { + if (initial != 0) { Setattr(c, key, initial); } return Getattr(c, key); } -DOH *JSEmitterState::function(bool _new) -{ +DOH *JSEmitterState::function(bool _new) { return getState("function", _new); } -DOH *JSEmitterState::function(const char* key, DOH *initial) -{ +DOH *JSEmitterState::function(const char *key, DOH *initial) { DOH *f = function(); - if(initial != 0) { + if (initial != 0) { Setattr(f, key, initial); } return Getattr(f, key); } -DOH *JSEmitterState::variable(bool _new) -{ +DOH *JSEmitterState::variable(bool _new) { return getState("variable", _new); } -DOH *JSEmitterState::variable(const char* key, DOH *initial) -{ +DOH *JSEmitterState::variable(const char *key, DOH *initial) { DOH *v = variable(); - if(initial != 0) { + if (initial != 0) { Setattr(v, key, initial); } return Getattr(v, key); } /*static*/ -int JSEmitterState::IsSet(DOH *val) -{ +int JSEmitterState::IsSet(DOH *val) { if (!val) { return 0; } else { @@ -2400,34 +2356,36 @@ String *Template::str() { return code; } -Template& Template::trim() { - const char* str = Char(code); - if (str == 0) return *this; +Template & Template::trim() { + const char *str = Char(code); + if (str == 0) + return *this; int length = Len(code); - if (length == 0) return *this; + if (length == 0) + return *this; int idx; - for(idx=0; idx < length; ++idx) { + for (idx = 0; idx < length; ++idx) { if (str[idx] != ' ' && str[idx] != '\t' && str[idx] != '\r' && str[idx] != '\n') break; } int start_pos = idx; - for(idx=length-1; idx >= start_pos; --idx) { + for (idx = length - 1; idx >= start_pos; --idx) { if (str[idx] != ' ' && str[idx] != '\t' && str[idx] != '\r' && str[idx] != '\n') break; } int end_pos = idx; - int new_length = end_pos-start_pos+1; - char* newstr = new char[new_length+1]; - memcpy(newstr, str+start_pos, new_length); + int new_length = end_pos - start_pos + 1; + char *newstr = new char[new_length + 1]; + memcpy(newstr, str + start_pos, new_length); newstr[new_length] = 0; Delete(code); code = NewString(newstr); - delete[] newstr; + delete[]newstr; return *this; } @@ -2442,27 +2400,27 @@ Template& Template::trim() { * - returns a reference to the Template to allow chaining of methods. * ----------------------------------------------------------------------------- */ -Template& Template::replace(const String *pattern, const String *repl) { +Template & Template::replace(const String *pattern, const String *repl) { Replaceall(code, pattern, repl); return *this; } -Template& Template::print(DOH *doh) { +Template & Template::print(DOH *doh) { Printv(doh, str(), 0); return *this; } -Template& Template::pretty_print(DOH *doh) { +Template & Template::pretty_print(DOH *doh) { Wrapper_pretty_print(str(), doh); return *this; } -Template::Template(const Template& t) { +Template::Template(const Template & t) { code = NewString(t.code); templateName = NewString(t.templateName); } -void Template::operator=(const Template& t) { +void Template::operator=(const Template & t) { Delete(code); Delete(templateName); code = NewString(t.code); From 0e0ac021927d72f59503db91b6a9f57b323beb8b Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 5 Mar 2014 01:50:46 +0100 Subject: [PATCH 0733/1048] Activate travis matrix for different Javascript interpreters. --- .travis.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 6f21c4755..58b3e4ca6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -14,7 +14,11 @@ matrix: - compiler: gcc env: SWIGLANG=java - compiler: gcc - env: SWIGLANG=javascript + env: SWIGLANG=javascript ENGINE=node + - compiler: gcc + env: SWIGLANG=javascript ENGINE=jsc + - compiler: gcc + env: SWIGLANG=javascript ENGINE=v8 - compiler: gcc env: SWIGLANG=lua - compiler: gcc From fe10555229b2d2636e16f16a9aa8b4b6ba1f6863 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 5 Mar 2014 01:51:29 +0100 Subject: [PATCH 0734/1048] Add check to skip javascript test-suite if default interpreter is not installed. --- configure.ac | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/configure.ac b/configure.ac index dc446897d..ac392028b 100644 --- a/configure.ac +++ b/configure.ac @@ -1128,6 +1128,13 @@ else ;; esac + #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + # Look for Node.js which is the default javascript engine + # without it, the javascript test-suite will be skipped + #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + AC_CHECK_PROGS(NODEJS, node) + #---------------------------------------------------------------- # Look for JavascriptCore (Webkit) settings (JSCOREINCDIR, JSCOREDYNAMICLINKING) #---------------------------------------------------------------- @@ -2455,6 +2462,9 @@ fi AC_SUBST(SKIP_JAVA) SKIP_JAVASCRIPT= +if test -z "$JAVASCRIPT" || test -z "$NODEJS"; then + SKIP_JAVASCRIPT="1" +fi AC_SUBST(SKIP_JAVASCRIPT) SKIP_GUILE= From cb2627ac03e5dd5270eb1c8e4413fd41436fe310 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Wed, 5 Mar 2014 02:00:25 +0100 Subject: [PATCH 0735/1048] Merged branch 'devel' from https://github.com/oliver----/swig-v8 (squashed commit): commit fe10555229b2d2636e16f16a9aa8b4b6ba1f6863 Author: Oliver Buchtala Date: Wed Mar 5 01:51:29 2014 +0100 Add check to skip javascript test-suite if default interpreter is not installed. commit 0e0ac021927d72f59503db91b6a9f57b323beb8b Author: Oliver Buchtala Date: Wed Mar 5 01:50:46 2014 +0100 Activate travis matrix for different Javascript interpreters. commit 89610e984ea3732a7da7bfc6bea1ffed2039201e Author: Oliver Buchtala Date: Wed Mar 5 01:39:26 2014 +0100 Beautified Javascript module. commit b5bc87667d62fa05a31ab85ba0b7894f83d7cdce Author: Oliver Buchtala Date: Wed Mar 5 01:10:55 2014 +0100 Fix regressions. - Adapted to changes in UTL - Fixed detection of setters and getters. commit a234542543088140e4dd925b0060a93960db9eee Merge: 8c05fe3 c99417a Author: Oliver Buchtala Date: Wed Mar 5 01:09:26 2014 +0100 Merge branch 'master' into tmp Conflicts: .travis.yml Examples/Makefile.in Examples/test-suite/director_nspace.i Examples/test-suite/nspace.i Examples/test-suite/nspace_extend.i Source/Modules/lang.cxx configure.ac commit 8c05fe37afcbcd6a2fc2a7d8bbe028e6d8f59239 Author: Oliver Buchtala Date: Tue Mar 4 22:55:32 2014 +0100 Removed obsolete paragraph from Javascript documentation. commit 924f373a2f6a58c4a8d40e6f61434a6e3f6df50b Author: Oliver Buchtala Date: Tue Mar 4 22:51:19 2014 +0100 Fix pandoc filter. And add a script that helps to run pandoc with appropriate command line flags. commit 6b82dff8f35d9ca743670a6131a87d493514c6b6 Author: Oliver Buchtala Date: Tue Mar 4 22:50:23 2014 +0100 Minor tweaks in Javascript documentation. commit 1a7e12911ac96e8b788686076f35771ac248220d Author: Oliver Buchtala Date: Tue Mar 4 12:00:13 2014 +0100 Adding a chapter about Javascript tests and examples. commit a9b8b85c1c1b2bfe5b9b389e6f9406258371d512 Author: Oliver Buchtala Date: Tue Mar 4 11:00:26 2014 +0100 Minor change in Javascript configuration. commit dbd61e40e1c92aa02c3ce5170534687f7ae8d42f Author: Oliver Buchtala Date: Tue Mar 4 10:41:35 2014 +0100 Fix issues that were observed with newer JavascriptCore. commit 70385842df0c68c4e7e7eeb4531f703330edb831 Author: Oliver Buchtala Date: Fri Feb 28 10:40:41 2014 +0100 Add missing copy ctor for Javascript Code Template class. commit b20b0f4e4b1626030c4155f22313af3ee0fd4e00 Author: Oliver Buchtala Date: Thu Feb 27 01:02:06 2014 +0100 Removed CMake. Started a separate project which acts as a CMake shell around SWIG. commit 7e015e4acf3cb6644f2002d4457a589f1d76f69d Author: Oliver Buchtala Date: Wed Feb 26 23:26:19 2014 +0100 Fix regression in Javascript configuration. commit 348cb2026e2edad29003281ed9b0a2f43c10aa54 Author: Oliver Buchtala Date: Wed Feb 26 22:56:31 2014 +0100 Fix regressions in configuration of some Javascript examples. commit 94869c922861adc007e1cfffde279f2c4e554311 Author: Oliver Buchtala Date: Wed Feb 26 22:47:29 2014 +0100 More gitignores filtering Javascript related files. commit 424e3f47123f8a7746d12d02204b896e55b8444d Author: Oliver Buchtala Date: Wed Feb 26 22:46:24 2014 +0100 Fix custom javascript interpreter configuration for OSX. commit 15f12d9b59b9e8522853f010f9d443164774a6a6 Author: Oliver Buchtala Date: Wed Feb 26 22:44:37 2014 +0100 Make examples work with node.js and the custom interpreter. commit b216a739c45cfb595a5b70da7e811b6130148a63 Author: Oliver Buchtala Date: Wed Feb 26 20:51:38 2014 +0100 Introduced an extra Makefile for the custom javascript interpreter. commit bf1606c0f9261dcb4ae8d5c24aebc987a67e7510 Author: Oliver Buchtala Date: Wed Feb 26 11:10:09 2014 +0100 Fix travis configuration. commit 16a702c0aac717462b1eb94fc4640446943d9396 Author: Oliver Buchtala Date: Wed Feb 26 10:48:38 2014 +0100 Added a comment. commit e62c6126e9d6645eaff2b96d7847d4a8c681bb84 Author: Oliver Buchtala Date: Wed Feb 26 10:47:48 2014 +0100 Fix regressions in Javascript example configuration. commit 15550dab450f003c0b42d6a3353b137435793999 Author: Oliver Buchtala Date: Tue Feb 25 20:16:15 2014 +0100 Fix issue with strange constants under OSX. Receiving strange constant nodes before the real tree under OSX 10.8. Not so under Ubuntu 12.04. commit 84ba91dc63d817376486cecfd7188f56303e6e3b Author: Oliver Buchtala Date: Thu Feb 20 12:38:53 2014 +0100 Some fixes in example section of Javascript documentation. commit 1ffacaab5b7635da623de6c49c22684a1c46d549 Author: Oliver Buchtala Date: Thu Feb 20 12:30:57 2014 +0100 Add note about '-node' command line flag for Node.js code generation. commit 462674ea11fc227501a485a878efd1ae9e111126 Author: Oliver Buchtala Date: Thu Feb 20 12:28:06 2014 +0100 Added examples to Javascript module documentation. commit 3f22a3d639a2884b8cd50d57fc22b6df49a85cdf Author: Oliver Buchtala Date: Thu Feb 20 11:37:40 2014 +0100 Simplification in common javascript example Makefile. commit 8e65414a764f390e0db4f8ded0031ecdef16d896 Author: Oliver Buchtala Date: Thu Feb 20 11:37:15 2014 +0100 Add an extra argument for enabling nodejs support. This is essentially using the v8 emitter plus setting a #define. commit 7c1f66c29e4d0fd72e656b4bd27b2010c053b2c7 Author: Oliver Buchtala Date: Thu Feb 20 11:15:46 2014 +0100 Add more notes about how to install node. commit 48e7df8eb2f7cb87e57dd7a890fbaa9ec8598ac7 Author: Oliver Buchtala Date: Thu Feb 20 11:15:18 2014 +0100 Better error message when no Javascript emitter is specified. commit fd0e75843d3ec7816c85a5d1ab84bd9319c9b27e Author: Oliver Buchtala Date: Thu Feb 20 11:14:48 2014 +0100 Deactivated broken JS examples. commit 77ead7017caca778eb3143fa487856ee8dcd4b7b Author: Oliver Buchtala Date: Thu Feb 20 11:13:57 2014 +0100 Refactored configuration for javascript examples. commit 8df34d54d0957552a53fe5f1e6598849c4ac9f81 Author: Oliver Buchtala Date: Fri Feb 14 13:21:52 2014 +0100 Beginning to document v8 integration. commit 05146e2aed5b8e9df390acdd12b6e5cda2ed2e00 Author: Oliver Buchtala Date: Fri Feb 14 13:04:21 2014 +0100 Documented extending Node.js and Webkit's Javascript engine. commit 68472802721264ec8adee4f80ce7576eb3dd1a3e Author: Oliver Buchtala Date: Fri Feb 14 09:02:37 2014 +0100 Pandoc filter detects shell blocks when not explicitely given. Considered as shell if the first character is '$', as in $ swig -javascript Alternatively you can specify the class explicitely: ```shell swig -javascript ``` commit 1fca61c59ad7a825725b76d394de688774f296e8 Author: Oliver Buchtala Date: Fri Feb 14 09:00:04 2014 +0100 Conitnued documenting the Javascript module. commit 915b7094331bf99f5cf6ed31d5747d10ae1bebb9 Author: Oliver Buchtala Date: Fri Feb 14 00:02:05 2014 +0100 Not a real change. Using a macro to reset JSEmitterStates for the sake of readability. commit 8148b017f879f272616c8bb36b6bcd60232f9c4f Author: Oliver Buchtala Date: Fri Feb 14 00:01:15 2014 +0100 Add a pandoc filter to create compatible html. commit e829ea601f573b96efdf0e1ed602d90a7d39e29f Author: Oliver Buchtala Date: Fri Feb 14 00:00:37 2014 +0100 Add Javascript to chapters. commit fa8b350cd67a8850a866ee52250a6955ef17699f Author: Oliver Buchtala Date: Fri Feb 14 00:00:12 2014 +0100 More Javascript module documentation. commit 02c55fc52fb30da3cec7188b64d456c7dcf8fc9f Author: Oliver Buchtala Date: Thu Feb 13 21:18:06 2014 +0100 Next iteration on creating a documentation for the Javascript module. commit 1e34ecdc31c82d30141097f7744617361ebb748c Author: Oliver Buchtala Date: Thu Feb 13 19:25:16 2014 +0100 Next iteration on creating a documentation for the Javascript module. commit 41ec3fb67e65f3448e52c0eb7372d0331bc7b6ca Author: Oliver Buchtala Date: Fri Sep 27 02:54:42 2013 +0200 Travis configuration for Javascript branch. commit 48af60d82904f1eef37b9beac03f8412947e883e Author: Oliver Buchtala Date: Fri Sep 27 02:46:11 2013 +0200 Javascript examples. commit ecf9f96079067386a5f8bc83fadd4ac9e03f551c Author: Oliver Buchtala Date: Fri Sep 27 02:45:22 2013 +0200 Javascript documentation. commit 00053169cd5d69c42b1b1bbf58336776e1820c97 Author: Oliver Buchtala Date: Fri Sep 27 02:44:53 2013 +0200 CMake configuration. commit 6a366cc050f25b3d358d8f4d85e37011ada82726 Author: Oliver Buchtala Date: Fri Sep 27 03:23:37 2013 +0200 Fix regression. commit 6dcbbf07db310a78457d1c00e84a60761502ea5d Merge: 4492a3d c2d3da2 Author: Oliver Buchtala Date: Fri Sep 27 02:29:02 2013 +0200 Conflicts: .gitignore .project .travis.yml Examples/Makefile.in Examples/test-suite/director_nspace.i commit c2d3da2eeca2d1923d9c69dda70a8ce2f1b2cf1e Author: Oliver Buchtala Date: Thu Sep 26 05:14:34 2013 +0200 Fix test configuration. commit 582bd297690605d98ae758d164cc48e299ae34b3 Author: Oliver Buchtala Date: Thu Sep 26 04:55:34 2013 +0200 Trying to install former working version of nodejs. commit 7adf93ef0f86babb564b1458228f5b4666f414dc Author: Oliver Buchtala Date: Thu Sep 26 04:13:32 2013 +0200 Fix test configuration for nodejs. commit 335d926c449d22821eb916d0f862062b925c2ca6 Author: Oliver Buchtala Date: Tue Sep 24 03:56:19 2013 +0200 Add stub std_deque.i files. commit 51b36d1a1f0c9efe3ef3d25c8bd8c3dfecfa4a52 Author: Oliver Buchtala Date: Tue Sep 24 03:55:51 2013 +0200 Add non pretty printing function to Templates. commit dc62a69775f7eff6a11e7ca7f162ae960b53e671 Author: Oliver Buchtala Date: Tue Sep 24 03:55:10 2013 +0200 Fix bug with typedefd function pointers. commit 2efe63ebb2c87e2e8cde445ffdf964f6cc38869e Author: Oliver Buchtala Date: Tue Sep 24 01:50:33 2013 +0200 Add some test runners. commit b9ecf75f17c05bc58d6e6347877b5aedd92d2d28 Author: Oliver Buchtala Date: Tue Sep 24 01:50:13 2013 +0200 Fix emitter for member pointer constants. However, I am not happy with the constant emitter in general. Should not return dynamic values but register constant wrappers statically. commit 8bf966a65c2120d2bf050857587e7e7bd7cafd58 Author: Oliver Buchtala Date: Tue Sep 24 01:47:13 2013 +0200 Fix %nspace support and activated relevant tests. commit d34a6da08c1dd59ad14731f4ea6a7e8b3b6dd8b7 Author: Oliver Buchtala Date: Tue Sep 17 01:53:22 2013 +0200 Disable warnings for some v8 test-cases. commit b3c198ccee3dad34f75c4617900e53e1770f0ee9 Author: Oliver Buchtala Date: Mon Sep 16 22:28:14 2013 +0200 Fix regression. commit b99e8613ad7103bd99d7f6c7e24b774c73467201 Author: Oliver Buchtala Date: Mon Sep 16 21:56:52 2013 +0200 Bugfix in argument marshalling. commit dd4ed7f3d6bc6a13c271ac7ffb629115414113ec Author: Oliver Buchtala Date: Mon Sep 16 11:46:52 2013 +0200 Disable testcase 'typemap_variables' for v8. It uses output typemaps that are not compatible with the v8 API. commit 0528fd3ac3f6205ce642fa6997908df160030608 Author: Oliver Buchtala Date: Mon Sep 16 11:46:00 2013 +0200 Bugfix for Javascript generator. commit 147cec70f1226dead5d93afd711b99bc9e81827f Author: Oliver Buchtala Date: Mon Sep 16 04:54:57 2013 +0200 Replace $symname in generated function wrappers. commit eb9523b5caef732bbd1b259850e16dc8a9e11564 Author: Oliver Buchtala Date: Mon Sep 16 04:12:55 2013 +0200 Add missing macros. commit 3e28d1e28f81688184cf2c362fa01b7efaaad790 Author: Oliver Buchtala Date: Mon Sep 16 04:12:42 2013 +0200 Let v8 generated code include stdlib.h commit b6426bde2501e6304193644ddc6e8c933db4412e Author: Oliver Buchtala Date: Mon Sep 16 04:12:06 2013 +0200 Add cdata.i typemaps. commit 1f07195812f79a20bb1f37178e596dd0bab8ef2e Author: Oliver Buchtala Date: Mon Sep 16 03:53:00 2013 +0200 Rearrange generation of init block to have custom init code within the initializer body. commit 80ce36c445c704a105a70d6820baefb74a7cd0ec Author: Oliver Buchtala Date: Mon Sep 16 02:27:51 2013 +0200 Make JSC inheritance definition more robust. commit 973042302b017111b06305bedafe47798fcfad86 Author: Oliver Buchtala Date: Mon Sep 16 01:57:55 2013 +0200 Removed dead code. commit bf416876ddf24249f75eff9854e551d789dfab42 Author: Oliver Buchtala Date: Mon Sep 16 01:33:19 2013 +0200 Bugfix for JSC %typemap(out) std::string&. commit b7f827e42ce3073d44f163877f7712782740d1bf Author: Oliver Buchtala Date: Mon Sep 16 01:23:03 2013 +0200 Fix typemap declarations for (unsigned) long long. commit 68eff3e81efd46692206dcf2ea762931f94c63ce Merge: bb7bd50 018847b Author: Oliver Buchtala Date: Mon Sep 16 00:55:57 2013 +0200 Merge branch 'devel' of github.com:oliver----/swig-v8 into devel commit bb7bd50eabdf5cc2f07640227713ef75dc1c8fce Author: Oliver Buchtala Date: Mon Sep 16 00:55:43 2013 +0200 Add support for IN/OUTPUT typemaps. commit 018847b0002a445a1e7110e16dd108aac34564a9 Merge: acfed20 325b544 Author: Oliver Buchtala Date: Sun Sep 15 06:00:06 2013 -0700 Merge pull request #28 from whoozle/devel fixed newer v8 compilation commit 325b5445d67ccf60855aac970ecb6ba913e2b32b Author: Vladimir Menshakov Date: Sat Sep 14 16:19:47 2013 +0400 removed Clear before Dispose from newer v8 code, consider the following code: template void Persistent::Dispose() { if (this->IsEmpty()) return; //Clear will trigger this V8::DisposeGlobal(reinterpret_cast(this->val_)); ... } commit 89fd7ed9c1b1c1e0a1a5344018ab9d0a5ce711b0 Author: Vladimir Menshakov Date: Sat Sep 14 16:17:21 2013 +0400 fixed newer v8 compilation commit 477b2393b10f664696b8cf1e49c2b98deab39d79 Author: Oliver Buchtala Date: Thu Sep 12 05:26:22 2013 +0200 Add stub 'typemaps.i' files. commit acfed20eba1c72571f65048c62653bf339d5564b Author: Oliver Buchtala Date: Thu Sep 12 05:10:23 2013 +0200 Bugfix Javascript generator: valid name for dispatcher functions. commit 1a04e488bc5e17de266181f6b39e00e114f9ae8a Author: Oliver Buchtala Date: Thu Sep 12 05:40:59 2013 +0300 Fix Javascript generator for smartpointeraccessed variables. commit 8bf95c4356b61da9f510245310a0bd3c1fafe36f Author: Oliver Buchtala Date: Thu Sep 12 05:09:35 2013 +0300 Bugfix for Javascript generator: avoid duplicate action code generation. commit 09a210e037c8d5ca46ee4edc4c904f11b04cb893 Author: Oliver Buchtala Date: Thu Sep 12 04:09:21 2013 +0300 Bugfix in Javascript generator: detect member setter/getters correctly. commit c53e3e4dab9b6ab61e63880476721c61ec9ff940 Author: Oliver Buchtala Date: Tue Sep 10 14:45:33 2013 +0300 Fix configuration for nodejs based tests. - use $(SWIGOPT) - less verbose commit dd84e6f9e0b67737ca1031cd6bbb4dcc4eb84340 Author: Oliver Buchtala Date: Tue Sep 10 14:16:36 2013 +0300 Some fixes and cleanup in Javascript generator. - v8 generator uses the correct mangled name for class templates - removed symbols for template variables in favor of using the string literals directly, as it is easier to understand when debugging. commit 001f38c6a9ebd19dee26196e9b0ee2421b8cbe5f Author: Oliver Buchtala Date: Tue Sep 10 13:29:16 2013 +0300 Fix settings for building nodejs tests. Removed the `-node` command line flag. Instead one has to use `-v8 -DBUILDING_NODE_EXTENSION=1`. commit be35d94fdb8b274b443e2467d8a1b6d2dd0723c6 Author: Oliver Buchtala Date: Tue Sep 10 11:53:12 2013 +0300 Add support for PackedData to Javascript generator. commit e5ad9cdc0527b21cbabaad02a22efd8418459d99 Author: Oliver Buchtala Date: Mon Sep 9 22:26:30 2013 +0300 Added two more Javascript tests. - `abstract_inherit` - `char_strings` commit 571c516a0b096564b070350c9b90255db3422768 Author: Oliver Buchtala Date: Mon Sep 9 22:25:51 2013 +0300 Some fixes for the Javascript generator. - added missing `exception.i` - added missing generator block `wrappers` for v8 commit 3c5946d998f2bcecc88f04de8df7a6f3da292b32 Author: Oliver Buchtala Date: Mon Sep 9 17:38:44 2013 +0300 Redefined set of Javascript smoke tests. commit 407d8ef5acff62578c701da74cfdf9a752baffd1 Author: Oliver Buchtala Date: Mon Sep 9 17:34:53 2013 +0300 Clean up in `javascripttypemaps.swg`. - following the same layout/order as pytypemaps - added typemaps for `long long` and `unsigned long long`, which are only copies of those for `long` and `unsigned long` and hence are just experimental. commit fc4d9b665c5839df06501e736163bfeadb7503d1 Author: Oliver Buchtala Date: Mon Sep 9 16:28:29 2013 +0300 Fix v8 generator to use a non clashing name for built-in 'equals' method. commit b6c9c97b96bc3039ccb291d76a64d009fc81fbb7 Author: Oliver Buchtala Date: Mon Sep 9 15:05:11 2013 +0300 Fix Javascript generator to use %renamed variable names. commit 108143951da3859e0c056780706b6841231febb3 Author: Oliver Buchtala Date: Mon Sep 9 13:55:08 2013 +0300 Activate Javascript test-cases `rename_simple` and `rename_scope`. These reveal current deficiencies in the Javascript generator with `%rename`ing. commit 64da1173ddf8bd1fe04800e2afbe0f9c5d2dc818 Author: Oliver Buchtala Date: Mon Sep 9 13:23:47 2013 +0300 Activate Javascript testcases `rename1-4`. commit 1438d0cfb45f0f1b740eb8d1d366f694ba99d0b6 Author: Oliver Buchtala Date: Mon Sep 9 13:17:38 2013 +0300 Add `infinity` test-case to list of smoke tests. commit e01e337d752dbbfc58a06b87fe1169d3f6ada76f Author: Eric Wing Date: Thu Sep 5 14:50:15 2013 -0700 Added unit test using C99 INFINITY. This test actually tests a float conversion bug where converting to float imposed overflow checking which should not be there and causes this program to error out. This was seen originally in Javascript, but it turns out Python has the same bug. Lua does not have this bug. Other generators have not been tested. This test also tests the rename feature. The Javascript generator was not renaming the variable correctly. commit 1729fac3605d6649919ee508bcf8b03f904886f4 Author: Oliver Buchtala Date: Mon Sep 9 12:46:07 2013 +0300 Bug-fix for static variables as proposed by Kota Iguchi. Fixes #20. commit 8408e9b19395f9f7ffca586de80012473b6c3a4e Merge: 6b35c2d b49da78 Author: Oliver Buchtala Date: Fri Sep 6 19:50:51 2013 -0700 Merge pull request #19 from whoozle/devel fixed deprecation warnings for v8-3.21 commit 6b35c2d419eac4f71780a939254e8a459c075849 Author: Oliver Buchtala Date: Fri Sep 6 16:26:02 2013 +0300 Let Travis test all three targets. - nodejs: 0.10.12 - libwebgitgtk 1.0 - libv8 3.7.12 We should soon switch to a new v8 version or add an extra runner. commit 0facc7ecf9f48a98a6f66c557917657d3adb2d36 Author: Oliver Buchtala Date: Fri Sep 6 15:59:43 2013 +0300 Allow to run the test suite with our list of smoke tests. The javascript generator can not deal with the whole test-suite. Moreover, during development I want to have immediate feedback using a set of smoke tests. commit 492d3010ff33c1b6af9bca9472ad08e0330ffb42 Author: Oliver Buchtala Date: Fri Sep 6 01:40:23 2013 +0300 Javascript V8 test-cases always create cpp wrappers. commit 26b5acbbe850c3494f4b79c62f678a92f219f61a Author: Oliver Buchtala Date: Fri Sep 6 00:42:56 2013 +0300 Test-suite Makefile now supports testing for all three Javascript variants. - node.js - custom JavascriptCore interpreter - custom V8 interpreter commit 962207e0f33a322af3f9303f1e15ce9e28eb7281 Author: Oliver Buchtala Date: Fri Sep 6 00:41:18 2013 +0300 Rewritten Javascript autoconfiguration. commit 29ccb270afa761d57d6a6728ca49d92fe9d35bc0 Author: Oliver Buchtala Date: Fri Sep 6 00:40:29 2013 +0300 Renamed object provided to JS initializers. JSC initializer create a new module object. V8 initializer fill a provided 'exports' object. commit 4794fa1884215982384535d25bfcc8e37b496629 Author: Oliver Buchtala Date: Fri Sep 6 00:38:07 2013 +0300 Refactored custom javascript engines to support primitive 'require' statements. commit b49da78b0a6ef1d6e9f624c60710f79e709fca2e Author: Vladimir Menshakov Date: Thu Sep 5 19:50:15 2013 +0400 fixed deprecation warnings for v8-3.21 commit 740da9c733e505d52a918742bc0ac559d7e4ccf6 Merge: 8b0ee54 2a39abe Author: Oliver Buchtala Date: Wed Sep 4 09:18:42 2013 -0700 Merge pull request #17 from whoozle/devel fixed v8-3.20+ compilation and deprecation warnings. commit 2a39abebb684e7e5a2bf878b9d74c54de415bae1 Author: Vladimir Menshakov Date: Wed Sep 4 20:10:42 2013 +0400 moved common swig v8 definitions in javascriptruntime.swg, fixed obsoleted api calls commit 8b0ee5491a9f19a57fef83433d755cc0a9e40c40 Author: Oliver Buchtala Date: Wed Sep 4 18:04:40 2013 +0200 Added missing template configuration files for nodejs based tests. commit 315287b6563f4730468e4b882e569fa72893ba71 Author: Oliver Buchtala Date: Wed Sep 4 17:55:44 2013 +0200 Put the SWIG_V8_VERSION macro into "runtime" block. commit 4068f31c6b66f08c24f760f46da5b4a4d7b6f11b Author: Oliver Buchtala Date: Wed Sep 4 17:54:35 2013 +0200 Use a diffent name for the V8_VERSION provided via command line. commit b7db2a84c907b96e3371b8c8301b32421a10fef5 Author: Vladimir Menshakov Date: Wed Sep 4 19:33:48 2013 +0400 fixed return values and added missing newer v8 dtor wrapper. commit fec11a8def1e1bea9626fab8f17d05c253178bec Author: Oliver Buchtala Date: Wed Sep 4 13:07:07 2013 +0200 Allow exceptions in generated example/test node extensions. commit 54dd7e96c0f9623649947f8f6237a8f1be1ac770 Author: Oliver Buchtala Date: Wed Sep 4 12:47:24 2013 +0200 Fix cleanup configuration for javascript test-suite. commit 8778146b4b45d5033bb65701ab881b1edcc51b9b Author: Oliver Buchtala Date: Wed Sep 4 12:10:08 2013 +0200 Relax type check in SWIG_AsVal_int. The array_member test-case revealed that integers come in as `Numbers`. commit 0e78fc0ad7a962f2d3687c1fb32294e174e68dd5 Author: Oliver Buchtala Date: Tue Sep 3 18:50:46 2013 +0200 Fixing travis configuration. commit da48f3307f4ac358ca2d325f8c04b9a5afb90323 Author: Oliver Buchtala Date: Tue Sep 3 18:24:19 2013 +0200 Remove javascript autoconf detection (Temporarily). I want to cut it down to a minimum having only nodejs. We will activate the others (native JSC and V8) later. commit 262aca8ead684a53c4f2029db5f32a3505e348b3 Author: Oliver Buchtala Date: Tue Sep 3 17:16:40 2013 +0200 Fix in travis config. commit 83e6aa85b6e7f8097eb02179bb8f3faaeb06037b Author: Oliver Buchtala Date: Tue Sep 3 17:13:38 2013 +0200 Not a real change. commit 0aabfeb231d74ac997b28e816987fb033d6b2fd9 Author: Oliver Buchtala Date: Tue Sep 3 17:07:49 2013 +0200 Slight modification to travis config. commit fa27ff29769031cef7dbb3b1951ec6adde09b0cf Author: Oliver Buchtala Date: Tue Sep 3 17:03:08 2013 +0200 Add a travis configuration (experimental). commit 8bbd92883101584583e3139e442bc418100b4a45 Author: Oliver Buchtala Date: Tue Sep 3 16:57:40 2013 +0200 Make javascript test-suite work with nodejs. commit cef82c720f4875b9ddf53667e5396d3b80c7eefd Author: Oliver Buchtala Date: Tue Sep 3 14:41:35 2013 +0200 Replace old style v8 version switches. commit d3074ba4c1cc46bfebd3b09671f92965cab533ed Author: Oliver Buchtala Date: Tue Sep 3 14:02:52 2013 +0200 Fix error in SWIG_V8_GetInstancePtr. commit f70c0e16f292e1fab77fb9ae63f56e86c3ae90c4 Author: Kota Iguchi Date: Wed Aug 28 15:08:50 2013 +0900 Add "equals" to compare between pointers Add "getCPtr" to retrieve pointer value commit a29975c69a0bf0628d740232cab722387588eed2 Author: Kota Iguchi Date: Fri Aug 16 16:08:47 2013 +0900 Typemap for natural support for arrays commit 78a3cc9e3e4bdf6d55cb52ab8812c4127e6ad475 Author: Kota Iguchi Date: Fri Aug 16 10:15:37 2013 +0900 Added the finalize callback (JSObjectFinalizeCallback) commit 14a137adca1a101595e103893d7143aa43525791 Author: Oliver Buchtala Date: Tue Sep 3 06:27:14 2013 +0200 Fix regression. commit 5da54ca435741f74a7212d7034b11b9fa17046d7 Author: Oliver Buchtala Date: Tue Sep 3 06:26:54 2013 +0200 Convert javascript examples to nodejs. commit dbf2b1fe945714641322c2f758bde63140db37fa Author: Oliver Buchtala Date: Tue Sep 3 05:46:19 2013 +0200 Ignore javascript Example build files. commit 11e2179dd318d49665fe665022a2a5ea30c59392 Author: Oliver Buchtala Date: Tue Sep 3 05:40:22 2013 +0200 First example that addresses node.js as primary execution environment. commit a48438c562b3f1601e5bbc9cedcf9f124af97975 Author: Oliver Buchtala Date: Tue Sep 3 05:39:37 2013 +0200 Better v8 version handling. You should start to specify a version on command line, e.g., swig -javascript -v8 -DSWIG_V8_VERSION=0x032007 commit 5228c0eeab0e96930d18e1b0b0d732636adc882f Author: Oliver Buchtala Date: Tue Sep 3 05:36:41 2013 +0200 Add a dedicated mode for creating node modules. commit 5aba4c7ea657f086519acb950e19c416d808b74a Author: Oliver Buchtala Date: Tue Sep 3 05:35:03 2013 +0200 Starting from scratch with Examples configuration. commit cb5f4dc47eeac71a0c5f39618027382567cb53d4 Author: Vladimir Menshakov Date: Thu Aug 15 14:33:00 2013 +0400 ported to newer, more efficient v8 api commit c291675ccef1b058ea5e4c642f0f5b2e72b9e006 Merge: 046ca76 0732592 Author: Jason Turner Date: Fri Aug 9 14:09:43 2013 -0600 Merge branch 'devel' of https://github.com/ewmailing/swig-v8 into devel commit 0732592ed99759afab2f05e6be1723659e955464 Author: Kota Iguchi Date: Wed Aug 7 18:10:53 2013 -0700 Patch to support argout typemap for your swig-v8 branch. commit 32f9cce600452a6210b0eebfd1d598219b90d7bc Merge: 4503c53 306b265 Author: Oliver Buchtala Date: Sat Aug 31 03:47:43 2013 +0200 Merged whoozle branch with ewmailing branch. Conflicts: Lib/javascript/v8/javascriptcode.swg commit 306b265af99613948481a60d55fa902ae6a84c17 Merge: 65a0be8 b511e33 Author: Oliver Buchtala Date: Sat Aug 31 03:47:08 2013 +0200 Merge branch 'devel' of git://github.com/oliver----/swig-v8 into devel Conflicts: Lib/javascript/v8/javascriptcode.swg commit 4503c5390304202275a849eaa8473985adf86f02 Author: Eric Wing Date: Wed Aug 7 15:12:36 2013 -0700 Since this code uses assert, #include is needed. commit 65a0be8876959dd9a79bc3d7290af15ab646202d Author: Eric Wing Date: Thu Jul 11 20:04:01 2013 -0700 v8: variable name bug fix in my template modifications for pointers to structs. commit f8feeacb68593063914c58c60e408d8515295b7f Author: Eric Wing Date: Thu Jul 11 19:11:56 2013 -0700 v8: Removed the extern "C" around the initialize function because it makes no sense since it requires a C++ templates object as a parameter. commit ed729f7d3adaf675bbf7f1f800cdcbe17287d987 Author: Eric Wing Date: Thu Jul 11 19:09:17 2013 -0700 This brings over the memory leak fixes for pointers to structs with a %extend destructor from my Neha fork. The generator was not generating and connecting the needed code for the requested destructor to the v8 dtor finalizer. I did not realize this branch has some JavaScriptCore stuff in it too. Unfortunately, it seems to have its own unique problems (like creating C++ files when it should be generating C files). My changes are targeted for v8, and I don't think my JSCore changes fully reach in this JSCore implementation so more work would need to be done to get this branch working. I think my Neha fork is in better shape at the moment. Also, I did port over the 'NULL out the dtor function pointer' in the %nodefaultdtor fix to v8. Usage case: struct MyData { %extend { ~MyData() { FreeData($self); } } }; %newobject CreateData; struct MyData* CreateData(void); %delobject FreeData; void FreeData(struct MyData* the_data); where the use case is something like: var my_data = example.CreateData(); my_data = null; commit 046ca7686b5605fc7e729d5a4afbe28f2d2c6807 Author: Jason Turner Date: Sat Jul 27 12:35:36 2013 -0600 Adjust for v8::Persistent API which was deprecated @ 3.19.16 https://groups.google.com/forum/#!topic/v8-users/oBE_DTpRC08 commit d5df0bb72101d057b6d59cf7d683263e65288884 Author: Eric Wing Date: Wed Aug 7 15:11:49 2013 -0700 Added #if defined guard for V8_3_14 to allow users from the original SWIG v8 implementation to continue using the new changes. It works similarly to the BUILDING_NODE_EXTENSION in all but two places. This define must be explicitly set by users because there is no way to auto detect. (Perhaps a command line switch can be added to generate this on request?) commit cf9b7e89ac52badd89acc2ba2bb5072055837ce0 Author: Jason Turner Date: Sat Jul 27 09:50:03 2013 -0600 Get memory updates working with Node.js again. commit 3af7d543cb52623f962a48f91a129181af29901a Author: Vladimir Menshakov Date: Wed Aug 7 16:11:59 2013 +0400 fixed crash while instantiating generic-wrapped objects from external code, please review commit 9e74bdb97e049511be20322aa85884c1249d3606 Author: Vladimir Menshakov Date: Tue Aug 6 15:50:43 2013 +0400 added virtual dtor to V8ErrorHandler commit 868803ce2ad158326cb70d2e5667baf4014df31a Author: Oliver Buchtala Date: Sat Aug 31 03:44:44 2013 +0200 Merge replayed as done by c778d16abed35829b103d607a53c8f88e3b2d595 commit a190288e663e207375a42bfb7476ab1ca336f2af Author: Vladimir Menshakov Date: Thu Jul 18 21:03:56 2013 +0400 fixed overloaded functions multiplication commit 45bfc97ef437eb919bec2579dd39e3bbb0fd1c12 Author: Vladimir Menshakov Date: Thu Jul 18 19:15:38 2013 +0400 converted function templates to the persistent ones (fixed crash on large wrappers) commit 9b6a4870dd96656f0e9ec731e9b2dea856ae4939 Author: Vladimir Menshakov Date: Thu Jul 18 18:53:15 2013 +0400 added missing scope.Close() commit fe25e2dfc8fd4fa29702685684337444f5948cb1 Author: Vladimir Menshakov Date: Thu Jul 18 18:42:03 2013 +0400 replaced GetInternalField with GetAlignedPointer (it does not work with SetAlignedPointer, btw) commit 9111773400ba10b6b98fea7996d3dcbf53b97ecf Author: Vladimir Menshakov Date: Thu Jul 11 16:41:40 2013 +0400 generate v8-3.19.x compatible code commit 26a4f849485d03fe57ba47435f11953b019ae515 Author: Vladimir Menshakov Date: Thu Jul 11 15:06:08 2013 +0400 added missing javascript/v8 dir commit b511e33121c5167a9a206ddc2f3417f56d39afa9 Author: Oliver Buchtala Date: Fri May 3 18:23:36 2013 +0200 Remove std::iostream relicts from generated v8 wrapper code. commit d3aa8e06fb3d3eb49c05975108acf2c84b716774 Author: Oliver Buchtala Date: Wed Jan 30 18:50:03 2013 +0100 Bugfix: treat persistent V8 references correctly. V8 is somewhat inconvenient regarding invoke of destructors for C++ proxies. commit 827cef75a35ff9ff84c76c46abf483672c4dbcc4 Author: Oliver Buchtala Date: Fri Jan 25 17:09:13 2013 +0100 Add an ifndef-guard to resolve a warning when building nodejs extension. commit 31feff8586c880bf91f7b6bde61b9dbdc6be57c9 Author: Oliver Buchtala Date: Fri Jan 25 17:03:23 2013 +0100 Add missing return statement in v8 code template. commit 5da4f5794c45a09f3e8b641568d38ff650403752 Author: Oliver Buchtala Date: Fri Jan 25 14:20:51 2013 +0100 Add preprocessor define for building node.js extensions. commit 65560a8664f19aaa03392bba33a4ac435867fa35 Author: Oliver Buchtala Date: Fri Jan 25 14:07:06 2013 +0100 Fix v8 string conversion in case of null arguments. commit e3da21ee442913c5554203bf8699cab62a69ed15 Author: Oliver Buchtala Date: Tue Jan 22 19:28:44 2013 +0100 Add more ignores. commit a4036deda841a9894e7228c4fb80cebe86ff8efc Author: Oliver Buchtala Date: Tue Jan 22 19:26:29 2013 +0100 Add pre-processor defines to detect the javascript engine. commit b0cb875ac1a1899c8752b7df33b7c70ab5ff4b3c Merge: 8b10c47 2252524 Author: Oliver Buchtala Date: Tue Jan 22 19:24:12 2013 +0100 Merge branch 'devel' of github.com:oliver----/swig-v8 into devel commit 8b10c47ed80a42c4f47b339820333132188659c0 Author: Oliver Buchtala Date: Tue Jan 22 19:23:11 2013 +0100 Fix regression: add an include for Node.js header. commit 22525249f26e36d6603c7ee7bce58cefd8ff611f Author: Oliver Buchtala Date: Tue Jan 22 15:54:08 2013 +0100 Resolve compile warnings in v8_shell. commit 8eb9aa9e73fca795fbd6a716ba830366a4919405 Author: Oliver Buchtala Date: Tue Jan 22 15:53:39 2013 +0100 Add gitignore file. commit 04c0803f736ef8bd264d7a099a88b4258461547f Author: Oliver Buchtala Date: Fri Jan 18 15:35:45 2013 +0100 Fixes in configuration to detect JavascriptCore on MacOSX correctly. commit 4ac7065c3ba1b73cdf081eaae45ccc28853a4770 Author: Oliver Buchtala Date: Fri Jan 18 15:34:11 2013 +0100 Bugfix: in javascript interpreter load extensions on MacOSX correctly. commit 04cdde05636f22d8504389a3a92a5c39885f04ad Author: Oliver Buchtala Date: Fri Jan 18 15:33:04 2013 +0100 Add test to check javascript unicode strings. commit caa92740d3241e6aa34ee38a6dbcf846d72c3275 Author: Oliver Buchtala Date: Wed Jan 9 00:33:09 2013 +0100 Add an option to deactivate creation of an extra module object in javascript. This is useful, if the extension host calls the initializer with custom local variables. E.g., this is the case with node.js. commit 213c107b7f4762bf58f7d6a7c7f8b463e2068206 Author: Oliver Buchtala Date: Tue Jan 8 22:37:16 2013 +0100 Add a swig macro to register node.js extensions. commit 4fea3a403e5856565d51a5bf0b0a4cec4c03a583 Author: Oliver Buchtala Date: Tue Jan 8 22:36:32 2013 +0100 Generate an extra file part after the initializer for v8 modules. E.g., this is useful for creating node.js modules. commit 31844ac72adfd82c310c239434db579ba7f6670a Author: Oliver Buchtala Date: Tue Jan 8 22:34:38 2013 +0100 Simplify the signature of the v8 module intializer. commit 9d630ab930f83252e75d6e66e2912cbe75ca253f Author: Oliver Buchtala Date: Tue Jan 8 21:48:22 2013 +0100 Fix std::string support for v8. commit 2c4a90a37d7818f792417bfff73a88b9efcbdd01 Author: Oliver Buchtala Date: Tue Dec 4 01:36:51 2012 +0100 Generate defines for initializer function. commit be06ceea2686f65a29a5d46d5d675d4366e5571c Author: Oliver Buchtala Date: Sun Dec 2 23:51:47 2012 +0100 Fixes in std_string for JSC generator. commit 7fffd801e410749c37a818b22c5682375c5f9a1b Author: Oliver Buchtala Date: Sat Dec 1 13:21:22 2012 +0100 Fix std_string.i which generated compile errors in certain cases. commit fb9c4955fb4c39f66ea74dcd714bb34f593b3b40 Author: Oliver Buchtala Date: Thu Nov 29 03:20:49 2012 +0100 Not a real change: removed some trailing spaces. commit f9d6afbdfef0d3ef3fb0d5a1675a0b1f4d2a5630 Author: Oliver Buchtala Date: Thu Nov 29 03:19:00 2012 +0100 Add a missing return statement in JS shell. commit 9d2264456334c88a6b0b74940cc3e96add527325 Author: Oliver Buchtala Date: Thu Nov 29 03:17:27 2012 +0100 Rename a argument variable to avoid errors with overloaded functions. commit bad64925eddf9f78b5bddd6fe559973c51b7f59f Author: Oliver Buchtala Date: Fri Nov 23 01:59:54 2012 +0100 Configuration is now easier for building and running examples and tests using v8. commit caa6827dafc4cc5b0ea3b8c16922905c46bbbf29 Author: Oliver Buchtala Date: Fri Nov 23 01:09:11 2012 +0100 Javascript interpreter supports for JSC and V8 simultaneously. Before, one had to build two different versions. commit 008adca72f5917d8a80cc252572f0b1e80ed4e69 Author: Oliver Buchtala Date: Thu Nov 22 22:50:50 2012 +0100 Provide more control about the target object/namespace where a v8 module is registered to. commit 6754bf2b49862211eb67bc2a31ce79ae31de9034 Author: Oliver Buchtala Date: Sat Nov 17 03:41:22 2012 +0100 Generate cleanup code for %newobject. commit 058a27bf32c6fc082c3753af3aaffb1ab4d85e83 Author: Oliver Buchtala Date: Sat Nov 17 02:12:12 2012 +0100 Simplify creation of a Javascript shell. commit 57980975a0f86961b3a9545fd24f34575609c6c7 Author: Oliver Buchtala Date: Fri Nov 16 22:10:02 2012 +0100 Generate cleanup code. commit 94730dad7a5d00468d4b2798c7cbd04db6b1d30d Author: Oliver Buchtala Date: Sat Sep 8 01:16:54 2012 +0000 Beautify output of v8 emitter. Trimming some of the code templates. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13830 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 86cb62146661f89f9cd3dd76c721ddfed529b99d Author: Oliver Buchtala Date: Sat Sep 8 01:16:42 2012 +0000 Add comments to v8 code templates. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13829 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 217ffb11d0cbcfbcfbaa679bd815a80b897b1c8b Author: Oliver Buchtala Date: Sat Sep 8 01:16:26 2012 +0000 Fix regressions of latest commits. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13828 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 9b06144d39f3f1b820ee90ad0bf1c2cf96cbaf6a Author: Oliver Buchtala Date: Sat Sep 8 01:16:09 2012 +0000 Fix handling of overloaded ctors in v8 emitter. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13827 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 131a106204e060ac15bd2474c8a5501f82868284 Author: Oliver Buchtala Date: Sat Sep 8 01:15:51 2012 +0000 Improve names and comments of code templates for javascript emitters. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13826 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 8b7a9fec2519aa5faac9c3bb26f7612ee1f5aefb Author: Oliver Buchtala Date: Sat Sep 8 01:15:29 2012 +0000 Add complex support to v8 module. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13825 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 7c7d1cf3b9e8a1dfd92b3ca199e2ee0b8bf1cc6f Author: Oliver Buchtala Date: Sat Sep 8 01:15:12 2012 +0000 Fix errors related to wrapping and destruction of (undefined) SWIG_TYPES. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13824 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 296a5d028547c0a0a013a24e65cdcb9c3086fb52 Author: Oliver Buchtala Date: Sat Sep 8 01:14:48 2012 +0000 Minor change in javascript example Makefile configuration. Propagate global CFLAGS and CXXFLAGS to inner javascript targets. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13823 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 4616f9643ff5ce8aefe0594289c9a97230cabf09 Author: Oliver Buchtala Date: Sat Sep 8 01:14:37 2012 +0000 Adapt test-suite configuration to allow switching between js engines. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13822 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 8948360725e853f2232188edd38a834ac1f87666 Author: Oliver Buchtala Date: Sat Sep 8 01:14:23 2012 +0000 Fix configuration_in for detecting v8 include and lib. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13821 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 20927938681c14e4f812879973f8e677c08d77b0 Author: Oliver Buchtala Date: Sat Sep 8 01:14:14 2012 +0000 Make v8 shell more quiet. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13820 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit f814a8e702dcfe2ae2f2480de372e78c5a997eb5 Author: Oliver Buchtala Date: Sat Sep 8 01:14:02 2012 +0000 Fix errors concerning object wrapping and cleanup in v8 emitter. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13819 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 8db76ddee10085765c41be3c5829ec0cce1e0933 Author: Oliver Buchtala Date: Sat Sep 8 01:13:42 2012 +0000 Remove generated file from repository. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13818 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 5425edc50894d32724b7cde8d11bce9fbd3fcdf8 Author: Oliver Buchtala Date: Sat Sep 8 01:13:29 2012 +0000 Add library flag for building v8 shell. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13817 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit da109ee764b0c48f93554f4cc093997fe530ec28 Author: Oliver Buchtala Date: Sat Sep 8 01:13:17 2012 +0000 Fix input string handling in v8 typemaps. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13816 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 91fc0ff205f6f6679a0cb51716adc91a21524929 Author: Oliver Buchtala Date: Sat Sep 8 01:13:03 2012 +0000 Use a throwing default setter in v8 emitter. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13815 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit a82e0a6e8f7ba258f29de6f8680e406a8b102ae5 Author: Oliver Buchtala Date: Sat Sep 8 01:12:46 2012 +0000 Fix c++ linking problem in example 'variables'. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13814 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 843c8a408cb76e22efc10ede577f17e2e5b7deb2 Author: Oliver Buchtala Date: Sat Sep 8 01:12:33 2012 +0000 Fix AsVal macros of long and int for v8. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13813 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit d13289cc918061b9ffea6aeb9fe1dba9990727e5 Author: Oliver Buchtala Date: Sat Sep 8 01:12:18 2012 +0000 Fix function dispatching for v8. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13812 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 68f0f859f887f7be4c61d53b37ec8989c02833b9 Author: Oliver Buchtala Date: Sat Sep 8 01:11:51 2012 +0000 Fix name collision in generated v8 initializer. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13811 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit da6307a19ea5668757ab59f95e670f99bd64b61a Author: Oliver Buchtala Date: Sat Sep 8 01:11:32 2012 +0000 Enable overloading ctors for v8. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13810 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 70383a1b61aacfb475f72652cf120515f11de2c1 Author: Oliver Buchtala Date: Sat Sep 8 01:11:11 2012 +0000 Enable string exceptions in v8. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13809 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 84e5476147cd141d1178cd25be35df6b01c5b92e Author: Oliver Buchtala Date: Sat Sep 8 01:10:57 2012 +0000 Add std::string support to v8 typemaps. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13808 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit a4f8e4c1c3bbcd36a771313f2516717aa113b771 Author: Oliver Buchtala Date: Sat Sep 8 01:10:42 2012 +0000 Fix bug in v8 ctor emitter. This bug leaded to flaky crashes of v8 engine. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13807 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 2893df9f7394ef48424f0b88e44af702a11fdd95 Author: Oliver Buchtala Date: Sat Sep 8 01:10:27 2012 +0000 Several fixes in v8 emitter. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13806 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit c4ab8790278b8ec1cb96f542985824af84e3144a Author: Oliver Buchtala Date: Sat Sep 8 01:10:10 2012 +0000 Fix string warnings of for char* constants in CPP wrappers. This has been done by changing the implementation of marshalOutputArgs, which now does not create a local result variable in this case, and uses the constant inline in the output typemap. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13805 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 58e4f9703c78052ee60f3021724bc3274f3d329a Author: Oliver Buchtala Date: Sat Sep 8 01:09:57 2012 +0000 Fix handling of Char constants in JSC typemaps. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13804 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 915e65135cdf90a484bd1078eb3cfe15f192e50e Author: Oliver Buchtala Date: Sat Sep 8 01:09:43 2012 +0000 Minor fix in v8 shell. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13803 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit c3918f3f822a09b297f30ef060c9269dc97e0f39 Author: Oliver Buchtala Date: Sat Sep 8 01:09:31 2012 +0000 Add string support to v8 typemaps. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13802 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit bd752ff86b94a082235d0ff424729c7d5e043715 Author: Oliver Buchtala Date: Sat Sep 8 01:09:18 2012 +0000 In example Makefiles for v8 forward to CPP target. As v8 is C++ it is not possible to build wrappers in C. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13801 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 1862f43cfcd93a3f79cf652da70f22a438de4cf9 Author: Oliver Buchtala Date: Sat Sep 8 01:09:05 2012 +0000 Minor clean up in class example. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13800 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit f1e9b21dfd63df4b694bac471daa1f9359c88378 Author: Oliver Buchtala Date: Sat Sep 8 01:08:50 2012 +0000 Add missing swig_type_info registration in v8 emitter. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13799 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 21bdb78f1ca2f016afb73c84b4286312f47d3175 Author: Oliver Buchtala Date: Sat Sep 8 01:08:33 2012 +0000 Activate SwigModuleInitializer for in v8 emitter. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13798 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 9a914af2b787b336228f779c519b39147e536a68 Author: Oliver Buchtala Date: Sat Sep 8 01:08:16 2012 +0000 Fix v8 shell to initialize v8 context in proper order. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13797 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 46cff47ada4ec3197798359425c165e09d4498a5 Author: Oliver Buchtala Date: Sat Sep 8 01:08:03 2012 +0000 Several fixes in generator for v8 initializer function. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13796 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 78f5b46381e4c93f3d1227a702761a8eda01f4ca Author: Oliver Buchtala Date: Sat Sep 8 01:07:43 2012 +0000 Fix class example. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13795 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 022c274256d5f61daa6a880d781b903cb82af677 Author: Oliver Buchtala Date: Sat Sep 8 01:07:21 2012 +0000 Minor fixes in v8 javascript shell. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13794 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit cda09239ad4b7f5367ea3382e4497cc8d830338b Author: Oliver Buchtala Date: Sat Sep 8 01:06:58 2012 +0000 Several fixes in v8 emitter and code templates. Achieves first compile of example "class" after re-integration. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13793 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 0cae8fccd0cfdbcc6dc426c75102ac8a08430b5d Author: Oliver Buchtala Date: Sat Sep 8 01:06:39 2012 +0000 Minor refactor of marshalInputArgs for generalization. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13792 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 9b0c8dae839def6e83b447230923630e819b64b4 Author: Oliver Buchtala Date: Sat Sep 8 01:06:26 2012 +0000 Add argcount checking to functions and ctors. Before argument counts were only checked for overloaded functions/ctors. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13791 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit d5c5f7ebeebeef78bb847dea31bda75e65d5d197 Author: Oliver Buchtala Date: Sat Sep 8 01:06:08 2012 +0000 Generalize ctor overloading. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13790 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 72002392770b42c3c1a15a4167426635bf9128db Author: Oliver Buchtala Date: Sat Sep 8 01:05:51 2012 +0000 Fix regression in javascript's test-suite configuration. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13789 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 78442b27647e2a3d7e45516c709632f8419b7fd6 Author: Oliver Buchtala Date: Sat Sep 8 01:05:37 2012 +0000 Several adaptations and fixes on the way to get V8 emitter running. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13788 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 8d72616e6598dac37109fce3562c32c31188beb1 Author: Oliver Buchtala Date: Sat Sep 8 01:05:11 2012 +0000 Refactor emitter and code templates to use defined template variables. Also switched from "${...}" to $..., which is swig's common notation of typemap variables. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13787 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit cdd450fbe4b9fa9a756cb464dbb3f54e2791106a Author: Oliver Buchtala Date: Sat Sep 8 01:04:51 2012 +0000 Delete obsolete source file. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13786 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 5fab9c8a3857f2c0499790461160bdb4bc9d3602 Author: Oliver Buchtala Date: Sat Sep 8 01:04:40 2012 +0000 Minor cleanup in javascript shell implementation. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13785 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 0341e6b14c9f118ca2bfe853385df88779f0521b Author: Oliver Buchtala Date: Sat Sep 8 01:04:26 2012 +0000 Clean up example Makefiles. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13784 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 10dc758cadc7e0f27eee867a071ba199678e8a0a Author: Oliver Buchtala Date: Sat Sep 8 01:03:42 2012 +0000 Refactored javascript shell implementation to support JSC and v8. Also changed configuration in examples Makefile.in to allow switching modes. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13783 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 672208d8d20eef3214bf4f48fce009eb3f053a81 Author: Oliver Buchtala Date: Sat Sep 8 01:03:17 2012 +0000 Adapt overload example to reflect changes in module. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13782 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit cbb5b711ab8d3038f993dc77f6397419cb7c1f7e Author: Oliver Buchtala Date: Sat Sep 8 01:03:00 2012 +0000 Fix examples after regressions. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13781 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 52aef2699700c957015c8ce88c5c75f756ffc86f Author: Oliver Buchtala Date: Sat Sep 8 01:02:30 2012 +0000 Add examples check list for batch runs. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13780 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 07d5ec24cebcaa7a08425fa4780937b3bca9fae5 Author: Oliver Buchtala Date: Sat Sep 8 01:02:16 2012 +0000 Add support for type-based dispatching of overloaded functions. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13779 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit eff094ef3942c026a0711abad56af9a8a54d9b9a Author: Oliver Buchtala Date: Sat Sep 8 01:01:57 2012 +0000 Add test "constructor_copy". git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13778 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 548287c600e8bd900e6976158ffe9c007a390e5f Author: Oliver Buchtala Date: Sat Sep 8 01:01:41 2012 +0000 Update configuration to detect V8 and allow testing with V8. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13777 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 4d9ca620abcfed848785ca4825f6a61648387829 Author: Oliver Buchtala Date: Sat Sep 8 01:00:15 2012 +0000 Refactored JSEmitters to share unified code. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13776 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 387da69e843e7359ba1fb70f0eadbd077e8cf461 Author: Oliver Buchtala Date: Sat Sep 8 00:59:55 2012 +0000 Pull namespace implementation up to be shared between js emitters. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13775 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 66ead9afb2501d02c9ded79309e64a5bc953da5a Author: Oliver Buchtala Date: Sat Sep 8 00:59:43 2012 +0000 Simplify implementation using new issetter flag. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13774 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit d2debe32703c0d1f6b4ca22623b2d13e206be64b Author: Oliver Buchtala Date: Sat Sep 8 00:59:31 2012 +0000 Add more verbose temporary flags for setters in variable wrappers. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13773 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 16077503c86919dbedd3d76318a23323404f4f58 Author: Oliver Buchtala Date: Sat Sep 8 00:59:18 2012 +0000 Fix former workaround by concerning static member functions. "storage" attribute is removed by Language::staticmemberfunctionHandler which was resolved by a workaround before. Now, the implementation relies completely on state flags retrieved at a proper point. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13772 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit c470864d127561d55d36e115ffffffc33cf2ff96 Author: Oliver Buchtala Date: Sat Sep 8 00:59:03 2012 +0000 Remove some dead code and an obsolete member variable from JSEmitter. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13771 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 46624e24e5b6204ce7fd03be433ec1883fd98f96 Author: Oliver Buchtala Date: Sat Sep 8 00:58:49 2012 +0000 Remove member variable current_wrapper from JSEmitter. Instead each emitting function creates local wrapper instance. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13770 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 8577ae41791303471a80fde1384f319ef5ababb9 Author: Oliver Buchtala Date: Sat Sep 8 00:58:37 2012 +0000 Minor clean up. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13769 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit b778c4816b63e12e72cb3c2a97e904411465329a Author: Oliver Buchtala Date: Sat Sep 8 00:58:23 2012 +0000 Remove a global variable from JSEmitter by making use of JSEmitterState. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13768 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 9af3c4879bbd2103548afbfbff200eff6a78418a Author: Oliver Buchtala Date: Sat Sep 8 00:58:11 2012 +0000 Switch to global variable for enabling code template debug information. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13767 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit b39e2bfff0c1082c31149079075faa0999059953 Author: Oliver Buchtala Date: Sat Sep 8 00:57:57 2012 +0000 Refactor JSC emitter to reduce global state variables. Also meld v8 emitter into javascript.cxx (provisional). git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13766 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 35e6b73d2acbcc010bd239a83fbf16cecefe7b70 Author: Oliver Buchtala Date: Sat Sep 8 00:57:42 2012 +0000 Add swig configuration files for v8. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13765 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 050219d998c0a518b54366c6c543fa926e601e5b Author: Oliver Buchtala Date: Sat Sep 8 00:56:48 2012 +0000 Merge branch 'devel' of https://github.com/Neha03/gsoc2012-javascript into devel Conflicts: .project COPYRIGHT Doc/Manual/style.css Examples/Makefile.in Examples/test-suite/common.mk Lib/typemaps/strings.swg Makefile.in Source/DOH/fio.c Source/Makefile.am Source/Modules/emit.cxx Source/Modules/javascript.cxx configure.in git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13764 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 360ef44e09e9072702215c46306731ccbbbc1d03 Author: Oliver Buchtala Date: Sat Sep 8 00:52:41 2012 +0000 Clean up in v8 helper functions. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13763 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 229f2d0fa5ffb71c36201a7c70f86e778d256128 Author: Oliver Buchtala Date: Sat Sep 8 00:52:28 2012 +0000 Add v8 input typemap for cstrings. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13762 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 8168750c1b43d42a24efa598a1da14c9f56a95f4 Author: Oliver Buchtala Date: Sat Sep 8 00:52:16 2012 +0000 Add example for string marshalling to v8 specification. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13761 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 67a3de9a93433585a8daca77d3e300713bf91762 Author: Oliver Buchtala Date: Sat Sep 8 00:52:02 2012 +0000 Add example for inheritance to v8 specification. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13760 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 32a32633ba1ad9fe12e07f90b1eeaee2665b2631 Author: Oliver Buchtala Date: Sat Sep 8 00:51:47 2012 +0000 Add support for static member variables and functions to v8 module. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13759 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit e8dd979d165faa481b057a1b4cb145b3b789d36e Author: Oliver Buchtala Date: Sat Sep 8 00:51:29 2012 +0000 Update v8 specification. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13758 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 0fd30dc60f462afa797acf84f0f0ad6cea0077a3 Author: Oliver Buchtala Date: Sat Sep 8 00:51:16 2012 +0000 Add examples to specification of v8 code generator. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13757 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit badf090cb5f2a3dd396b616ba0b997f562a28496 Author: Oliver Buchtala Date: Sat Sep 8 00:51:00 2012 +0000 Extend and rename v8 helper functions. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13756 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 65d4769af8792f4193cba47ef56547f9998c247c Author: Oliver Buchtala Date: Sat Sep 8 00:50:41 2012 +0000 Add initial support for argument marshalling using typemaps to v8 module. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13755 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 0e60acfebde30181f93b1acfa57c65b50a13e6c5 Author: Oliver Buchtala Date: Sat Sep 8 00:50:19 2012 +0000 Minor restructuring in v8 generator. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13754 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 71bee1e78c52a65c5a159768c2f6f02cf3eb903f Author: Oliver Buchtala Date: Sat Sep 8 00:50:06 2012 +0000 Complement variable processing in v8 generator. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13753 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 8e0711cbc63ceb6b0adcc1a2ec4133b0fa198a25 Author: Oliver Buchtala Date: Sat Sep 8 00:49:44 2012 +0000 Fix memory related bug in generalized javascript emitter. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13752 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 285badb95b03a3f1ee7a84fa1b473b06c477f35d Author: Oliver Buchtala Date: Sat Sep 8 00:49:32 2012 +0000 Improve v8 generator regarding registration of function wrappers. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13751 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 7ba26c8a26e52d2f499e20b866b273571c6264b8 Author: Oliver Buchtala Date: Sat Sep 8 00:49:15 2012 +0000 Minor change in v8 emitter. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13750 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 9a599be8ab6c3426362beb3dd572cd399620da8d Author: Oliver Buchtala Date: Sat Sep 8 00:49:02 2012 +0000 Fix order of registration in v8 generator. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13749 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 886f17c34372ded14504ad684b71cd786faa8e42 Author: Oliver Buchtala Date: Sat Sep 8 00:48:43 2012 +0000 Implement namespace support for v8 generator. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13748 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 90bbc6430bf5fb8f234c5ea46a09ef5f528ec72d Author: Oliver Buchtala Date: Sat Sep 8 00:48:24 2012 +0000 Update v8 specification. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13747 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 6c90d1eb6d46bd1dd52aa3121d38511974423d8b Author: Oliver Buchtala Date: Sat Sep 8 00:48:11 2012 +0000 Minor improvements in v8 emitter implementation git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13746 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 83ac7193155a0d91fad992f197a448591f3e829c Author: Oliver Buchtala Date: Sat Sep 8 00:47:51 2012 +0000 Add manual generated v8 wrapper examples to v8 specification. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13745 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit a0b71935f278ff342583e17cdf6e94d43ac77c58 Author: Oliver Buchtala Date: Sat Sep 8 00:47:38 2012 +0000 Update v8 code generator specification. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13744 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 3c30e2d382cbbacef66563bcc8d54289f9543339 Author: Oliver Buchtala Date: Sat Sep 8 00:47:19 2012 +0000 Add initial Javascript V8 emitter implementation. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13743 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 4bcfca05dd0eff51c4ecfa11ed182a6bcf147dbf Author: Oliver Buchtala Date: Sat Sep 8 00:46:31 2012 +0000 Add some implementation details to specification of v8 code generator. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13742 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit e888d7a892702aa0a3e42449737c8f1bfb747a2f Author: Oliver Buchtala Date: Sat Sep 8 00:46:18 2012 +0000 Add a document about mapping C++ language features to Javascript. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13741 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 5b5fdb171e720228b24c2f9fbb1667649693b3ab Author: Oliver Buchtala Date: Sat Sep 8 00:46:03 2012 +0000 Add a paragraph about control flow analysis to V8 specification. Control flow analysis for use cases: - static variables - simple class - class properties - class methods - static class variables and functions - inheritance. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13740 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit 5c3fef6367ba41982032dea8a2b29f6a7f62de9f Author: Oliver Buchtala Date: Sat Sep 8 00:45:49 2012 +0000 Add initial version of a CMake configuration. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13739 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit ba40fffd91bc07fc5020fe7870a6104863a39f94 Author: Oliver Buchtala Date: Sat Sep 8 00:45:35 2012 +0000 Add initial specification of code generator templates for V8 module. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13738 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit d71a5f483a6ad3307ff306ce2c72cfcd0e361556 Author: Oliver Buchtala Date: Sat Sep 8 00:44:54 2012 +0000 Add module for Javascript target. This module comes with a design that allows different code emitter implementations. For the the phase of development the module is split into multiple files which will be merged together when development converges. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13737 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit c86ce942c2d0498169d4371bdd6c9acd503fdffa Author: Oliver Buchtala Date: Fri May 11 19:20:07 2012 +0000 Correct place of copyright entry. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13070 626c5289-ae23-0410-ae9c-e8d60b6d4f22 commit d6060ceced397c2dd3baaba94c783d0045ddc38e Author: Oliver Buchtala Date: Fri May 11 13:55:16 2012 +0000 Add copyright entry for Oliver Buchtala. git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/branches/oliverb-javascript-v8@13067 626c5289-ae23-0410-ae9c-e8d60b6d4f22 --- .gitignore | 8 + .travis.yml | 10 +- COPYRIGHT | 4 +- Doc/Manual/Javascript.html | 770 ++++++ Doc/Manual/chapters | 1 + Doc/Manual/style.css | 6 +- Examples/Makefile.in | 80 + Examples/javascript/check.list | 13 + Examples/javascript/class/Makefile | 3 + Examples/javascript/class/binding.gyp | 8 + Examples/javascript/class/example.cxx | 28 + Examples/javascript/class/example.h | 34 + Examples/javascript/class/example.i | 10 + Examples/javascript/class/example.js | 1 + Examples/javascript/class/runme.js | 46 + Examples/javascript/constant/Makefile | 3 + Examples/javascript/constant/binding.gyp | 8 + Examples/javascript/constant/example.h | 8 + Examples/javascript/constant/example.i | 24 + Examples/javascript/constant/example.js | 1 + Examples/javascript/constant/runme.js | 14 + Examples/javascript/enum/Makefile | 3 + Examples/javascript/enum/binding.gyp | 8 + Examples/javascript/enum/example.cxx | 37 + Examples/javascript/enum/example.h | 13 + Examples/javascript/enum/example.i | 11 + Examples/javascript/enum/example.js | 1 + Examples/javascript/enum/runme.js | 34 + Examples/javascript/exception/Makefile | 3 + Examples/javascript/exception/binding.gyp | 8 + Examples/javascript/exception/example.cxx | 1 + Examples/javascript/exception/example.h | 53 + Examples/javascript/exception/example.i | 12 + Examples/javascript/exception/example.js | 1 + Examples/javascript/exception/runme.js | 64 + Examples/javascript/functor/Makefile | 3 + Examples/javascript/functor/binding.gyp | 8 + Examples/javascript/functor/example.cxx | 0 Examples/javascript/functor/example.i | 25 + Examples/javascript/functor/example.js | 1 + Examples/javascript/functor/runme.js | 15 + Examples/javascript/js_example.mk | 52 + Examples/javascript/namespace/Makefile | 3 + Examples/javascript/namespace/binding.gyp | 8 + Examples/javascript/namespace/example.cxx | 36 + Examples/javascript/namespace/example.h | 20 + Examples/javascript/namespace/example.i | 10 + Examples/javascript/namespace/example.js | 1 + Examples/javascript/namespace/runme.js | 10 + Examples/javascript/operator/Makefile | 3 + Examples/javascript/operator/binding.gyp | 8 + Examples/javascript/operator/example.h | 36 + Examples/javascript/operator/example.i | 34 + Examples/javascript/operator/example.js | 1 + Examples/javascript/operator/runme.js | 25 + Examples/javascript/overload/Makefile | 3 + Examples/javascript/overload/binding.gyp | 8 + Examples/javascript/overload/example.h | 28 + Examples/javascript/overload/example.i | 16 + Examples/javascript/overload/example.js | 1 + Examples/javascript/overload/runme.js | 9 + Examples/javascript/pointer/Makefile | 3 + Examples/javascript/pointer/binding.gyp | 8 + Examples/javascript/pointer/example.cxx | 16 + Examples/javascript/pointer/example.i | 30 + Examples/javascript/pointer/example.js | 1 + Examples/javascript/pointer/runme.js | 35 + Examples/javascript/pointer/typemaps.i | 0 Examples/javascript/reference/Makefile | 3 + Examples/javascript/reference/binding.gyp | 8 + Examples/javascript/reference/example.cxx | 46 + Examples/javascript/reference/example.h | 26 + Examples/javascript/reference/example.i | 42 + Examples/javascript/reference/example.js | 1 + Examples/javascript/reference/runme.js | 67 + Examples/javascript/reference/swig_gdb.log | 22 + Examples/javascript/simple/Makefile | 3 + Examples/javascript/simple/binding.gyp | 8 + Examples/javascript/simple/example.cxx | 18 + Examples/javascript/simple/example.i | 7 + Examples/javascript/simple/example.js | 1 + Examples/javascript/simple/runme.js | 26 + Examples/javascript/template/Makefile | 3 + Examples/javascript/template/binding.gyp | 8 + Examples/javascript/template/example.h | 32 + Examples/javascript/template/example.i | 17 + Examples/javascript/template/example.js | 1 + Examples/javascript/template/runme.js | 30 + Examples/javascript/variables/Makefile | 3 + Examples/javascript/variables/binding.gyp | 8 + Examples/javascript/variables/example.cxx | 96 + Examples/javascript/variables/example.h | 6 + Examples/javascript/variables/example.i | 49 + Examples/javascript/variables/example.js | 1 + Examples/javascript/variables/runme.js | 68 + Examples/javascript/variables/swig_gdb.log | 9 + Examples/test-suite/common.mk | 7 +- Examples/test-suite/constructor_copy.i | 2 +- Examples/test-suite/director_nspace.i | 2 +- Examples/test-suite/infinity.i | 48 + Examples/test-suite/javascript/Makefile.in | 181 ++ .../javascript/abstract_access_runme.js | 6 + .../javascript/abstract_inherit_runme.js | 40 + .../javascript/abstract_typedef2_runme.js | 6 + .../javascript/abstract_typedef_runme.js | 8 + .../javascript/abstract_virtual_runme.js | 11 + .../javascript/array_member_runme.js | 22 + .../javascript/arrays_global_runme.js | 18 + .../test-suite/javascript/callback_runme.js | 30 + .../javascript/char_binary_runme.js | 38 + .../javascript/char_strings_runme.js | 11 + .../javascript/class_ignore_runme.js | 6 + .../javascript/class_scope_weird_runme.js | 6 + .../javascript/complextest_runme.js | 22 + .../test-suite/javascript/constover_runme.js | 33 + .../javascript/constructor_copy_runme.js | 42 + .../test-suite/javascript/cpp_enum_runme.js | 28 + .../javascript/cpp_namespace_runme.js | 47 + .../test-suite/javascript/cpp_static_runme.js | 9 + .../javascript/director_alternating_runme.js | 5 + .../test-suite/javascript/disown_runme.js | 22 + .../javascript/dynamic_cast_runme.js | 12 + Examples/test-suite/javascript/empty_runme.js | 1 + .../javascript/enum_template_runme.js | 8 + .../test-suite/javascript/infinity_runme.js | 4 + .../javascript/javascript_unicode_runme.js | 9 + .../namespace_virtual_method_runme.js | 3 + .../javascript/node_template/binding.gyp.in | 30 + .../javascript/node_template/index.js.in | 1 + .../javascript/nspace_extend_runme.js | 27 + .../test-suite/javascript/nspace_runme.js | 77 + .../javascript/overload_copy_runme.js | 4 + .../javascript/preproc_include_runme.js | 23 + .../test-suite/javascript/preproc_runme.js | 14 + .../test-suite/javascript/rename1_runme.js | 68 + .../test-suite/javascript/rename2_runme.js | 68 + .../test-suite/javascript/rename3_runme.js | 68 + .../test-suite/javascript/rename4_runme.js | 68 + .../javascript/rename_scope_runme.js | 17 + .../javascript/rename_simple_runme.js | 50 + .../javascript/ret_by_value_runme.js | 8 + Examples/test-suite/javascript/setup_test.sh | 6 + .../javascript/struct_value_runme.js | 11 + .../javascript/template_static_runme.js | 3 + .../javascript/typedef_class_runme.js | 7 + .../javascript/typedef_inherit_runme.js | 23 + .../javascript/typedef_scope_runme.js | 12 + .../javascript/typemap_arrays_runme.js | 5 + .../javascript/typemap_delete_runme.js | 5 + .../javascript/typemap_namespace_runme.js | 7 + .../javascript/typemap_ns_using_runme.js | 4 + .../test-suite/javascript/using1_runme.js | 4 + .../test-suite/javascript/using2_runme.js | 4 + .../test-suite/javascript/varargs_runme.js | 44 + Examples/test-suite/javascript_unicode.i | 10 + Examples/test-suite/nspace.i | 2 +- Examples/test-suite/nspace_extend.i | 2 +- Lib/javascript/jsc/arrays_javascript.i | 123 + Lib/javascript/jsc/ccomplex.i | 26 + Lib/javascript/jsc/cdata.i | 1 + Lib/javascript/jsc/complex.i | 6 + Lib/javascript/jsc/exception.i | 1 + Lib/javascript/jsc/javascript.swg | 19 + Lib/javascript/jsc/javascriptcode.swg | 418 +++ Lib/javascript/jsc/javascriptcomplex.swg | 146 + Lib/javascript/jsc/javascriptfragments.swg | 23 + Lib/javascript/jsc/javascripthelpers.swg | 69 + Lib/javascript/jsc/javascriptinit.swg | 67 + Lib/javascript/jsc/javascriptkw.swg | 40 + Lib/javascript/jsc/javascriptprimtypes.swg | 182 ++ Lib/javascript/jsc/javascriptrun.swg | 298 ++ Lib/javascript/jsc/javascriptruntime.swg | 19 + Lib/javascript/jsc/javascriptstrings.swg | 184 ++ Lib/javascript/jsc/javascripttypemaps.swg | 54 + Lib/javascript/jsc/std_common.i | 5 + Lib/javascript/jsc/std_complex.i | 19 + Lib/javascript/jsc/std_deque.i | 1 + Lib/javascript/jsc/std_except.i | 1 + Lib/javascript/jsc/std_map.i | 74 + Lib/javascript/jsc/std_pair.i | 34 + Lib/javascript/jsc/std_string.i | 69 + Lib/javascript/jsc/std_vector.i | 85 + Lib/javascript/jsc/stl.i | 10 + Lib/javascript/jsc/typemaps.i | 148 + Lib/javascript/v8/arrays_javascript.i | 125 + Lib/javascript/v8/ccomplex.i | 26 + Lib/javascript/v8/cdata.i | 1 + Lib/javascript/v8/complex.i | 6 + Lib/javascript/v8/exception.i | 1 + Lib/javascript/v8/javascript.swg | 19 + Lib/javascript/v8/javascriptcode.swg | 468 ++++ Lib/javascript/v8/javascriptcomplex.swg | 123 + Lib/javascript/v8/javascriptfragments.swg | 23 + Lib/javascript/v8/javascripthelpers.swg | 87 + Lib/javascript/v8/javascriptinit.swg | 118 + Lib/javascript/v8/javascriptkw.swg | 40 + Lib/javascript/v8/javascriptprimtypes.swg | 198 ++ Lib/javascript/v8/javascriptrun.swg | 462 ++++ Lib/javascript/v8/javascriptruntime.swg | 39 + Lib/javascript/v8/javascriptstrings.swg | 59 + Lib/javascript/v8/javascripttypemaps.swg | 43 + Lib/javascript/v8/node.i | 12 + Lib/javascript/v8/std_common.i | 5 + Lib/javascript/v8/std_complex.i | 19 + Lib/javascript/v8/std_deque.i | 1 + Lib/javascript/v8/std_except.i | 1 + Lib/javascript/v8/std_map.i | 74 + Lib/javascript/v8/std_pair.i | 33 + Lib/javascript/v8/std_string.i | 79 + Lib/javascript/v8/std_vector.i | 85 + Lib/javascript/v8/stl.i | 10 + Lib/javascript/v8/typemaps.i | 148 + Lib/typemaps/strings.swg | 4 +- Makefile.in | 19 +- Source/Makefile.am | 1 + Source/Modules/javascript.cxx | 2428 +++++++++++++++++ Source/Modules/swigmain.cxx | 2 + Tools/javascript/Makefile.in | 58 + Tools/javascript/javascript.cxx | 66 + Tools/javascript/js_shell.cxx | 156 ++ Tools/javascript/js_shell.h | 53 + Tools/javascript/jsc_shell.cxx | 233 ++ Tools/javascript/v8_shell.cxx | 310 +++ Tools/swigconfig.h.cmake | 89 + Tools/swigprinters.gdb | 24 + Tools/swigprinters.py | 574 ++++ configure.ac | 232 ++ swig-v8/swig-v8.xcodeproj/project.pbxproj | 153 ++ 228 files changed, 12567 insertions(+), 16 deletions(-) create mode 100644 Doc/Manual/Javascript.html create mode 100644 Examples/javascript/check.list create mode 100755 Examples/javascript/class/Makefile create mode 100644 Examples/javascript/class/binding.gyp create mode 100755 Examples/javascript/class/example.cxx create mode 100755 Examples/javascript/class/example.h create mode 100755 Examples/javascript/class/example.i create mode 100644 Examples/javascript/class/example.js create mode 100755 Examples/javascript/class/runme.js create mode 100755 Examples/javascript/constant/Makefile create mode 100644 Examples/javascript/constant/binding.gyp create mode 100644 Examples/javascript/constant/example.h create mode 100755 Examples/javascript/constant/example.i create mode 100644 Examples/javascript/constant/example.js create mode 100755 Examples/javascript/constant/runme.js create mode 100755 Examples/javascript/enum/Makefile create mode 100644 Examples/javascript/enum/binding.gyp create mode 100755 Examples/javascript/enum/example.cxx create mode 100755 Examples/javascript/enum/example.h create mode 100755 Examples/javascript/enum/example.i create mode 100644 Examples/javascript/enum/example.js create mode 100755 Examples/javascript/enum/runme.js create mode 100755 Examples/javascript/exception/Makefile create mode 100644 Examples/javascript/exception/binding.gyp create mode 100644 Examples/javascript/exception/example.cxx create mode 100644 Examples/javascript/exception/example.h create mode 100644 Examples/javascript/exception/example.i create mode 100644 Examples/javascript/exception/example.js create mode 100644 Examples/javascript/exception/runme.js create mode 100755 Examples/javascript/functor/Makefile create mode 100644 Examples/javascript/functor/binding.gyp create mode 100644 Examples/javascript/functor/example.cxx create mode 100644 Examples/javascript/functor/example.i create mode 100644 Examples/javascript/functor/example.js create mode 100644 Examples/javascript/functor/runme.js create mode 100644 Examples/javascript/js_example.mk create mode 100755 Examples/javascript/namespace/Makefile create mode 100644 Examples/javascript/namespace/binding.gyp create mode 100644 Examples/javascript/namespace/example.cxx create mode 100644 Examples/javascript/namespace/example.h create mode 100644 Examples/javascript/namespace/example.i create mode 100644 Examples/javascript/namespace/example.js create mode 100644 Examples/javascript/namespace/runme.js create mode 100755 Examples/javascript/operator/Makefile create mode 100644 Examples/javascript/operator/binding.gyp create mode 100644 Examples/javascript/operator/example.h create mode 100644 Examples/javascript/operator/example.i create mode 100644 Examples/javascript/operator/example.js create mode 100644 Examples/javascript/operator/runme.js create mode 100755 Examples/javascript/overload/Makefile create mode 100644 Examples/javascript/overload/binding.gyp create mode 100644 Examples/javascript/overload/example.h create mode 100644 Examples/javascript/overload/example.i create mode 100644 Examples/javascript/overload/example.js create mode 100644 Examples/javascript/overload/runme.js create mode 100755 Examples/javascript/pointer/Makefile create mode 100644 Examples/javascript/pointer/binding.gyp create mode 100755 Examples/javascript/pointer/example.cxx create mode 100755 Examples/javascript/pointer/example.i create mode 100644 Examples/javascript/pointer/example.js create mode 100755 Examples/javascript/pointer/runme.js create mode 100644 Examples/javascript/pointer/typemaps.i create mode 100755 Examples/javascript/reference/Makefile create mode 100644 Examples/javascript/reference/binding.gyp create mode 100755 Examples/javascript/reference/example.cxx create mode 100755 Examples/javascript/reference/example.h create mode 100755 Examples/javascript/reference/example.i create mode 100644 Examples/javascript/reference/example.js create mode 100755 Examples/javascript/reference/runme.js create mode 100644 Examples/javascript/reference/swig_gdb.log create mode 100755 Examples/javascript/simple/Makefile create mode 100644 Examples/javascript/simple/binding.gyp create mode 100644 Examples/javascript/simple/example.cxx create mode 100644 Examples/javascript/simple/example.i create mode 100644 Examples/javascript/simple/example.js create mode 100755 Examples/javascript/simple/runme.js create mode 100755 Examples/javascript/template/Makefile create mode 100644 Examples/javascript/template/binding.gyp create mode 100644 Examples/javascript/template/example.h create mode 100644 Examples/javascript/template/example.i create mode 100644 Examples/javascript/template/example.js create mode 100644 Examples/javascript/template/runme.js create mode 100755 Examples/javascript/variables/Makefile create mode 100644 Examples/javascript/variables/binding.gyp create mode 100755 Examples/javascript/variables/example.cxx create mode 100755 Examples/javascript/variables/example.h create mode 100755 Examples/javascript/variables/example.i create mode 100644 Examples/javascript/variables/example.js create mode 100755 Examples/javascript/variables/runme.js create mode 100644 Examples/javascript/variables/swig_gdb.log create mode 100644 Examples/test-suite/infinity.i create mode 100755 Examples/test-suite/javascript/Makefile.in create mode 100644 Examples/test-suite/javascript/abstract_access_runme.js create mode 100644 Examples/test-suite/javascript/abstract_inherit_runme.js create mode 100644 Examples/test-suite/javascript/abstract_typedef2_runme.js create mode 100644 Examples/test-suite/javascript/abstract_typedef_runme.js create mode 100644 Examples/test-suite/javascript/abstract_virtual_runme.js create mode 100644 Examples/test-suite/javascript/array_member_runme.js create mode 100644 Examples/test-suite/javascript/arrays_global_runme.js create mode 100644 Examples/test-suite/javascript/callback_runme.js create mode 100644 Examples/test-suite/javascript/char_binary_runme.js create mode 100644 Examples/test-suite/javascript/char_strings_runme.js create mode 100644 Examples/test-suite/javascript/class_ignore_runme.js create mode 100644 Examples/test-suite/javascript/class_scope_weird_runme.js create mode 100644 Examples/test-suite/javascript/complextest_runme.js create mode 100644 Examples/test-suite/javascript/constover_runme.js create mode 100644 Examples/test-suite/javascript/constructor_copy_runme.js create mode 100644 Examples/test-suite/javascript/cpp_enum_runme.js create mode 100644 Examples/test-suite/javascript/cpp_namespace_runme.js create mode 100644 Examples/test-suite/javascript/cpp_static_runme.js create mode 100644 Examples/test-suite/javascript/director_alternating_runme.js create mode 100644 Examples/test-suite/javascript/disown_runme.js create mode 100644 Examples/test-suite/javascript/dynamic_cast_runme.js create mode 100644 Examples/test-suite/javascript/empty_runme.js create mode 100644 Examples/test-suite/javascript/enum_template_runme.js create mode 100644 Examples/test-suite/javascript/infinity_runme.js create mode 100644 Examples/test-suite/javascript/javascript_unicode_runme.js create mode 100644 Examples/test-suite/javascript/namespace_virtual_method_runme.js create mode 100644 Examples/test-suite/javascript/node_template/binding.gyp.in create mode 100644 Examples/test-suite/javascript/node_template/index.js.in create mode 100644 Examples/test-suite/javascript/nspace_extend_runme.js create mode 100644 Examples/test-suite/javascript/nspace_runme.js create mode 100644 Examples/test-suite/javascript/overload_copy_runme.js create mode 100644 Examples/test-suite/javascript/preproc_include_runme.js create mode 100644 Examples/test-suite/javascript/preproc_runme.js create mode 100644 Examples/test-suite/javascript/rename1_runme.js create mode 100644 Examples/test-suite/javascript/rename2_runme.js create mode 100644 Examples/test-suite/javascript/rename3_runme.js create mode 100644 Examples/test-suite/javascript/rename4_runme.js create mode 100644 Examples/test-suite/javascript/rename_scope_runme.js create mode 100644 Examples/test-suite/javascript/rename_simple_runme.js create mode 100644 Examples/test-suite/javascript/ret_by_value_runme.js create mode 100644 Examples/test-suite/javascript/setup_test.sh create mode 100644 Examples/test-suite/javascript/struct_value_runme.js create mode 100644 Examples/test-suite/javascript/template_static_runme.js create mode 100644 Examples/test-suite/javascript/typedef_class_runme.js create mode 100644 Examples/test-suite/javascript/typedef_inherit_runme.js create mode 100644 Examples/test-suite/javascript/typedef_scope_runme.js create mode 100644 Examples/test-suite/javascript/typemap_arrays_runme.js create mode 100644 Examples/test-suite/javascript/typemap_delete_runme.js create mode 100644 Examples/test-suite/javascript/typemap_namespace_runme.js create mode 100644 Examples/test-suite/javascript/typemap_ns_using_runme.js create mode 100644 Examples/test-suite/javascript/using1_runme.js create mode 100644 Examples/test-suite/javascript/using2_runme.js create mode 100644 Examples/test-suite/javascript/varargs_runme.js create mode 100644 Examples/test-suite/javascript_unicode.i create mode 100644 Lib/javascript/jsc/arrays_javascript.i create mode 100644 Lib/javascript/jsc/ccomplex.i create mode 100644 Lib/javascript/jsc/cdata.i create mode 100644 Lib/javascript/jsc/complex.i create mode 100644 Lib/javascript/jsc/exception.i create mode 100644 Lib/javascript/jsc/javascript.swg create mode 100644 Lib/javascript/jsc/javascriptcode.swg create mode 100644 Lib/javascript/jsc/javascriptcomplex.swg create mode 100644 Lib/javascript/jsc/javascriptfragments.swg create mode 100644 Lib/javascript/jsc/javascripthelpers.swg create mode 100644 Lib/javascript/jsc/javascriptinit.swg create mode 100644 Lib/javascript/jsc/javascriptkw.swg create mode 100644 Lib/javascript/jsc/javascriptprimtypes.swg create mode 100644 Lib/javascript/jsc/javascriptrun.swg create mode 100644 Lib/javascript/jsc/javascriptruntime.swg create mode 100644 Lib/javascript/jsc/javascriptstrings.swg create mode 100644 Lib/javascript/jsc/javascripttypemaps.swg create mode 100755 Lib/javascript/jsc/std_common.i create mode 100644 Lib/javascript/jsc/std_complex.i create mode 100644 Lib/javascript/jsc/std_deque.i create mode 100644 Lib/javascript/jsc/std_except.i create mode 100755 Lib/javascript/jsc/std_map.i create mode 100755 Lib/javascript/jsc/std_pair.i create mode 100755 Lib/javascript/jsc/std_string.i create mode 100755 Lib/javascript/jsc/std_vector.i create mode 100755 Lib/javascript/jsc/stl.i create mode 100644 Lib/javascript/jsc/typemaps.i create mode 100644 Lib/javascript/v8/arrays_javascript.i create mode 100644 Lib/javascript/v8/ccomplex.i create mode 100644 Lib/javascript/v8/cdata.i create mode 100644 Lib/javascript/v8/complex.i create mode 100644 Lib/javascript/v8/exception.i create mode 100644 Lib/javascript/v8/javascript.swg create mode 100644 Lib/javascript/v8/javascriptcode.swg create mode 100644 Lib/javascript/v8/javascriptcomplex.swg create mode 100644 Lib/javascript/v8/javascriptfragments.swg create mode 100644 Lib/javascript/v8/javascripthelpers.swg create mode 100644 Lib/javascript/v8/javascriptinit.swg create mode 100644 Lib/javascript/v8/javascriptkw.swg create mode 100644 Lib/javascript/v8/javascriptprimtypes.swg create mode 100644 Lib/javascript/v8/javascriptrun.swg create mode 100644 Lib/javascript/v8/javascriptruntime.swg create mode 100644 Lib/javascript/v8/javascriptstrings.swg create mode 100644 Lib/javascript/v8/javascripttypemaps.swg create mode 100644 Lib/javascript/v8/node.i create mode 100755 Lib/javascript/v8/std_common.i create mode 100644 Lib/javascript/v8/std_complex.i create mode 100644 Lib/javascript/v8/std_deque.i create mode 100644 Lib/javascript/v8/std_except.i create mode 100755 Lib/javascript/v8/std_map.i create mode 100755 Lib/javascript/v8/std_pair.i create mode 100755 Lib/javascript/v8/std_string.i create mode 100755 Lib/javascript/v8/std_vector.i create mode 100755 Lib/javascript/v8/stl.i create mode 100644 Lib/javascript/v8/typemaps.i create mode 100644 Source/Modules/javascript.cxx create mode 100644 Tools/javascript/Makefile.in create mode 100644 Tools/javascript/javascript.cxx create mode 100644 Tools/javascript/js_shell.cxx create mode 100644 Tools/javascript/js_shell.h create mode 100644 Tools/javascript/jsc_shell.cxx create mode 100755 Tools/javascript/v8_shell.cxx create mode 100644 Tools/swigconfig.h.cmake create mode 100644 Tools/swigprinters.gdb create mode 100755 Tools/swigprinters.py create mode 100644 swig-v8/swig-v8.xcodeproj/project.pbxproj diff --git a/.gitignore b/.gitignore index 48826d914..8d72cea5d 100644 --- a/.gitignore +++ b/.gitignore @@ -5,6 +5,8 @@ # Editor files and various other junk .*.sw? *.bak +*.log +.DS_Store # Local PCRE pcre @@ -23,6 +25,7 @@ pcre *.so *.so.* *.dylib +*.bundle # C/C++ static libraries, based on: # https://github.com/github/gitignore/blob/master/C.gitignore @@ -71,6 +74,7 @@ Examples/xml/Makefile Source/Include/stamp-h1 Source/Include/swigconfig.h Source/Makefile +Tools/javascript/Makefile .deps config.log config.status @@ -85,6 +89,7 @@ Source/CParse/parser.c Source/CParse/parser.h Source/eswig swig +Tools/javascript/javascript # Generated documentation Doc/Manual/CCache.html @@ -102,6 +107,7 @@ Examples/test-suite/d/*/ Examples/test-suite/go/*/ Examples/test-suite/guile/*/ Examples/test-suite/java/*/ +Examples/test-suite/javascript/*/ Examples/test-suite/lua/*/ Examples/test-suite/mzscheme/*/ Examples/test-suite/ocaml/*/ @@ -114,6 +120,8 @@ Examples/test-suite/r/*/ Examples/test-suite/ruby/*/ Examples/test-suite/tcl/*/ Examples/test-suite/uffi/*/ +*_wrap.c +*_wrap.cxx # Python generated files, based on: # https://github.com/github/gitignore/blob/master/Python.gitignore diff --git a/.travis.yml b/.travis.yml index 5d47074e9..58b3e4ca6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,5 @@ -language: cpp +language: c compiler: - - clang - gcc env: - SWIGLANG= @@ -14,6 +13,12 @@ matrix: env: SWIGLANG=guile - compiler: gcc env: SWIGLANG=java + - compiler: gcc + env: SWIGLANG=javascript ENGINE=node + - compiler: gcc + env: SWIGLANG=javascript ENGINE=jsc + - compiler: gcc + env: SWIGLANG=javascript ENGINE=v8 - compiler: gcc env: SWIGLANG=lua - compiler: gcc @@ -43,6 +48,7 @@ before_install: - 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" = "javascript"; then sudo apt-get install -qq rlwrap python-software-properties && echo 'yes' | sudo add-apt-repository ppa:chris-lea/node.js && sudo apt-get -qq update && sudo apt-get install -qq nodejs libv8-dev libwebkitgtk-dev && sudo npm install -g node-gyp; fi - if test "$SWIGLANG" = "guile"; then sudo apt-get -qq install guile-2.0-dev; fi - if test "$SWIGLANG" = "lua"; then sudo apt-get -qq install lua5.1 liblua5.1-dev; fi - if test "$SWIGLANG" = "octave"; then sudo apt-get -qq install octave3.2 octave3.2-headers; fi diff --git a/COPYRIGHT b/COPYRIGHT index 3f4711a47..28b7f1f0d 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -15,7 +15,9 @@ Active SWIG Developers: Olly Betts (olly@survex.com) (PHP) Joseph Wang (joequant@gmail.com) (R) Xavier Delacour (xavier.delacour@gmail.com) (Octave) - David Nadlinger (code@klickverbot.at) (D) + David Nadlinger (code@klickverbot.at) + Oliver Buchtala (oliver.buchtala@gmail.com) (Javascript) + Neha Narang (narangneha03@gmail.com) (Javascript) Past SWIG developers and major contributors include: Dave Beazley (dave-swig@dabeaz.com) (SWIG core, Python, Tcl, Perl) diff --git a/Doc/Manual/Javascript.html b/Doc/Manual/Javascript.html new file mode 100644 index 000000000..a53e2a7cd --- /dev/null +++ b/Doc/Manual/Javascript.html @@ -0,0 +1,770 @@ + + + + + + + SWIG AND JAVASCRIPT + + + + + +
        +

        Overview

        +

        This chapter describes SWIG support for Javascript. The module is designed to support JavascriptCore and V8 as target engine. Currently only JavascriptCore support is implemented. JavaScriptCore is the built-in JavaScript engine for WebKit, whereas V8 is the engine used by Chromium.

        +

        JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions. Its arguably the most popular language for web development. C++, on the other hand, is statically typed, compiled, general purpose programming language. The approach I followed here is "Test driven" where I have written the examples/test-cases to be supported for Javascript one-by-one and implemented the required module files in parallel. The support for Javascript would be added similar to other supported target languages in swig. Swig comes with an "Examples" directory for Javascript like other supported language. The directory contains examples for every supported feature of the target language. There is also a test-suite directory for javascript which contains additional tests.

        +

        Preliminaries

        +

        In order to use this module, you will need to have installed javascriptcore and you can install it by installing package libwebkit-dev You can find out some necessary compiler/linker flag by

        +
        pkg-config javascriptcoregtk-1.0 --cflags --libs
        +
        +

        Using the module

        +

        To generate an extension for JavascriptCore one would call swig as follows

        +

        swig -c++ -javascript -jsc example.i +
        +

        This generates a C++ source file containing the wrapper.

        +

        How does Javascript talk to C++?

        +

        JavascriptCore provides a C-API which allows to extend a Javascript interpreter with native methods and structures. Normally, this is used to implement the builtin features of the language. However, by extending the interpreter, it is also possible to add your own commands and variables. A reference manual of this API can be found here.

        +

        Typically, when you add a new command to the javascript interpreter you need to do two things: first you need to write a special "wrapper" function that serves as the glue between the interpreter and the underlying C function. Then you need to give the interpreter information about the wrapper by providing details about the name of the function, arguments, and so forth. The next few sections illustrate the process.

        +

        Wrapper functions

        +

        Suppose you have an ordinary C function like this :

        +

        int fact(int n) { + if (n <= 1) return 1; + else return n*fact(n-1); +} +
        +

        In order to access this function from a scripting language, it is necessary to write a special "wrapper" function that serves as the glue between the scripting language and the underlying C function. A wrapper function must do three things :

        +
          +
        • Gather function arguments and make sure they are valid.
        • +
        • Call the C function.
        • +
        • Convert the return value into a form recognized by the javascript.
        • +
        +

        As an example, the javascript wrapper function for the fact() function above example might look like the following :

        +

        JSValueRef wrap_fact(JSContextRef context, JSObjectRef function, JSObjectRef globalobj, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + int arg1 = (int)JSValueToNumber(context, argv[0], NULL); + int arg2 = (int)JSValueToNumber(context, argv[1], NULL); + int result = (int)fact(arg1,arg2); + JSValueRef jsresult = JSValueMakeNumber(context, result); + return jsresult; +} +
        +

        Once you have created a wrapper function, the final step is to tell the javascript about the new function. This is done by register function called by the javascript when the module is loaded. For example, adding the above function to the javascript interpreter requires code like the following :

        +

        bool jsc_registerFunction(JSGlobalContextRef context, JSObjectRef object, + const char* functionName, JSObjectCallAsFunctionCallback callback) +{ + JSStringRef js_globalvarsclassname = JSStringCreateWithUTF8CString(globalvarsclassname); + JSObjectSetProperty(context,js_globalvarsclassname,JSObjectMakeFunctionWithCallback(context, + js_globalvarsclassname, callback), kJSPropertyAttributeNone,NULL); + JSStringRelease(jsstring); + return true; +} + +int example_init(JSContextRef context) { + JSObjectRef global; + ... + jsc_registerFunction(context, global, "fact", wrap_fact); + ... +} +
        +

        When executed, javascript will now have a new command called "fact" that you can use like any other Javascript command. Although the process of adding a new function to javascript has been illustrated, the procedure is almost identical for Perl and Python. Both require special wrappers to be written and both need additional initialization code.

        +

        Variable Linking

        +

        Variable linking refers to the problem of mapping a C/C++ global variable to a variable in the scripting language interpreter. For example, suppose you had the following variable:

        +

        double Foo = 3.5; +
        +

        To provide such access, variables are commonly manipulated using a pair of get/set functions. For example, whenever the value of a variable is read, a "get" function is invoked. Similarly, whenever the value of a variable is changed, a "set" function is called.

        +

        bool Foo_set(JSContextRef context, JSObjectRef globalobj, JSStringRef propertyName, JSValueRef value, + JSValueRef* exception) +{ + JSValueRef jsresult; + double arg1 = (double)JSValueToNumber(context, value, NULL); + Foo = arg1; + jscresult = JSValueMakeUndefined(context); + return jsresult; +} + +JSValueRef Foo_get(JSContextRef context, JSObjectRef globalobj, JSStringRef propertyName, JSValueRef* exception) +{ + JSValueRef jsresult; + double result = (double)Foo; + jsresult = JSValueMakeNumber(context, result); + return jsresult; +} +
        +

        In many languages, calls to the get/set functions can be attached to evaluation and assignment operators. Therefore, evaluating a variable such as Foo might implicitly call the get function. Similarly, typing Foo = 4 would call the underlying set function to change the value.

        +

        A tour of basic C/C++ wrapping

        +

        By default, SWIG tries to build a very natural javascript interface to your C/C++ code. Functions are wrapped as functions, classes are wrapped as classes, and so forth. This section briefly covers the essential aspects of this wrapping.

        +

        Modules

        +

        The SWIG %module directive specifies the name of the Javascript module. If you specify %module example, then everything is wrapped into a Javascript 'example' module. Underneath the covers, this module consists of a cpp source file example.cpp. When choosing a module name, make sure you don't use the same name as a built-in Javascript command or standard module name.

        +

        Global variables

        +

        C/C++ global variables are fully supported by SWIG. However, the underlying mechanism is somewhat different than you might expect due to the way that javascript works.

        +

        // SWIG interface file with global variables +%module example +... +%inline %{ +extern double Foo; +extern int gcd(int x, int y); +%} +... +
        +

        Now look at the javascript:

        +

        print("Global variable Foo=" + example.Foo); +example.Foo = 3.1415926; +print("Variable Foo changed to=" + example.Foo); +print("GCD of x and y is=" + example.gcd(x,y)); +
        +

        Constants and enums

        +

        C/C++ constants are installed as javascript objects containing the appropriate value. To create a constant, use #define, enum, or the %constant directive. For example:

        +

        #define ICONST 42 +#define FCONST 2.1828 +%constant int iconst = 37; +
        +

        In javascript they are treated as:

        +

        print("ICONST = " + example.ICONST + " (should be 42)\n"); +print("FCONST = " + example.FCONST + " (should be 2.1828)\n"); +print("iconst = " + example.iconst + " (should be 37)\n"); +
        +

        For enums, make sure that the definition of the enumeration actually appears in a header file or in the wrapper file somehow---if you just stick an enum in a SWIG interface without also telling the C compiler about it, the wrapper code won't compile. Enums are treated as constants.So if we have enums in c++ as:

        +

        void enum_test(color c, Foo::speed s); +
        +

        In javascript they are treated as:

        +

        example.enum_test(example.RED, example.Foo.IMPULSE); +example.enum_test(example.BLUE, example.Foo.WARP); +example.enum_test(example.GREEN, example.Foo.LUDICROUS); +
        +

        Inside the class

        +

        For class enums as below:

        +

        class Foo { +public: +Foo() { } +enum speed { IMPULSE, WARP, LUDICROUS }; +} +
        +

        In javascript they are treated as:

        +

        print(" Foo_IMPULSE =" + example.Foo.IMPULSE); +print(" Foo_WARP =" + example.Foo.WARP); +print(" Foo_LUDICROUS =" + example.Foo.LUDICROUS); +
        +

        Pointers

        +

        C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Here is a rather simple interface

        +

        /* File : example.i */ +%module example +%{ +extern void add(int *, int *, int *); +%} +
        +

        When wrapped, you will be able to use the functions in a natural way from javascript. For example:

        +

        // Call the add() function with some pointers +example.add(a, b, c); +
        +

        // In javascript the code look like as:

        +

        a = example.new_intp(); +example.intp_assign(a,37); +
        +
          +
        • The first one creates an int-pointer instance.
        • +
        • The second one assigns it the value 37.
        • +
        +

        C++ classes

        +

        C++ classes are wrapped by javascript classes as well. For example, if you have this class,

        +

        class Circle +{ +public: + Circle(); + Circle(double r); + double area(); + double radius; +}; +
        +

        you can use it in javascript like this:

        +

        print("Creating some objects:"); +c = new example.Circle(10); +print("area = " + c.area()); +
        +

        Class data members are accessed in the same manner as C structures.

        +

        Static class members and functions are mapped to javascript in a straight-forward manner:

        +

        class Spam { +public: + static void foo(); + static int bar; +}; +
        +

        In javascript, the static member can be access in this way:

        +

        // ----- Access a static member ----- +print("\nA access of static member is" + example.Spam.Foo); // access static member as properties of the class object. +
        +

        C++ inheritance

        +

        SWIG is fully aware of issues related to C++ inheritance. Therefore, if you have classes like this

        +

        class A { +public: + void foo(); + virtual void bar(); +}; +class B: public A { +public: + virtual void bar(); +}; +
        +

        Those classes are wrapped into a hierarchy of javascript classes that reflect the same inheritance structure. All of the usual javascript utility functions work normally:

        +

        var a = new example.A(); +a.foo(); +a.bar(); +var b = new example.B(); +b.foo(); +b.bar(); +print("b.cPtr = " + b.getCPtr()); +
        +

        C++ overloaded functions

        +

        C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example, if you have two functions like this:

        +

        void f(int val) { + std::cout << "Called f(int)." << std::endl; +} +void f(int val1, int val2) { + std::cout << "Called f(int, int)." << std::endl; +} +void f(const char* s) { + std::cout << "Called f(const char*)." << std::endl; +} +
        +

        You can use them in javascript in a straightforward manner:

        +

        example.f(1); +example.f(1, 2); +example.f("bla"); +
        +

        C++ operators

        +

        Certain C++ overloaded operators can be handled automatically by SWIG. Though, in javascript operator overloading is not possible. Instead one has to make use of the %rename feature.

        +

        For example, consider a class like this:

        +

        /* File : example.h */ +#include <math.h> +class Complex { +private: + double rpart, ipart; +public: + Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { } + Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { } + Complex &operator=(const Complex &c) { + rpart = c.rpart; + ipart = c.ipart; + return *this; + } + Complex operator+(const Complex &c) const { + return Complex(rpart+c.rpart, ipart+c.ipart); + } + Complex operator-(const Complex &c) const { + return Complex(rpart-c.rpart, ipart-c.ipart); + } + Complex operator*(const Complex &c) const { + return Complex(rpart*c.rpart - ipart*c.ipart, + rpart*c.ipart + c.rpart*ipart); + } + Complex operator-() const { + return Complex(-rpart, -ipart); + } + + double re() const { return rpart; } + double im() const { return ipart; } +}; +
        +

        When wrapped, it works like you expect:

        +

        a = new example.Complex(2,3); +b = new example.Complex(-5,10); + +print ("a =" + a); +print ("b =" + b); + +c = a.plus(b); + +print("c =" + c); +print("a*b =" + a.times(b)); +print("a-c =" + a.minus(c)); + +e = example.Complex.copy(a.minus(c)); +print("e =" + e); + +// Big expression +f = a.plus(b).times(c.plus(b.times(e))).plus(a.uminus()); +print("f =" + f); +
        +

        One restriction with operator overloading support is that SWIG is not able to fully handle operators that aren't defined as part of the class. For example, if you had code like this

        +

        class Complex { +... +friend Complex operator+(double, const Complex &c); +... +}; +
        +

        then SWIG ignores it and issues a warning. You can still wrap the operator, but you may have to encapsulate it in a special function. For example:

        +

        %rename(Complex_add_dc) operator+(double, const Complex &);

        +

        There are ways to make this operator appear as part of the class using the %extend directive.

        +

        C++ namespaces:

        +

        SWIG is aware of C++ namespaces, but namespace names do not appear in the module nor do namespaces result in a module that is broken up into submodules or packages. For example, if you have a file like this,

        +

        %module example +namespace nspace { +extern int gcd(int x, int y); +extern double Foo; +class Circle +{ +public: + Circle(); + Circle(double r); + double area(); + double radius; + }; +} +
        +

        for namespaces, you use the %feature directive in interface file. %feature attaches a new attribute to any parse tree node that matches given prototype.

        +

        /* File : example.i */ +%module example +%{ +#include "example.h" +%} +%feature("nspace", 1); +%include "example.h" +
        +

        it works in javascript as follows:

        +

        print("Global variable Foo=" + example.nspace.Foo); +example.nspace.Foo = 5; +print("Variable Foo changed to " + example.nspace.Foo); +print("GCD of number 6,18 is " + example.nspace.gcd(6,18)); +print("Creating some objects:"); +c = new example.nspace.Circle(10); +print("area = " + c.area()); +
        +

        If your program has more than one namespace, name conflicts (if any) can be resolved using %rename For example:

        +

        %rename(Bar_spam) Bar::spam; +namespace Foo { + int spam(); +} +namespace Bar { + int spam(); +} +
        +

        If you have more than one namespace and your want to keep their symbols separate, consider wrapping them as separate SWIG modules. For example, make the module name the same as the namespace and create extension modules for each namespace separately. If your program utilizes thousands of small deeply nested namespaces each with identical symbol names, well, then you get what you deserve. SWIG resolves overloaded functions and methods using a disambiguation scheme that ranks and sorts declarations according to a set of type-precedence rules. The order in which declarations appear in the input does not matter except in situations where ambiguity arises--in this case, the first declaration takes precedence.

        +

        C++ templates

        +

        C++ templates don't present a huge problem for SWIG. However, in order to create wrappers, you have to tell SWIG to create wrappers for a particular template instantiation. To do this, you use the %template directive. For example:

        +

        /* File : example.i */ +%module example +%{ +#include "example.h" +%} +/* Let's just grab the original header file here */ +%include "example.h" + +/* Now instantiate some specific template declarations */ +%template(maxint) max<int>; +%template(maxdouble) max<double>; +%template(vecint) vector<int>; +%template(vecdouble) vector<double>; +
        +

        In javascript:

        +

        //Call some templated functions +print(example.maxint(3,7)); +print(example.maxdouble(3.14,2.18)); + +// Create some class + +iv = new example.vecint(100); +dv = new example.vecdouble(1000); + +for(i=0;i<=100;i++) + iv.setitem(i,2*i); + +for(i=0;i<=1000;i++) + dv.setitem(i, 1.0/(i+1)); + +sum = 0; +for(i=0;i<=100;i++) + sum = sum + iv.getitem(i); + +print(sum); + +sum = 0.0; +for(i=0;i<=1000;i++) + sum = sum + dv.getitem(i); +print(sum); +
        +

        Exception handling

        +

        The SWIG %exception directive can be used to create a user-definable exception handler for converting exceptions in your C/C++ program into javascript exceptions. The chapter on customization features contains more details, but suppose you have a C++ class like the following:

        +

        Since several methods in this class can throw an exception for an out-of-bounds access, you might want to catch this in the javascript extension by writing the following in an interface file:

        +

        /* File : example.i */ +%module example +%{ +#include "example.h" +%} +%include "std_string.i" + +/* Let's just grab the original header file here */ +%include "example.h" +
        +

        Actually in JS there is no support for typed exceptions.For now there is support for integer and string exception. Example for integer exception

        +

        JSValueRef jsc_gcd(JSContextRef context, JSObjectRef function, JSObjectRef globalobj, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ +int arg1 = (int)JSValueToNumber(context, argv[0], NULL); +int arg2 = (int)JSValueToNumber(context, argv[1], NULL); +*exception = JSValueMakeNumber(context, 13); +int result = (int)gcd(arg1,arg2); +JSValueRef jsresult = JSValueMakeNumber(context, result); +
        +

        and for string exception:

        +

        JSValueRef wrap_gcd(JSContextRef context, JSObjectRef function, JSObjectRef globalobj, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ +int arg1 = (int)JSValueToNumber(context, argv[0], NULL); +int arg2 = (int)JSValueToNumber(context, argv[1], NULL); +JSStringRef message = JSStringCreateWithUTF8CString("This is a test error."); +*exception = JSValueMakeString(context, message); +JSStringRelease(message); +int result = (int)gcd(arg1,arg2); +JSValueRef jscresult = JSValueMakeNumber(context, result); +return jsresult; +} +
        +

        How to use generated modules?

        +

        Basically there is no standard extension mechanism in Javascript. We provided a custom interpreter with extension abilities. If JSC is embedded into a custom application, one has to make use of a generated module initializer function that allows easy extension of interpreter. The basic approach is as follows:

        +

        Basic Mechanism

        +
          +
        • Creating the context
        • +
        • Calling module initializer
        • +
        • Evaluate Javascript
        • +
        +

        Creating the context

        +

        JSGlobalContextRef context = JSGlobalContextCreate(NULL); +JSObjectRef globalObject = JSContextGetGlobalObject(context); +... +
        +

        Calling module initializer

        +

        extern int example_init(JSGlobalContextRef context); + ... + example_init(context); + ... +
        +

        Evaluate Javascript

        +

        // Evaluate the javascript +char* scriptContent = jsccreateStringWithContentsOfFile(scriptPath.c_str()); +JSStringRef jsScript; +if(!scriptContent) { + printf("FAIL: runme script could not be loaded.\n"); + failed = 1; + } + else { + JSValueRef ex; + jsScript = JSStringCreateWithUTF8CString(scriptContent); + JSValueRef jsResult = JSEvaluateScript(context, jsScript, 0, 0, 0, &ex); + if (!jsResult && ex) { + jsc_printError(context, ex, scriptPath); + failed = 1; + } + } + if (scriptContent != NULL) { + free(scriptContent); + } + JSStringRelease(jsScript); + JSGlobalContextRelease(context); + globalObject = 0; + for(std::vector<HANDLE>::iterator it = loaded_modules.begin(); + it != loaded_modules.end(); ++it) { + HANDLE handle = *it; + dlclose(handle); + } + if (failed) { + printf("FAIL: Some tests failed.\n"); + return 1; + } +} +
        +

        Typemaps

        +

        A typemap is nothing more than a code generation rule that is attached to a specific C datatype. For example, to convert integers from javascript to C, you might define a typemap like this:

        +

        %typemap(in) int { + $1 = ($1_ltype)JSValueToNumber(context, $input, NULL); %} + printf("Received an integer : %d\n",$1); +} +
        +

        Typemaps are always associated with some specific aspect of code generation. In this case, the "in" method refers to the conversion of input arguments to C/C++. The datatype int is the datatype to which the typemap will be applied. The supplied C code is used to convert values. In this code a number of special variable prefaced by a $ are used. The $1 variable is placeholder for a local variable of type int.

        +

        Javascript typemaps

        +

        The previous section illustrated an "in" typemap for converting javascript objects to C. A variety of different typemap methods are defined by the javascript module. For example, to convert a C integer back into a javascript object, you might define an "out" typemap like this:

        +

        %typemap(out) int { + $result = JSValueMakeNumber(context, $1); +} +
        +

        The Javascript module makes use of Swig's unified template library.

        +

        Typemap variables

        +

        Within typemap code, a number of special variables prefaced with a $ may appear. A full list of variables can be found in the "Typemaps" chapter. This is a list of the most common variables:

        +

        $1: A C local variable corresponding to the actual type specified in the %typemap directive. For input values, this is a C local variable that's supposed to hold an argument value. For output values, this is the raw result that's supposed to be returned to Javascript.

        +

        $input: A javascript Object * holding a raw javascript object with an argument or variable value.

        +

        $result: A javascript Object * that holds the result to be returned to javascript.

        +

        $1_name: The parameter name that was matched.

        +

        $1_type: The actual C datatype matched by the typemap.

        +

        $1_ltype: An assignable version of the datatype matched by the typemap (a type that can appear on the left-hand-side of a C assignment operation). This type is stripped of qualifiers and may be an altered version of $1_type. All arguments and local variables in wrapper functions are declared using this type so that their values can be properly assigned.

        +

        $symname: The javascript name of the wrapper function being created.

        +

        Javascript: Specification of a Code Generator for JSC

        +

        The module implementation tries to accomplish a separation of logic and code generation by making use of code templates. In the following, the templates are explained.

        +

        Top Level structure

        +

        The generated code consists of the following blocks:

        +

        <RUNTIME> +<INCLUDES> +<HELPER_FUNCTIONS> +<FUNCTION_WRAPPERS> +<INITIALIZER> +
        +
          +
        • RUNTIME: runtime code generated by swig
        • +
        • HELPER_FUNCTIONS: static, from swg-file
        • +
        • INCLUDES: static, module property
        • +
        • FUNCTION_WRAPPERS: dynamically growing, on method declarations
        • +
        • INITIALIZER: dynamically growing, aggregates everything
        • +
        +

        INCLUDES

        +

        #include <JavaScriptCore/JavaScript.h> +<USER_DEFINED_INCLUDES> +
        +

        USER_DEFINED_INCLUDES: a module property

        +

        HELPER_FUNCTIONS

        +

        A lot of boiler-plate code can be shifted into static helper functions:

        +

        bool JS_registerClass(JSGlobalContextRef& context, JSObjectRef& parentObject,const char* className, + JSClassDefinition* definition) { + JSStringRef js_className = JSStringCreateWithUTF8CString(className); + JSObjectRef classObject = JSObjectMake(context, JSClassCreate(definition), NULL); + JSObjectSetProperty(context, parentObject,js_className, classObject,kJSPropertyAttributeNone, NULL); + JSStringRelease(js_className); + return true; +} + +bool JS_registerNamespace(JSGlobalContextRef& context,JSObjectRef& namespaceObj,JSObjectRef& parentNamespace,const char* name) +{ + JSStringRef js_name = JSStringCreateWithUTF8CString(name); + JSObjectSetProperty(context, parentNamespace,js_name, namespaceObj,kJSPropertyAttributeNone, NULL); + JSStringRelease(js_name); + return true; +} + +bool JS_registerFunction(JSGlobalContextRef context, JSObjectRef object, const char* functionName, JSObjectCallAsFunctionCallback callback) +{ + JSStringRef js_functionName = JSStringCreateWithUTF8CString(functionName); + JSObjectSetProperty(context,object,js_functionName,JSObjectMakeFunctionWithCallback(context, + js_functionName, callback), kJSPropertyAttributeNone, NULL); + JSStringRelease(js_functionName); + return true; +} +bool JS_veto_set_variable(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + char buffer[256]; + char msg[512]; + int res; + JSStringGetUTF8CString(propertyName, buffer, 256); + res = sprintf(msg, "Tried to write read-only variable: %s.", buffer); + if(res<0) { + SWIG_exception(SWIG_ERROR, "Tried to write read-only variable."); + } else { + SWIG_exception(SWIG_ERROR, msg); + } + return false; +} + +JSValueRef JS_CharPtrToJSValue(JSContextRef context, char* cstr) { + JSValueRef val; + JSStringRef jsstring = JSStringCreateWithUTF8CString((char*) cstr); + val = JSValueMakeString(context, jsstring); + JSStringRelease(jsstring); + return val; +} +
        +

        FUNCTION_WRAPPERS

        +

        There are different types of function wrappers: - Member Functions - Getproperty / Setproperty - Global Functions (global/namespace/class) - Constructors / Destructors

        +

        Member Functions

        +

        JSValueRef ${functionname}(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + ${LOCALS} + ${CODE} + return jsresult; + + goto fail; + fail: + return NULL; +} +
        +
          +
        • functionname: the name of generated wrapper for function
        • +
        • LOCALS: declarations for input arguments
        • +
        • CODE: contains input marshalling, the action, and output marshalling
        • +
        +

        Setproperty

        +

        bool ${setname}(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + ${LOCALS} + ${CODE} + return jsresult; + + goto fail; + fail: + return NULL; +} +
        +
          +
        • setname: the name of the generated wrapper for setproperty.
        • +
        • LOCALS: declarations for input arguments
        • +
        • CODE: contains input marshalling, and the action
        • +
        +

        Getproperty

        +

        JSValueRef ${getname}(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + ${LOCALS} + ${CODE} + return jsresult; + + goto fail; + fail: + return NULL; +} +
        +
          +
        • getname: the name of the generated wrapper for the getproperty
        • +
        • LOCALS: declarations for output arguments
        • +
        • CODE: contains the action, and output marshalling
        • +
        +

        Global Functions

        +

        JSStaticValue ${namespace}_values[] = { + ${jsglobalvariables} + { 0, 0, 0, 0 } +}; +JSStaticFunction ${namespace}_functions[] = { + ${jsglobalfunctions} + { 0, 0, 0 } +}; +JSClassDefinition ${namespace}_classDefinition; +
        +

        Variable declaration

        +

        {"${propertyname}",${getname}, ${setname}, kJSPropertyAttributeNone} +
        +

        This is used to fill variable definition tables. kJSPropertyAttributeNone is JSC specific and means that the variable has a getter and setter. Even for read-only variables a setter is used which throws an exception.

        +

        Constructor

        +

        ~~

        +

        JSObjectRef wrap_createclassnamemangled{overloadext}(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) { ${LOCALS} ${CODE} return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_${type_mangled}, SWIG_POINTER_OWN);

        +
        goto fail;
        +fail:
        +return NULL;
        +
        +

        }

        +
        - `classname_mangled` is the mangled qualified class name,   e.g., `foo::A -> foo_A`
        +- `LOCALS`: declarations for input arguments 
        +- `CODE`: contains input marshalling, and the action 
        +
        +## Destructors
        +
        +

        void wrap${classname_mangled}_finalize(JSObjectRef thisObject) { SWIG_PRV_DATA* t = (SWIG_PRV_DATA*)JSObjectGetPrivate(thisObject); if(t && t->swigCMemOwn) delete (${type}*)(t->swigCObject); if(t) delete t; }

        +

        - `classname_mangled` is the mangled qualified class name, e.g., `foo::A -> foo_A` + +## Initializer +
        +

        bool ${modulename}_initialize(JSGlobalContextRef context) { SWIG_InitializeModule(0);

        +
        JSObjectRef global_object = JSContextGetGlobalObject(context);
        +
        +/* Initialize the base swig type object */
        +_SwigObject_objectDefinition.staticFunctions = _SwigObject_functions;
        +_SwigObject_objectDefinition.staticValues = _SwigObject_values;
        +_SwigObject_classRef = JSClassCreate(&_SwigObject_objectDefinition);
        +
        +/* Create objects for namespaces */
        +${create_namespaces}
        +
        +/* Create classes */
        +${initializercode}
        +
        +/* Register namespaces */
        +${register_namespaces}
        +
        +return true;
        +
        +

        }

        +

        ## Class template defintions + +A class is specified by a static part (`*_classDefinition`) and a dynamic part (`*_objectDefinition`). +
        +

        ${classname_mangled}_classDefinition.staticFunctions = ${classname_mangled}_staticFunctions; ${classname_mangled}_classDefinition.staticValues = ${classname_mangled}_staticValues; ${classname_mangled}_classDefinition.callAsConstructor = _wrap_create_${classname_mangled}; ${classname_mangled}_objectDefinition.staticValues = ${classname_mangled}_values; ${classname_mangled}_objectDefinition.staticFunctions = ${classname_mangled}_functions; ${classname_mangled}_objectDefinition.parentClass = ${base_classname}_classRef; JSClassRef ${classname_mangled}_classRef = JSClassCreate(&${classname_mangled}objectDefinition); SWIGTYPE${classtype_mangled}->clientdata = ${classname_mangled}_classRef;%}

        +

        Notes: +- `classname_mangled` is the mangled qualified class name, e.g., `foo::A -> foo_A` + which is retrieved by `Swig_name_mangle(Getattr(n, "name"))` +- ClassDefinitions are built using the staticValues array and the staticFunction array. The staticValues and staticFunctions arrays are the simplest and most efficient means for vending custom properties to the class object. + +## Inheritance +
        +

        {${classname_mangled}_objectDefinition.parentClass = ${base_classname}_classRef};

        +

        - `classname_mangled` is the mangled qualified class name, e.g., `foo::A -> foo_A` +- Note: multiple inheritance is not possible; thus we will always take the first parent class + +## Namespaces + +Namespaces are objects without class templates. i.e., instances are created, referenced locally, used as contexts for other registrations, and stored in the according parent contexts. +
        +

        ${namespace}_classDefinition.staticFunctions = ${namespace}_functions; ${namespace}_classDefinition.staticValues = ${namespace}_values; JSObjectRef ${namespace}_object = JSObjectMake(context, JSClassCreate(&${namespace}_classDefinition), NULL);

        +

        ## Registration + +The registration part consists of registering classes at contexts (i.e., global or namespace), methods and properties at classes or contexts, and namespaces as objects at parent contexts. + +* Global functions +
        +

        JS_registerFunction(${context}, ${context_object}, "${functionname}", ${functionwrapper}

        +

        * Classes +
        +

        JS_registerClass(context, ${namespace}_object, "${classname}", &${classname_mangled}_classDefinition)

        +

        Note: every class template has an associated constructor function wrapper, which is registered here + +* Namespaces +
        +

        ${namespace}_classDefinition.staticFunctions = ${namespace}_functions; ${namespace}_classDefinition.staticValues = ${namespace}_values; JSObjectRef ${namespace}_object = JSObjectMake(context, JSClassCreate(&${namespace}_classDefinition), NULL);

        +

        Namespaces are registered using: +
        +

        JS_registerNamespace(context, ${namespace}_object, ${parent_namespace}_object, "${namespace}");

        +

        ~~

        +
        + + diff --git a/Doc/Manual/chapters b/Doc/Manual/chapters index 45d35e793..c5f655254 100644 --- a/Doc/Manual/chapters +++ b/Doc/Manual/chapters @@ -23,6 +23,7 @@ D.html Go.html Guile.html Java.html +Javascript.html Lisp.html Lua.html Modula3.html diff --git a/Doc/Manual/style.css b/Doc/Manual/style.css index 02329e56f..7eabf91ae 100644 --- a/Doc/Manual/style.css +++ b/Doc/Manual/style.css @@ -25,7 +25,7 @@ div.indent { margin-right: 4em; } -div.code { +div.code, div:not(.code) pre { border-style: solid; border-width: 1px; padding: 2pt; @@ -82,3 +82,7 @@ div.indent p { margin-right: 0; } +h1 a, h2 a, h3 a, h4 a, h5 a, h6 a { + text-decoration:none; + color: #000000; +} diff --git a/Examples/Makefile.in b/Examples/Makefile.in index 218d8eca5..c06f09f9a 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -589,6 +589,86 @@ java_clean: rm -f core @EXTRA_CLEAN@ rm -f *.@OBJEXT@ *@JAVASO@ +################################################################## +##### JAVASCRIPT ###### +################################################################## + +# Note: These targets are also from within Makefiles in the Example directories. +# There is a common makefile, 'Examples/javascript/js_example.mk' to simplify +# create a configuration for a new example. + + +ROOT_DIR = @ROOT_DIR@ +JSCFLAGS = @JSCFLAGS@ +JSCXXFLAGS = @JSCXXFLAGS@ +JSINCLUDES = @JSCOREINC@ @JSV8INC@ +JSDYNAMICLINKING = @JSCOREDYNAMICLINKING@ @JSV8DYNAMICLINKING@ +JSLIBRARYPREFIX = @JSLIBRARYPREFIX@ +JSSO =@JSSO@ +JSLDSHARED = @JSLDSHARED@ +JSCXXSHARED = @JSCXXSHARED@ + +SWIGJS = $(SWIG) -javascript + +# ---------------------------------------------------------------- +# Creating and building Javascript wrappers +# ---------------------------------------------------------------- + +javascript_wrapper: + $(SWIGJS) $(SWIGOPT) -o $(INTERFACEDIR)$(TARGET)_wrap.c $(INTERFACEPATH) + +javascript_wrapper_cpp: $(SRCS) + $(SWIGJS) -c++ $(SWIGOPT) -o $(INTERFACEDIR)$(TARGET)_wrap.cxx $(INTERFACEPATH) + +javascript_build: $(SRCS) + $(CC) -c $(CCSHARED) $(CFLAGS) $(JSCFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) $(JSINCLUDES) + $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + +javascript_build_cpp:: $(SRCS) + $(CXX) -c $(CCSHARED) $(CFLAGS) $(JSCFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(JSINCLUDES) + $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + +# TODO: make node-gyp configurable and detected via ./configure +javascript_build_node: $(SRCS) + node-gyp --loglevel=silent configure build 1>>/dev/null + +# These targets are used by the test-suite: + +javascript: $(SRCS) javascript_custom_interpreter + $(SWIGJS) $(SWIGOPT) $(INTERFACEPATH) + $(CC) -c $(CCSHARED) $(CFLAGS) $(JSCFLAGS) $(ISRCS) $(SRCS) $(INCLUDES) $(JSINCLUDES) + $(LDSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + +javascript_cpp: $(SRCS) javascript_custom_interpreter + $(SWIGJS) -c++ $(SWIGOPT) $(INTERFACEPATH) + $(CXX) -c $(CCSHARED) $(CFLAGS) $(JSCFLAGS) $(ICXXSRCS) $(SRCS) $(CXXSRCS) $(INCLUDES) $(JSINCLUDES) + $(CXXSHARED) $(CFLAGS) $(OBJS) $(IOBJS) $(JSDYNAMICLINKING) $(LIBS) $(CPP_DLLIBS) -o $(LIBPREFIX)$(TARGET)$(SO) + +# ----------------------------------------------------------------- +# Running a javascript example +# ----------------------------------------------------------------- + +javascript_custom_interpreter: + (cd $(ROOT_DIR)/Tools/javascript && $(MAKE) JSENGINE='$(JSENGINE)') + +javascript_run: javascript_custom_interpreter + $(ROOT_DIR)/Tools/javascript/javascript -$(JSENGINE) -L $(TARGET) runme.js + +# TODO: make node configurable and detected via ./configure +javascript_run_node: + node runme.js + +# ----------------------------------------------------------------- +# Cleaning the javascript examples +# ----------------------------------------------------------------- + +javascript_clean: + rm -rf build + rm -f *_wrap* runme + rm -f core @EXTRA_CLEAN@ + rm -f *.@OBJEXT@ *@JSSO@ *.$(SO) + (cd $(ROOT_DIR)/Tools/javascript && $(MAKE) -s clean) + ################################################################## ##### ANDROID ###### ################################################################## diff --git a/Examples/javascript/check.list b/Examples/javascript/check.list new file mode 100644 index 000000000..040267812 --- /dev/null +++ b/Examples/javascript/check.list @@ -0,0 +1,13 @@ +class +constant +enum +#exception +functor +#namespace +operator +overload +pointer +#reference +simple +template +variables diff --git a/Examples/javascript/class/Makefile b/Examples/javascript/class/Makefile new file mode 100755 index 000000000..b0934786a --- /dev/null +++ b/Examples/javascript/class/Makefile @@ -0,0 +1,3 @@ +SRCS = example.cxx + +include ../js_example.mk diff --git a/Examples/javascript/class/binding.gyp b/Examples/javascript/class/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/class/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/class/example.cxx b/Examples/javascript/class/example.cxx new file mode 100755 index 000000000..e23fa6f73 --- /dev/null +++ b/Examples/javascript/class/example.cxx @@ -0,0 +1,28 @@ +/* File : example.c */ +#include +#include "example.h" +#define M_PI 3.14159265358979323846 + +/* Move the shape to a new location */ +void Shape::move(double dx, double dy) { + x += dx; + y += dy; +} + +int Shape::nshapes = 0; + +double Circle::area(void) { + return M_PI*radius*radius; +} + +double Circle::perimeter(void) { + return 2*M_PI*radius; +} + +double Square::area(void) { + return width*width; +} + +double Square::perimeter(void) { + return 4*width; +} diff --git a/Examples/javascript/class/example.h b/Examples/javascript/class/example.h new file mode 100755 index 000000000..64b7684fa --- /dev/null +++ b/Examples/javascript/class/example.h @@ -0,0 +1,34 @@ +/* File : example.h */ + +class Shape { +public: + Shape() { + nshapes++; + } + virtual ~Shape() { + nshapes--; + }; + double x, y; + void move(double dx, double dy); + virtual double area(void) = 0; + virtual double perimeter(void) = 0; + static int nshapes; +}; + +class Circle : public Shape { +private: + double radius; +public: + Circle(double r) : radius(r) { }; + virtual double area(void); + virtual double perimeter(void); +}; + +class Square : public Shape { +private: + double width; +public: + Square(double w) : width(w) { }; + virtual double area(void); + virtual double perimeter(void); +}; diff --git a/Examples/javascript/class/example.i b/Examples/javascript/class/example.i new file mode 100755 index 000000000..75700b305 --- /dev/null +++ b/Examples/javascript/class/example.i @@ -0,0 +1,10 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +/* Let's just grab the original header file here */ +%include "example.h" + diff --git a/Examples/javascript/class/example.js b/Examples/javascript/class/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/class/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/class/runme.js b/Examples/javascript/class/runme.js new file mode 100755 index 000000000..e1d5d9797 --- /dev/null +++ b/Examples/javascript/class/runme.js @@ -0,0 +1,46 @@ +var example = require("./example"); + +// ----- Object creation ----- + +console.log("Creating some objects:"); +c = new example.Circle(10); +console.log("Created circle " + c); +s = new example.Square(10); +console.log("Created square " + s); + +// ----- Access a static member ----- +console.log("\nA total of " + example.Shape.nshapes + " shapes were created"); // access static member as properties of the class object + +// ----- Member data access ----- +// Set the location of the object. +// Note: methods in the base class Shape are used since +// x and y are defined there. + +c.x = 20; +c.y = 30; +s.x = -10; +s.y = 5; + +console.log("\nHere is their new position:"); +console.log("Circle = (" + c.x + "," + c.y + ")"); +console.log("Square = (" + s.x + "," + s.y + ")"); + +// ----- Call some methods ----- +console.log("\nHere are some properties of the shapes:"); +console.log("Circle:"); +console.log("area = " + c.area() + ""); +console.log("perimeter = " + c.perimeter() + ""); +console.log("\n"); +console.log("Square:"); +console.log("area = " + s.area() + ""); +console.log("perimeter = " + s.perimeter() + ""); + +// ----- Delete everything ----- +console.log("\nGuess I'll clean up now"); +// Note: this invokes the virtual destructor +delete c; +delete s; + +console.log(example.Shape.nshapes + " shapes remain"); + +console.log("Goodbye"); diff --git a/Examples/javascript/constant/Makefile b/Examples/javascript/constant/Makefile new file mode 100755 index 000000000..a2570636e --- /dev/null +++ b/Examples/javascript/constant/Makefile @@ -0,0 +1,3 @@ +SRCS = + +include ../js_example.mk diff --git a/Examples/javascript/constant/binding.gyp b/Examples/javascript/constant/binding.gyp new file mode 100644 index 000000000..69af46b22 --- /dev/null +++ b/Examples/javascript/constant/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/constant/example.h b/Examples/javascript/constant/example.h new file mode 100644 index 000000000..2c88ebd1e --- /dev/null +++ b/Examples/javascript/constant/example.h @@ -0,0 +1,8 @@ +#define ICONST 42 +#define FCONST 2.1828 +#define CCONST 'x' +#define CCONST2 '\n' +#define SCONST "Hello World" +#define SCONST2 "\"Hello World\"" +#define EXTERN extern +#define FOO (ICONST + BAR) diff --git a/Examples/javascript/constant/example.i b/Examples/javascript/constant/example.i new file mode 100755 index 000000000..a6d28e7c9 --- /dev/null +++ b/Examples/javascript/constant/example.i @@ -0,0 +1,24 @@ +/* File : example.i */ +%module example + +/* A few preprocessor macros */ + +#define ICONST 42 +#define FCONST 2.1828 +#define CCONST 'x' +#define CCONST2 '\n' +#define SCONST "Hello World" +#define SCONST2 "\"Hello World\"" + +/* This should work just fine */ +#define EXPR ICONST + 3*(FCONST) + +/* This shouldn't do anything */ +#define EXTERN extern + +/* Neither should this (BAR isn't defined) */ +#define FOO (ICONST + BAR) + +/* The following directives also produce constants */ +%constant int iconst = 37; +%constant double fconst = 3.14; diff --git a/Examples/javascript/constant/example.js b/Examples/javascript/constant/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/constant/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/constant/runme.js b/Examples/javascript/constant/runme.js new file mode 100755 index 000000000..2188bf099 --- /dev/null +++ b/Examples/javascript/constant/runme.js @@ -0,0 +1,14 @@ +var example = require("./example"); + +console.log("ICONST = " + example.ICONST + " (should be 42)\n"); +console.log("FCONST = " + example.FCONST + " (should be 2.1828)\n"); +console.log("CCONST = " + example.CCONST + " (should be 'x')\n"); +console.log("CCONST2 = " + example.CCONST2 + " (this should be on a new line)\n"); +console.log("SCONST = " + example.SCONST + " (should be 'Hello World')\n"); +console.log("SCONST2 = " + example.SCONST2 + " (should be '\"Hello World\"')\n"); +console.log("EXPR = " + example.EXPR + " (should be 48.5484)\n"); +console.log("iconst = " + example.iconst + " (should be 37)\n"); +console.log("fconst = " + example.fconst + " (should be 3.14)\n"); + +console.log("EXTERN = " + example.EXTERN + " (should be undefined)\n"); +console.log("FOO = " + example.FOO + " (should be undefined)\n"); diff --git a/Examples/javascript/enum/Makefile b/Examples/javascript/enum/Makefile new file mode 100755 index 000000000..b0934786a --- /dev/null +++ b/Examples/javascript/enum/Makefile @@ -0,0 +1,3 @@ +SRCS = example.cxx + +include ../js_example.mk diff --git a/Examples/javascript/enum/binding.gyp b/Examples/javascript/enum/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/enum/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/enum/example.cxx b/Examples/javascript/enum/example.cxx new file mode 100755 index 000000000..6785e57ac --- /dev/null +++ b/Examples/javascript/enum/example.cxx @@ -0,0 +1,37 @@ +/* File : example.c */ + +#include "example.h" +#include + +void Foo::enum_test(speed s) { + if (s == IMPULSE) { + printf("IMPULSE speed\n"); + } else if (s == WARP) { + printf("WARP speed\n"); + } else if (s == LUDICROUS) { + printf("LUDICROUS speed\n"); + } else { + printf("Unknown speed\n"); + } +} + +void enum_test(color c, Foo::speed s) { + if (c == RED) { + printf("color = RED, "); + } else if (c == BLUE) { + printf("color = BLUE, "); + } else if (c == GREEN) { + printf("color = GREEN, "); + } else { + printf("color = Unknown color!, "); + } + if (s == Foo::IMPULSE) { + printf("speed = IMPULSE speed\n"); + } else if (s == Foo::WARP) { + printf("speed = WARP speed\n"); + } else if (s == Foo::LUDICROUS) { + printf("speed = LUDICROUS speed\n"); + } else { + printf("speed = Unknown speed!\n"); + } +} diff --git a/Examples/javascript/enum/example.h b/Examples/javascript/enum/example.h new file mode 100755 index 000000000..9119cd9fc --- /dev/null +++ b/Examples/javascript/enum/example.h @@ -0,0 +1,13 @@ +/* File : example.h */ + +enum color { RED, BLUE, GREEN }; + +class Foo { + public: + Foo() { } + enum speed { IMPULSE=10, WARP=20, LUDICROUS=30 }; + void enum_test(speed s); +}; + +void enum_test(color c, Foo::speed s); + diff --git a/Examples/javascript/enum/example.i b/Examples/javascript/enum/example.i new file mode 100755 index 000000000..23ee8a822 --- /dev/null +++ b/Examples/javascript/enum/example.i @@ -0,0 +1,11 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +/* Let's just grab the original header file here */ + +%include "example.h" + diff --git a/Examples/javascript/enum/example.js b/Examples/javascript/enum/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/enum/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/enum/runme.js b/Examples/javascript/enum/runme.js new file mode 100755 index 000000000..d4e89e8c8 --- /dev/null +++ b/Examples/javascript/enum/runme.js @@ -0,0 +1,34 @@ +var example = require("./example"); + +// ----- Object creation ----- + +// Print out the value of some enums +console.log("*** color ***"); +console.log(" RED =" + example.RED); +console.log(" BLUE =" + example.BLUE); +console.log(" GREEN =" + example.GREEN); + +console.log("\n*** Foo::speed ***"); +console.log(" Foo_IMPULSE =" + example.Foo.IMPULSE); +console.log(" Foo_WARP =" + example.Foo.WARP); +console.log(" Foo_LUDICROUS =" + example.Foo.LUDICROUS); + +console.log("\nTesting use of enums with functions\n"); + +example.enum_test(example.RED, example.Foo.IMPULSE); +example.enum_test(example.BLUE, example.Foo.WARP); +example.enum_test(example.GREEN, example.Foo.LUDICROUS); +example.enum_test(1234,5678); + +console.log("\nTesting use of enum with class method"); +f = new example.Foo(); + +f.enum_test(example.Foo.IMPULSE); +f.enum_test(example.Foo.WARP); +f.enum_test(example.Foo.LUDICROUS); + +// enum value BLUE of enum color is accessed as property of cconst +console.log("example.BLUE= " + example.BLUE); + +// enum value LUDICROUS of enum Foo::speed is accessed as as property of cconst +console.log("example.speed.LUDICROUS= " + example.Foo.LUDICROUS); diff --git a/Examples/javascript/exception/Makefile b/Examples/javascript/exception/Makefile new file mode 100755 index 000000000..b0934786a --- /dev/null +++ b/Examples/javascript/exception/Makefile @@ -0,0 +1,3 @@ +SRCS = example.cxx + +include ../js_example.mk diff --git a/Examples/javascript/exception/binding.gyp b/Examples/javascript/exception/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/exception/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/exception/example.cxx b/Examples/javascript/exception/example.cxx new file mode 100644 index 000000000..8b1378917 --- /dev/null +++ b/Examples/javascript/exception/example.cxx @@ -0,0 +1 @@ + diff --git a/Examples/javascript/exception/example.h b/Examples/javascript/exception/example.h new file mode 100644 index 000000000..7cf917d01 --- /dev/null +++ b/Examples/javascript/exception/example.h @@ -0,0 +1,53 @@ +/* File : example.h */ + +#include +#ifndef SWIG +struct A { +}; +#endif + +class Exc { +public: + Exc(int c, const char *m) { + code = c; + strncpy(msg,m,256); + } + int code; + char msg[256]; +}; + +#if defined(_MSC_VER) + #pragma warning(disable: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow) +#endif + +class Test { +public: + int simple() throw(int) { + throw(37); + return 1; + } + int message() throw(const char *) { + throw("I died."); + return 1; + } + int hosed() throw(Exc) { + throw(Exc(42,"Hosed")); + return 1; + } + int unknown() throw(A*) { + static A a; + throw &a; + return 1; + } + int multi(int x) throw(int, const char *, Exc) { + if (x == 1) throw(37); + if (x == 2) throw("Bleah!"); + if (x == 3) throw(Exc(42,"No-go-diggy-die")); + return 1; + } +}; + +#if defined(_MSC_VER) + #pragma warning(default: 4290) // C++ exception specification ignored except to indicate a function is not __declspec(nothrow) +#endif + diff --git a/Examples/javascript/exception/example.i b/Examples/javascript/exception/example.i new file mode 100644 index 000000000..08672c3a8 --- /dev/null +++ b/Examples/javascript/exception/example.i @@ -0,0 +1,12 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +%include "std_string.i" + +/* Let's just grab the original header file here */ +%include "example.h" + diff --git a/Examples/javascript/exception/example.js b/Examples/javascript/exception/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/exception/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/exception/runme.js b/Examples/javascript/exception/runme.js new file mode 100644 index 000000000..977f51ebc --- /dev/null +++ b/Examples/javascript/exception/runme.js @@ -0,0 +1,64 @@ +var example = require("./example"); + +console.log("Trying to catch some exceptions."); +t = new example.Test(); +try{ + t.unknown(); + throw -1; +} catch(error) +{ + if(error == -1) { + console.log("t.unknown() didn't throw"); + } else { + console.log("successfully catched throw in Test::unknown()."); + } +} + +try{ + t.simple(); + throw -1; +} +catch(error){ + if(error == -1) { + console.log("t.simple() did not throw"); + } else { + console.log("successfully catched throw in Test::simple()."); + } +} + +try{ + t.message(); + throw -1; +} catch(error){ + if(error == -1) { + console.log("t.message() did not throw"); + } else { + console.log("successfully catched throw in Test::message()."); + } +} + +try{ + t.hosed(); + throw -1; +} +catch(error){ + if(error == -1) { + console.log("t.hosed() did not throw"); + } else { + console.log("successfully catched throw in Test::hosed()."); + } +} + +for (var i=1; i<4; i++) { + try{ + t.multi(i); + throw -1; + } + catch(error){ + if(error == -1) { + console.log("t.multi(" + i + ") did not throw"); + } else { + console.log("successfully catched throw in Test::multi()."); + } + } +} diff --git a/Examples/javascript/functor/Makefile b/Examples/javascript/functor/Makefile new file mode 100755 index 000000000..b0934786a --- /dev/null +++ b/Examples/javascript/functor/Makefile @@ -0,0 +1,3 @@ +SRCS = example.cxx + +include ../js_example.mk diff --git a/Examples/javascript/functor/binding.gyp b/Examples/javascript/functor/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/functor/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/functor/example.cxx b/Examples/javascript/functor/example.cxx new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/javascript/functor/example.i b/Examples/javascript/functor/example.i new file mode 100644 index 000000000..0450c2124 --- /dev/null +++ b/Examples/javascript/functor/example.i @@ -0,0 +1,25 @@ +/* File : example.i */ +%module example + + +%inline %{ +// From B. Strousjoup, "The C++ Programming Language, Third Edition", p. 514 +template class Sum { + T res; +public: + Sum(T i = 0) : res(i) { } + void operator() (T x) { res += x; } + T result() const { return res; } +}; + +%} + +%rename(call) *::operator(); // the fn call operator + +// Instantiate a few versions +%template(intSum) Sum; +%template(doubleSum) Sum; + + + + diff --git a/Examples/javascript/functor/example.js b/Examples/javascript/functor/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/functor/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/functor/runme.js b/Examples/javascript/functor/runme.js new file mode 100644 index 000000000..dc12470f4 --- /dev/null +++ b/Examples/javascript/functor/runme.js @@ -0,0 +1,15 @@ +var example = require("./example"); + +a = new example.intSum(0); +b = new example.doubleSum(100.0); + +// Use the objects. They should be callable just like a normal +// javascript function. + +for (i=1;i<=100;i++) + a.call(i); // Note: function call + b.call(Math.sqrt(i)); // Note: function call + +console.log(a.result()); +console.log(b.result()); + diff --git a/Examples/javascript/js_example.mk b/Examples/javascript/js_example.mk new file mode 100644 index 000000000..6cb6eb113 --- /dev/null +++ b/Examples/javascript/js_example.mk @@ -0,0 +1,52 @@ +# Note: as a convention an example must be in a child directory of this. +# These paths are relative to such an example directory +EXAMPLES_TOP=../.. +SWIG_TOP=../../.. + +SWIG = $(SWIG_TOP)/preinst-swig + +# TODO: we could only set these only if not yet set... +JS_SCRIPT = runme.js +TARGET = example +INTERFACE = example.i + +ifneq (, $(ENGINE)) + JSENGINE=$(ENGINE) +else + JSENGINE=node +endif + +SWIGOPT=-$(JSENGINE) + +ifeq (node,$(JSENGINE)) + +build: wrapper + $(MAKE) -f $(EXAMPLES_TOP)/Makefile CXXSRCS='$(SRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' JSENGINE='$(JSENGINE)' javascript_build_node + +else + +build: wrapper + $(MAKE) -f $(EXAMPLES_TOP)/Makefile CXXSRCS='$(SRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' JSENGINE='$(JSENGINE)' javascript_build_cpp + +endif + +wrapper: + $(MAKE) -f $(EXAMPLES_TOP)/Makefile CXXSRCS='$(SRCS)' SWIG='$(SWIG)' \ + SWIGOPT='$(SWIGOPT)' TARGET='$(TARGET)' INTERFACE='$(INTERFACE)' javascript_wrapper_cpp + +ifeq (node,$(JSENGINE)) + +check: build + $(MAKE) -f $(EXAMPLES_TOP)/Makefile JSENGINE='$(JSENGINE)' javascript_run_node + +else + +check: build + $(MAKE) -f $(EXAMPLES_TOP)/Makefile JSENGINE='$(JSENGINE)' TARGET='$(TARGET)' javascript_run + +endif + +clean: + $(MAKE) -f $(EXAMPLES_TOP)/Makefile javascript_clean diff --git a/Examples/javascript/namespace/Makefile b/Examples/javascript/namespace/Makefile new file mode 100755 index 000000000..b0934786a --- /dev/null +++ b/Examples/javascript/namespace/Makefile @@ -0,0 +1,3 @@ +SRCS = example.cxx + +include ../js_example.mk diff --git a/Examples/javascript/namespace/binding.gyp b/Examples/javascript/namespace/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/namespace/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/namespace/example.cxx b/Examples/javascript/namespace/example.cxx new file mode 100644 index 000000000..5beeb09fe --- /dev/null +++ b/Examples/javascript/namespace/example.cxx @@ -0,0 +1,36 @@ +/* File : example.c */ + +#include +#include "example.h" + +#define M_PI 3.14159 + + +/* A global variable */ +namespace nspace +{ +double Foo = 3.0; + +/* Compute the greatest common divisor of positive integers */ +int gcd(int x, int y) { + int g; + g = y; + while (x > 0) { + g = x; + x = y % x; + y = g; + } + return g; +} + +Circle::Circle(): radius(1.0) {} + +Circle::Circle(double r): radius(r) { + std::cout << "created Circle with r=" << radius << std::endl; +} + +double Circle::area() { + std::cout << "Circle::area called, r=" << radius << std::endl; + return M_PI*radius*radius; +} +} diff --git a/Examples/javascript/namespace/example.h b/Examples/javascript/namespace/example.h new file mode 100644 index 000000000..7f76c2f07 --- /dev/null +++ b/Examples/javascript/namespace/example.h @@ -0,0 +1,20 @@ + +namespace nspace { + +extern int gcd(int x, int y); +extern double Foo; + +class Circle +{ +public: + Circle(); + + Circle(double r); + + double area(); + + double radius; + +}; + +} diff --git a/Examples/javascript/namespace/example.i b/Examples/javascript/namespace/example.i new file mode 100644 index 000000000..e14b10b44 --- /dev/null +++ b/Examples/javascript/namespace/example.i @@ -0,0 +1,10 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +%feature("nspace", 1); + +%include "example.h" diff --git a/Examples/javascript/namespace/example.js b/Examples/javascript/namespace/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/namespace/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/namespace/runme.js b/Examples/javascript/namespace/runme.js new file mode 100644 index 000000000..08e0d3769 --- /dev/null +++ b/Examples/javascript/namespace/runme.js @@ -0,0 +1,10 @@ +var example = require("./example"); + +console.log("Global variable Foo=" + example.nspace.Foo); +example.nspace.Foo = 5; +console.log("Variable Foo changed to " + example.nspace.Foo); +console.log("GCD of number 6,18 is " + example.nspace.gcd(6,18)); + +console.log("Creating some objects:"); +c = new example.nspace.Circle(10); +console.log("area = " + c.area()); diff --git a/Examples/javascript/operator/Makefile b/Examples/javascript/operator/Makefile new file mode 100755 index 000000000..a2570636e --- /dev/null +++ b/Examples/javascript/operator/Makefile @@ -0,0 +1,3 @@ +SRCS = + +include ../js_example.mk diff --git a/Examples/javascript/operator/binding.gyp b/Examples/javascript/operator/binding.gyp new file mode 100644 index 000000000..69af46b22 --- /dev/null +++ b/Examples/javascript/operator/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/operator/example.h b/Examples/javascript/operator/example.h new file mode 100644 index 000000000..4da6a2307 --- /dev/null +++ b/Examples/javascript/operator/example.h @@ -0,0 +1,36 @@ +/* File : example.h */ +#include + +class Complex { +private: + double rpart, ipart; +public: + Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { } + Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { } + Complex &operator=(const Complex &c) { + rpart = c.rpart; + ipart = c.ipart; + return *this; + } + Complex operator+(const Complex &c) const { + return Complex(rpart+c.rpart, ipart+c.ipart); + } + Complex operator-(const Complex &c) const { + return Complex(rpart-c.rpart, ipart-c.ipart); + } + Complex operator*(const Complex &c) const { + return Complex(rpart*c.rpart - ipart*c.ipart, + rpart*c.ipart + c.rpart*ipart); + } + Complex operator-() const { + return Complex(-rpart, -ipart); + } + + double re() const { return rpart; } + double im() const { return ipart; } +}; + + + + + diff --git a/Examples/javascript/operator/example.i b/Examples/javascript/operator/example.i new file mode 100644 index 000000000..7a1bd45e1 --- /dev/null +++ b/Examples/javascript/operator/example.i @@ -0,0 +1,34 @@ +/* File : example.i */ +%module example +#pragma SWIG nowarn=SWIGWARN_IGNORE_OPERATOR_EQ +%{ +#include "example.h" +%} + +/* This header file is a little tough to handle because it has overloaded + operators and constructors. We're going to try and deal with that here */ + +/* This turns the copy constructor in a function ComplexCopy() that can + be called */ + +%rename(assign) Complex::operator=; +%rename(plus) Complex::operator+; +%rename(minus) Complex::operator-(const Complex &) const; +%rename(uminus) Complex::operator-() const; +%rename(times) Complex::operator*; + +/* Now grab the original header file */ +%include "example.h" + +/* An output method that turns a complex into a short string */ +%extend Complex { + char *toString() { + static char temp[512]; + sprintf(temp,"(%g,%g)", $self->re(), $self->im()); + return temp; + } + static Complex* copy(const Complex& c) { + return new Complex(c); + } +}; + diff --git a/Examples/javascript/operator/example.js b/Examples/javascript/operator/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/operator/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/operator/runme.js b/Examples/javascript/operator/runme.js new file mode 100644 index 000000000..a700918d6 --- /dev/null +++ b/Examples/javascript/operator/runme.js @@ -0,0 +1,25 @@ +var example = require("./example"); + +a = new example.Complex(2,3); +b = new example.Complex(-5,10); + +console.log ("a =" + a); +console.log ("b =" + b); + +c = a.plus(b); + +console.log("c =" + c); +console.log("a*b =" + a.times(b)); +console.log("a-c =" + a.minus(c)); + +e = example.Complex.copy(a.minus(c)); +console.log("e =" + e); + +// Big expression +f = a.plus(b).times(c.plus(b.times(e))).plus(a.uminus()); +console.log("f =" + f); + + + + + diff --git a/Examples/javascript/overload/Makefile b/Examples/javascript/overload/Makefile new file mode 100755 index 000000000..a2570636e --- /dev/null +++ b/Examples/javascript/overload/Makefile @@ -0,0 +1,3 @@ +SRCS = + +include ../js_example.mk diff --git a/Examples/javascript/overload/binding.gyp b/Examples/javascript/overload/binding.gyp new file mode 100644 index 000000000..69af46b22 --- /dev/null +++ b/Examples/javascript/overload/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/overload/example.h b/Examples/javascript/overload/example.h new file mode 100644 index 000000000..2f112f1e1 --- /dev/null +++ b/Examples/javascript/overload/example.h @@ -0,0 +1,28 @@ +#include + +void f() { + std::cout << "Called f()." << std::endl; +} + +void f(int val) { + std::cout << "Called f(int)." << std::endl; +} +void f(int val1, int val2) { + std::cout << "Called f(int, int)." << std::endl; +} + +void f(const char* s) { + std::cout << "Called f(const char*)." << std::endl; +} + +void f(bool val) { + std::cout << "Called f(bool)." << std::endl; +} + +void f(long val) { + std::cout << "Called f(long)." << std::endl; +} + +void f(double val) { + std::cout << "Called f(double)." << std::endl; +} diff --git a/Examples/javascript/overload/example.i b/Examples/javascript/overload/example.i new file mode 100644 index 000000000..b86689f8a --- /dev/null +++ b/Examples/javascript/overload/example.i @@ -0,0 +1,16 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +/* + Note: overloading is implemented in a sloppy way currently + i.e., only the number of arguments is taken into conideration + for dispatching. + To solve the problem one has to rename such conflicting methods. +*/ +%rename(f_double) f(double val); + +%include "example.h" diff --git a/Examples/javascript/overload/example.js b/Examples/javascript/overload/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/overload/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/overload/runme.js b/Examples/javascript/overload/runme.js new file mode 100644 index 000000000..1e6c861a6 --- /dev/null +++ b/Examples/javascript/overload/runme.js @@ -0,0 +1,9 @@ +var example = require("./example"); + +example.f(); +example.f(1); +example.f(1, 2); +example.f("bla"); +example.f(false); +example.f(11111111111); +example.f_double(1.0); diff --git a/Examples/javascript/pointer/Makefile b/Examples/javascript/pointer/Makefile new file mode 100755 index 000000000..b0934786a --- /dev/null +++ b/Examples/javascript/pointer/Makefile @@ -0,0 +1,3 @@ +SRCS = example.cxx + +include ../js_example.mk diff --git a/Examples/javascript/pointer/binding.gyp b/Examples/javascript/pointer/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/pointer/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/pointer/example.cxx b/Examples/javascript/pointer/example.cxx new file mode 100755 index 000000000..8762329fe --- /dev/null +++ b/Examples/javascript/pointer/example.cxx @@ -0,0 +1,16 @@ +/* File : example.c */ + +void add(int *x, int *y, int *result) { + *result = *x + *y; +} + +void subtract(int *x, int *y, int *result) { + *result = *x - *y; +} + +int divide(int n, int d, int *r) { + int q; + q = n/d; + *r = n - q*d; + return q; +} diff --git a/Examples/javascript/pointer/example.i b/Examples/javascript/pointer/example.i new file mode 100755 index 000000000..38c67d7d2 --- /dev/null +++ b/Examples/javascript/pointer/example.i @@ -0,0 +1,30 @@ +/* File : example.i */ +%module example + +%{ +extern void add(int *, int *, int *); +extern void subtract(int *, int *, int *); +extern int divide(int, int, int *); +%} + +/* This example illustrates a couple of different techniques + for manipulating C pointers */ + +/* First we'll use the pointer library */ +extern void add(int *x, int *y, int *result); +%include cpointer.i +%pointer_functions(int, intp); + +/* Next we'll use some typemaps */ + +%include typemaps.i +extern void subtract(int *INPUT, int *INPUT, int *OUTPUT); + +/* Next we'll use typemaps and the %apply directive */ + +%apply int *OUTPUT { int *r }; +extern int divide(int n, int d, int *r); + + + + diff --git a/Examples/javascript/pointer/example.js b/Examples/javascript/pointer/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/pointer/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/pointer/runme.js b/Examples/javascript/pointer/runme.js new file mode 100755 index 000000000..7f1e51c9e --- /dev/null +++ b/Examples/javascript/pointer/runme.js @@ -0,0 +1,35 @@ +var example = require("./example"); + +// First create some objects using the pointer library. +console.log("Testing the pointer library\n"); +a = example.new_intp(); +b = example.new_intp(); +c = example.new_intp(); + +example.intp_assign(a,37); +example.intp_assign(b,42); + +console.log(" a = " + example.intp_value(a) + "\n"); +console.log(" b = " + example.intp_value(b) + "\n"); +console.log(" c = " + example.intp_value(c) + "\n"); + +//// Call the add() function with some pointers +example.add(a, b, c); + +// +//// Now get the result +r = example.intp_value(c); +console.log(" 37 + 42 = " + r + "\n"); + +// Clean up the pointers +example.delete_intp(a); +example.delete_intp(b); +example.delete_intp(c); + +//// Now try the typemap library +//// This should be much easier. Now how it is no longer +//// necessary to manufacture pointers. +//"OUTPUT" Mapping is not supported +//console.log("Trying the typemap library"); +//r = example.subtract(37,42); +//console.log("37 - 42 =" + r); diff --git a/Examples/javascript/pointer/typemaps.i b/Examples/javascript/pointer/typemaps.i new file mode 100644 index 000000000..e69de29bb diff --git a/Examples/javascript/reference/Makefile b/Examples/javascript/reference/Makefile new file mode 100755 index 000000000..b0934786a --- /dev/null +++ b/Examples/javascript/reference/Makefile @@ -0,0 +1,3 @@ +SRCS = example.cxx + +include ../js_example.mk diff --git a/Examples/javascript/reference/binding.gyp b/Examples/javascript/reference/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/reference/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/reference/example.cxx b/Examples/javascript/reference/example.cxx new file mode 100755 index 000000000..8a513bf49 --- /dev/null +++ b/Examples/javascript/reference/example.cxx @@ -0,0 +1,46 @@ +/* File : example.cxx */ + +/* Deal with Microsoft's attempt at deprecating C standard runtime functions */ +#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +# define _CRT_SECURE_NO_DEPRECATE +#endif + +#include "example.h" +#include +#include + +Vector operator+(const Vector &a, const Vector &b) { + Vector r; + r.x = a.x + b.x; + r.y = a.y + b.y; + r.z = a.z + b.z; + return r; +} + +char *Vector::print() { + static char temp[512]; + sprintf(temp,"Vector %p (%g,%g,%g)", this, x,y,z); + return temp; +} + +VectorArray::VectorArray(int size) { + items = new Vector[size]; + maxsize = size; +} + +VectorArray::~VectorArray() { + delete [] items; +} + +Vector &VectorArray::operator[](int index) { + if ((index < 0) || (index >= maxsize)) { + printf("Panic! Array index out of bounds.\n"); + exit(1); + } + return items[index]; +} + +int VectorArray::size() { + return maxsize; +} + diff --git a/Examples/javascript/reference/example.h b/Examples/javascript/reference/example.h new file mode 100755 index 000000000..4915adb1b --- /dev/null +++ b/Examples/javascript/reference/example.h @@ -0,0 +1,26 @@ +/* File : example.h */ + +class Vector { +private: + double x,y,z; +public: + Vector() : x(0), y(0), z(0) { }; + Vector(double x, double y, double z) : x(x), y(y), z(z) { }; + friend Vector operator+(const Vector &a, const Vector &b); + char *print(); +}; + +class VectorArray { +private: + Vector *items; + int maxsize; +public: + VectorArray(int maxsize); + ~VectorArray(); + Vector &operator[](int); + int size(); +}; + + + + diff --git a/Examples/javascript/reference/example.i b/Examples/javascript/reference/example.i new file mode 100755 index 000000000..1cf19c82c --- /dev/null +++ b/Examples/javascript/reference/example.i @@ -0,0 +1,42 @@ +/* File : example.i */ + +/* This file has a few "typical" uses of C++ references. */ + +%module example + +%{ +#include "example.h" +%} + +class Vector { +public: + Vector(double x, double y, double z); + ~Vector(); + char *print(); +}; + +/* This helper function calls an overloaded operator */ +%inline %{ +Vector addv(Vector &a, Vector &b) { + return a+b; +} +%} + +/* Wrapper around an array of vectors class */ + +class VectorArray { +public: + VectorArray(int maxsize); + ~VectorArray(); + int size(); + + /* This wrapper provides an alternative to the [] operator */ + %extend { + Vector &get(int index) { + return (*$self)[index]; + } + void set(int index, Vector &a) { + (*$self)[index] = a; + } + } +}; diff --git a/Examples/javascript/reference/example.js b/Examples/javascript/reference/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/reference/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/reference/runme.js b/Examples/javascript/reference/runme.js new file mode 100755 index 000000000..935d2b948 --- /dev/null +++ b/Examples/javascript/reference/runme.js @@ -0,0 +1,67 @@ +// This file illustrates the manipulation of C++ references in Javascript. +var example = require("./example"); + +// ----- Object creation ----- + +console.log("Creating some objects:\n"); +a = new example.Vector(3,4,5); +b = new example.Vector(10,11,12); + +console.log(" created" + a.print()); +console.log(" created" + b.print()); + +// ----- Call an overloaded operator ----- + +// This calls the wrapper we placed around operator+(const Vector &a, const Vector &) +// It returns a new allocated object. + +console.log("Adding a+b\n"); +c = example.addv(a, b); +console.log("a+b = " + c.print()); + + +// TODO: Note: Unless we free the result, a memory leak will occur +//delete_Vector(c); + +// ----- Create a vector array ----- + +// Note: Using the high-level interface here +console.log("Creating an array of vectors\n"); +va = new example.VectorArray(10); +console.log("va = " + va + "\n"); + +// ----- Set some values in the array ----- + +// These operators copy the value of a and b to the vector array +va.set(0,a); +va.set(1,b); + +// This will work, but it will cause a memory leak! +va.set(2,example.addv(a,b)); + +// The non-leaky way to do it +//c = addv(a,b); +//va.set(3,c); +//delete_Vector(c); + +// Get some values from the array + +console.log("Getting some array values\n"); +for (i = 0; i < 5; i++) { + temp = va.get(i); + console.log(i,temp.print()); +} + +// Watch under resource meter to check on this +console.log("Making sure we don't leak memory.\n"); +for (i = 0; i < 1000000; i++) { + c = va.get(i % 10); +} +//---------TODO--------- +//----- Clean up ----- +//console.log("Cleaning up\n"); + +//example.delete_VectorArray(va); +//example.delete_Vector(a); +//example.delete_Vector(b); + diff --git a/Examples/javascript/reference/swig_gdb.log b/Examples/javascript/reference/swig_gdb.log new file mode 100644 index 000000000..57bca0306 --- /dev/null +++ b/Examples/javascript/reference/swig_gdb.log @@ -0,0 +1,22 @@ +Loaded swig printers +SwigStringPrinter: Could not convert const char* to string +SwigListIterator: Construction failed. + Cannot access memory at address 0x7d894828ec834853. +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigListIterator: Construction failed. + Cannot access memory at address 0x7d894828ec834853. +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not dereference struct String* +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not dereference struct String* +SwigStringPrinter: Could not dereference struct String* +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not dereference struct String* +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not dereference struct String* +SwigStringPrinter: Could not dereference struct String* diff --git a/Examples/javascript/simple/Makefile b/Examples/javascript/simple/Makefile new file mode 100755 index 000000000..b0934786a --- /dev/null +++ b/Examples/javascript/simple/Makefile @@ -0,0 +1,3 @@ +SRCS = example.cxx + +include ../js_example.mk diff --git a/Examples/javascript/simple/binding.gyp b/Examples/javascript/simple/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/simple/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/simple/example.cxx b/Examples/javascript/simple/example.cxx new file mode 100644 index 000000000..1c2af789c --- /dev/null +++ b/Examples/javascript/simple/example.cxx @@ -0,0 +1,18 @@ +/* File : example.c */ + +/* A global variable */ +double Foo = 3.0; + +/* Compute the greatest common divisor of positive integers */ +int gcd(int x, int y) { + int g; + g = y; + while (x > 0) { + g = x; + x = y % x; + y = g; + } + return g; +} + + diff --git a/Examples/javascript/simple/example.i b/Examples/javascript/simple/example.i new file mode 100644 index 000000000..24093b9bf --- /dev/null +++ b/Examples/javascript/simple/example.i @@ -0,0 +1,7 @@ +/* File : example.i */ +%module example + +%inline %{ +extern int gcd(int x, int y); +extern double Foo; +%} diff --git a/Examples/javascript/simple/example.js b/Examples/javascript/simple/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/simple/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/simple/runme.js b/Examples/javascript/simple/runme.js new file mode 100755 index 000000000..be2c18669 --- /dev/null +++ b/Examples/javascript/simple/runme.js @@ -0,0 +1,26 @@ +var example = require("./example"); + +/* Call our gcd() function */ + +x = 42; +y = 105; +g = example.gcd(x,y); +console.log("GCD of x and y is=" + g); + +/* Manipulate the Foo global variable */ + +/* Output its current value */ +console.log("Global variable Foo=" + example.Foo); + +/* Change its value */ +example.Foo = 3.1415926; + +/* See if the change took effect */ +console.log("Variable Foo changed to=" + example.Foo); + + + + + + + diff --git a/Examples/javascript/template/Makefile b/Examples/javascript/template/Makefile new file mode 100755 index 000000000..a2570636e --- /dev/null +++ b/Examples/javascript/template/Makefile @@ -0,0 +1,3 @@ +SRCS = + +include ../js_example.mk diff --git a/Examples/javascript/template/binding.gyp b/Examples/javascript/template/binding.gyp new file mode 100644 index 000000000..69af46b22 --- /dev/null +++ b/Examples/javascript/template/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/template/example.h b/Examples/javascript/template/example.h new file mode 100644 index 000000000..7401df650 --- /dev/null +++ b/Examples/javascript/template/example.h @@ -0,0 +1,32 @@ +/* File : example.h */ + +// Some template definitions + +template T max(T a, T b) { return a>b ? a : b; } + +template class vector { + T *v; + int sz; + public: + vector(int _sz) { + v = new T[_sz]; + sz = _sz; + } + T &get(int index) { + return v[index]; + } + void set(int index, T &val) { + v[index] = val; + } +#ifdef SWIG + %extend { + T getitem(int index) { + return $self->get(index); + } + void setitem(int index, T val) { + $self->set(index,val); + } + } +#endif +}; + diff --git a/Examples/javascript/template/example.i b/Examples/javascript/template/example.i new file mode 100644 index 000000000..8f94c4da1 --- /dev/null +++ b/Examples/javascript/template/example.i @@ -0,0 +1,17 @@ +/* File : example.i */ +%module example + +%{ +#include "example.h" +%} + +/* Let's just grab the original header file here */ +%include "example.h" + +/* Now instantiate some specific template declarations */ + +%template(maxint) max; +%template(maxdouble) max; +%template(vecint) vector; +%template(vecdouble) vector; + diff --git a/Examples/javascript/template/example.js b/Examples/javascript/template/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/template/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/template/runme.js b/Examples/javascript/template/runme.js new file mode 100644 index 000000000..55894dfd5 --- /dev/null +++ b/Examples/javascript/template/runme.js @@ -0,0 +1,30 @@ +var example = require("./example"); + +//Call some templated functions +console.log(example.maxint(3,7)); +console.log(example.maxdouble(3.14,2.18)); + +// Create some class + +iv = new example.vecint(100); +dv = new example.vecdouble(1000); + +for(i=0;i<=100;i++) + iv.setitem(i,2*i); + +for(i=0;i<=1000;i++) + dv.setitem(i, 1.0/(i+1)); + +sum = 0; +for(i=0;i<=100;i++) + sum = sum + iv.getitem(i); + +console.log(sum); + +sum = 0.0; +for(i=0;i<=1000;i++) + sum = sum + dv.getitem(i); +console.log(sum); + +delete iv; +delete dv; diff --git a/Examples/javascript/variables/Makefile b/Examples/javascript/variables/Makefile new file mode 100755 index 000000000..b0934786a --- /dev/null +++ b/Examples/javascript/variables/Makefile @@ -0,0 +1,3 @@ +SRCS = example.cxx + +include ../js_example.mk diff --git a/Examples/javascript/variables/binding.gyp b/Examples/javascript/variables/binding.gyp new file mode 100644 index 000000000..54eebfaa0 --- /dev/null +++ b/Examples/javascript/variables/binding.gyp @@ -0,0 +1,8 @@ +{ + "targets": [ + { + "target_name": "example", + "sources": [ "example.cxx", "example_wrap.cxx" ] + } + ] +} diff --git a/Examples/javascript/variables/example.cxx b/Examples/javascript/variables/example.cxx new file mode 100755 index 000000000..3ad4c2323 --- /dev/null +++ b/Examples/javascript/variables/example.cxx @@ -0,0 +1,96 @@ +/* File : example.c */ + +/* I'm a file containing some C global variables */ + +/* Deal with Microsoft's attempt at deprecating C standard runtime functions */ +#if !defined(SWIG_NO_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +# define _CRT_SECURE_NO_DEPRECATE +#endif + +#include +#include +#include "example.h" + +int ivar = 0; +short svar = 0; +long lvar = 0; +unsigned int uivar = 0; +unsigned short usvar = 0; +unsigned long ulvar = 0; +signed char scvar = 0; +unsigned char ucvar = 0; +char cvar = 0; +float fvar = 0; +double dvar = 0; +char *strvar = 0; +#ifdef __cplusplus // Note: for v8 this must be linkable with g++, without extern cstrvar is mangled +extern const char cstrvar[] = "Goodbye"; +#else +const char cstrvar[] = "Goodbye"; +#endif +const +int *iptrvar = 0; +char name[256] = "Dave"; +char path[256] = "/home/beazley"; + + +/* Global variables involving a structure */ +Point *ptptr = 0; +Point pt = { 10, 20 }; + +/* A variable that we will make read-only in the interface */ +int status = 1; + +/* A debugging function to print out their values */ + +void print_vars() { + printf("ivar = %d\n", ivar); + printf("svar = %d\n", svar); + printf("lvar = %ld\n", lvar); + printf("uivar = %u\n", uivar); + printf("usvar = %u\n", usvar); + printf("ulvar = %lu\n", ulvar); + printf("scvar = %d\n", scvar); + printf("ucvar = %u\n", ucvar); + printf("fvar = %g\n", fvar); + 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("iptrvar = %p\n", iptrvar); + printf("name = %s\n", name); + printf("ptptr = %p (%d, %d)\n", ptptr, ptptr ? ptptr->x : 0, ptptr ? ptptr->y : 0); + printf("pt = (%d, %d)\n", pt.x, pt.y); + printf("status = %d\n", status); +} + +/* A function to create an integer (to test iptrvar) */ + +int *new_int(int value) { + int *ip = (int *) malloc(sizeof(int)); + *ip = value; + return ip; +} + +/* A function to create a point */ + +Point *new_Point(int x, int y) { + Point *p = (Point *) malloc(sizeof(Point)); + p->x = x; + p->y = y; + return p; +} + +char * Point_print(Point *p) { + static char buffer[256]; + if (p) { + sprintf(buffer,"(%d,%d)", p->x,p->y); + } else { + sprintf(buffer,"null"); + } + return buffer; +} + +void pt_print() { + printf("(%d, %d)\n", pt.x, pt.y); +} diff --git a/Examples/javascript/variables/example.h b/Examples/javascript/variables/example.h new file mode 100755 index 000000000..0f7e89594 --- /dev/null +++ b/Examples/javascript/variables/example.h @@ -0,0 +1,6 @@ +/* File: example.h */ + +typedef struct { + int x,y; +} Point; + diff --git a/Examples/javascript/variables/example.i b/Examples/javascript/variables/example.i new file mode 100755 index 000000000..591b871ed --- /dev/null +++ b/Examples/javascript/variables/example.i @@ -0,0 +1,49 @@ +/* File : example.i */ +%module example +%{ +#include "example.h" +%} + +/* Some global variable declarations */ +%inline %{ +extern int ivar; +extern short svar; +extern long lvar; +extern unsigned int uivar; +extern unsigned short usvar; +extern unsigned long ulvar; +extern signed char scvar; +extern unsigned char ucvar; +extern char cvar; +extern float fvar; +extern double dvar; +extern char *strvar; +extern const char cstrvar[]; +extern int *iptrvar; +extern char name[256]; + +extern Point *ptptr; +extern Point pt; +%} + + +/* Some read-only variables */ + +%immutable; + +%inline %{ +extern int status; +extern char path[256]; +%} + +%mutable; + +/* Some helper functions to make it easier to test */ +%inline %{ +extern void print_vars(); +extern int *new_int(int value); +extern Point *new_Point(int x, int y); +extern char *Point_print(Point *p); +extern void pt_print(); +%} + diff --git a/Examples/javascript/variables/example.js b/Examples/javascript/variables/example.js new file mode 100644 index 000000000..79cd3913f --- /dev/null +++ b/Examples/javascript/variables/example.js @@ -0,0 +1 @@ +module.exports = require("./build/Release/example"); diff --git a/Examples/javascript/variables/runme.js b/Examples/javascript/variables/runme.js new file mode 100755 index 000000000..d07861713 --- /dev/null +++ b/Examples/javascript/variables/runme.js @@ -0,0 +1,68 @@ +var example = require("./example"); + +// Try to set the values of some global variables +example.ivar = 42; +example.svar = -31000; +example.lvar = 65537; +example.uivar = 123456; +example.usvar = 61000; +example.ulvar = 654321; +example.scvar = -13; +example.ucvar = 251; +example.cvar = "S"; +example.fvar = 3.14159; +example.dvar = 2.1828; +example.strvar = "Hello World"; +example.iptrvar= example.new_int(37); +example.ptptr = example.new_Point(37,42); +example.name = "Bill"; + +// Now console.log out the values of the variables +console.log("Variables (values console.loged from Python)" + "\n"); +console.log("ivar = " + example.ivar + "\n"); +console.log("svar = " + example.svar + "\n"); +console.log("lvar = " + example.lvar + "\n"); +console.log("uivar = " + example.uivar + "\n"); +console.log("usvar = " + example.usvar + "\n"); +console.log("ulvar = " + example.ulvar + "\n"); +console.log("scvar = " + example.scvar + "\n"); +console.log("ucvar = " + example.ucvar + "\n"); +console.log("fvar = " + example.fvar + "\n"); +console.log("dvar = " + example.dvar + "\n"); +console.log("cvar = " + example.cvar + "\n"); +console.log("strvar = " + example.strvar+ "\n"); +console.log("cstrvar = " + example.cstrvar+ "\n"); +console.log("iptrvar = " + example.iptrvar+ "\n"); +console.log("name = " + example.name + "\n"); +console.log("ptptr = " + example.ptptr + ": " + example.Point_print(example.ptptr) + "\n"); +console.log("pt = " + example.pt + ": " + example.Point_print(example.pt) + "\n"); + + +console.log("\nVariables (values console.loged from C)"); + +example.print_vars(); + +console.log("\nNow I'm going to try and modify some read only variables"); + +console.log("Tring to set 'path'"); +try{ + example.path = "Whoa!"; + console.log("Hey, what's going on?!?! This shouldn't work"); +} +catch(e){ + console.log("Good."); +} + +console.log("Trying to set 'status'"); +try{ + example.status = 0; + console.log("Hey, what's going on?!?! This shouldn't work"); +} catch(e){ + console.log("Good."); +} + +console.log("\nI'm going to try and update a structure variable.\n"); +example.pt = example.ptptr; +console.log("The new value is: "); +example.pt_print(); +console.log("You should see the value: " + example.Point_print(example.ptptr)); diff --git a/Examples/javascript/variables/swig_gdb.log b/Examples/javascript/variables/swig_gdb.log new file mode 100644 index 000000000..2fe437110 --- /dev/null +++ b/Examples/javascript/variables/swig_gdb.log @@ -0,0 +1,9 @@ +Loaded swig printers +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string +SwigStringPrinter: Could not convert const char* to string diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index b9239315a..14f13bed8 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -98,6 +98,7 @@ C_TEST_BROKEN += \ tag_no_clash_with_variable # C++ test cases. (Can be run individually using: make testcase.cpptest) +ifndef SKIP_CPP_CASES CPP_TEST_CASES += \ abstract_access \ abstract_inherit \ @@ -489,6 +490,7 @@ CPP_TEST_CASES += \ voidtest \ wallkw \ wrapmacro +endif # C++11 test cases. CPP11_TEST_CASES = \ @@ -562,6 +564,7 @@ CPP_TEST_CASES += $(CPP11_TEST_CASES) endif # C test cases. (Can be run individually using: make testcase.ctest) +ifndef SKIP_C_CASES C_TEST_CASES += \ arrays \ bom_utf8 \ @@ -612,9 +615,10 @@ C_TEST_CASES += \ typemap_subst \ union_parameter \ unions - +endif # Multi-module C++ test cases . (Can be run individually using make testcase.multicpptest) +ifndef SKIP_MULTI_CPP_CASES MULTI_CPP_TEST_CASES += \ clientdata_prop \ imports \ @@ -623,6 +627,7 @@ MULTI_CPP_TEST_CASES += \ mod \ template_typedef_import \ multi_import +endif # Custom tests - tests with additional commandline options wallkw.cpptest: SWIGOPT += -Wallkw diff --git a/Examples/test-suite/constructor_copy.i b/Examples/test-suite/constructor_copy.i index bfbd706f4..8e92e7840 100644 --- a/Examples/test-suite/constructor_copy.i +++ b/Examples/test-suite/constructor_copy.i @@ -73,7 +73,7 @@ public: %include "std_vector.i" -#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGPYTHON) || defined(SWIGR) || defined(SWIGOCTAVE) || defined(SWIGRUBY) +#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGPYTHON) || defined(SWIGR) || defined(SWIGOCTAVE) || defined(SWIGRUBY) || defined(SWIGJAVASCRIPT) #define SWIG_GOOD_VECTOR %ignore std::vector::vector(size_type); %ignore std::vector::resize(size_type); diff --git a/Examples/test-suite/director_nspace.i b/Examples/test-suite/director_nspace.i index fdea75e2f..f24227c68 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) || defined(SWIGLUA) +#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGD) || defined(SWIGLUA) || defined(SWIGJAVASCRIPT) %nspace TopLevel::Bar::Foo; %nspace TopLevel::Bar::FooBar; #else diff --git a/Examples/test-suite/infinity.i b/Examples/test-suite/infinity.i new file mode 100644 index 000000000..41741eb94 --- /dev/null +++ b/Examples/test-suite/infinity.i @@ -0,0 +1,48 @@ +%module infinity + +#include + +/* C99 defines INFINITY + Because INFINITY may be defined by compiler built-ins, we can't use #define. + Instead, expose the variable MYINFINITY and then use %rename to make it INFINITY in the scripting language. +*/ +%rename(INFINITY) MYINFINITY; + + +%inline %{ +#include + +/* C99 math.h defines INFINITY. If not available, this is the fallback. */ +#ifndef INFINITY + #ifdef _MSC_VER + union MSVC_EVIL_FLOAT_HACK + { + unsigned __int8 Bytes[4]; + float Value; + }; + static union MSVC_EVIL_FLOAT_HACK INFINITY_HACK = {{0x00, 0x00, 0x80, 0x7F}}; + #define INFINITY (INFINITY_HACK.Value) + #endif + + #ifdef __GNUC__ + #define INFINITY (__builtin_inf()) + #elif defined(__clang__) + #if __has_builtin(__builtin_inf) + #define INFINITY (__builtin_inf()) + #endif + #endif + + #ifndef INFINITY + #define INFINITY (1e1000) + #endif +#endif + +/* This will allow us to bind the real INFINITY value through SWIG via MYINFINITY. Use %rename to fix the name. */ +const double MYINFINITY = INFINITY; + +/* Use of float is intentional because the original bug was in the float conversion due to overflow checking. */ +float use_infinity(float inf_val) +{ + return inf_val; +} +%} diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in new file mode 100755 index 000000000..49652f0bd --- /dev/null +++ b/Examples/test-suite/javascript/Makefile.in @@ -0,0 +1,181 @@ +####################################################################### +# Makefile for javascript test-suite +####################################################################### + +LANGUAGE = javascript +SCRIPTSUFFIX = _runme.js +srcdir = @srcdir@ +top_srcdir = @top_srcdir@ +top_builddir = @top_builddir@ +SWIG = $(top_builddir)/preinst_swig + +ifneq (, $(ENGINE)) + JSENGINE=$(ENGINE) +else + JSENGINE=node +endif + +# Note: the javascript generator is not ready yet for the real game. +# To be able keep the behavior continously tested that is expected to work already +# we have a 'light' version of the test-suite +# This will be removed and replaced by a list of 'BROKEN_TEST_CASES' when +# the number gets smaller (currently we have about 65 broken tests for JSC, and 85 for V8) + +ifneq (,$(SMOKE)) + +C_TEST_CASES = \ + preproc \ + preproc_include + +CPP_TEST_CASES = \ + abstract_access \ + abstract_typedef \ + abstract_typedef2 \ + abstract_virtual \ + arrays_global \ + array_member \ + char_binary \ + class_ignore \ + class_scope_weird \ + complextest \ + constover \ + constructor_copy \ + cpp_enum \ + cpp_namespace \ + cpp_static \ + enum_template \ + namespace_virtual_method \ + nspace \ + nspace_extend \ + overload_copy \ + rename_simple \ + rename_scope \ + ret_by_value \ + struct_value \ + template_static \ + typedef_class \ + typedef_inherit \ + typedef_scope \ + typemap_arrays \ + typemap_delete \ + typemap_namespace \ + typemap_ns_using \ + using1 \ + using2 \ + javascript_unicode + +SKIP_CPP_CASES = @SKIP_CPP_CASES@ +SKIP_C_CASES = @SKIP_C_CASES@ +SKIP_CPP_STD_CASES = @SKIP_CPP_STD_CASES@ +SKIP_MULTI_CPP_CASES = @SKIP_MULTI_CPP_CASES@ + +endif + +include $(srcdir)/../common.mk + +_setup = \ + if [ -f $(srcdir)/$(SCRIPTPREFIX)$*$(SCRIPTSUFFIX) ]; then \ + echo "$(ACTION)ing testcase $* (with run test) under javascript ($(JSENGINE))" ; \ + else \ + echo "$(ACTION)ing testcase $* under javascript ($(JSENGINE))" ; \ + fi; + +ifneq (jsc,$(ENGINE)) + + # This test can not be run with v8 as it uses v8 API incompatible output typemaps + typemap_variables.cpptest: + echo "skipping testcase typemap_variables under javascript ($(JSENGINE))." + + # with v8 we have to generate C++ wrappers only + # these tests did raise warnings which are ignored + nested.ctest: SWIGOPT += -w312,-325 + nested_structs.ctest: SWIGOPT += -w312,-325 + unions.ctest: SWIGOPT += -w312,-325 + +endif + +ifeq (node,$(JSENGINE)) + + SWIGOPT += -v8 -DBUILDING_NODE_EXTENSION=1 + + # shut up some warnings + # contract macro has an empty 'else' at the end... + aggregate.cpptest: GYP_CFLAGS = \"-Wno-empty-body\" + contract.cpptest: GYP_CFLAGS = \"-Wno-empty-body\" + + # dunno... ignoring generously + apply_signed_char.cpptest: GYP_CFLAGS = \"-Wno-ignored-qualifiers\" + constant_pointers.cpptest: GYP_CFLAGS = \"-Wno-ignored-qualifiers\" + enum_thorough.cpptest: GYP_CFLAGS = \"-Wno-ignored-qualifiers\" + + __setup = \ + sh ./setup_test.sh $* $(GYP_CFLAGS); \ + $(SWIG) -c++ -javascript $(SWIGOPT) ../$*.i; + + nodejs_swig_and_compile = \ + node-gyp --loglevel=silent --directory $* configure build 1>>/dev/null + + run_testcase = \ + if [ -f $(srcdir)/$*$(SCRIPTSUFFIX) ]; then \ + node $(srcdir)/$*$(SCRIPTSUFFIX); \ + fi + + %.cpptest: + $(_setup) + $(__setup) + $(nodejs_swig_and_compile) + $(run_testcase) + + %.ctest: + $(_setup) + $(__setup) + $(nodejs_swig_and_compile) + $(run_testcase) + + %.multicpptest: + $(_setup) + +else + + SWIGOPT += -$(JSENGINE) + + run_testcase = \ + if [ -f $(srcdir)/$*$(SCRIPTSUFFIX) ]; then \ + $(top_srcdir)/Tools/javascript/javascript -$(JSENGINE) $(srcdir)/$*$(SCRIPTSUFFIX); \ + fi + + %.cpptest: + $(_setup) + +$(swig_and_compile_cpp) + $(run_testcase) + + %.multicpptest: + $(_setup) + +$(swig_and_compile_multi_cpp) + $(run_testcase) + +endif + +ifeq (v8,$(ENGINE)) + %.ctest: + $(_setup) + +$(swig_and_compile_cpp) + $(run_testcase) + +endif + +ifeq (jsc,$(ENGINE)) + %.ctest: + $(_setup) + +$(swig_and_compile_c) + $(run_testcase) +endif + +%.clean: + rm -rf $* + +clean: + rm -f *_wrap.cxx + rm -f *_wrap.c + rm -f *.so + rm -f *.o diff --git a/Examples/test-suite/javascript/abstract_access_runme.js b/Examples/test-suite/javascript/abstract_access_runme.js new file mode 100644 index 000000000..8f87d2105 --- /dev/null +++ b/Examples/test-suite/javascript/abstract_access_runme.js @@ -0,0 +1,6 @@ +var abstract_access = require("./abstract_access"); + +var d = new abstract_access.D() +if (d.do_x() != 1) { + throw "Error"; +} diff --git a/Examples/test-suite/javascript/abstract_inherit_runme.js b/Examples/test-suite/javascript/abstract_inherit_runme.js new file mode 100644 index 000000000..3af2eae74 --- /dev/null +++ b/Examples/test-suite/javascript/abstract_inherit_runme.js @@ -0,0 +1,40 @@ +var abstract_inherit = require("./abstract_inherit"); + +// Shouldn't be able to instantiate any of these classes +// since none of them implements the pure virtual function +// declared in the base class (Foo). +var Foo = abstract_inherit.Foo; +var Bar = abstract_inherit.Bar; +var Spam = abstract_inherit.Spam; + +var caughtException = false; +try { + new Foo(); +} catch (err) { + caughtException = true; +} +if (!caughtException) { + throw new Error("Foo should be instantiated as it is abstract"); +} + +caughtException = false; +try { + new Bar(); +} catch (err) { + caughtException = true; +} + +if (!caughtException) { + throw new Error("Bar should be instantiated as it is abstract"); +} + +caughtException = false; +try { + new Spam(); +} catch (err) { + caughtException = true; +} + +if (!caughtException) { + throw new Error("Spam should be instantiated as it is abstract"); +} diff --git a/Examples/test-suite/javascript/abstract_typedef2_runme.js b/Examples/test-suite/javascript/abstract_typedef2_runme.js new file mode 100644 index 000000000..c177e49c3 --- /dev/null +++ b/Examples/test-suite/javascript/abstract_typedef2_runme.js @@ -0,0 +1,6 @@ +var abstract_typedef2 = require("./abstract_typedef2"); + +var a = new abstract_typedef2.A_UF(); + +if (a == undefined) + throw "Error"; diff --git a/Examples/test-suite/javascript/abstract_typedef_runme.js b/Examples/test-suite/javascript/abstract_typedef_runme.js new file mode 100644 index 000000000..abcfc581d --- /dev/null +++ b/Examples/test-suite/javascript/abstract_typedef_runme.js @@ -0,0 +1,8 @@ +var abstract_typedef = require("./abstract_typedef"); + +var e = new abstract_typedef.Engine(); +var a = new abstract_typedef.A() + +if (a.write(e) != 1) { + throw "Error"; +} diff --git a/Examples/test-suite/javascript/abstract_virtual_runme.js b/Examples/test-suite/javascript/abstract_virtual_runme.js new file mode 100644 index 000000000..9e2814e41 --- /dev/null +++ b/Examples/test-suite/javascript/abstract_virtual_runme.js @@ -0,0 +1,11 @@ +var abstract_virtual = require("./abstract_virtual"); + +d = new abstract_virtual.D() + +if (d == undefined) + throw "Error"; + +e = new abstract_virtual.E() + +if (e == undefined) + throw "Error"; diff --git a/Examples/test-suite/javascript/array_member_runme.js b/Examples/test-suite/javascript/array_member_runme.js new file mode 100644 index 000000000..8c4ef1da5 --- /dev/null +++ b/Examples/test-suite/javascript/array_member_runme.js @@ -0,0 +1,22 @@ +var array_member = require("./array_member"); + +var f = new array_member.Foo(); +f.data = array_member.global_data; + +for (var i=0; i<8; i++) { + if (array_member.get_value(f.data,i) != array_member.get_value(array_member.global_data,i)) { + throw "Bad array assignment (1)"; + } +} + +for (var i=0; i<8; i++) { + array_member.set_value(f.data,i,-i); +} + +array_member.global_data = f.data; + +for (var i=0; i<8; i++){ + if (array_member.get_value(f.data,i) != array_member.get_value(array_member.global_data,i)) { + throw "Bad array assignment (2)"; + } +} diff --git a/Examples/test-suite/javascript/arrays_global_runme.js b/Examples/test-suite/javascript/arrays_global_runme.js new file mode 100644 index 000000000..fdb365f83 --- /dev/null +++ b/Examples/test-suite/javascript/arrays_global_runme.js @@ -0,0 +1,18 @@ +var arrays_global = require("./arrays_global"); + +arrays_global.array_i = arrays_global.array_const_i; + +arrays_global.BeginString_FIX44a; +arrays_global.BeginString_FIX44b; +arrays_global.BeginString_FIX44c; +arrays_global.BeginString_FIX44d; +arrays_global.BeginString_FIX44d; +arrays_global.BeginString_FIX44b = "12"+'\0'+"45"; +arrays_global.BeginString_FIX44b; +arrays_global.BeginString_FIX44d; +arrays_global.BeginString_FIX44e; +arrays_global.BeginString_FIX44f; + +arrays_global.test_a("hello","hi","chello","chi"); + +arrays_global.test_b("1234567","hi"); diff --git a/Examples/test-suite/javascript/callback_runme.js b/Examples/test-suite/javascript/callback_runme.js new file mode 100644 index 000000000..9b1ef01a3 --- /dev/null +++ b/Examples/test-suite/javascript/callback_runme.js @@ -0,0 +1,30 @@ +var callback = require("./callback"); + +if (callback.foo(2) !== 2) { + throw new Error("Failed."); +} +if (callback.A_bar(2) !== 4) { + throw new Error("Failed."); +} +if (callback.foobar(3, callback.foo) != callback.foo(3)) { + throw new Error("Failed."); +} +if (callback.foobar(3, foo) != callback.foo(3)) { + throw new Error("Failed."); +} +if (callback.foobar(3, callback.A_bar) != callback.A_bar(3)) { + throw new Error("Failed."); +} +if (callback.foobar(3, callback.foof) != callback.foof(3)) { + throw new Error("Failed."); +} +if (callback.foobar_i(3, callback.foo_i) != callback.foo_i(3)) { + throw new Error("Failed."); +} +if (callback.foobar_d(3.5, callback.foo_d) != callback.foo_d(3.5)) { + throw new Error("Failed."); +} +var a = new callback.A(); +if (callback.foobarm(3, a, callback.A.foom_cb_ptr) != a.foom(3)) { + throw new Error("Failed."); +} diff --git a/Examples/test-suite/javascript/char_binary_runme.js b/Examples/test-suite/javascript/char_binary_runme.js new file mode 100644 index 000000000..42abe6060 --- /dev/null +++ b/Examples/test-suite/javascript/char_binary_runme.js @@ -0,0 +1,38 @@ +var char_binary = require("./char_binary"); + +var t = new char_binary.Test(); +if (t.strlen('hile') != 4) { + print(t.strlen('hile')); + throw("bad multi-arg typemap 1"); +} + +if (t.strlen('hil\0') != 4) { + throw("bad multi-arg typemap 2"); +} + +/* + * creating a raw char* + */ +var pc = char_binary.new_pchar(5); +char_binary.pchar_setitem(pc, 0, 'h'); +char_binary.pchar_setitem(pc, 1, 'o'); +char_binary.pchar_setitem(pc, 2, 'l'); +char_binary.pchar_setitem(pc, 3, 'a'); +char_binary.pchar_setitem(pc, 4, 0); + + +if (t.strlen(pc) != 4) { + throw("bad multi-arg typemap (3)"); +} + +char_binary.var_pchar = pc; +if (char_binary.var_pchar != "hola") { + print(char_binary.var_pchar); + throw("bad pointer case (1)"); +} + +char_binary.var_namet = pc; +if (char_binary.var_namet != "hola") { + throw("bad pointer case (2)"); +} +char_binary.delete_pchar(pc); diff --git a/Examples/test-suite/javascript/char_strings_runme.js b/Examples/test-suite/javascript/char_strings_runme.js new file mode 100644 index 000000000..cca50d851 --- /dev/null +++ b/Examples/test-suite/javascript/char_strings_runme.js @@ -0,0 +1,11 @@ +var char_strings = require("./char_strings"); + +var assertIsEqual = function(expected, actual) { + if (expected !== actual) { + throw new Error("Expected "+expected+", was "+actual); + } +}; + +assertIsEqual("hi there", char_strings.CharPingPong("hi there")); +assertIsEqual("hi there", char_strings.CharArrayPingPong("hi there")); +assertIsEqual("hi there", char_strings.CharArrayDimsPingPong("hi there")); diff --git a/Examples/test-suite/javascript/class_ignore_runme.js b/Examples/test-suite/javascript/class_ignore_runme.js new file mode 100644 index 000000000..f0a32a1c4 --- /dev/null +++ b/Examples/test-suite/javascript/class_ignore_runme.js @@ -0,0 +1,6 @@ +var class_ignore = require("./class_ignore"); + +a = new class_ignore.Bar(); + +if (class_ignore.do_blah(a) != "Bar::blah") + throw "Error"; diff --git a/Examples/test-suite/javascript/class_scope_weird_runme.js b/Examples/test-suite/javascript/class_scope_weird_runme.js new file mode 100644 index 000000000..ac745d023 --- /dev/null +++ b/Examples/test-suite/javascript/class_scope_weird_runme.js @@ -0,0 +1,6 @@ +var class_scope_weird = require("./class_scope_weird"); + +f = new class_scope_weird.Foo(); +g = new class_scope_weird.Foo(3); +if (f.bar(3) != 3) + throw RuntimeError; diff --git a/Examples/test-suite/javascript/complextest_runme.js b/Examples/test-suite/javascript/complextest_runme.js new file mode 100644 index 000000000..1fcc97648 --- /dev/null +++ b/Examples/test-suite/javascript/complextest_runme.js @@ -0,0 +1,22 @@ +var complextest = require("./complextest"); + +a = [-1,2]; + +expected = [-1, -2]; + +a_c = complextest.Conj(a); +if (a_c.toString() != expected.toString()) + throw "Error in Conj(a)"; + +a_c_f = complextest.Conjf(a); +if (a_c_f.toString() != expected.toString()) + throw "Error in Conjf(a)"; + +v = new complextest.VectorStdCplx(); +v.add([1,2]); +v.add([2,3]); +v.add([4,3]); +v.add(1); + +// TODO: how to check validity? +complextest.Copy_h(v); diff --git a/Examples/test-suite/javascript/constover_runme.js b/Examples/test-suite/javascript/constover_runme.js new file mode 100644 index 000000000..764d8b328 --- /dev/null +++ b/Examples/test-suite/javascript/constover_runme.js @@ -0,0 +1,33 @@ +var constover = require("./constover"); + +p = constover.test("test"); +if (p != "test") { + throw "test failed!"; +} + +p = constover.test_pconst("test"); +if (p != "test_pconst") { + throw "test_pconst failed!"; +} + +f = new constover.Foo(); + +p = f.test("test"); +if (p != "test") { + throw "member-test failed!"; +} + +p = f.test_pconst("test"); +if (p != "test_pconst") { + throw "member-test_pconst failed!"; +} + +p = f.test_constm("test"); +if (p != "test_constmethod") { + throw "member-test_constm failed!"; +} + +p = f.test_pconstm("test"); +if (p != "test_pconstmethod") { + throw "member-test_pconstm failed!"; +} diff --git a/Examples/test-suite/javascript/constructor_copy_runme.js b/Examples/test-suite/javascript/constructor_copy_runme.js new file mode 100644 index 000000000..39dce52ce --- /dev/null +++ b/Examples/test-suite/javascript/constructor_copy_runme.js @@ -0,0 +1,42 @@ +var constructor_copy = require("./constructor_copy"); + +f1 = new constructor_copy.Foo1(3); +f11 = new constructor_copy.Foo1(f1); + +if (f1.x != f11.x) { + throw "error in ctor copy for Foo1"; +} + +var good = 0; + +f8 = new constructor_copy.Foo8() +try { + f81 = new constructor_copy.Foo8(f8); + good = 0; +} catch (err) { + good = 1; +} + +if (good == 0) { + throw "Error: should not allow calling copy ctor for Foo8"; +} + + +bi = new constructor_copy.Bari(5); +bc = new constructor_copy.Bari(bi); + +if (bi.x != bc.x) { + throw "Error in copy ctor of Bari"; +} + +bd = new constructor_copy.Bard(5); +try { + bc = new constructor_copy.Bard(bd); + good = 0; +} catch (err) { + good = 1; +} + +if (good == 0) { + throw "Error: should not allow calling copy ctor for Bard"; +} diff --git a/Examples/test-suite/javascript/cpp_enum_runme.js b/Examples/test-suite/javascript/cpp_enum_runme.js new file mode 100644 index 000000000..35f7c60ac --- /dev/null +++ b/Examples/test-suite/javascript/cpp_enum_runme.js @@ -0,0 +1,28 @@ +var cpp_enum = require("./cpp_enum"); + +var f = new cpp_enum.Foo() + +if(f.hola != cpp_enum.Hello){ + print(f.hola); + throw "Error"; +} + +f.hola = cpp_enum.Foo.Hi +if(f.hola != cpp_enum.Foo.Hi){ + print(f.hola); + throw "Error"; +} + +f.hola = cpp_enum.Hello + +if(f.hola != cpp_enum.Hello){ + print(f.hola); + throw "Error"; +} + +cpp_enum.Foo.hi = cpp_enum.Hello +if(cpp_enum.Foo.hi != cpp_enum.Hello){ + print(cpp_enum.Foo.hi); + throw "Error"; +} + diff --git a/Examples/test-suite/javascript/cpp_namespace_runme.js b/Examples/test-suite/javascript/cpp_namespace_runme.js new file mode 100644 index 000000000..3bdfef3e9 --- /dev/null +++ b/Examples/test-suite/javascript/cpp_namespace_runme.js @@ -0,0 +1,47 @@ +var cpp_namespace = require("./cpp_namespace"); + +var n = cpp_namespace.fact(4); +if (n != 24){ + throw ("Bad return value error!"); +} +if (cpp_namespace.Foo != 42){ + throw ("Bad variable value error!"); +} + +t = new cpp_namespace.Test(); +if (t.method() != "Test::method"){ + throw ("Bad method return value error!"); +} +if (cpp_namespace.do_method(t) != "Test::method"){ + throw ("Bad return value error!"); +} + +if (cpp_namespace.do_method2(t) != "Test::method"){ + throw ("Bad return value error!"); +} +cpp_namespace.weird("hello", 4); +delete t; + +t2 = new cpp_namespace.Test2(); +t3 = new cpp_namespace.Test3(); +t4 = new cpp_namespace.Test4(); +t5 = new cpp_namespace.Test5(); +if (cpp_namespace.foo3(42) != 42){ + throw ("Bad return value error!"); +} + +if (cpp_namespace.do_method3(t2,40) != "Test2::method"){ + throw ("Bad return value error!"); +} + +if (cpp_namespace.do_method3(t3,40) != "Test3::method"){ + throw ("Bad return value error!"); +} + +if (cpp_namespace.do_method3(t4,40) != "Test4::method"){ + throw ("Bad return value error!"); +} + +if (cpp_namespace.do_method3(t5,40) != "Test5::method"){ + throw ("Bad return value error!"); +} diff --git a/Examples/test-suite/javascript/cpp_static_runme.js b/Examples/test-suite/javascript/cpp_static_runme.js new file mode 100644 index 000000000..2579aeafe --- /dev/null +++ b/Examples/test-suite/javascript/cpp_static_runme.js @@ -0,0 +1,9 @@ +var cpp_static = require("./cpp_static"); + +cpp_static.StaticFunctionTest.static_func(); +cpp_static.StaticFunctionTest.static_func_2(1); +cpp_static.StaticFunctionTest.static_func_3(1,2); +cpp_static.StaticMemberTest.static_int = 10; +if (cpp_static.StaticMemberTest.static_int != 10) +throw "error"; + diff --git a/Examples/test-suite/javascript/director_alternating_runme.js b/Examples/test-suite/javascript/director_alternating_runme.js new file mode 100644 index 000000000..a0411eace --- /dev/null +++ b/Examples/test-suite/javascript/director_alternating_runme.js @@ -0,0 +1,5 @@ +var director_alternating = require("./director_alternating"); + +id = director_alternating.getBar().id(); +if (id != director_alternating.idFromGetBar()) + throw ("Error, Got wrong id: " + str(id)); diff --git a/Examples/test-suite/javascript/disown_runme.js b/Examples/test-suite/javascript/disown_runme.js new file mode 100644 index 000000000..a4a6fd880 --- /dev/null +++ b/Examples/test-suite/javascript/disown_runme.js @@ -0,0 +1,22 @@ +var disown = require("./disown"); + +var a = new disown.A(); +var tmp = a.thisown; +a.thisown = 0 +if (a.thisown) { + throw new Error("Failed."); +} +a.thisown = 1 +if (!a.thisown) { + throw new Error("Failed."); +} +a.thisown = tmp +if (a.thisown != tmp) { + throw new Error("Failed."); +} + +var b = new disown.B(); +b.acquire(a); +if (a.thisown) { + throw new Error("Failed."); +} diff --git a/Examples/test-suite/javascript/dynamic_cast_runme.js b/Examples/test-suite/javascript/dynamic_cast_runme.js new file mode 100644 index 000000000..0029cb0f8 --- /dev/null +++ b/Examples/test-suite/javascript/dynamic_cast_runme.js @@ -0,0 +1,12 @@ +var dynamic_cast = require("./dynamic_cast"); + +var f = new dynamic_cast.Foo(); +var b = new dynamic_cast.Bar(); + +var x = f.blah(); +var y = b.blah(); + +var a = dynamic_cast.do_test(y); +if (a != "Bar::test") { + throw new Error("Failed."); +} diff --git a/Examples/test-suite/javascript/empty_runme.js b/Examples/test-suite/javascript/empty_runme.js new file mode 100644 index 000000000..db06b3902 --- /dev/null +++ b/Examples/test-suite/javascript/empty_runme.js @@ -0,0 +1 @@ +var empty = require("./empty"); \ No newline at end of file diff --git a/Examples/test-suite/javascript/enum_template_runme.js b/Examples/test-suite/javascript/enum_template_runme.js new file mode 100644 index 000000000..20f8c3482 --- /dev/null +++ b/Examples/test-suite/javascript/enum_template_runme.js @@ -0,0 +1,8 @@ +var enum_template = require("./enum_template"); + +if (enum_template.MakeETest() != 1) + throw "RuntimeError"; + +if (enum_template.TakeETest(0) != null) + throw "RuntimeError"; + diff --git a/Examples/test-suite/javascript/infinity_runme.js b/Examples/test-suite/javascript/infinity_runme.js new file mode 100644 index 000000000..1dcf366c6 --- /dev/null +++ b/Examples/test-suite/javascript/infinity_runme.js @@ -0,0 +1,4 @@ +var infinity = require("./infinity"); + +var my_infinity = infinity.INFINTY; +var ret_val = infinity.use_infinity(my_infinity); diff --git a/Examples/test-suite/javascript/javascript_unicode_runme.js b/Examples/test-suite/javascript/javascript_unicode_runme.js new file mode 100644 index 000000000..f5f747aa7 --- /dev/null +++ b/Examples/test-suite/javascript/javascript_unicode_runme.js @@ -0,0 +1,9 @@ +var javascript_unicode = require("./javascript_unicode"); + +var str = "olé"; + +var copy = javascript_unicode.copy_string(str); + +if (str !== copy) { + print("Error: copy is not equal: original="+str+", copy="+copy); +} diff --git a/Examples/test-suite/javascript/namespace_virtual_method_runme.js b/Examples/test-suite/javascript/namespace_virtual_method_runme.js new file mode 100644 index 000000000..24d3bd487 --- /dev/null +++ b/Examples/test-suite/javascript/namespace_virtual_method_runme.js @@ -0,0 +1,3 @@ +var namespace_virtual_method = require("./namespace_virtual_method"); + +x = new namespace_virtual_method.Spam(); diff --git a/Examples/test-suite/javascript/node_template/binding.gyp.in b/Examples/test-suite/javascript/node_template/binding.gyp.in new file mode 100644 index 000000000..209774ae0 --- /dev/null +++ b/Examples/test-suite/javascript/node_template/binding.gyp.in @@ -0,0 +1,30 @@ +{ + "targets": [ + { + "target_name": "$testcase", + "sources":[ "../$testcase_wrap.cxx" ], + "include_dirs": ["../.."], + 'defines': [ + 'BUILDING_NODE_EXTENSION=1', + ], + 'conditions': [ + ['OS=="mac"', + { + 'xcode_settings': { + 'GCC_ENABLE_CPP_RTTI': 'YES', + 'GCC_ENABLE_CPP_EXCEPTIONS' : 'YES' + } + } + ], + ['OS=="linux" or OS=="freebsd" or OS=="openbsd" or OS=="solaris"', + { + 'cflags': [ "-Wno-unused-variable", "-Wno-unused-but-set-variable", "-Wno-unused-but-set-parameter", $cflags], + 'cflags_cc': [ "-Wno-unused-variable", "-Wno-unused-but-set-variable", "-Wno-unused-but-set-parameter", $cflags], + 'cflags!': [ '-fno-exceptions' ], + 'cflags_cc!': [ '-fno-exceptions', '-fno-rtti' ] + } + ] + ], + } + ], +} diff --git a/Examples/test-suite/javascript/node_template/index.js.in b/Examples/test-suite/javascript/node_template/index.js.in new file mode 100644 index 000000000..72330499d --- /dev/null +++ b/Examples/test-suite/javascript/node_template/index.js.in @@ -0,0 +1 @@ +module.exports = require('./build/Release/$testcase'); diff --git a/Examples/test-suite/javascript/nspace_extend_runme.js b/Examples/test-suite/javascript/nspace_extend_runme.js new file mode 100644 index 000000000..ab81c19d3 --- /dev/null +++ b/Examples/test-suite/javascript/nspace_extend_runme.js @@ -0,0 +1,27 @@ +var nspace_extend = require("./nspace_extend"); + +// constructors and destructors +var color1 = new nspace_extend.Outer.Inner1.Color(); +var color = new nspace_extend.Outer.Inner1.Color(color1); +delete color1; + +// class methods +color.colorInstanceMethod(20.0); +nspace_extend.Outer.Inner1.Color.colorStaticMethod(20.0); +var created = nspace_extend.Outer.Inner1.Color.create(); + + +// constructors and destructors +var color2 = new nspace_extend.Outer.Inner2.Color(); +color = new nspace_extend.Outer.Inner2.Color(color2); +delete color2; + +// class methods +color.colorInstanceMethod(20.0); +nspace_extend.Outer.Inner2.Color.colorStaticMethod(20.0); +created = nspace_extend.Outer.Inner2.Color.create(); + +// Same class different namespaces +var col1 = new nspace_extend.Outer.Inner1.Color(); +var col2 = nspace_extend.Outer.Inner2.Color.create(); +col2.colors(col1, col1, col2, col2, col2); diff --git a/Examples/test-suite/javascript/nspace_runme.js b/Examples/test-suite/javascript/nspace_runme.js new file mode 100644 index 000000000..929a6b21d --- /dev/null +++ b/Examples/test-suite/javascript/nspace_runme.js @@ -0,0 +1,77 @@ +var nspace = require("./nspace"); + +var color1 = new nspace.Outer.Inner1.Color(); +var color = new nspace.Outer.Inner1.Color(color1); +delete color1; + +// class methods +color.colorInstanceMethod(20.0); +nspace.Outer.Inner1.Color.colorStaticMethod(20.0); +var created = nspace.Outer.Inner1.Color.create(); + +// class enums +var someClass = new nspace.Outer.SomeClass(); +var channel = someClass.GetInner1ColorChannel(); +if (channel != nspace.Outer.Inner1.Color.Transmission) { + throw new Error("Failed."); +} + +// class anonymous enums +var val1 = nspace.Outer.Inner1.Color.ColorEnumVal1; +var val2 = nspace.Outer.Inner1.Color.ColorEnumVal2; +if (val1 !== 0 || val2 !== 0x22) { + throw new Error("Failed."); +} + +// instance member variables +color.instanceMemberVariable = 123; +if (color.instanceMemberVariable !== 123) { + throw new Error("Failed."); +} + +// static member variables +nspace.Outer.Inner1.Color.staticMemberVariable = 789; +if (nspace.Outer.Inner1.Color.staticMemberVariable !== 789) { + throw new Error("Failed."); +} + +if (nspace.Outer.Inner1.Color.staticConstMemberVariable !== 222) { + throw new Error("Failed."); +} + +if (nspace.Outer.Inner1.Color.staticConstEnumMemberVariable !== nspace.Outer.Inner1.Color.Transmission) { + throw new Error("Failed."); +} + +// Same class different namespaces +var col1 = new nspace.Outer.Inner1.Color(); +var col2 = nspace.Outer.Inner2.Color.create(); +col2.colors(col1, col1, col2, col2, col2); + +// TODO: why isn't it scoped in the namespace??? +nspace.namespaceFunction(color); +nspace.Outer.Inner1.namespaceVar = 111; +if (nspace.Outer.Inner1.namespaceVar !== 111) { + throw new Error("Failed."); +} + +// global enums +var outerChannel1 = someClass.GetInner1Channel(); +if (outerChannel1 != nspace.Outer.Inner1.Transmission1) { + throw new Error("Failed."); +} + +var outerChannel2 = someClass.GetInner2Channel(); +if (outerChannel2 !== nspace.Outer.Inner2.Transmission2) { + throw new Error("Failed."); +} + +// turn feature off / ignoring +var ns = new nspace.Outer.namespce(); +var nons = new nspace.NoNSpacePlease(); + +// Derived class +var blue3 = new nspace.Outer.Inner3.Blue(); +blue3.blueInstanceMethod(); +var blue4 = new nspace.Outer.Inner4.Blue(); +blue4.blueInstanceMethod(); diff --git a/Examples/test-suite/javascript/overload_copy_runme.js b/Examples/test-suite/javascript/overload_copy_runme.js new file mode 100644 index 000000000..1039ffda1 --- /dev/null +++ b/Examples/test-suite/javascript/overload_copy_runme.js @@ -0,0 +1,4 @@ +var overload_copy = require("./overload_copy"); + +f = new overload_copy.Foo(); +g = new overload_copy.Foo(f); diff --git a/Examples/test-suite/javascript/preproc_include_runme.js b/Examples/test-suite/javascript/preproc_include_runme.js new file mode 100644 index 000000000..4b827fbcc --- /dev/null +++ b/Examples/test-suite/javascript/preproc_include_runme.js @@ -0,0 +1,23 @@ +var preproc_include = require("./preproc_include"); + +if (preproc_include.multiply10(10) != 100) + throw "RuntimeError"; + +if (preproc_include.multiply20(10) != 200) + throw "RuntimeError"; + +if (preproc_include.multiply30(10) != 300) + throw "RuntimeError"; + +if (preproc_include.multiply40(10) != 400) + throw "RuntimeError"; + +if (preproc_include.multiply50(10) != 500) + throw "RuntimeError"; + +if (preproc_include.multiply60(10) != 600) + throw "RuntimeError"; + +if (preproc_include.multiply70(10) != 700) + throw "RuntimeError"; + diff --git a/Examples/test-suite/javascript/preproc_runme.js b/Examples/test-suite/javascript/preproc_runme.js new file mode 100644 index 000000000..669f9d1f0 --- /dev/null +++ b/Examples/test-suite/javascript/preproc_runme.js @@ -0,0 +1,14 @@ +var preproc = require("./preproc"); + +if (preproc.endif != 1) + throw "RuntimeError"; + +if (preproc.define != 1) + throw "RuntimeError"; + +if (preproc.defined != 1) + throw "RuntimeError"; + +if (2*preproc.one != preproc.two) + throw "RuntimeError"; + diff --git a/Examples/test-suite/javascript/rename1_runme.js b/Examples/test-suite/javascript/rename1_runme.js new file mode 100644 index 000000000..8374e6a89 --- /dev/null +++ b/Examples/test-suite/javascript/rename1_runme.js @@ -0,0 +1,68 @@ +var rename = require("./rename1"); + +function part1() { + var xyz = new rename.XYZInt(); + notxyz = new rename.NotXYZInt(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother2(); + xyz.opT2(); + xyz.tMethod2(0); + xyz.tMethodNotXYZ2(notxyz); + xyz.opNotXYZ2(); + xyz.opXYZ2(); +} + +function part2() { + var xyz = new rename.XYZDouble(); + var notxyz = new rename.NotXYZDouble(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother1(); + xyz.opT1(); + xyz.tMethod1(0); + xyz.tMethodNotXYZ1(notxyz); + xyz.opNotXYZ1(); + xyz.opXYZ1(); +} + +function part3(){ + var xyz = new rename.XYZKlass(); + var notxyz = new rename.NotXYZKlass(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother3(); + xyz.opT3(); + xyz.tMethod3(new rename.Klass()); + xyz.tMethodNotXYZ3(notxyz); + xyz.opNotXYZ3(); + xyz.opXYZ3(); +} + +function part4() { + var xyz = new rename.XYZEnu(); + var notxyz = new rename.NotXYZEnu(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother4(); + xyz.opT4(); + xyz.tMethod4(rename.En1); + xyz.tMethodNotXYZ4(notxyz); + xyz.opNotXYZ4(); + xyz.opXYZ4(); +} + +function part5() { + var abc = new rename.ABC(); + abc.methodABC(abc); + var k = new rename.Klass(); + abc.methodKlass(k); + var a = abc.opABC(); + k = abc.opKlass(); +} + +part1(); +part2(); +part3(); +part4(); +part5(); diff --git a/Examples/test-suite/javascript/rename2_runme.js b/Examples/test-suite/javascript/rename2_runme.js new file mode 100644 index 000000000..bc6a95a59 --- /dev/null +++ b/Examples/test-suite/javascript/rename2_runme.js @@ -0,0 +1,68 @@ +var rename = require("./rename2"); + +function part1() { + var xyz = new rename.XYZInt(); + notxyz = new rename.NotXYZInt(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother2(); + xyz.opT2(); + xyz.tMethod2(0); + xyz.tMethodNotXYZ2(notxyz); + xyz.opNotXYZ2(); + xyz.opXYZ2(); +} + +function part2() { + var xyz = new rename.XYZDouble(); + var notxyz = new rename.NotXYZDouble(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother1(); + xyz.opT1(); + xyz.tMethod1(0); + xyz.tMethodNotXYZ1(notxyz); + xyz.opNotXYZ1(); + xyz.opXYZ1(); +} + +function part3(){ + var xyz = new rename.XYZKlass(); + var notxyz = new rename.NotXYZKlass(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother3(); + xyz.opT3(); + xyz.tMethod3(new rename.Klass()); + xyz.tMethodNotXYZ3(notxyz); + xyz.opNotXYZ3(); + xyz.opXYZ3(); +} + +function part4() { + var xyz = new rename.XYZEnu(); + var notxyz = new rename.NotXYZEnu(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother4(); + xyz.opT4(); + xyz.tMethod4(rename.En1); + xyz.tMethodNotXYZ4(notxyz); + xyz.opNotXYZ4(); + xyz.opXYZ4(); +} + +function part5() { + var abc = new rename.ABC(); + abc.methodABC(abc); + var k = new rename.Klass(); + abc.methodKlass(k); + var a = abc.opABC(); + k = abc.opKlass(); +} + +part1(); +part2(); +part3(); +part4(); +part5(); diff --git a/Examples/test-suite/javascript/rename3_runme.js b/Examples/test-suite/javascript/rename3_runme.js new file mode 100644 index 000000000..9e57e80ea --- /dev/null +++ b/Examples/test-suite/javascript/rename3_runme.js @@ -0,0 +1,68 @@ +var rename = require("./rename3"); + +function part1() { + var xyz = new rename.XYZInt(); + notxyz = new rename.NotXYZInt(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother2(); + xyz.opT2(); + xyz.tMethod2(0); + xyz.tMethodNotXYZ2(notxyz); + xyz.opNotXYZ2(); + xyz.opXYZ2(); +} + +function part2() { + var xyz = new rename.XYZDouble(); + var notxyz = new rename.NotXYZDouble(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother1(); + xyz.opT1(); + xyz.tMethod1(0); + xyz.tMethodNotXYZ1(notxyz); + xyz.opNotXYZ1(); + xyz.opXYZ1(); +} + +function part3(){ + var xyz = new rename.XYZKlass(); + var notxyz = new rename.NotXYZKlass(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother3(); + xyz.opT3(); + xyz.tMethod3(new rename.Klass()); + xyz.tMethodNotXYZ3(notxyz); + xyz.opNotXYZ3(); + xyz.opXYZ3(); +} + +function part4() { + var xyz = new rename.XYZEnu(); + var notxyz = new rename.NotXYZEnu(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother4(); + xyz.opT4(); + xyz.tMethod4(rename.En1); + xyz.tMethodNotXYZ4(notxyz); + xyz.opNotXYZ4(); + xyz.opXYZ4(); +} + +function part5() { + var abc = new rename.ABC(); + abc.methodABC(abc); + var k = new rename.Klass(); + abc.methodKlass(k); + var a = abc.opABC(); + k = abc.opKlass(); +} + +part1(); +part2(); +part3(); +part4(); +part5(); diff --git a/Examples/test-suite/javascript/rename4_runme.js b/Examples/test-suite/javascript/rename4_runme.js new file mode 100644 index 000000000..d651fc7a1 --- /dev/null +++ b/Examples/test-suite/javascript/rename4_runme.js @@ -0,0 +1,68 @@ +var rename = require("./rename4"); + +function part1() { + var xyz = new rename.XYZInt(); + notxyz = new rename.NotXYZInt(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother2(); + xyz.opT2(); + xyz.tMethod2(0); + xyz.tMethodNotXYZ2(notxyz); + xyz.opNotXYZ2(); + xyz.opXYZ2(); +} + +function part2() { + var xyz = new rename.XYZDouble(); + var notxyz = new rename.NotXYZDouble(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother1(); + xyz.opT1(); + xyz.tMethod1(0); + xyz.tMethodNotXYZ1(notxyz); + xyz.opNotXYZ1(); + xyz.opXYZ1(); +} + +function part3(){ + var xyz = new rename.XYZKlass(); + var notxyz = new rename.NotXYZKlass(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother3(); + xyz.opT3(); + xyz.tMethod3(new rename.Klass()); + xyz.tMethodNotXYZ3(notxyz); + xyz.opNotXYZ3(); + xyz.opXYZ3(); +} + +function part4() { + var xyz = new rename.XYZEnu(); + var notxyz = new rename.NotXYZEnu(); + xyz.opIntPtrA(); + xyz.opIntPtrB(); + xyz.opAnother4(); + xyz.opT4(); + xyz.tMethod4(rename.En1); + xyz.tMethodNotXYZ4(notxyz); + xyz.opNotXYZ4(); + xyz.opXYZ4(); +} + +function part5() { + var abc = new rename.ABC(); + abc.methodABC(abc); + var k = new rename.Klass(); + abc.methodKlass(k); + var a = abc.opABC(); + k = abc.opKlass(); +} + +part1(); +part2(); +part3(); +part4(); +part5(); diff --git a/Examples/test-suite/javascript/rename_scope_runme.js b/Examples/test-suite/javascript/rename_scope_runme.js new file mode 100644 index 000000000..c0226df69 --- /dev/null +++ b/Examples/test-suite/javascript/rename_scope_runme.js @@ -0,0 +1,17 @@ +var rename_scope = require("./rename_scope"); + +var a = new rename_scope.Natural_UP(); +var b = new rename_scope.Natural_BP(); + +if (a.rtest() !== 1) { + throw new Error("a.rtest(): Expected 1, was " + a.rtest()); +} + +if (b.rtest() !== 1) { + throw new Error("b.rtest(): Expected 1, was " + b.rtest()); +} + +var f = rename_scope.equals; +if (f === undefined) { + throw new Error("Equality operator has not been renamed."); +} diff --git a/Examples/test-suite/javascript/rename_simple_runme.js b/Examples/test-suite/javascript/rename_simple_runme.js new file mode 100644 index 000000000..918dd68a5 --- /dev/null +++ b/Examples/test-suite/javascript/rename_simple_runme.js @@ -0,0 +1,50 @@ +var rename_simple = require("./rename_simple"); +var NewStruct = rename_simple.NewStruct; + +var s = new NewStruct(); + +// renamed instance variable +if (s.NewInstanceVariable !== 111) { + throw new Error("NewInstanceVariable: Expected 111, was " + s.NewInstanceVariable); +} + +// renamed instance method +if (s.NewInstanceMethod() !== 222) { + throw new Error("NewInstanceMethod(): Expected 222, was " + s.NewInstanceMethod()); +} + +// renamed static method +if (NewStruct.NewStaticMethod() !== 333) { + throw new Error("NewInstanceMethod(): Expected 333, was " + NewStruct.NewStaticMethod()); +} + +// renamed static variable +if (NewStruct.NewStaticVariable !== 444) { + throw new Error("NewInstanceMethod(): Expected 444, was " + NewStruct.NewStaticVariable); +} + +// renamed global function +if (rename_simple.NewFunction() !== 555) { + throw new Error("rename_simple.NewFunction(): Expected 555, was " + rename_simple.NewFunction()); +} + +// renamed global variable +if (rename_simple.NewGlobalVariable !== 666) { + throw new Error("rename_simple.NewGlobalVariable: Expected 666, was " + rename_simple.NewGlobalVariable); +} + +// setting renamed variables +s.NewInstanceVariable = 1111; +if (s.NewInstanceVariable !== 1111) { + throw new Error("NewInstanceVariable: Expected 1111, was " + s.NewInstanceVariable); +} + +NewStruct.NewStaticVariable = 4444; +if (NewStruct.NewStaticVariable !== 4444) { + throw new Error("NewInstanceMethod(): Expected 4444, was " + NewStruct.NewStaticVariable); +} + +rename_simple.NewGlobalVariable = 6666; +if (rename_simple.NewGlobalVariable !== 6666) { + throw new Error("rename_simple.NewGlobalVariable: Expected 6666, was " + rename_simple.NewGlobalVariable); +} diff --git a/Examples/test-suite/javascript/ret_by_value_runme.js b/Examples/test-suite/javascript/ret_by_value_runme.js new file mode 100644 index 000000000..d9a77a20b --- /dev/null +++ b/Examples/test-suite/javascript/ret_by_value_runme.js @@ -0,0 +1,8 @@ +var ret_by_value = require("./ret_by_value"); + +a = ret_by_value.get_test(); +if (a.myInt != 100) + throw "RuntimeError"; + +if (a.myShort != 200) + throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/setup_test.sh b/Examples/test-suite/javascript/setup_test.sh new file mode 100644 index 000000000..913a74c4b --- /dev/null +++ b/Examples/test-suite/javascript/setup_test.sh @@ -0,0 +1,6 @@ +#!/bin/sh +if [ ! -d $1 ]; then + mkdir $1; +fi +sed -e "s/\$testcase/$1/" -e "s/\$cflags/$2/" < node_template/binding.gyp.in > $1/binding.gyp +sed s/\$testcase/$1/ node_template/index.js.in > $1/index.js diff --git a/Examples/test-suite/javascript/struct_value_runme.js b/Examples/test-suite/javascript/struct_value_runme.js new file mode 100644 index 000000000..d6b26f726 --- /dev/null +++ b/Examples/test-suite/javascript/struct_value_runme.js @@ -0,0 +1,11 @@ +var struct_value = require("./struct_value"); + +b = new struct_value.Bar(); + +b.a.x = 3; +if (b.a.x != 3) +throw "RuntimeError"; + +b.b.x = 3; +if (b.b.x != 3) +throw "RuntimeError" diff --git a/Examples/test-suite/javascript/template_static_runme.js b/Examples/test-suite/javascript/template_static_runme.js new file mode 100644 index 000000000..477d97249 --- /dev/null +++ b/Examples/test-suite/javascript/template_static_runme.js @@ -0,0 +1,3 @@ +var template_static = require("./template_static"); + +template_static.Foo.bar_double(1); diff --git a/Examples/test-suite/javascript/typedef_class_runme.js b/Examples/test-suite/javascript/typedef_class_runme.js new file mode 100644 index 000000000..3e4dc9093 --- /dev/null +++ b/Examples/test-suite/javascript/typedef_class_runme.js @@ -0,0 +1,7 @@ +var typedef_class = require("./typedef_class"); + +a = new typedef_class.RealA(); +a.a = 3; + +b = new typedef_class.B(); +b.testA(a); diff --git a/Examples/test-suite/javascript/typedef_inherit_runme.js b/Examples/test-suite/javascript/typedef_inherit_runme.js new file mode 100644 index 000000000..4abcc2536 --- /dev/null +++ b/Examples/test-suite/javascript/typedef_inherit_runme.js @@ -0,0 +1,23 @@ +var typedef_inherit = require("./typedef_inherit"); + +a = new typedef_inherit.Foo(); +b = new typedef_inherit.Bar(); + +x = typedef_inherit.do_blah(a); +if (x != "Foo::blah") + print("Whoa! Bad return" + x); + +x = typedef_inherit.do_blah(b); +if (x != "Bar::blah") + print("Whoa! Bad return" + x); + +c = new typedef_inherit.Spam(); +d = new typedef_inherit.Grok(); + +x = typedef_inherit.do_blah2(c); +if (x != "Spam::blah") + print("Whoa! Bad return" + x); + +x = typedef_inherit.do_blah2(d); +if (x != "Grok::blah") + print ("Whoa! Bad return" + x); diff --git a/Examples/test-suite/javascript/typedef_scope_runme.js b/Examples/test-suite/javascript/typedef_scope_runme.js new file mode 100644 index 000000000..0ac56884c --- /dev/null +++ b/Examples/test-suite/javascript/typedef_scope_runme.js @@ -0,0 +1,12 @@ +var typedef_scope = require("./typedef_scope"); + +b = new typedef_scope.Bar(); +x = b.test1(42,"hello"); +if (x != 42) + print("Failed!!"); + +x = b.test2(42,"hello"); +if (x != "hello") + print("Failed!!"); + + diff --git a/Examples/test-suite/javascript/typemap_arrays_runme.js b/Examples/test-suite/javascript/typemap_arrays_runme.js new file mode 100644 index 000000000..cd6827ac9 --- /dev/null +++ b/Examples/test-suite/javascript/typemap_arrays_runme.js @@ -0,0 +1,5 @@ +var typemap_arrays = require("./typemap_arrays"); + +if (typemap_arrays.sumA(null) != 60) + throw "RuntimeError, Sum is wrong"; + diff --git a/Examples/test-suite/javascript/typemap_delete_runme.js b/Examples/test-suite/javascript/typemap_delete_runme.js new file mode 100644 index 000000000..4b3174956 --- /dev/null +++ b/Examples/test-suite/javascript/typemap_delete_runme.js @@ -0,0 +1,5 @@ +var typemap_delete = require("./typemap_delete"); + +r = new typemap_delete.Rect(123); +if (r.val != 123) + throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/typemap_namespace_runme.js b/Examples/test-suite/javascript/typemap_namespace_runme.js new file mode 100644 index 000000000..614e0ffeb --- /dev/null +++ b/Examples/test-suite/javascript/typemap_namespace_runme.js @@ -0,0 +1,7 @@ +var typemap_namespace = require("./typemap_namespace"); + +if (typemap_namespace.test1("hello") != "hello") + throw "RuntimeError"; + +if (typemap_namespace.test2("hello") != "hello") + throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/typemap_ns_using_runme.js b/Examples/test-suite/javascript/typemap_ns_using_runme.js new file mode 100644 index 000000000..9115c16ae --- /dev/null +++ b/Examples/test-suite/javascript/typemap_ns_using_runme.js @@ -0,0 +1,4 @@ +var typemap_ns_using = require("./typemap_ns_using"); + +if (typemap_ns_using.spam(37) != 37) + throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/using1_runme.js b/Examples/test-suite/javascript/using1_runme.js new file mode 100644 index 000000000..a2e37fcb6 --- /dev/null +++ b/Examples/test-suite/javascript/using1_runme.js @@ -0,0 +1,4 @@ +var using1 = require("./using1"); + +if (using1.spam(37) != 37) + throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/using2_runme.js b/Examples/test-suite/javascript/using2_runme.js new file mode 100644 index 000000000..aa5e9b15f --- /dev/null +++ b/Examples/test-suite/javascript/using2_runme.js @@ -0,0 +1,4 @@ +var using2 = require("./using2"); + +if (using2.spam(37) != 37) + throw "RuntimeError"; diff --git a/Examples/test-suite/javascript/varargs_runme.js b/Examples/test-suite/javascript/varargs_runme.js new file mode 100644 index 000000000..69d761e63 --- /dev/null +++ b/Examples/test-suite/javascript/varargs_runme.js @@ -0,0 +1,44 @@ +var varargs = require("./varargs"); + +if (varargs.test("Hello") != "Hello") { + throw new Error("Failed"); +} + +var f = new varargs.Foo("Greetings") +if (f.str != "Greetings") { + throw new Error("Failed"); +} + +if (f.test("Hello") != "Hello") { + throw new Error("Failed"); +} + +if (varargs.test_def("Hello",1) != "Hello") { + throw new Error("Failed"); +} + +if (varargs.test_def("Hello") != "Hello") { + throw new Error("Failed"); +} + +if (varargs.test_plenty("Hello") != "Hello") { + throw new Error("Failed"); +} + +if (varargs.test_plenty("Hello", 1) != "Hello") { + throw new Error("Failed"); +} + +if (varargs.test_plenty("Hello", 1, 2) != "Hello") { + throw new Error("Failed"); +} + +var thrown = false; +try { + varargs.test_plenty("Hello", 1, 2, 3); +} catch (err) { + thrown = true; +} +if (!thrown) { + throw new Error("Failed"); +} diff --git a/Examples/test-suite/javascript_unicode.i b/Examples/test-suite/javascript_unicode.i new file mode 100644 index 000000000..516eee5dd --- /dev/null +++ b/Examples/test-suite/javascript_unicode.i @@ -0,0 +1,10 @@ +%module javascript_unicode + +%newobject copy_string; + +%inline %{ +#include +const char* copy_string(const char* str) { + return strdup(str); +} +%} diff --git a/Examples/test-suite/nspace.i b/Examples/test-suite/nspace.i index 58c560412..3e4b3c214 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) || defined(SWIGLUA) +#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGD) || defined(SWIGLUA) || defined(SWIGJAVASCRIPT) #if defined(SWIGJAVA) SWIG_JAVABODY_PROXY(public, public, SWIGTYPE) diff --git a/Examples/test-suite/nspace_extend.i b/Examples/test-suite/nspace_extend.i index e92ff8c1d..2f7c6fbe1 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) || defined(SWIGLUA) +#if defined(SWIGJAVA) || defined(SWIGCSHARP) || defined(SWIGD) || defined(SWIGLUA) || defined(SWIGJAVASCRIPT) #if defined(SWIGJAVA) SWIG_JAVABODY_PROXY(public, public, SWIGTYPE) diff --git a/Lib/javascript/jsc/arrays_javascript.i b/Lib/javascript/jsc/arrays_javascript.i new file mode 100644 index 000000000..b9199d86b --- /dev/null +++ b/Lib/javascript/jsc/arrays_javascript.i @@ -0,0 +1,123 @@ +/* ----------------------------------------------------------------------------- + * arrays_javascript.i + * + * These typemaps give more natural support for arrays. The typemaps are not efficient + * as there is a lot of copying of the array values whenever the array is passed to C/C++ + * from JavaScript and vice versa. The JavaScript array is expected to be the same size as the C array. + * An exception is thrown if they are not. + * + * Example usage: + * Wrapping: + * + * %include + * %inline %{ + * extern int FiddleSticks[3]; + * %} + * + * Use from JavaScript like this: + * + * var fs = [10, 11, 12]; + * example.FiddleSticks = fs; + * fs = example.FiddleSticks; + * ----------------------------------------------------------------------------- */ + +%fragment("SWIG_JSCGetIntProperty", "header", fragment=SWIG_AsVal_frag(int)) {} +%fragment("SWIG_JSCGetNumberProperty", "header", fragment=SWIG_AsVal_frag(double)) {} + +%typemap(in, fragment="SWIG_JSCGetIntProperty") int[], int[ANY] + (int length = 0, JSObjectRef array, JSValueRef jsvalue, int i = 0, int res = 0, $*1_ltype temp) { + if (JSValueIsObject(context, $input)) + { + // Convert into Array + array = JSValueToObject(context, $input, NULL); + + length = $1_dim0; + + $1 = ($*1_ltype *)malloc(sizeof($*1_ltype) * length); + + // Get each element from array + for (i = 0; i < length; i++) + { + jsvalue = JSObjectGetPropertyAtIndex(context, array, i, NULL); + + // Get primitive value from JSObject + res = SWIG_AsVal(int)(jsvalue, &temp); + if (!SWIG_IsOK(res)) + { + SWIG_exception_fail(SWIG_ERROR, "Failed to convert $input to double"); + } + arg$argnum[i] = temp; + } + + } + else + { + SWIG_exception_fail(SWIG_ERROR, "$input is not JSObjectRef"); + } +} + +%typemap(freearg) int[], int[ANY] { + free($1); +} + +%typemap(out, fragment=SWIG_From_frag(int)) int[], int[ANY] (int length = 0, int i = 0) +{ + length = $1_dim0; + JSValueRef values[length]; + + for (i = 0; i < length; i++) + { + values[i] = SWIG_From(int)($1[i]); + } + + $result = JSObjectMakeArray(context, length, values, NULL); +} + +%typemap(in, fragment="SWIG_JSCGetNumberProperty") double[], double[ANY] + (int length = 0, JSObjectRef array, JSValueRef jsvalue, int i = 0, int res = 0, $*1_ltype temp) { + if (JSValueIsObject(context, $input)) + { + // Convert into Array + array = JSValueToObject(context, $input, NULL); + + length = $1_dim0; + + $1 = ($*1_ltype *)malloc(sizeof($*1_ltype) * length); + + // Get each element from array + for (i = 0; i < length; i++) + { + jsvalue = JSObjectGetPropertyAtIndex(context, array, i, NULL); + + // Get primitive value from JSObject + res = SWIG_AsVal(double)(jsvalue, &temp); + if (!SWIG_IsOK(res)) + { + SWIG_exception_fail(SWIG_ERROR, "Failed to convert $input to double"); + } + arg$argnum[i] = temp; + } + + } + else + { + SWIG_exception_fail(SWIG_ERROR, "$input is not JSObjectRef"); + } +} + +%typemap(freearg) double[], double[ANY] { + free($1); +} + +%typemap(out, fragment=SWIG_From_frag(double)) double[], double[ANY] (int length = 0, int i = 0) +{ + length = $1_dim0; + JSValueRef values[length]; + + for (i = 0; i < length; i++) + { + values[i] = SWIG_From(double)($1[i]); + } + + $result = JSObjectMakeArray(context, length, values, NULL); +} diff --git a/Lib/javascript/jsc/ccomplex.i b/Lib/javascript/jsc/ccomplex.i new file mode 100644 index 000000000..50f0f95fe --- /dev/null +++ b/Lib/javascript/jsc/ccomplex.i @@ -0,0 +1,26 @@ +/* ----------------------------------------------------------------------------- + * ccomplex.i + * + * C complex typemaps + * ISO C99: 7.3 Complex arithmetic + * ----------------------------------------------------------------------------- */ + + +%include + +%{ +#include +%} + + +/* C complex constructor */ +#define CCplxConst(r, i) ((r) + I*(i)) + +%swig_cplxflt_convn(float complex, CCplxConst, creal, cimag); +%swig_cplxdbl_convn(double complex, CCplxConst, creal, cimag); +%swig_cplxdbl_convn(complex, CCplxConst, creal, cimag); + +/* declaring the typemaps */ +%typemaps_primitive(SWIG_TYPECHECK_CPLXFLT, float complex); +%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, double complex); +%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, complex); diff --git a/Lib/javascript/jsc/cdata.i b/Lib/javascript/jsc/cdata.i new file mode 100644 index 000000000..367965990 --- /dev/null +++ b/Lib/javascript/jsc/cdata.i @@ -0,0 +1 @@ +%include diff --git a/Lib/javascript/jsc/complex.i b/Lib/javascript/jsc/complex.i new file mode 100644 index 000000000..4c3b3c5e2 --- /dev/null +++ b/Lib/javascript/jsc/complex.i @@ -0,0 +1,6 @@ +#ifdef __cplusplus +%include +#else +%include +#endif + diff --git a/Lib/javascript/jsc/exception.i b/Lib/javascript/jsc/exception.i new file mode 100644 index 000000000..0246cfde8 --- /dev/null +++ b/Lib/javascript/jsc/exception.i @@ -0,0 +1 @@ +%include diff --git a/Lib/javascript/jsc/javascript.swg b/Lib/javascript/jsc/javascript.swg new file mode 100644 index 000000000..3a83b6495 --- /dev/null +++ b/Lib/javascript/jsc/javascript.swg @@ -0,0 +1,19 @@ +/* ----------------------------------------------------------------------------- + * javascript.swg + * + * Javascript typemaps + * ----------------------------------------------------------------------------- */ + +%include + +%include + +%include + +%include + +%include + +%include + +%include diff --git a/Lib/javascript/jsc/javascriptcode.swg b/Lib/javascript/jsc/javascriptcode.swg new file mode 100644 index 000000000..60c52b2b3 --- /dev/null +++ b/Lib/javascript/jsc/javascriptcode.swg @@ -0,0 +1,418 @@ +/* ----------------------------------------------------------------------------- + * js_ctor: template for wrapping a ctor. + * - $jswrapper: wrapper of called ctor + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * - $jsargcount: number of arguments + * - $jsmangledtype: mangled type of class + * ----------------------------------------------------------------------------- */ +%fragment ("js_ctor", "templates") +%{ +JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + $jslocals + if(argc != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); + + $jscode + return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); + goto fail; + fail: + return NULL; +} +%} + +/* ----------------------------------------------------------------------------- + * js_veto_ctor: a vetoing ctor for abstract classes + * - $jswrapper: name of wrapper + * - $jsname: class name + * ----------------------------------------------------------------------------- */ +%fragment ("js_veto_ctor", "templates") +%{ +JSObjectRef $jswrapper(JSContextRef context, JSObjectRef ctorObject, + size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + SWIG_exception(SWIG_ERROR, "Class $jsname can not be instantiated"); + return 0; +} +%} + +/* ----------------------------------------------------------------------------- + * js_ctor_dispatcher: dispatcher for overloaded constructors + * - $jswrapper: name of wrapper + * - $jsname: class name + * - $jsdispatchcases: part containing code for dispatching + * ----------------------------------------------------------------------------- */ +%fragment ("js_ctor_dispatcher", "templates") +%{ +JSObjectRef $jswrapper(JSContextRef context, JSObjectRef ctorObject, + size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + JSObjectRef thisObject = NULL; + + // switch all cases by means of series of if-returns. + $jsdispatchcases + + // default: + SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for contruction of $jsname"); + + fail: + return thisObject; +} +%} + +/* ----------------------------------------------------------------------------- + * js_overloaded_ctor: template for wrapping a ctor. + * - $jswrapper: wrapper of called ctor + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * - $jsargcount: number of arguments + * - $jsmangledtype: mangled type of class + * ----------------------------------------------------------------------------- */ +%fragment ("js_overloaded_ctor", "templates") +%{ +JSObjectRef $jswrapper(JSContextRef context, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + $jslocals + $jscode + return SWIG_JSC_NewPointerObj(context, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); + + goto fail; + fail: + return NULL; +} +%} + +/* ----------------------------------------------------------------------------- + * js_ctor_dispatch_case: template for a dispatch case for calling an overloaded ctor. + * - $jsargcount: number of arguments of called ctor + * - $jswrapper: wrapper of called ctor + * + * Note: a try-catch-like mechanism is used to switch cases + * ----------------------------------------------------------------------------- */ +%fragment ("js_ctor_dispatch_case", "templates") +%{ + if(argc == $jsargcount) { + thisObject = $jswrapper(context, NULL, argc, argv, exception); + if(thisObject != NULL) { *exception=0; return thisObject; } /* reset exception and return */ + } +%} + + +/* ----------------------------------------------------------------------------- + * js_dtor: template for a destructor wrapper + * - $jsmangledname: mangled class name + * - $jstype: class type + * ----------------------------------------------------------------------------- */ +%fragment ("js_dtor", "templates") +%{ +void $jswrapper(JSObjectRef thisObject) +{ + SwigPrivData* t = (SwigPrivData*) JSObjectGetPrivate(thisObject); + if(t && t->swigCMemOwn) free (($jstype)t->swigCObject); + if(t) free(t); +} +%} + +/* ----------------------------------------------------------------------------- + * js_dtor: template for a destructor wrapper + * - $jsmangledname: mangled class name + * - $jstype: class type + * - ${destructor_action}: The custom destructor action to invoke. + * ----------------------------------------------------------------------------- */ +%fragment ("js_dtoroverride", "templates") +%{ +void $jswrapper(JSObjectRef thisObject) +{ + SwigPrivData* t = (SwigPrivData*) JSObjectGetPrivate(thisObject); + if(t && t->swigCMemOwn) { + $jstype arg1 = ($jstype)t->swigCObject; + ${destructor_action} + } + if(t) free(t); +} +%} + +/* ----------------------------------------------------------------------------- + * js_getter: template for getter function wrappers + * - $jswrapper: wrapper function name + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ +%fragment ("js_getter", "templates") +%{ +JSValueRef $jswrapper(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef* exception) +{ + $jslocals + JSValueRef jsresult; + + $jscode + return jsresult; + + goto fail; + fail: + return NULL; +} +%} + +/* ----------------------------------------------------------------------------- + * js_setter: template for setter function wrappers + * - $jswrapper: wrapper function name + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ +%fragment ("js_setter", "templates") +%{ +bool $jswrapper(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + $jslocals + $jscode + + return true; + + goto fail; + fail: + return false; +} +%} + +/* ----------------------------------------------------------------------------- + * js_function: template for function wrappers + * - $jswrapper: wrapper function name + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ +%fragment ("js_function", "templates") +%{ +JSValueRef $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + $jslocals + JSValueRef jsresult; + + if(argc != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); + + $jscode + return jsresult; + + goto fail; + fail: + return NULL; +} +%} + +/* ----------------------------------------------------------------------------- + * js_function_dispatcher: template for a function dispatcher for overloaded functions + * - $jswrapper: wrapper function name + * - $jsname: name of the wrapped function + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ +%fragment ("js_function_dispatcher", "templates") +%{ +JSValueRef $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + $jslocals + JSValueRef jsresult; + int res; + $jscode + + SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function $jsname."); + return jsresult; + + goto fail; + fail: + return NULL; +} +%} + +/* ----------------------------------------------------------------------------- + * js_overloaded_function: template for a overloaded function + * - $jswrapper: wrapper function name + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ +%fragment ("js_overloaded_function", "templates") +%{ +int $jswrapper(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception, JSValueRef* p_result) +{ + $jslocals + JSValueRef jsresult; + + if(argc != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); + + $jscode + *p_result = jsresult; + return SWIG_OK; + + goto fail; + fail: + return SWIG_TypeError; +} +%} + +/* ----------------------------------------------------------------------------- + * js_function_dispatch_case: template for a case used in the function dispatcher + * - $jswrapper: wrapper function name + * - $jsargcount: number of arguments of overloaded function + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ +%fragment ("js_function_dispatch_case", "templates") +%{ + if(argc == $jsargcount) { + res = $jswrapper(context, function, thisObject, argc, argv, exception, &jsresult); + if(res == SWIG_OK) { *exception = 0; return jsresult; } + } +%} + +/* ----------------------------------------------------------------------------- + * jsc_variable_declaration: template for a variable table entry + * - $jsname: name of the variable + * - $jsgetter: wrapper of getter function + * - $jssetter: wrapper of setter function + * ----------------------------------------------------------------------------- */ +%fragment ("jsc_variable_declaration", "templates") +%{ + {"$jsname", $jsgetter, $jssetter, kJSPropertyAttributeNone}, +%} + + +/* ----------------------------------------------------------------------------- + * jsc_function_declaration: template for a function table entry + * - $jsname: name of the variable + * - $jswrapper: wrapper function + * ----------------------------------------------------------------------------- */ +%fragment ("jsc_function_declaration", "templates") +%{ + {"$jsname", $jswrapper, kJSPropertyAttributeNone}, +%} + +/* ----------------------------------------------------------------------------- + * jsc_classtemplate_declaration: template for a namespace declaration + * - $jsmangledname: mangled class name + * ----------------------------------------------------------------------------- */ +%fragment ("jsc_class_declaration", "templates") +%{ +JSClassDefinition $jsmangledname_classDefinition; + +JSClassDefinition $jsmangledname_objectDefinition; + +JSClassRef $jsmangledname_classRef; +%} + +/* ----------------------------------------------------------------------------- + * jsc_class_tables: template for a namespace declaration + * - $jsmangledname: mangled class name + * - $jsstaticclassvariables: list of static variable entries + * - $jsstaticclassfunctions: list of static function entries + * - $jsclassvariables: list of member variable entries + * - $jsclassfunctions: list of member function entries + * ----------------------------------------------------------------------------- */ +%fragment ("jsc_class_tables", "templates") +%{ +JSStaticValue $jsmangledname_staticValues[] = { + $jsstaticclassvariables + { 0, 0, 0, 0 } +}; + +JSStaticFunction $jsmangledname_staticFunctions[] = { + $jsstaticclassfunctions + { 0, 0, 0 } +}; + +JSStaticValue $jsmangledname_values[] = { + $jsclassvariables + { 0, 0, 0, 0 } +}; + +JSStaticFunction $jsmangledname_functions[] = { + $jsclassfunctions + { 0, 0, 0 } +}; +%} + +/* ----------------------------------------------------------------------------- + * jsc_define_class_template: template for defining a class template + * - $jsmangledname: mangled class name + * - $jsmangledtype: mangled class type + * - $jsctor: wrapper of ctor + * - $jsbaseclass: mangled name of base class + * ----------------------------------------------------------------------------- */ +%fragment ("jsc_class_definition", "templates") +%{ + $jsmangledname_classDefinition.staticFunctions = $jsmangledname_staticFunctions; + $jsmangledname_classDefinition.staticValues = $jsmangledname_staticValues; + $jsmangledname_classDefinition.callAsConstructor = $jsctor; + $jsmangledname_classDefinition.finalize = $jsdtor; + $jsmangledname_objectDefinition.staticValues = $jsmangledname_values; + $jsmangledname_objectDefinition.staticFunctions = $jsmangledname_functions; + $jsclass_inheritance + JSClassRef $jsmangledname_classRef = JSClassCreate(&$jsmangledname_objectDefinition); + SWIGTYPE_$jsmangledtype->clientdata = $jsmangledname_classRef; +%} + +%fragment ("jsc_class_inherit", templates) +%{ + if (SWIGTYPE_p$jsbaseclassmangled != NULL) { + $jsmangledname_objectDefinition.parentClass = (JSClassRef) SWIGTYPE_p$jsbaseclassmangled->clientdata; + } +%} + +%fragment ("jsc_class_noinherit", templates) +%{ + $jsmangledname_objectDefinition.parentClass = _SwigObject_classRef; +%} + + +/* ----------------------------------------------------------------------------- + * jsc_register_class: template for registration of a class + * - $jsname: class name + * - $jsmangledname: mangled class name + * - $jsnspace: mangled name of namespace + * ----------------------------------------------------------------------------- */ +%fragment ("jsc_class_registration", "templates") +%{ + JS_registerClass(context, $jsnspace_object, "$jsname", &$jsmangledname_classDefinition); +%} + + +/* ----------------------------------------------------------------------------- + * jsc_nspace_declaration: template for a namespace declaration + * - $jsnspace: mangled name of the namespace + * - $jsglobalvariables: list of variable entries + * - $jsglobalfunctions: list if fuction entries + * ----------------------------------------------------------------------------- */ +%fragment ("jsc_nspace_declaration", "templates") +%{ +JSStaticValue $jsnspace_values[] = { + $jsglobalvariables + { 0, 0, 0, 0 } +}; + +JSStaticFunction $jsnspace_functions[] = { + $jsglobalfunctions + { 0, 0, 0 } +}; + +JSClassDefinition $jsnspace_classDefinition; +%} + +/* ----------------------------------------------------------------------------- + * jsc_nspace_definition: template for definition of a namespace object + * - $jsmangledname: mangled name of namespace + * ----------------------------------------------------------------------------- */ +%fragment ("jsc_nspace_definition", "templates") +%{ + $jsmangledname_classDefinition.staticFunctions = $jsmangledname_functions; + $jsmangledname_classDefinition.staticValues = $jsmangledname_values; + JSObjectRef $jsmangledname_object = JSObjectMake(context, JSClassCreate(&$jsmangledname_classDefinition), NULL); +%} + +/* ----------------------------------------------------------------------------- + * jsc_nspace_registration: template for registration of a namespace object + * - $jsname: name of namespace + * - $jsmangledname: mangled name of namespace + * - $jsparent: mangled name of parent namespace + * ----------------------------------------------------------------------------- */ +%fragment ("jsc_nspace_registration", "templates") +%{ + JS_registerNamespace(context, $jsmangledname_object, $jsparent_object, "$jsname"); +%} diff --git a/Lib/javascript/jsc/javascriptcomplex.swg b/Lib/javascript/jsc/javascriptcomplex.swg new file mode 100644 index 000000000..7d165dce4 --- /dev/null +++ b/Lib/javascript/jsc/javascriptcomplex.swg @@ -0,0 +1,146 @@ +/* + Defines the As/From converters for double/float complex, you need to + provide complex Type, the Name you want to use in the converters, + the complex Constructor method, and the Real and Imag complex + accessor methods. + + See the std_complex.i and ccomplex.i for concret examples. +*/ + +/* the common from converter */ +%define %swig_fromcplx_conv(Type, Real, Imag) +%fragment(SWIG_From_frag(Type),"header", + fragment=SWIG_From_frag(double)) +{ +SWIGINTERNINLINE JSObjectRef +SWIG_From_dec(Type)(%ifcplusplus(const Type&, Type) c) +{ + JSValueRef vals[2]; + vals[0] = SWIG_From(double)(Real(c)); + vals[1] = SWIG_From(double)(Imag(c)); + return JSObjectMakeArray(context, 2, vals, NULL); +} +} +%enddef + +/* the double case */ +%define %swig_cplxdbl_conv(Type, Constructor, Real, Imag) +%fragment(SWIG_AsVal_frag(Type),"header", + fragment=SWIG_AsVal_frag(double)) +{ +SWIGINTERN int +SWIG_AsVal_dec(Type) (JSValueRef o, Type* val) +{ + if (JSValueIsObject(context, o)) { + JSObjectRef array; + JSValueRef exception, js_re, js_im; + double re, im; + int res; + + exception = 0; + res = 0; + + array = JSValueToObject(context, o, &exception); + if(exception != 0) + return SWIG_TypeError; + + js_re = JSObjectGetPropertyAtIndex(context, array, 0, &exception); + if(exception != 0) + return SWIG_TypeError; + + js_im = JSObjectGetPropertyAtIndex(context, array, 1, &exception); + if(exception != 0) + return SWIG_TypeError; + + res = SWIG_AsVal(double)(js_re, &re); + if(!SWIG_IsOK(res)) { + return SWIG_TypeError; + } + + res = SWIG_AsVal(double)(js_im, &im); + if(!SWIG_IsOK(res)) { + return SWIG_TypeError; + } + + if (val) *val = Constructor(re, im); + return SWIG_OK; + } else { + double d; + int res = SWIG_AddCast(SWIG_AsVal(double)(o, &d)); + if (SWIG_IsOK(res)) { + if (val) *val = Constructor(d, 0.0); + return res; + } + } + return SWIG_TypeError; +} +} +%swig_fromcplx_conv(Type, Real, Imag); +%enddef + +/* the float case */ +%define %swig_cplxflt_conv(Type, Constructor, Real, Imag) +%fragment(SWIG_AsVal_frag(Type),"header", + fragment=SWIG_AsVal_frag(float)) { +SWIGINTERN int +SWIG_AsVal_dec(Type)(JSValueRef o, Type *val) +{ + if (JSValueIsObject(context, o)) { + JSObjectRef array; + JSValueRef exception, js_re, js_im; + double re, im; + int res; + + exception = 0; + res = 0; + + array = JSValueToObject(context, o, &exception); + if(exception != 0) + return SWIG_TypeError; + + js_re = JSObjectGetPropertyAtIndex(context, array, 0, &exception); + if(exception != 0) + return SWIG_TypeError; + + js_im = JSObjectGetPropertyAtIndex(context, array, 1, &exception); + if(exception != 0) + return SWIG_TypeError; + + res = SWIG_AsVal(double)(js_re, &re); + if(!SWIG_IsOK(res)) { + return SWIG_TypeError; + } + + res = SWIG_AsVal(double)(js_im, &im); + if(!SWIG_IsOK(res)) { + return SWIG_TypeError; + } + + if ((-FLT_MAX <= re && re <= FLT_MAX) && (-FLT_MAX <= im && im <= FLT_MAX)) { + if (val) *val = Constructor(%numeric_cast(re, float), + %numeric_cast(im, float)); + return SWIG_OK; + } else { + return SWIG_OverflowError; + } + } else { + float re; + int res = SWIG_AddCast(SWIG_AsVal(float)(o, &re)); + if (SWIG_IsOK(res)) { + if (val) *val = Constructor(re, 0.0); + return res; + } + } + return SWIG_TypeError; +} +} + +%swig_fromcplx_conv(Type, Real, Imag); +%enddef + +#define %swig_cplxflt_convn(Type, Constructor, Real, Imag) \ +%swig_cplxflt_conv(Type, Constructor, Real, Imag) + + +#define %swig_cplxdbl_convn(Type, Constructor, Real, Imag) \ +%swig_cplxdbl_conv(Type, Constructor, Real, Imag) diff --git a/Lib/javascript/jsc/javascriptfragments.swg b/Lib/javascript/jsc/javascriptfragments.swg new file mode 100644 index 000000000..4778bf033 --- /dev/null +++ b/Lib/javascript/jsc/javascriptfragments.swg @@ -0,0 +1,23 @@ +/* + + Create a file with this name, 'javascriptfragments.swg', in your working + directory and add all the %fragments you want to take precedence + over the default ones defined by swig. + + For example, if you add: + + %fragment(SWIG_AsVal_frag(int),"header") { + SWIGINTERNINLINE int + SWIG_AsVal(int)(PyObject *obj, int *val) + { + ; + } + } + + this will replace the code used to retrieve an integer value for all + the typemaps that need it, including: + + int, std::vector, std::list >, etc. + + +*/ diff --git a/Lib/javascript/jsc/javascripthelpers.swg b/Lib/javascript/jsc/javascripthelpers.swg new file mode 100644 index 000000000..820075ca6 --- /dev/null +++ b/Lib/javascript/jsc/javascripthelpers.swg @@ -0,0 +1,69 @@ +%insert(wrapper) %{ + +bool JS_registerClass(JSGlobalContextRef context, JSObjectRef parentObject, + const char* className, + JSClassDefinition* definition) { + + JSStringRef js_className = JSStringCreateWithUTF8CString(className); + JSObjectRef classObject = JSObjectMake(context, JSClassCreate(definition), NULL); + JSObjectSetProperty(context, parentObject, + js_className, classObject, + kJSPropertyAttributeNone, NULL); + JSStringRelease(js_className); + + return true; +} + +bool JS_registerNamespace(JSGlobalContextRef context, + JSObjectRef namespaceObj, JSObjectRef parentNamespace, + const char* name) +{ + JSStringRef js_name = JSStringCreateWithUTF8CString(name); + JSObjectSetProperty(context, parentNamespace, + js_name, namespaceObj, + kJSPropertyAttributeNone, NULL); + JSStringRelease(js_name); + + return true; +} + + +bool JS_registerFunction(JSGlobalContextRef context, JSObjectRef object, + const char* functionName, JSObjectCallAsFunctionCallback callback) +{ + JSStringRef js_functionName = JSStringCreateWithUTF8CString(functionName); + JSObjectSetProperty(context, object, js_functionName, + JSObjectMakeFunctionWithCallback(context, js_functionName, callback), + kJSPropertyAttributeNone, NULL); + JSStringRelease(js_functionName); + return true; +} + +bool JS_veto_set_variable(JSContextRef context, JSObjectRef thisObject, JSStringRef propertyName, JSValueRef value, JSValueRef* exception) +{ + char buffer[256]; + char msg[512]; + int res; + + JSStringGetUTF8CString(propertyName, buffer, 256); + res = sprintf(msg, "Tried to write read-only variable: %s.", buffer); + + if(res<0) { + SWIG_exception(SWIG_ERROR, "Tried to write read-only variable."); + } else { + SWIG_exception(SWIG_ERROR, msg); + } + + return false; +} + +JSValueRef JS_CharPtrToJSValue(JSContextRef context, char* cstr) { + JSValueRef val; + + JSStringRef jsstring = JSStringCreateWithUTF8CString((char*) cstr); + val = JSValueMakeString(context, jsstring); + JSStringRelease(jsstring); + + return val; +} +%} diff --git a/Lib/javascript/jsc/javascriptinit.swg b/Lib/javascript/jsc/javascriptinit.swg new file mode 100644 index 000000000..a32ba336c --- /dev/null +++ b/Lib/javascript/jsc/javascriptinit.swg @@ -0,0 +1,67 @@ +%insert(init) %{ +SWIGRUNTIME void +SWIG_JSC_SetModule(swig_module_info *swig_module) {} + +SWIGRUNTIME swig_module_info * +SWIG_JSC_GetModule(void) { + return 0; +} + +#define SWIG_GetModule(clientdata) SWIG_JSC_GetModule() +#define SWIG_SetModule(clientdata, pointer) SWIG_JSC_SetModule(pointer) +%} + +%insert(init) "swiginit.swg" + +%fragment ("js_initializer_define", "templates") %{ +#define SWIGJSC_INIT $jsname_initialize +%} + +// Open the initializer function +%insert(init) +%{ + +#ifdef __cplusplus +extern "C" { +#endif + +bool SWIGJSC_INIT (JSGlobalContextRef context, JSObjectRef *exports) { + SWIG_InitializeModule(0); +%} + +/* ----------------------------------------------------------------------------- + * js_initializer: template for the module initializer function + * - $jsname: module name + * - $jscreatenamespaces: part with code for creating namespace objects + * - $jscreateclasses: part with code for creating classes + * - $jsregisternamespaces: part with code for registration of namespaces + * ----------------------------------------------------------------------------- */ +%fragment ("js_initializer", "templates") %{ + /* Initialize the base swig type object */ + _SwigObject_objectDefinition.staticFunctions = _SwigObject_functions; + _SwigObject_objectDefinition.staticValues = _SwigObject_values; + _SwigObject_classRef = JSClassCreate(&_SwigObject_objectDefinition); + + /* Initialize the PackedData class */ + _SwigPackedData_objectDefinition.staticFunctions = _SwigPackedData_functions; + _SwigPackedData_objectDefinition.staticValues = _SwigPackedData_values; + _SwigPackedData_objectDefinition.finalize = _wrap_SwigPackedData_delete; + _SwigPackedData_classRef = JSClassCreate(&_SwigPackedData_objectDefinition); + + /* Create objects for namespaces */ + $jscreatenamespaces + + /* Register classes */ + $jsregisterclasses + + /* Register namespaces */ + $jsregisternamespaces + + *exports = exports_object; + + return true; +} +#ifdef __cplusplus +} +#endif +%} diff --git a/Lib/javascript/jsc/javascriptkw.swg b/Lib/javascript/jsc/javascriptkw.swg new file mode 100644 index 000000000..c3c118391 --- /dev/null +++ b/Lib/javascript/jsc/javascriptkw.swg @@ -0,0 +1,40 @@ +#ifndef JAVASCRIPT_JAVASCRIPTKW_SWG_ +#define JAVASCRIPT_JAVASCRIPTKW_SWG_ + +/* Warnings for Java keywords */ +#define JAVASCRIPTKW(x) %keywordwarn("'" `x` "' is a javascript keyword, renaming to '_"`x`"'",rename="_%s") `x` + +/* Taken from https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Reserved_Words */ + +JAVASCRIPTKW(break); +JAVASCRIPTKW(case); +JAVASCRIPTKW(catch); +JAVASCRIPTKW(continue); +JAVASCRIPTKW(default); +JAVASCRIPTKW(delete); +JAVASCRIPTKW(do); +JAVASCRIPTKW(else); +JAVASCRIPTKW(finally); +JAVASCRIPTKW(for); +JAVASCRIPTKW(function); +JAVASCRIPTKW(if); +JAVASCRIPTKW(in); +JAVASCRIPTKW(instanceof); +JAVASCRIPTKW(new); +JAVASCRIPTKW(return); +JAVASCRIPTKW(switch); +JAVASCRIPTKW(this); +JAVASCRIPTKW(throw); +JAVASCRIPTKW(try); +JAVASCRIPTKW(typeof); +JAVASCRIPTKW(var); +JAVASCRIPTKW(void); +JAVASCRIPTKW(while); +JAVASCRIPTKW(with); + +/* others bad names if any*/ +// for example %namewarn("321:clone() is a javascript bad method name") *::clone(); + +#undef JAVASCRIPTKW + +#endif //JAVASCRIPT_JAVASCRIPTKW_SWG_ diff --git a/Lib/javascript/jsc/javascriptprimtypes.swg b/Lib/javascript/jsc/javascriptprimtypes.swg new file mode 100644 index 000000000..7e9898a24 --- /dev/null +++ b/Lib/javascript/jsc/javascriptprimtypes.swg @@ -0,0 +1,182 @@ +/* ------------------------------------------------------------ + * Primitive Types + * ------------------------------------------------------------ */ + +/* boolean */ + +%fragment(SWIG_From_frag(bool),"header") { +SWIGINTERNINLINE +JSValueRef SWIG_From_dec(bool)(bool value) +{ + return JSValueMakeBoolean(context, value); +} +} + +%fragment(SWIG_AsVal_frag(bool),"header", + fragment=SWIG_AsVal_frag(long)) { +SWIGINTERN +int SWIG_AsVal_dec(bool)(JSValueRef obj, bool *val) +{ + if(!JSValueIsBoolean(context, obj)) { + return SWIG_ERROR; + } + if (val) *val = JSValueToBoolean(context, obj); + return SWIG_OK; +} +} + +/* int */ + +%fragment(SWIG_From_frag(int),"header") { +SWIGINTERNINLINE JSValueRef + SWIG_From_dec(int)(int value) +{ + return JSValueMakeNumber(context, value); +} +} + +/* long */ + +%fragment(SWIG_From_frag(long),"header") { +SWIGINTERNINLINE JSValueRef +SWIG_From_dec(long)(long value) +{ + return JSValueMakeNumber(context, value); +} +} + +%fragment(SWIG_AsVal_frag(long),"header", + fragment="SWIG_CanCastAsInteger") { +SWIGINTERN int +SWIG_AsVal_dec(long)(JSValueRef obj, long* val) +{ + if (!JSValueIsNumber(context, obj)) { + return SWIG_TypeError; + } + if(val) *val = (long) JSValueToNumber(context, obj, NULL); + + return SWIG_OK; +} +} + +/* unsigned long */ + +%fragment(SWIG_From_frag(unsigned long),"header", + fragment=SWIG_From_frag(long)) { +SWIGINTERNINLINE JSValueRef +SWIG_From_dec(unsigned long)(unsigned long value) +{ + return (value > LONG_MAX) ? + JSValueMakeNumber(context, value) : JSValueMakeNumber(context, %numeric_cast(value,long)); +} +} + +%fragment(SWIG_AsVal_frag(unsigned long),"header", + fragment="SWIG_CanCastAsInteger") { +SWIGINTERN int +SWIG_AsVal_dec(unsigned long)(JSValueRef obj, unsigned long *val) +{ + if(!JSValueIsNumber(context, obj)) { + return SWIG_TypeError; + } + + long longVal = (long) JSValueToNumber(context, obj, NULL); + + if(longVal < 0) { + return SWIG_OverflowError; + } + + if(val) *val = longVal; + + return SWIG_OK; +} +} + +/* long long */ +// Note: these are copied from 'long' and probably need fixing + +%fragment(SWIG_From_frag(long long),"header", + fragment=SWIG_From_frag(long), + fragment="") { +SWIGINTERNINLINE JSValueRef +SWIG_From_dec(long long)(long long value) +{ + return JSValueMakeNumber(context, value); +} +} + +%fragment(SWIG_AsVal_frag(long long),"header", + fragment=SWIG_AsVal_frag(long), + fragment="SWIG_CanCastAsInteger", + fragment="") { +SWIGINTERN int +SWIG_AsVal_dec(long long)(JSValueRef obj, long long* val) +{ + if (!JSValueIsNumber(context, obj)) { + return SWIG_TypeError; + } + if(val) *val = (long long) JSValueToNumber(context, obj, NULL); + + return SWIG_OK; +} +} + +/* unsigned long long */ +// Note: these are copied from 'unsigned long' and probably need fixing + +%fragment(SWIG_From_frag(unsigned long long),"header", + fragment=SWIG_From_frag(long long), + fragment="") { +SWIGINTERN JSValueRef +SWIG_From_dec(unsigned long long)(unsigned long long value) +{ + return (value > LONG_MAX) ? + JSValueMakeNumber(context, value) : JSValueMakeNumber(context, %numeric_cast(value,long)); +} +} + +%fragment(SWIG_AsVal_frag(unsigned long long),"header", + fragment=SWIG_AsVal_frag(unsigned long), + fragment="SWIG_CanCastAsInteger", + fragment="") { +SWIGINTERN int +SWIG_AsVal_dec(unsigned long long)(JSValueRef obj, unsigned long long *val) +{ + if(!JSValueIsNumber(context, obj)) { + return SWIG_TypeError; + } + + long long longVal = (unsigned long long) JSValueToNumber(context, obj, NULL); + + if(longVal < 0) { + return SWIG_OverflowError; + } + + if(val) *val = longVal; + + return SWIG_OK; +} +} + +/* double */ + +%fragment(SWIG_From_frag(double),"header") { +SWIGINTERN JSValueRef +SWIG_From_dec(double) (double val) +{ + return JSValueMakeNumber(context, val); +} +} + +%fragment(SWIG_AsVal_frag(double),"header") { +SWIGINTERN int +SWIG_AsVal_dec(double)(JSValueRef obj, double *val) +{ + if(!JSValueIsNumber(context, obj)) { + return SWIG_TypeError; + } + if(val) *val = JSValueToNumber(context, obj, NULL); + + return SWIG_OK; +} +} diff --git a/Lib/javascript/jsc/javascriptrun.swg b/Lib/javascript/jsc/javascriptrun.swg new file mode 100644 index 000000000..3463d2351 --- /dev/null +++ b/Lib/javascript/jsc/javascriptrun.swg @@ -0,0 +1,298 @@ +/* ---------------------------------------------------------------------------- + * Errors and exceptions + * + * ---------------------------------------------------------------------------*/ + +#define SWIG_Error(code, msg) SWIG_JSC_exception(context, exception, code, msg) +#define SWIG_exception(code, msg) SWIG_JSC_exception(context, exception, code, msg) +#define SWIG_fail goto fail + +void SWIG_Javascript_Raise(JSContextRef context, JSValueRef *exception, const char* type) { + JSStringRef message = JSStringCreateWithUTF8CString(type); + *exception = JSValueMakeString(context, message); + JSStringRelease(message); +} + +void SWIG_JSC_exception(JSContextRef context, JSValueRef *exception, int code, const char* msg) { + SWIG_Javascript_Raise(context, exception, msg); +} + +/* ---------------------------------------------------------------------------- + * The parent class of all Proxies + * + * ---------------------------------------------------------------------------*/ + +typedef struct { + bool swigCMemOwn; + void *swigCObject; + swig_type_info *info; +} SwigPrivData; + +JSValueRef _wrap_SwigObject_disown(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + JSValueRef jsresult; + + JSObjectRef obj = JSValueToObject(context, thisObject, NULL); + SwigPrivData *cdata = (SwigPrivData *) JSObjectGetPrivate(obj); + + cdata->swigCMemOwn = false; + + jsresult = JSValueMakeUndefined(context); + return jsresult; +} + +JSValueRef _wrap_SwigObject_getCPtr(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + JSValueRef jsresult; + long result; + + JSObjectRef obj = JSValueToObject(context, thisObject, NULL); + SwigPrivData *cdata = (SwigPrivData*) JSObjectGetPrivate(obj); + + result = (long) cdata->swigCObject; + jsresult = JSValueMakeNumber(context, result); + + return jsresult; +} + +JSValueRef _wrap_SwigObject_equals(JSContextRef context, JSObjectRef function, JSObjectRef thisObject, size_t argc, const JSValueRef argv[], JSValueRef* exception) +{ + JSValueRef jsresult; + bool result; + + JSObjectRef obj = JSValueToObject(context, thisObject, NULL); + SwigPrivData *cdata = (SwigPrivData*) JSObjectGetPrivate(obj); + + JSObjectRef obj2 = JSValueToObject(context, argv[0], NULL); + SwigPrivData *cdata2 = (SwigPrivData*) JSObjectGetPrivate(obj2); + + result = (cdata->swigCObject == cdata2->swigCObject); + jsresult = JSValueMakeBoolean(context, result); + + return jsresult; +} + +JSStaticValue _SwigObject_values[] = { + { + 0, 0, 0, 0 + } +}; + +JSStaticFunction _SwigObject_functions[] = { + { + "disown",_wrap_SwigObject_disown, kJSPropertyAttributeNone + }, + { + "equals",_wrap_SwigObject_equals, kJSPropertyAttributeNone + }, + { + "getCPtr",_wrap_SwigObject_getCPtr, kJSPropertyAttributeNone + }, + { + 0, 0, 0 + } +}; + +JSClassDefinition _SwigObject_objectDefinition; + +JSClassRef _SwigObject_classRef; + + +int SWIG_JSC_ConvertInstancePtr(JSContextRef context, JSObjectRef objRef, void** ptr, swig_type_info *info, int flags) { + SwigPrivData *cdata = (SwigPrivData *) JSObjectGetPrivate(objRef); + if(cdata == NULL) { + return SWIG_ERROR; + } + if(cdata->info != info) { + bool type_valid = false; + swig_cast_info *t = info->cast; + while(t != NULL) { + if(t->type == cdata->info) { + type_valid = true; + break; + } + t = t->next; + } + if(!type_valid) { + return SWIG_TypeError; + } + } + + *ptr = cdata->swigCObject; + + if(flags & SWIG_POINTER_DISOWN) { + cdata->swigCMemOwn = false; + } + + return SWIG_OK; +} + +int SWIG_JSC_ConvertPtr(JSContextRef context, JSValueRef valRef, void** ptr, swig_type_info *info, int flags) { + if(!JSValueIsObject(context, valRef)) { + return SWIG_TypeError; + } + + JSObjectRef objRef = JSValueToObject(context, valRef, NULL); + if(objRef == NULL) { + return SWIG_ERROR; + } + + return SWIG_JSC_ConvertInstancePtr(context, objRef, ptr, info, flags); +} + +JSObjectRef SWIG_JSC_NewPointerObj(JSContextRef context, void *ptr, swig_type_info *info, int flags) { + + JSClassRef classRef; + if(info->clientdata == NULL) { + classRef = _SwigObject_classRef; + } else { + classRef = (JSClassRef) info->clientdata; + } + + JSObjectRef result = JSObjectMake(context, classRef, NULL); + + SwigPrivData* cdata = (SwigPrivData*) malloc(sizeof(SwigPrivData)); + cdata->swigCObject = ptr; + cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; + cdata->info = info; + + JSObjectSetPrivate(result, cdata); + + return result; +} + +#define SWIG_ConvertPtr(obj, ptr, info, flags) SWIG_JSC_ConvertPtr(context, obj, ptr, info, flags) +#define SWIG_NewPointerObj(ptr, info, flags) SWIG_JSC_NewPointerObj(context, ptr, info, flags) + +#define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_JSC_ConvertInstancePtr(context, obj, pptr, type, flags) +#define SWIG_NewInstanceObj(thisvalue, type, flags) SWIG_JSC_NewPointerObj(context, thisvalue, type, flags) + +#define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_JSC_ConvertPtr(context, obj, pptr, type, 0) +#define SWIG_NewFunctionPtrObj(ptr, type) SWIG_JSC_NewPointerObj(context, ptr, type, 0) + +/* ---------------------------------------------------------------------------- + * A class for packed data + * + * ---------------------------------------------------------------------------*/ + +typedef struct { + void *data; + size_t size; + swig_type_info *type; +} SwigPackedData; + +JSStaticValue _SwigPackedData_values[] = { + { + 0, 0, 0, 0 + } +}; +JSStaticFunction _SwigPackedData_functions[] = { + { + 0, 0, 0 + } +}; +JSClassDefinition _SwigPackedData_objectDefinition; +JSClassRef _SwigPackedData_classRef; + +SWIGRUNTIMEINLINE +int SwigJSCPacked_Check(JSContextRef context, JSValueRef valRef) { + return JSValueIsObjectOfClass(context, valRef, _SwigPackedData_classRef); +} + +SWIGRUNTIME +swig_type_info* SwigJSCPacked_UnpackData(JSContextRef context, JSValueRef valRef, void *ptr, size_t size) { + if (SwigJSCPacked_Check(context, valRef)) { + JSObjectRef objRef = JSValueToObject(context, valRef, NULL); + SwigPackedData *sobj = (SwigPackedData *) JSObjectGetPrivate(objRef); + if (sobj->size != size) return 0; + memcpy(ptr, sobj->data, size); + return sobj->type; + } else { + return 0; + } +} + +SWIGRUNTIME +int SWIG_JSC_ConvertPacked(JSContextRef context, JSValueRef valRef, void *ptr, size_t sz, swig_type_info *ty) { + swig_type_info *to = SwigJSCPacked_UnpackData(context, valRef, 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; +} + +SWIGRUNTIME +JSValueRef SWIG_JSC_NewPackedObj(JSContextRef context, void *data, size_t size, swig_type_info *type) { + + JSClassRef classRef = _SwigObject_classRef; + JSObjectRef result = JSObjectMake(context, classRef, NULL); + + SwigPackedData* cdata = (SwigPackedData*) malloc(sizeof(SwigPackedData)); + cdata->data = data; + cdata->size = size; + cdata->type = type; + + JSObjectSetPrivate(result, cdata); + + return result; +} + +/* SwigPackedData wrappers */ + +void _wrap_SwigPackedData_delete(JSObjectRef obj) +{ + SwigPackedData* cdata = (SwigPackedData*) JSObjectGetPrivate(obj); + if (cdata) { + free(cdata->data); + } +} + +/* for C++ member pointers, ie, member methods */ + +#define SWIG_ConvertMember(obj, ptr, sz, ty) SWIG_JSC_ConvertPacked(context, obj, ptr, sz, ty) +#define SWIG_NewMemberObj(ptr, sz, type) SWIG_JSC_NewPackedObj(context, ptr, sz, type) + + +/* --------------------------------------------------------------------------- + * Support for IN/OUTPUT typemaps (see Lib/typemaps/inoutlist.swg) + * + * ---------------------------------------------------------------------------*/ + +unsigned int SWIGJSC_ArrayLength(JSContextRef context, JSObjectRef arr) { + static JSStringRef LENGTH = 0; + JSValueRef exception = NULL; + JSValueRef js_length; + double length; + + if (LENGTH == 0) { + LENGTH = JSStringCreateWithUTF8CString("length"); + } + + js_length = JSObjectGetProperty(context, arr, LENGTH, &exception); + if (exception == 0 && JSValueIsNumber(context, js_length)) { + length = JSValueToNumber(context, js_length, 0); + return (unsigned int) length; + } else { + return 0; + } +} + +SWIGRUNTIME +JSValueRef SWIGJSC_AppendOutput(JSContextRef context, JSValueRef value, JSValueRef obj) { + JSObjectRef arr; + unsigned int length; + + if (JSValueIsUndefined(context, value)) { + arr = JSObjectMakeArray(context, 0, 0, 0); + } else { + arr = JSValueToObject(context, value, 0); + } + + length = SWIGJSC_ArrayLength(context, arr); + JSObjectSetPropertyAtIndex(context, arr, length, obj, 0); +} diff --git a/Lib/javascript/jsc/javascriptruntime.swg b/Lib/javascript/jsc/javascriptruntime.swg new file mode 100644 index 000000000..8f8390890 --- /dev/null +++ b/Lib/javascript/jsc/javascriptruntime.swg @@ -0,0 +1,19 @@ +/* ----------------------------------------------------------------------------- + * javascriptruntime.swg + * + * Javascript support code + * ----------------------------------------------------------------------------- */ + +%insert(runtime) %{ +#include +#include +#include +#include +#include +#include +%} + +%insert(runtime) "swigrun.swg"; /* SWIG API */ +%insert(runtime) "swigerrors.swg"; /* SWIG errors */ + +%insert(runtime) "javascriptrun.swg"; /* SWIG errors */ diff --git a/Lib/javascript/jsc/javascriptstrings.swg b/Lib/javascript/jsc/javascriptstrings.swg new file mode 100644 index 000000000..0581c1920 --- /dev/null +++ b/Lib/javascript/jsc/javascriptstrings.swg @@ -0,0 +1,184 @@ +/* ------------------------------------------------------------ + * utility methods for char strings + * ------------------------------------------------------------ */ +%fragment("SWIG_AsCharPtrAndSize","header",fragment="SWIG_pchar_descriptor") { +SWIGINTERN int +SWIG_JSC_AsCharPtrAndSize(JSContextRef context, JSValueRef valRef, char** cptr, size_t* psize, int *alloc) +{ + if(JSValueIsString(context, valRef)) { + JSStringRef js_str = JSValueToStringCopy(context, valRef, NULL); + size_t len = JSStringGetMaximumUTF8CStringSize(js_str); + char* cstr = (char*) malloc(len * sizeof(char)); + /* JSStringGetUTF8CString returns the length including 0-terminator */ + len = JSStringGetUTF8CString(js_str, cstr, len); + + if(alloc) *alloc = SWIG_NEWOBJ; + if(psize) *psize = len; + if(cptr) *cptr = cstr; + + return SWIG_OK; + } else { + if(JSValueIsObject(context, valRef)) { + JSObjectRef obj = JSValueToObject(context, valRef, NULL); + // try if the object is a wrapped char[] + swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); + if (pchar_descriptor) { + void* vptr = 0; + if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { + if (cptr) *cptr = (char *) vptr; + if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; + if (alloc) *alloc = SWIG_OLDOBJ; + return SWIG_OK; + } + } + return SWIG_TypeError; + } else { + return SWIG_TypeError; + } + } +} +} + +%fragment("SWIG_FromCharPtrAndSize","header",fragment="SWIG_pchar_descriptor") { +SWIGINTERNINLINE JSValueRef +SWIG_JSC_FromCharPtrAndSize(JSContextRef context, const char* carray, size_t size) +{ + if (carray) { + if (size > INT_MAX) { + // TODO: handle extra long strings + //swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); + //return pchar_descriptor ? + // SWIG_InternalNewPointerObj(%const_cast(carray,char *), pchar_descriptor, 0) : SWIG_Py_Void(); + return JSValueMakeUndefined(context); + } else { + JSStringRef jsstring; + if(size < 2) { + char c[size+1]; + int i; + for(i=0;i + +/* Look for user fragments file. */ +%include + +/* Javascript fragments for fundamental types */ +%include + +/* Javascript fragments for char* strings */ +%include + +/* ------------------------------------------------------------ + * Unified typemap section + * ------------------------------------------------------------ */ + +#define SWIG_Object JSValueRef +#define VOID_Object JSValueMakeUndefined(context) + +/* append output */ +#define SWIG_AppendOutput(result, obj) SWIGJSC_AppendOutput(context, result, obj) + +/* set constant */ +#define SWIG_SetConstant(name, obj) + +/* raise */ +#define SWIG_Raise(obj, type, desc) SWIG_Javascript_Raise(context, exception, type) + +%insert("runtime") %{ +#define SWIG_JSC_FROM_DECL_ARGS(arg1) (JSContextRef context, arg1) +#define SWIG_JSC_FROM_CALL_ARGS(arg1) (context, arg1) +#define SWIG_JSC_AS_DECL_ARGS(arg1, arg2) (JSContextRef context, arg1, arg2) +#define SWIG_JSC_AS_CALL_ARGS(arg1, arg2) (context, arg1, arg2) +%} + +/* Include the unified typemap library */ +%include diff --git a/Lib/javascript/jsc/std_common.i b/Lib/javascript/jsc/std_common.i new file mode 100755 index 000000000..cee11e8ca --- /dev/null +++ b/Lib/javascript/jsc/std_common.i @@ -0,0 +1,5 @@ +%include + +%apply size_t { std::size_t }; +%apply const size_t& { const std::size_t& }; + diff --git a/Lib/javascript/jsc/std_complex.i b/Lib/javascript/jsc/std_complex.i new file mode 100644 index 000000000..088a4fe7b --- /dev/null +++ b/Lib/javascript/jsc/std_complex.i @@ -0,0 +1,19 @@ +/* + * STD C++ complex typemaps + */ + +%include + +%{ +#include +%} + +/* defining the complex as/from converters */ + +%swig_cplxdbl_convn(std::complex, std::complex, std::real, std::imag) +%swig_cplxflt_convn(std::complex, std::complex, std::real, std::imag) + +/* defining the typemaps */ + +%typemaps_primitive(%checkcode(CPLXDBL), std::complex); +%typemaps_primitive(%checkcode(CPLXFLT), std::complex); diff --git a/Lib/javascript/jsc/std_deque.i b/Lib/javascript/jsc/std_deque.i new file mode 100644 index 000000000..cb98f6c2f --- /dev/null +++ b/Lib/javascript/jsc/std_deque.i @@ -0,0 +1 @@ +%include diff --git a/Lib/javascript/jsc/std_except.i b/Lib/javascript/jsc/std_except.i new file mode 100644 index 000000000..af98428f6 --- /dev/null +++ b/Lib/javascript/jsc/std_except.i @@ -0,0 +1 @@ +%include diff --git a/Lib/javascript/jsc/std_map.i b/Lib/javascript/jsc/std_map.i new file mode 100755 index 000000000..e7812f38a --- /dev/null +++ b/Lib/javascript/jsc/std_map.i @@ -0,0 +1,74 @@ +/* ----------------------------------------------------------------------------- + * std_map.i + * + * SWIG typemaps for std::map + * ----------------------------------------------------------------------------- */ + +%include + +// ------------------------------------------------------------------------ +// std::map +// ------------------------------------------------------------------------ + +%{ +#include +#include +#include +%} + +// exported class + +namespace std { + + template class map { + // add typemaps here + public: + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef K key_type; + typedef T mapped_type; + map(); + map(const map &); + + unsigned int size() const; + bool empty() const; + void clear(); + %extend { + const T& get(const K& key) throw (std::out_of_range) { + std::map::iterator i = self->find(key); + if (i != self->end()) + return i->second; + else + throw std::out_of_range("key not found"); + } + void set(const K& key, const T& x) { + (*self)[key] = x; + } + void del(const K& key) throw (std::out_of_range) { + std::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 K& key) { + std::map::iterator i = self->find(key); + return i != self->end(); + } + } + }; + +// Legacy macros (deprecated) +%define specialize_std_map_on_key(K,CHECK,CONVERT_FROM,CONVERT_TO) +#warning "specialize_std_map_on_key ignored - macro is deprecated and no longer necessary" +%enddef + +%define specialize_std_map_on_value(T,CHECK,CONVERT_FROM,CONVERT_TO) +#warning "specialize_std_map_on_value ignored - macro is deprecated and no longer necessary" +%enddef + +%define specialize_std_map_on_both(K,CHECK_K,CONVERT_K_FROM,CONVERT_K_TO, T,CHECK_T,CONVERT_T_FROM,CONVERT_T_TO) +#warning "specialize_std_map_on_both ignored - macro is deprecated and no longer necessary" +%enddef + +} diff --git a/Lib/javascript/jsc/std_pair.i b/Lib/javascript/jsc/std_pair.i new file mode 100755 index 000000000..fe45ee676 --- /dev/null +++ b/Lib/javascript/jsc/std_pair.i @@ -0,0 +1,34 @@ +/* ----------------------------------------------------------------------------- + * std_pair.i + * + * SWIG typemaps for std::pair + * ----------------------------------------------------------------------------- */ + +%include +%include + +// ------------------------------------------------------------------------ +// std::pair +// ------------------------------------------------------------------------ + +%{ +#include +%} + +namespace std { + + template struct pair { + + pair(); + pair(T first, U second); + pair(const pair& p); + + template pair(const pair &p); + + T first; + U second; + }; + + // add specializations here + +} diff --git a/Lib/javascript/jsc/std_string.i b/Lib/javascript/jsc/std_string.i new file mode 100755 index 000000000..fb1bd62b5 --- /dev/null +++ b/Lib/javascript/jsc/std_string.i @@ -0,0 +1,69 @@ +/* ----------------------------------------------------------------------------- + * std_string.i + * + * Typemaps for const std::string&. + * To use non-const std::string references use the following %apply: + * %apply const std::string & {std::string &}; + * + * ----------------------------------------------------------------------------- */ + +%{ +#include + +std::string SWIGJSC_valueToString(JSContextRef context, JSValueRef value) { + JSStringRef jsstring = JSValueToStringCopy(context, value, /* JSValueRef *exception */ 0); + unsigned int length = JSStringGetLength(jsstring); + char *cstr = new char[length + 1]; + JSStringGetUTF8CString(jsstring, cstr, length + 1); + + // create a copy + std::string result(cstr); + + JSStringRelease(jsstring); + delete[] cstr; + + return result; +} + +JSValueRef SWIGJSC_stringToValue(JSContextRef context, const std::string& s) +{ + JSValueRef result; + JSStringRef jsstring = JSStringCreateWithUTF8CString(s.c_str()); + result = JSValueMakeString(context, jsstring); + JSStringRelease(jsstring); + return result; +} +%} + +namespace std { + %naturalvar string; + + class string; + + + %typemap(in) string + %{ + $1 = SWIGJSC_valueToString(context, $input); + %} + + %typemap(in) const string & + %{ + $1 = new std::string(SWIGJSC_valueToString(context, $input)); + %} + + %typemap(freearg) const string & + %{ + delete $1; + %} + + %typemap(out) string + %{ + $result = SWIGJSC_stringToValue(context, $1); + %} + + %typemap(out) const string & + %{ + $result = SWIGJSC_stringToValue(context, *$1); + %} + +} diff --git a/Lib/javascript/jsc/std_vector.i b/Lib/javascript/jsc/std_vector.i new file mode 100755 index 000000000..3f29b19c7 --- /dev/null +++ b/Lib/javascript/jsc/std_vector.i @@ -0,0 +1,85 @@ +/* ----------------------------------------------------------------------------- + * std_vector.i + * ----------------------------------------------------------------------------- */ + +%include + +%{ +#include +#include +%} + +namespace std { + + template class vector { + public: + typedef size_t size_type; + typedef T value_type; + typedef const value_type& const_reference; + vector(); + vector(size_type n); + size_type size() const; + size_type capacity() const; + void reserve(size_type n); + %rename(isEmpty) empty; + bool empty() const; + void clear(); + %rename(add) push_back; + void push_back(const value_type& x); + %extend { + const_reference get(int i) throw (std::out_of_range) { + int size = int(self->size()); + if (i>=0 && isize()); + if (i>=0 && i class vector { + public: + typedef size_t size_type; + typedef bool value_type; + typedef bool const_reference; + vector(); + vector(size_type n); + size_type size() const; + size_type capacity() const; + void reserve(size_type n); + %rename(isEmpty) empty; + bool empty() const; + void clear(); + %rename(add) push_back; + void push_back(const value_type& x); + %extend { + const_reference get(int i) throw (std::out_of_range) { + int size = int(self->size()); + if (i>=0 && isize()); + if (i>=0 && i +%include +%include +%include +%include + diff --git a/Lib/javascript/jsc/typemaps.i b/Lib/javascript/jsc/typemaps.i new file mode 100644 index 000000000..d3d8afb19 --- /dev/null +++ b/Lib/javascript/jsc/typemaps.i @@ -0,0 +1,148 @@ +/* ----------------------------------------------------------------------------- + * typemaps.i + * + * Pointer handling + * These mappings provide support for input/output arguments and common + * uses for C/C++ pointers. + * ----------------------------------------------------------------------------- */ + +// INPUT typemaps. +// These remap a C pointer to be an "INPUT" value which is passed by value +// instead of reference. + +/* +The following methods can be applied to turn a pointer into a simple +"input" value. That is, instead of passing a pointer to an object, +you would use a real value instead. + + int *INPUT + short *INPUT + long *INPUT + long long *INPUT + unsigned int *INPUT + unsigned short *INPUT + unsigned long *INPUT + unsigned long long *INPUT + unsigned char *INPUT + bool *INPUT + float *INPUT + double *INPUT + +To use these, suppose you had a C function like this : + + double fadd(double *a, double *b) { + return *a+*b; + } + +You could wrap it with SWIG as follows : + + %include + double fadd(double *INPUT, double *INPUT); + +or you can use the %apply directive : + + %include + %apply double *INPUT { double *a, double *b }; + double fadd(double *a, double *b); + +*/ + +// OUTPUT typemaps. These typemaps are used for parameters that +// are output only. The output value is appended to the result as +// a list element. + +/* +The following methods can be applied to turn a pointer into an "output" +value. When calling a function, no input value would be given for +a parameter, but an output value would be returned. In the case of +multiple output values, they are returned in the form of a Python tuple. + + int *OUTPUT + short *OUTPUT + long *OUTPUT + long long *OUTPUT + unsigned int *OUTPUT + unsigned short *OUTPUT + unsigned long *OUTPUT + unsigned long long *OUTPUT + unsigned char *OUTPUT + bool *OUTPUT + float *OUTPUT + double *OUTPUT + +For example, suppose you were trying to wrap the modf() function in the +C math library which splits x into integral and fractional parts (and +returns the integer part in one of its parameters).K: + + double modf(double x, double *ip); + +You could wrap it with SWIG as follows : + + %include + double modf(double x, double *OUTPUT); + +or you can use the %apply directive : + + %include + %apply double *OUTPUT { double *ip }; + double modf(double x, double *ip); + +The Python output of the function would be a tuple containing both +output values. + +*/ + +// INOUT +// Mappings for an argument that is both an input and output +// parameter + +/* +The following methods can be applied to make a function parameter both +an input and output value. This combines the behavior of both the +"INPUT" and "OUTPUT" methods described earlier. Output values are +returned in the form of a Python tuple. + + int *INOUT + short *INOUT + long *INOUT + long long *INOUT + unsigned int *INOUT + unsigned short *INOUT + unsigned long *INOUT + unsigned long long *INOUT + unsigned char *INOUT + bool *INOUT + float *INOUT + double *INOUT + +For example, suppose you were trying to wrap the following function : + + void neg(double *x) { + *x = -(*x); + } + +You could wrap it with SWIG as follows : + + %include + void neg(double *INOUT); + +or you can use the %apply directive : + + %include + %apply double *INOUT { double *x }; + void neg(double *x); + +Unlike C, this mapping does not directly modify the input value (since +this makes no sense in Python). Rather, the modified input value shows +up as the return value of the function. Thus, to apply this function +to a Python variable you might do this : + + x = neg(x) + +Note : previous versions of SWIG used the symbol 'BOTH' to mark +input/output arguments. This is still supported, but will be slowly +phased out in future releases. + +*/ + +%include diff --git a/Lib/javascript/v8/arrays_javascript.i b/Lib/javascript/v8/arrays_javascript.i new file mode 100644 index 000000000..22b50be8f --- /dev/null +++ b/Lib/javascript/v8/arrays_javascript.i @@ -0,0 +1,125 @@ +/* ----------------------------------------------------------------------------- + * arrays_javascript.i + * + * These typemaps give more natural support for arrays. The typemaps are not efficient + * as there is a lot of copying of the array values whenever the array is passed to C/C++ + * from JavaScript and vice versa. The JavaScript array is expected to be the same size as the C array. + * An exception is thrown if they are not. + * + * Example usage: + * Wrapping: + * + * %include + * %inline %{ + * extern int FiddleSticks[3]; + * %} + * + * Use from JavaScript like this: + * + * var fs = [10, 11, 12]; + * example.FiddleSticks = fs; + * fs = example.FiddleSticks; + * ----------------------------------------------------------------------------- */ + +%fragment("SWIG_JSCGetIntProperty", "header", fragment=SWIG_AsVal_frag(int)) {} +%fragment("SWIG_JSCGetNumberProperty", "header", fragment=SWIG_AsVal_frag(double)) {} + +%typemap(in, fragment="SWIG_JSCGetIntProperty") int[], int[ANY] + (int length = 0, v8::Local array, v8::Local jsvalue, int i = 0, int res = 0, $*1_ltype temp) { + if ($input->IsArray()) + { + // Convert into Array + array = v8::Local::Cast($input); + + length = $1_dim0; + + $1 = ($*1_ltype *)malloc(sizeof($*1_ltype) * length); + + // Get each element from array + for (i = 0; i < length; i++) + { + jsvalue = array->Get(i); + + // Get primitive value from JSObject + res = SWIG_AsVal(int)(jsvalue, &temp); + if (!SWIG_IsOK(res)) + { + SWIG_exception_fail(SWIG_ERROR, "Failed to convert $input to double"); + } + arg$argnum[i] = temp; + } + + } + else + { + SWIG_exception_fail(SWIG_ERROR, "$input is not JSObjectRef"); + } +} + +%typemap(freearg) int[], int[ANY] { + free($1); +} + +%typemap(out, fragment=SWIG_From_frag(int)) int[], int[ANY] (int length = 0, int i = 0) +{ + length = $1_dim0; + v8::Local array = v8::Array::New(length); + + for (i = 0; i < length; i++) + { + array->Set(i, SWIG_From(int)($1[i])); + } + + + $result = array; +} + +%typemap(in, fragment="SWIG_JSCGetNumberProperty") double[], double[ANY] + (int length = 0, v8::Local array, v8::Local jsvalue, int i = 0, int res = 0, $*1_ltype temp) { + if ($input->IsArray()) + { + // Convert into Array + array = v8::Local::Cast($input); + + length = $1_dim0; + + $1 = ($*1_ltype *)malloc(sizeof($*1_ltype) * length); + + // Get each element from array + for (i = 0; i < length; i++) + { + jsvalue = array->Get(i); + + // Get primitive value from JSObject + res = SWIG_AsVal(double)(jsvalue, &temp); + if (!SWIG_IsOK(res)) + { + SWIG_exception_fail(SWIG_ERROR, "Failed to convert $input to double"); + } + arg$argnum[i] = temp; + } + + } + else + { + SWIG_exception_fail(SWIG_ERROR, "$input is not JSObjectRef"); + } +} + +%typemap(freearg) double[], double[ANY] { + free($1); +} + +%typemap(out, fragment=SWIG_From_frag(double)) double[], double[ANY] (int length = 0, int i = 0) +{ + length = $1_dim0; + v8::Local array = v8::Array::New(length); + + for (i = 0; i < length; i++) + { + array->Set(i, SWIG_From(double)($1[i])); + } + + + $result = array; +} diff --git a/Lib/javascript/v8/ccomplex.i b/Lib/javascript/v8/ccomplex.i new file mode 100644 index 000000000..8eda920bb --- /dev/null +++ b/Lib/javascript/v8/ccomplex.i @@ -0,0 +1,26 @@ +/* ----------------------------------------------------------------------------- + * ccomplex.i + * + * C complex typemaps + * ISO C99: 7.3 Complex arithmetic + * ----------------------------------------------------------------------------- */ + + +%include + +%{ +#include +%} + + +/* C complex constructor */ +#define CCplxConst(r, i) ((r) + I*(i)) + +%swig_cplxflt_convn(float complex, CCplxConst, creal, cimag); +%swig_cplxdbl_convn(double complex, CCplxConst, creal, cimag); +%swig_cplxdbl_convn(complex, CCplxConst, creal, cimag); + +/* declaring the typemaps */ +%typemaps_primitive(SWIG_TYPECHECK_CPLXFLT, float complex); +%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, double complex); +%typemaps_primitive(SWIG_TYPECHECK_CPLXDBL, complex); diff --git a/Lib/javascript/v8/cdata.i b/Lib/javascript/v8/cdata.i new file mode 100644 index 000000000..367965990 --- /dev/null +++ b/Lib/javascript/v8/cdata.i @@ -0,0 +1 @@ +%include diff --git a/Lib/javascript/v8/complex.i b/Lib/javascript/v8/complex.i new file mode 100644 index 000000000..4c3b3c5e2 --- /dev/null +++ b/Lib/javascript/v8/complex.i @@ -0,0 +1,6 @@ +#ifdef __cplusplus +%include +#else +%include +#endif + diff --git a/Lib/javascript/v8/exception.i b/Lib/javascript/v8/exception.i new file mode 100644 index 000000000..0246cfde8 --- /dev/null +++ b/Lib/javascript/v8/exception.i @@ -0,0 +1 @@ +%include diff --git a/Lib/javascript/v8/javascript.swg b/Lib/javascript/v8/javascript.swg new file mode 100644 index 000000000..3a83b6495 --- /dev/null +++ b/Lib/javascript/v8/javascript.swg @@ -0,0 +1,19 @@ +/* ----------------------------------------------------------------------------- + * javascript.swg + * + * Javascript typemaps + * ----------------------------------------------------------------------------- */ + +%include + +%include + +%include + +%include + +%include + +%include + +%include diff --git a/Lib/javascript/v8/javascriptcode.swg b/Lib/javascript/v8/javascriptcode.swg new file mode 100644 index 000000000..9bcb33176 --- /dev/null +++ b/Lib/javascript/v8/javascriptcode.swg @@ -0,0 +1,468 @@ +/* ----------------------------------------------------------------------------- + * js_ctor: template for wrapping a ctor. + * - $jswrapper: wrapper of called ctor + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * - $jsargcount: number of arguments + * - $jsmangledtype: mangled type of class + * ----------------------------------------------------------------------------- */ + +%fragment("js_ctor", "templates") %{ +SwigV8ReturnValue $jswrapper(const SwigV8Arguments& args) { + v8::HandleScope scope; + v8::Handle self = args.Holder(); + $jslocals + if(args.Length() != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); + $jscode + + SWIGV8_SetPrivateData(self, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); + SWIGV8_RETURN(self); + + goto fail; +fail: + SWIGV8_RETURN(v8::Undefined()); +} +%} + +/* ----------------------------------------------------------------------------- + * js_veto_ctor: a vetoing ctor for abstract classes + * - $jswrapper: name of wrapper + * - $jsname: class name + * ----------------------------------------------------------------------------- */ +%fragment ("js_veto_ctor", "templates") +%{ +SwigV8ReturnValue $jswrapper(const SwigV8Arguments& args) { + v8::HandleScope scope; + SWIG_exception(SWIG_ERROR, "Class $jsname can not be instantiated"); + SWIGV8_RETURN(v8::Undefined()); +} +%} + +/* ----------------------------------------------------------------------------- + * js_ctor_dispatcher: dispatcher for overloaded constructors + * - $jswrapper: name of wrapper + * - $jsname: class name + * - $jsdispatchcases: part containing code for dispatching + * ----------------------------------------------------------------------------- */ +%fragment ("js_ctor_dispatcher", "templates") +%{ +SwigV8ReturnValue $jswrapper(const SwigV8Arguments& args) { + v8::HandleScope scope; + OverloadErrorHandler errorHandler; + v8::Handle self; + + // switch all cases by means of series of if-returns. + $jsdispatchcases + + // default: + SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for contruction of $jsmangledname"); + +fail: + SWIGV8_RETURN(v8::Undefined()); +} +%} + +/* ----------------------------------------------------------------------------- + * js_overloaded_ctor: template for wrapping a ctor. + * - $jswrapper: wrapper of called ctor + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * - $jsargcount: number of arguments + * - $jsmangledtype: mangled type of class + * ----------------------------------------------------------------------------- */ +%fragment("js_overloaded_ctor", "templates") %{ +SwigV8ReturnValue $jswrapper(const SwigV8Arguments& args, V8ErrorHandler& SWIGV8_ErrorHandler) { + v8::HandleScope scope; + v8::Handle self = args.Holder(); + $jslocals + if(args.Length() != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); + $jscode + + SWIGV8_SetPrivateData(self, result, SWIGTYPE_$jsmangledtype, SWIG_POINTER_OWN); + SWIGV8_RETURN(self); + + goto fail; +fail: + SWIGV8_RETURN(v8::Undefined()); +} +%} + +/* ----------------------------------------------------------------------------- + * js_ctor_dispatch_case: template for a dispatch case for calling an overloaded ctor. + * - $jsargcount: number of arguments of called ctor + * - $jswrapper: wrapper of called ctor + * + * Note: a try-catch-like mechanism is used to switch cases + * ----------------------------------------------------------------------------- */ +%fragment ("js_ctor_dispatch_case", "templates") +%{ + if(args.Length() == $jsargcount) { + errorHandler.err.Clear(); +#if SWIG_V8_VERSION < 0x031900 + self = $jswrapper(args, errorHandler); + if(errorHandler.err.IsEmpty()) { + return scope.Close(self); + } +#else + $jswrapper(args, errorHandler); + if(errorHandler.err.IsEmpty()) { + return; + } +#endif + } +%} + +/* ----------------------------------------------------------------------------- + * js_dtor: template for a destructor wrapper + * - $jsmangledname: mangled class name + * - $jstype: class type + * ----------------------------------------------------------------------------- */ +%fragment ("js_dtor", "templates") +%{ + +#if (SWIG_V8_VERSION < 0x031900) +void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) +{ + SWIGV8_Proxy *proxy = static_cast(parameter); +#else +void $jswrapper(v8::Isolate *isolate, v8::Persistent< v8::Object > * object, SWIGV8_Proxy *proxy) +{ +#endif + + if(proxy->swigCMemOwn && proxy->swigCObject) { +#ifdef SWIGRUNTIME_DEBUG + printf("Deleting wrapped instance: %s\n", proxy->info->name); +#endif + $jsfree proxy->swigCObject; + } + delete proxy; + + object.Clear(); +#if (SWIG_V8_VERSION < 0x031900) + object.Dispose(); +#elif (SWIG_V8_VERSION < 0x032100) + object->Dispose(isolate); +#else + object->Dispose(); +#endif +} +%} + +/* ----------------------------------------------------------------------------- + * js_dtoroverride: template for a destructor wrapper + * - $jsmangledname: mangled class name + * - $jstype: class type + * - ${destructor_action}: The custom destructor action to invoke. + * ----------------------------------------------------------------------------- */ +%fragment ("js_dtoroverride", "templates") +%{ +#if (SWIG_V8_VERSION < 0x031900) +void $jswrapper(v8::Persistent< v8::Value > object, void *parameter) +{ + SWIGV8_Proxy *proxy = static_cast(parameter); +#else +void $jswrapper(v8::Isolate *isolate, v8::Persistent< v8::Object > * object, SWIGV8_Proxy *proxy) +{ +#endif + if(proxy->swigCMemOwn && proxy->swigCObject) { + $jstype arg1 = ($jstype)proxy->swigCObject; + ${destructor_action} + } + delete proxy; + +#if (SWIG_V8_VERSION < 0x031900) + object.Dispose(); +#elif (SWIG_V8_VERSION < 0x032100) + object->Dispose(isolate); +#else + object->Dispose(); +#endif +} +%} + +/* ----------------------------------------------------------------------------- + * js_getter: template for getter function wrappers + * - $jswrapper: wrapper function name + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ +%fragment("js_getter", "templates") +%{ +SwigV8ReturnValue $jswrapper(v8::Local property, const SwigV8PropertyCallbackInfo& info) { + v8::HandleScope scope; + v8::Handle jsresult; + $jslocals + $jscode + SWIGV8_RETURN_INFO(jsresult, info); + + goto fail; +fail: + SWIGV8_RETURN_INFO(v8::Undefined(), info); +} +%} + +/* ----------------------------------------------------------------------------- + * js_setter: template for setter function wrappers + * - $jswrapper: wrapper function name + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ +%fragment("js_setter", "templates") +%{ +void $jswrapper(v8::Local property, v8::Local value, + const SwigV8PropertyCallbackInfoVoid& info) { + v8::HandleScope scope; + $jslocals + $jscode + goto fail; +fail: + return; +} +%} + +/* ----------------------------------------------------------------------------- + * js_function: template for function wrappers + * - $jswrapper: wrapper function name + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ +%fragment("js_function", "templates") +%{ +SwigV8ReturnValue $jswrapper(const SwigV8Arguments& args) { + v8::HandleScope scope; + v8::Handle jsresult; + $jslocals + if(args.Length() != $jsargcount) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for $jswrapper."); + + $jscode + SWIGV8_RETURN(jsresult); + + goto fail; +fail: + SWIGV8_RETURN(v8::Undefined()); +} +%} + +/* ----------------------------------------------------------------------------- + * js_function_dispatcher: template for a function dispatcher for overloaded functions + * - $jswrapper: wrapper function name + * - $jsname: name of the wrapped function + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ +%fragment("js_function_dispatcher", "templates") +%{ +SwigV8ReturnValue $jswrapper(const SwigV8Arguments& args) { + v8::HandleScope scope; + v8::Handle jsresult; + OverloadErrorHandler errorHandler; + $jscode + + SWIG_exception_fail(SWIG_ERROR, "Illegal arguments for function $jsname."); + + goto fail; +fail: + SWIGV8_RETURN(v8::Undefined()); +} +%} + +/* ----------------------------------------------------------------------------- + * js_overloaded_function: template for a overloaded function + * - $jswrapper: wrapper function name + * - $jslocals: locals part of wrapper + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ +%fragment ("js_overloaded_function", "templates") +%{ +SwigV8ReturnValue $jswrapper(const SwigV8Arguments& args, V8ErrorHandler& SWIGV8_ErrorHandler) +{ + v8::HandleScope scope; + v8::Handle jsresult; + $jslocals + $jscode + SWIGV8_RETURN(jsresult); + + goto fail; +fail: + SWIGV8_RETURN(v8::Undefined()); +} +%} + +/* ----------------------------------------------------------------------------- + * js_function_dispatch_case: template for a case used in the function dispatcher + * - $jswrapper: wrapper function name + * - $jsargcount: number of arguments of overloaded function + * - $jscode: code part of wrapper + * ----------------------------------------------------------------------------- */ +%fragment ("js_function_dispatch_case", "templates") +%{ + + if(args.Length() == $jsargcount) { + errorHandler.err.Clear(); +#if (SWIG_V8_VERSION < 0x031900) + jsresult = $jswrapper(args, errorHandler); + if(errorHandler.err.IsEmpty()) { + return scope.Close(jsresult); + } +#else + $jswrapper(args, errorHandler); + if(errorHandler.err.IsEmpty()) { + return; + } +#endif + } +%} + +/* ----------------------------------------------------------------------------- + * jsv8_declare_class_template: template for a class template declaration. + * - $jsmangledname: mangled class name + * ----------------------------------------------------------------------------- */ +%fragment("jsv8_declare_class_template", "templates") +%{ + SWIGV8_ClientData $jsmangledname_clientData; +%} + +/* ----------------------------------------------------------------------------- + * jsv8_define_class_template: template for a class template definition. + * - $jsmangledname: mangled class name + * - $jsmangledtype: mangled class type + * - $jsdtor: the dtor wrapper + * ----------------------------------------------------------------------------- */ +%fragment("jsv8_define_class_template", "templates") +%{ + v8::Handle $jsmangledname_class = SWIGV8_CreateClassTemplate("$jsmangledname"); +#if (SWIG_V8_VERSION < 0x031900) + $jsmangledname_clientData.class_templ = v8::Persistent::New($jsmangledname_class); +#else + $jsmangledname_clientData.class_templ.Reset(v8::Isolate::GetCurrent(), $jsmangledname_class); +#endif + $jsmangledname_clientData.dtor = $jsdtor; + if (SWIGTYPE_$jsmangledtype->clientdata == 0) { + SWIGTYPE_$jsmangledtype->clientdata = &$jsmangledname_clientData; + } +%} + + +/* ----------------------------------------------------------------------------- + * jsv8_inherit: template for an class inherit statement. + * - $jsmangledname: mangled class name + * - $jsbaseclass: mangled name of the base class + * ----------------------------------------------------------------------------- */ +%fragment("jsv8_inherit", "templates") +%{ + if (SWIGTYPE_p$jsbaseclass->clientdata && !(static_cast(SWIGTYPE_p$jsbaseclass->clientdata)->class_templ.IsEmpty())) + { +#if (SWIG_V8_VERSION < 0x031900) + $jsmangledname_class->Inherit(static_cast(SWIGTYPE_p$jsbaseclass->clientdata)->class_templ); +#else + $jsmangledname_class->Inherit( + v8::Handle::New( + v8::Isolate::GetCurrent(), + static_cast(SWIGTYPE_p$jsbaseclass->clientdata)->class_templ) + ); +#endif + +#ifdef SWIGRUNTIME_DEBUG + printf("Inheritance successful $jsmangledname $jsbaseclass\n"); +#endif + } else { +#ifdef SWIGRUNTIME_DEBUG + printf("Unable to inherit baseclass, it didn't exist $jsmangledname $jsbaseclass\n"); +#endif + } +%} + +/* ----------------------------------------------------------------------------- + * jsv8_create_class_instance: template for creating an class object. + * - $jsname: class name + * - $jsmangledname: mangled class name + * ----------------------------------------------------------------------------- */ +%fragment("jsv8_create_class_instance", "templates") +%{ + v8::Handle $jsmangledname_class_0 = SWIGV8_CreateClassTemplate("$jsname"); + $jsmangledname_class_0->SetCallHandler($jsctor); + $jsmangledname_class_0->Inherit($jsmangledname_class); + $jsmangledname_class_0->SetHiddenPrototype(true); + v8::Handle $jsmangledname_obj = $jsmangledname_class_0->GetFunction(); +%} + +/* ----------------------------------------------------------------------------- + * jsv8_register_class: template for a statement that registers a class in a parent namespace. + * - $jsname: class name + * - $jsmangledname: mangled class name + * - $jsparent: mangled name of parent namespace + * ----------------------------------------------------------------------------- */ +%fragment("jsv8_register_class", "templates") +%{ + $jsparent_obj->Set(v8::String::NewSymbol("$jsname"), $jsmangledname_obj); +%} + +/* ----------------------------------------------------------------------------- + * jsv8_create_namespace: template for a statement that creates a namespace object. + * - $jsmangledname: mangled namespace name + * ----------------------------------------------------------------------------- */ +%fragment("jsv8_create_namespace", "templates") +%{ + v8::Handle $jsmangledname_obj = v8::Object::New(); +%} + +/* ----------------------------------------------------------------------------- + * jsv8_register_namespace: template for a statement that registers a namespace in a parent namespace. + * - $jsname: name of namespace + * - $jsmangledname: mangled name of namespace + * - $jsparent: mangled name of parent namespace + * ----------------------------------------------------------------------------- */ +%fragment("jsv8_register_namespace", "templates") +%{ + $jsparent_obj->Set(v8::String::NewSymbol("$jsname"), $jsmangledname_obj); +%} + +/* ----------------------------------------------------------------------------- + * jsv8_register_member_function: template for a statement that registers a member function. + * - $jsmangledname: mangled class name + * - $jsname: name of the function + * - $jswrapper: wrapper of the member function + * ----------------------------------------------------------------------------- */ +%fragment("jsv8_register_member_function", "templates") +%{ + SWIGV8_AddMemberFunction($jsmangledname_class, "$jsname", $jswrapper); +%} + +/* ----------------------------------------------------------------------------- + * jsv8_register_member_variable: template for a statement that registers a member variable. + * - $jsmangledname: mangled class name + * - $jsname: name of the function + * - $jsgetter: wrapper of the getter function + * - $jssetter: wrapper of the setter function + * ----------------------------------------------------------------------------- */ +%fragment("jsv8_register_member_variable", "templates") +%{ + SWIGV8_AddMemberVariable($jsmangledname_class, "$jsname", $jsgetter, $jssetter); +%} + +/* ----------------------------------------------------------------------------- + * jsv8_register_static_function: template for a statement that registers a static class function. + * - $jsname: function name + * - $jswrapper: wrapper of the function + * - $jsparent: mangled name of parent namespace + * + * Note: this template is also used for global functions. + * ----------------------------------------------------------------------------- */ +%fragment("jsv8_register_static_function", "templates") +%{ + SWIGV8_AddStaticFunction($jsparent_obj, "$jsname", $jswrapper); +%} + +/* ----------------------------------------------------------------------------- + * jsv8_register_static_variable: template for a statement that registers a static variable. + * - $jsname: variable name + * - $jsparent: mangled name of parent namespace + * - $jsgetter: wrapper of the getter function + * - $jssetter: wrapper of the setter function + * + * Note: this template is also used for global variables. + * ----------------------------------------------------------------------------- */ +%fragment("jsv8_register_static_variable", "templates") +%{ + SWIGV8_AddStaticVariable($jsparent_obj, "$jsname", $jsgetter, $jssetter); +%} diff --git a/Lib/javascript/v8/javascriptcomplex.swg b/Lib/javascript/v8/javascriptcomplex.swg new file mode 100644 index 000000000..70c5baffb --- /dev/null +++ b/Lib/javascript/v8/javascriptcomplex.swg @@ -0,0 +1,123 @@ +/* + Defines the As/From converters for double/float complex, you need to + provide complex Type, the Name you want to use in the converters, + the complex Constructor method, and the Real and Imag complex + accessor methods. + + See the std_complex.i and ccomplex.i for concret examples. +*/ + +/* the common from converter */ +%define %swig_fromcplx_conv(Type, Real, Imag) +%fragment(SWIG_From_frag(Type),"header", + fragment=SWIG_From_frag(double)) +{ +SWIGINTERNINLINE v8::Handle +SWIG_From_dec(Type)(%ifcplusplus(const Type&, Type) c) +{ + v8::HandleScope scope; + v8::Local vals = v8::Array::New(2); + + vals->Set(0, SWIG_From(double)(Real(c))); + vals->Set(1, SWIG_From(double)(Imag(c))); + return scope.Close(vals); +} +} +%enddef + +/* the double case */ +%define %swig_cplxdbl_conv(Type, Constructor, Real, Imag) +%fragment(SWIG_AsVal_frag(Type),"header", + fragment=SWIG_AsVal_frag(double)) +{ +SWIGINTERN int +SWIG_AsVal_dec(Type) (v8::Handle o, Type* val) +{ + v8::HandleScope scope; + + if (o->IsArray()) { + v8::Handle array = v8::Handle::Cast(o); + + if(array->Length() != 2) SWIG_Error(SWIG_TypeError, "Illegal argument for complex: must be array[2]."); + double re, im; + int res; + + res = SWIG_AsVal(double)(array->Get(0), &re); + if(!SWIG_IsOK(res)) { + return SWIG_TypeError; + } + + res = SWIG_AsVal(double)(array->Get(1), &im); + if(!SWIG_IsOK(res)) { + return SWIG_TypeError; + } + + if (val) *val = Constructor(re, im); + return SWIG_OK; + } else if(o->IsNumber()){ + double d; + int res = SWIG_AddCast(SWIG_AsVal(double)(o, &d)); + if (SWIG_IsOK(res)) { + if (val) *val = Constructor(d, 0.0); + return res; + } + } + return SWIG_TypeError; +} +} +%swig_fromcplx_conv(Type, Real, Imag); +%enddef + +/* the float case */ +%define %swig_cplxflt_conv(Type, Constructor, Real, Imag) +%fragment(SWIG_AsVal_frag(Type),"header", + fragment=SWIG_AsVal_frag(float)) { +SWIGINTERN int +SWIG_AsVal_dec(Type) (v8::Handle o, Type* val) +{ + v8::HandleScope scope; + + if (o->IsArray()) { + v8::Handle array = v8::Handle::Cast(o); + + if(array->Length() != 2) SWIG_Error(SWIG_TypeError, "Illegal argument for complex: must be array[2]."); + double re, im; + int res; + + res = SWIG_AsVal(double)(array->Get(0), &re); + if(!SWIG_IsOK(res)) { + return SWIG_TypeError; + } + + res = SWIG_AsVal(double)(array->Get(1), &im); + if(!SWIG_IsOK(res)) { + return SWIG_TypeError; + } + + if ((-FLT_MAX <= re && re <= FLT_MAX) && (-FLT_MAX <= im && im <= FLT_MAX)) { + if (val) *val = Constructor(%numeric_cast(re, float), + %numeric_cast(im, float)); + return SWIG_OK; + } else { + return SWIG_OverflowError; + } + } else if(o->IsNumber()){ + float re; + int res = SWIG_AddCast(SWIG_AsVal(float)(o, &re)); + if (SWIG_IsOK(res)) { + if (val) *val = Constructor(re, 0.0); + return res; + } + } + return SWIG_TypeError; +} +} +%swig_fromcplx_conv(Type, Real, Imag); +%enddef + +#define %swig_cplxflt_convn(Type, Constructor, Real, Imag) \ +%swig_cplxflt_conv(Type, Constructor, Real, Imag) + + +#define %swig_cplxdbl_convn(Type, Constructor, Real, Imag) \ +%swig_cplxdbl_conv(Type, Constructor, Real, Imag) diff --git a/Lib/javascript/v8/javascriptfragments.swg b/Lib/javascript/v8/javascriptfragments.swg new file mode 100644 index 000000000..4778bf033 --- /dev/null +++ b/Lib/javascript/v8/javascriptfragments.swg @@ -0,0 +1,23 @@ +/* + + Create a file with this name, 'javascriptfragments.swg', in your working + directory and add all the %fragments you want to take precedence + over the default ones defined by swig. + + For example, if you add: + + %fragment(SWIG_AsVal_frag(int),"header") { + SWIGINTERNINLINE int + SWIG_AsVal(int)(PyObject *obj, int *val) + { + ; + } + } + + this will replace the code used to retrieve an integer value for all + the typemaps that need it, including: + + int, std::vector, std::list >, etc. + + +*/ diff --git a/Lib/javascript/v8/javascripthelpers.swg b/Lib/javascript/v8/javascripthelpers.swg new file mode 100644 index 000000000..8da6627e2 --- /dev/null +++ b/Lib/javascript/v8/javascripthelpers.swg @@ -0,0 +1,87 @@ +%insert(runtime) %{ + +// Note: since 3.19 there are new CallBack types, since 03.21.9 the old ones have been removed +#if SWIG_V8_VERSION < 0x031900 +typedef v8::InvocationCallback SwigV8FunctionCallback; +typedef v8::AccessorGetter SwigV8AccessorGetterCallback; +typedef v8::AccessorSetter SwigV8AccessorSetterCallback; +typedef v8::AccessorInfo SwigV8PropertyCallbackInfoVoid; +#else +typedef v8::FunctionCallback SwigV8FunctionCallback; +typedef v8::AccessorGetterCallback SwigV8AccessorGetterCallback; +typedef v8::AccessorSetterCallback SwigV8AccessorSetterCallback; +typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfoVoid; +#endif + +/** + * Creates a class template for a class with specified initialization function. + */ +v8::Handle SWIGV8_CreateClassTemplate(const char* symbol) { + v8::HandleScope scope; + v8::Local class_templ = v8::FunctionTemplate::New(); + class_templ->SetClassName(v8::String::NewSymbol(symbol)); + + v8::Handle inst_templ = class_templ->InstanceTemplate(); + inst_templ->SetInternalFieldCount(1); + + v8::Handle equals_templ = class_templ->PrototypeTemplate(); + equals_templ->Set(v8::String::NewSymbol("equals"), v8::FunctionTemplate::New(_SWIGV8_wrap_equals)); + + v8::Handle cptr_templ = class_templ->PrototypeTemplate(); + cptr_templ->Set(v8::String::NewSymbol("getCPtr"), v8::FunctionTemplate::New(_wrap_getCPtr)); + + return scope.Close(class_templ); +} + +/** + * Registers a class method with given name for a given class template. + */ +void SWIGV8_AddMemberFunction(v8::Handle class_templ, const char* symbol, + SwigV8FunctionCallback _func) { + v8::Handle proto_templ = class_templ->PrototypeTemplate(); + proto_templ->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)); +} + +/** + * Registers a class property with given name for a given class template. + */ +void SWIGV8_AddMemberVariable(v8::Handle class_templ, const char* symbol, + SwigV8AccessorGetterCallback getter, SwigV8AccessorSetterCallback setter) { + v8::Handle proto_templ = class_templ->InstanceTemplate(); + proto_templ->SetAccessor(v8::String::NewSymbol(symbol), getter, setter); +} + +/** + * Registers a class method with given name for a given object. + */ +void SWIGV8_AddStaticFunction(v8::Handle obj, const char* symbol, + const SwigV8FunctionCallback& _func) { + obj->Set(v8::String::NewSymbol(symbol), v8::FunctionTemplate::New(_func)->GetFunction()); +} + +/** + * Registers a class method with given name for a given object. + */ +void SWIGV8_AddStaticVariable(v8::Handle obj, const char* symbol, + SwigV8AccessorGetterCallback getter, SwigV8AccessorSetterCallback setter) { + obj->SetAccessor(v8::String::NewSymbol(symbol), getter, setter); +} + +void JS_veto_set_variable(v8::Local property, v8::Local value, + const SwigV8PropertyCallbackInfoVoid& info) +{ + char buffer[256]; + char msg[512]; + int res; + + property->WriteUtf8(buffer, 256); + res = sprintf(msg, "Tried to write read-only variable: %s.", buffer); + + if(res<0) { + SWIG_exception(SWIG_ERROR, "Tried to write read-only variable."); + } else { + SWIG_exception(SWIG_ERROR, msg); + } +} + +%} // v8_helper_functions diff --git a/Lib/javascript/v8/javascriptinit.swg b/Lib/javascript/v8/javascriptinit.swg new file mode 100644 index 000000000..de1fe91f4 --- /dev/null +++ b/Lib/javascript/v8/javascriptinit.swg @@ -0,0 +1,118 @@ +%insert(init) %{ + +#include + +SWIGRUNTIME void +SWIG_V8_SetModule(void *, swig_module_info *swig_module) { + v8::Local global_obj = v8::Context::GetCurrent()->Global(); + v8::Local mod = v8::External::New(swig_module); + assert(!mod.IsEmpty()); + global_obj->SetHiddenValue(v8::String::New("swig_module_info_data"), mod); +} + +SWIGRUNTIME swig_module_info * +SWIG_V8_GetModule(void *) { + v8::Local global_obj = v8::Context::GetCurrent()->Global(); + v8::Local moduleinfo = global_obj->GetHiddenValue(v8::String::New("swig_module_info_data")); + + if (moduleinfo.IsEmpty()) + { + // It's not yet loaded + return 0; + } + + v8::Local moduleinfo_extern = v8::Local::Cast(moduleinfo); + + if (moduleinfo_extern.IsEmpty()) + { + // Something's not right + return 0; + } + + void *ptr = moduleinfo_extern->Value(); + assert(ptr); + swig_module_info *retptr = static_cast(ptr); + assert(retptr); + return retptr; +} + +#define SWIG_GetModule(clientdata) SWIG_V8_GetModule(clientdata) +#define SWIG_SetModule(clientdata, pointer) SWIG_V8_SetModule(clientdata, pointer) + +%} + +%insert(init) "swiginit.swg" + +// Open the initializer function definition here + +%fragment ("js_initializer_define", "templates") %{ +#define SWIGV8_INIT $jsname_initialize +%} + +%insert(init) %{ +// Note: 'extern "C"'' disables name mangling which makes it easier to load the symbol manually +// TODO: is it ok to do that? +extern "C" +#if (NODE_MODULE_VERSION < 0x000C) +void SWIGV8_INIT (v8::Handle exports) +#else +void SWIGV8_INIT (v8::Handle exports, v8::Handle /*module*/) +#endif +{ + SWIG_InitializeModule(static_cast(&exports)); + + v8::HandleScope scope; + v8::Handle exports_obj = exports; +%} + + +/* ----------------------------------------------------------------------------- + * js_initializer: template for the module initializer function + * - $jsname: module name + * - $jsv8nspaces: part with code creating namespace objects + * - $jsv8classtemplates: part with code creating class templates + * - $jsv8wrappers: part with code that registers wrapper functions + * - $jsv8inheritance: part with inherit statements + * - $jsv8classinstances: part with code creating class objects + * - $jsv8staticwrappers: part with code adding static functions to class objects + * - $jsv8registerclasses: part with code that registers class objects in namespaces + * - $jsv8registernspaces: part with code that registers namespaces in parent namespaces + * ----------------------------------------------------------------------------- */ +%fragment("js_initializer", "templates") +%{ + // a class template for creating proxies of undefined types +#if (SWIG_V8_VERSION < 0x031900) + SWIGV8_SWIGTYPE_Proxy_class_templ = v8::Persistent::New(SWIGV8_CreateClassTemplate("SwigProxy")); +#else + SWIGV8_SWIGTYPE_Proxy_class_templ.Reset(v8::Isolate::GetCurrent(), SWIGV8_CreateClassTemplate("SwigProxy")); +#endif + + /* create objects for namespaces */ + $jsv8nspaces + + /* create class templates */ + $jsv8classtemplates + + /* register wrapper functions */ + $jsv8wrappers + + /* setup inheritances */ + $jsv8inheritance + + /* class instances */ + $jsv8classinstances + + /* add static class functions and variables */ + $jsv8staticwrappers + + /* register classes */ + $jsv8registerclasses + + /* create and register namespace objects */ + $jsv8registernspaces +} + +#if defined(BUILDING_NODE_EXTENSION) +NODE_MODULE($jsname, $jsname_initialize); +#endif +%} diff --git a/Lib/javascript/v8/javascriptkw.swg b/Lib/javascript/v8/javascriptkw.swg new file mode 100644 index 000000000..c3c118391 --- /dev/null +++ b/Lib/javascript/v8/javascriptkw.swg @@ -0,0 +1,40 @@ +#ifndef JAVASCRIPT_JAVASCRIPTKW_SWG_ +#define JAVASCRIPT_JAVASCRIPTKW_SWG_ + +/* Warnings for Java keywords */ +#define JAVASCRIPTKW(x) %keywordwarn("'" `x` "' is a javascript keyword, renaming to '_"`x`"'",rename="_%s") `x` + +/* Taken from https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Reserved_Words */ + +JAVASCRIPTKW(break); +JAVASCRIPTKW(case); +JAVASCRIPTKW(catch); +JAVASCRIPTKW(continue); +JAVASCRIPTKW(default); +JAVASCRIPTKW(delete); +JAVASCRIPTKW(do); +JAVASCRIPTKW(else); +JAVASCRIPTKW(finally); +JAVASCRIPTKW(for); +JAVASCRIPTKW(function); +JAVASCRIPTKW(if); +JAVASCRIPTKW(in); +JAVASCRIPTKW(instanceof); +JAVASCRIPTKW(new); +JAVASCRIPTKW(return); +JAVASCRIPTKW(switch); +JAVASCRIPTKW(this); +JAVASCRIPTKW(throw); +JAVASCRIPTKW(try); +JAVASCRIPTKW(typeof); +JAVASCRIPTKW(var); +JAVASCRIPTKW(void); +JAVASCRIPTKW(while); +JAVASCRIPTKW(with); + +/* others bad names if any*/ +// for example %namewarn("321:clone() is a javascript bad method name") *::clone(); + +#undef JAVASCRIPTKW + +#endif //JAVASCRIPT_JAVASCRIPTKW_SWG_ diff --git a/Lib/javascript/v8/javascriptprimtypes.swg b/Lib/javascript/v8/javascriptprimtypes.swg new file mode 100644 index 000000000..706a799b7 --- /dev/null +++ b/Lib/javascript/v8/javascriptprimtypes.swg @@ -0,0 +1,198 @@ +/* ------------------------------------------------------------ + * Primitive Types + * ------------------------------------------------------------ */ + +/* boolean */ + +%fragment(SWIG_From_frag(bool),"header") { +SWIGINTERNINLINE +v8::Handle +SWIG_From_dec(bool)(bool value) +{ + return v8::Boolean::New(value); +} +} + +%fragment(SWIG_AsVal_frag(bool),"header", + fragment=SWIG_AsVal_frag(long)) { +SWIGINTERN +int SWIG_AsVal_dec(bool)(v8::Handle obj, bool *val) +{ + if(!obj->IsBoolean()) { + return SWIG_ERROR; + } + + if (val) *val = obj->BooleanValue(); + return SWIG_OK; +} +} + +/* int */ + +%fragment(SWIG_From_frag(int),"header") { +SWIGINTERNINLINE +v8::Handle SWIG_From_dec(int)(int value) +{ + return v8::Int32::New(value); +} +} + +%fragment(SWIG_AsVal_frag(int),"header") { +SWIGINTERN +int SWIG_AsVal_dec(int)(v8::Handle valRef, int* val) +{ + if (!valRef->IsNumber()) { + return SWIG_TypeError; + } + if(val) *val = valRef->IntegerValue(); + + return SWIG_OK; +} +} + +/* long */ + +%fragment(SWIG_From_frag(long),"header") { +SWIGINTERNINLINE +v8::Handle SWIG_From_dec(long)(long value) +{ + return v8::Number::New(value); +} +} + +%fragment(SWIG_AsVal_frag(long),"header", + fragment="SWIG_CanCastAsInteger") { +SWIGINTERN +int SWIG_AsVal_dec(long)(v8::Handle obj, long* val) +{ + if (!obj->IsNumber()) { + return SWIG_TypeError; + } + if(val) *val = (long) obj->IntegerValue(); + + return SWIG_OK; +} +} + +/* unsigned long */ + +%fragment(SWIG_From_frag(unsigned long),"header", + fragment=SWIG_From_frag(long)) { +SWIGINTERNINLINE +v8::Handle SWIG_From_dec(unsigned long)(unsigned long value) +{ + return (value > LONG_MAX) ? + v8::Integer::NewFromUnsigned(value) : v8::Integer::New(%numeric_cast(value,long)); +} +} + +%fragment(SWIG_AsVal_frag(unsigned long),"header", + fragment="SWIG_CanCastAsInteger") { +SWIGINTERN +int SWIG_AsVal_dec(unsigned long)(v8::Handle obj, unsigned long *val) +{ + if(!obj->IsNumber()) { + return SWIG_TypeError; + } + + long longVal = (long) obj->NumberValue(); + + if(longVal < 0) { + return SWIG_OverflowError; + } + + if(val) *val = longVal; + + return SWIG_OK; +} +} + +/* long long */ +// Note: these are copied from 'long' and probably need fixing + +%fragment(SWIG_From_frag(long long),"header", + fragment=SWIG_From_frag(long), + fragment="") { +SWIGINTERNINLINE +v8::Handle SWIG_From_dec(long long)(long long value) +{ + return v8::Number::New(value); +} +} + +%fragment(SWIG_AsVal_frag(long long),"header", + fragment=SWIG_AsVal_frag(long), + fragment="SWIG_CanCastAsInteger", + fragment="") { +SWIGINTERN +int SWIG_AsVal_dec(long long)(v8::Handle obj, long long* val) +{ + if (!obj->IsNumber()) { + return SWIG_TypeError; + } + if(val) *val = (long long) obj->IntegerValue(); + + return SWIG_OK; +} +} + +/* unsigned long long */ +// Note: these are copied from 'unsigned long' and probably need fixing + +%fragment(SWIG_From_frag(unsigned long long),"header", + fragment=SWIG_From_frag(long long), + fragment="") { +SWIGINTERNINLINE +v8::Handle SWIG_From_dec(unsigned long long)(unsigned long long value) +{ + return (value > LONG_MAX) ? + v8::Integer::NewFromUnsigned(value) : v8::Integer::New(%numeric_cast(value,long)); +} +} + +%fragment(SWIG_AsVal_frag(unsigned long long),"header", + fragment=SWIG_AsVal_frag(unsigned long), + fragment="SWIG_CanCastAsInteger", + fragment="") { +SWIGINTERN +int SWIG_AsVal_dec(unsigned long long)(v8::Handle obj, unsigned long long *val) +{ + if(!obj->IsNumber()) { + return SWIG_TypeError; + } + + long long longVal = (long long) obj->NumberValue(); + + if(longVal < 0) { + return SWIG_OverflowError; + } + + if(val) *val = longVal; + + return SWIG_OK; +} +} + +/* double */ + +%fragment(SWIG_From_frag(double),"header") { +SWIGINTERN +v8::Handle SWIG_From_dec(double) (double val) +{ + return v8::Number::New(val); +} +} + +%fragment(SWIG_AsVal_frag(double),"header") { +SWIGINTERN +int SWIG_AsVal_dec(double)(v8::Handle obj, double *val) +{ + if(!obj->IsNumber()) { + return SWIG_TypeError; + } + if(val) *val = obj->NumberValue(); + + return SWIG_OK; +} +} + diff --git a/Lib/javascript/v8/javascriptrun.swg b/Lib/javascript/v8/javascriptrun.swg new file mode 100644 index 000000000..2e0a46717 --- /dev/null +++ b/Lib/javascript/v8/javascriptrun.swg @@ -0,0 +1,462 @@ +/* --------------------------------------------------------------------------- + * Error handling + * + * ---------------------------------------------------------------------------*/ + +#define SWIG_Error(code, msg) SWIGV8_ErrorHandler.error(code, msg) +#define SWIG_exception(code, msg) SWIGV8_ErrorHandler.error(code, msg) +#define SWIG_fail goto fail +#define SWIGV8_OVERLOAD false + +void SWIG_V8_Raise(const char* msg) { + v8::ThrowException(v8::Exception::Error(v8::String::New(msg))); +} + +/* + Note: There are two contexts for handling errors. + A static V8ErrorHandler is used in not overloaded methods. + For overloaded methods the throwing type checking mechanism is used + during dispatching. As V8 exceptions can not be resetted properly + the trick is to use a dynamic ErrorHandler with same local name as the global + one. + + - See defintion of SWIG_Error above. + - See code templates 'JS_function_dispatcher', 'JS_functionwrapper_overload', + and 'JS_function_dispatch_case' in javascriptcode.swg + +*/ +class V8ErrorHandler { +public: + virtual ~V8ErrorHandler() {} + virtual void error(int code, const char* msg) { + SWIG_V8_Raise(msg); + } +}; +// this is used in usually +V8ErrorHandler SWIGV8_ErrorHandler; + +// instances of this are used in overloaded functions +class OverloadErrorHandler: public V8ErrorHandler { +public: + virtual void error(int code, const char* msg) { + err = v8::Exception::Error(v8::String::New(msg)); + if(code != SWIG_TypeError) { + v8::ThrowException(err); + } + } + v8::Handle err; +}; + +// Note: these typedefs and defines are used to deal with v8 API changes since version 3.19.00 + +#if (SWIG_V8_VERSION < 0x031900) +typedef v8::Handle SwigV8ReturnValue; +typedef v8::Arguments SwigV8Arguments; +typedef v8::AccessorInfo SwigV8PropertyCallbackInfo; +#define SWIGV8_RETURN(val) return scope.Close(val) +#define SWIGV8_RETURN_INFO(val, info) return scope.Close(val) +#else +typedef void SwigV8ReturnValue; +typedef v8::FunctionCallbackInfo SwigV8Arguments; +typedef v8::PropertyCallbackInfo SwigV8PropertyCallbackInfo; +#define SWIGV8_RETURN(val) args.GetReturnValue().Set(val); return +#define SWIGV8_RETURN_INFO(val, info) info.GetReturnValue().Set(val); return +#endif + + +/* --------------------------------------------------------------------------- + * Basic Proxy object + * + * ---------------------------------------------------------------------------*/ + +// Note: to trigger the v8 gc more often one can tell v8 about the memory consumption +// TODO: we could add a v8 specific parameter to control this value +#define SWIGV8_AVG_OBJ_SIZE 1000 + +class SWIGV8_Proxy { +public: + SWIGV8_Proxy(): swigCMemOwn(false), swigCObject(0), info(0) { + v8::V8::AdjustAmountOfExternalAllocatedMemory(SWIGV8_AVG_OBJ_SIZE); + }; + + ~SWIGV8_Proxy() { +#if (SWIG_V8_VERSION < 0x031900 || SWIG_V8_VERSION >= 0x032100) + handle.ClearWeak(); + handle.Dispose(); +#else + handle.ClearWeak(v8::Isolate::GetCurrent()); + handle.Dispose(v8::Isolate::GetCurrent()); +#endif + + handle.Clear(); + v8::V8::AdjustAmountOfExternalAllocatedMemory(-SWIGV8_AVG_OBJ_SIZE); + } + + bool swigCMemOwn; + void *swigCObject; + swig_type_info *info; + v8::Persistent handle; +}; + +class SWIGV8_ClientData { +public: + v8::Persistent class_templ; + +#if (SWIG_V8_VERSION < 0x031900) + void (*dtor) (v8::Persistent< v8::Value> object, void *parameter); +#else + void (*dtor) (v8::Isolate *isolate, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy); +#endif +}; + +v8::Persistent SWIGV8_SWIGTYPE_Proxy_class_templ; + +int SWIG_V8_ConvertInstancePtr(v8::Handle objRef, void** ptr, swig_type_info *info, int flags) { + v8::HandleScope scope; + + if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; + +#if (SWIG_V8_VERSION < 0x031900) + v8::Handle cdataRef = objRef->GetInternalField(0); + SWIGV8_Proxy *cdata = static_cast(v8::External::Unwrap(cdataRef)); +#else + SWIGV8_Proxy *cdata = static_cast(objRef->GetAlignedPointerFromInternalField(0)); +#endif + + if(cdata == NULL) { + return SWIG_ERROR; + } + if(cdata->info != info) { + swig_cast_info *tc = SWIG_TypeCheckStruct(cdata->info, info); + if (!tc && cdata->info->name) { + tc = SWIG_TypeCheck(cdata->info->name, info); + } + bool type_valid = tc != 0; + if(!type_valid) { + return SWIG_TypeError; + } + } + *ptr = cdata->swigCObject; + if(flags & SWIG_POINTER_DISOWN) { + cdata->swigCMemOwn = false; + } + return SWIG_OK; +} + +#if (SWIG_V8_VERSION < 0x031900) +void SWIGV8_Proxy_DefaultDtor(v8::Persistent< v8::Value > object, void *parameter) +#else +void SWIGV8_Proxy_DefaultDtor(v8::Isolate *, v8::Persistent< v8::Object > *object, SWIGV8_Proxy *proxy) +#endif +{ +#if (SWIG_V8_VERSION < 0x031900) + SWIGV8_Proxy *proxy = static_cast(parameter); +#endif + + delete proxy; +} + +int SWIG_V8_GetInstancePtr(v8::Handle valRef, void** ptr) { + if(!valRef->IsObject()) { + return SWIG_TypeError; + } + v8::Handle objRef = valRef->ToObject(); + + if(objRef->InternalFieldCount() < 1) return SWIG_ERROR; + +#if (SWIG_V8_VERSION < 0x031900) + v8::Handle cdataRef = objRef->GetInternalField(0); + SWIGV8_Proxy *cdata = static_cast(v8::External::Unwrap(cdataRef)); +#else + SWIGV8_Proxy *cdata = static_cast(objRef->GetAlignedPointerFromInternalField(0)); +#endif + + if(cdata == NULL) { + return SWIG_ERROR; + } + + *ptr = cdata->swigCObject; + + return SWIG_OK; +} + +void SWIGV8_SetPrivateData(v8::Handle obj, void* ptr, swig_type_info *info, int flags) { + SWIGV8_Proxy* cdata = new SWIGV8_Proxy(); + cdata->swigCObject = ptr; + cdata->swigCMemOwn = (flags & SWIG_POINTER_OWN) ? 1 : 0; + cdata->info = info; + +#if (SWIG_V8_VERSION < 0x031900) + obj->SetPointerInInternalField(0, cdata); + cdata->handle = v8::Persistent::New(obj); +#else + obj->SetAlignedPointerInInternalField(0, cdata); + cdata->handle.Reset(v8::Isolate::GetCurrent(), obj); +#endif + +#if (SWIG_V8_VERSION < 0x031900) + // clientdata must be set for owned data as we need to register the dtor + if(cdata->swigCMemOwn && (SWIGV8_ClientData*)info->clientdata) { + cdata->handle.MakeWeak(cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); + } else { + cdata->handle.MakeWeak(cdata, SWIGV8_Proxy_DefaultDtor); + } + cdata->handle.MarkIndependent(); +#else + if(cdata->swigCMemOwn && (SWIGV8_ClientData*)info->clientdata) { + cdata->handle.MakeWeak(v8::Isolate::GetCurrent(), cdata, ((SWIGV8_ClientData*)info->clientdata)->dtor); + } else { + cdata->handle.MakeWeak(v8::Isolate::GetCurrent(), cdata, SWIGV8_Proxy_DefaultDtor); + } + +#if (SWIG_V8_VERSION < 0x032100) + cdata->handle.MarkIndependent(v8::Isolate::GetCurrent()); +#else + cdata->handle.MarkIndependent(); +#endif + +#endif +} + +int SWIG_V8_ConvertPtr(v8::Handle valRef, void** ptr, swig_type_info *info, int flags) { + v8::HandleScope scope; + + if(!valRef->IsObject()) { + return SWIG_TypeError; + } + v8::Handle objRef = valRef->ToObject(); + return SWIG_V8_ConvertInstancePtr(objRef, ptr, info, flags); +} + +v8::Handle SWIG_V8_NewPointerObj(void *ptr, swig_type_info *info, int flags) { + v8::HandleScope scope; + v8::Handle class_templ; + +#if (SWIG_V8_VERSION < 0x031900) + if(info->clientdata != 0) { + class_templ = ((SWIGV8_ClientData*) info->clientdata)->class_templ; + } else { + class_templ = SWIGV8_SWIGTYPE_Proxy_class_templ; + } +#else + v8::Isolate *iso = v8::Isolate::GetCurrent(); + + if(info->clientdata != 0) { + class_templ = v8::Handle::New(iso, ((SWIGV8_ClientData*) info->clientdata)->class_templ); + } else { + class_templ = v8::Handle::New(iso, SWIGV8_SWIGTYPE_Proxy_class_templ); + } +#endif + + v8::Handle result = class_templ->InstanceTemplate()->NewInstance(); + SWIGV8_SetPrivateData(result, ptr, info, flags); + + return scope.Close(result); +} + +#define SWIG_ConvertPtr(obj, ptr, info, flags) SWIG_V8_ConvertPtr(obj, ptr, info, flags) +#define SWIG_NewPointerObj(ptr, info, flags) SWIG_V8_NewPointerObj(ptr, info, flags) + +#define SWIG_ConvertInstance(obj, pptr, type, flags) SWIG_V8_ConvertInstancePtr(obj, pptr, type, flags) +#define SWIG_NewInstanceObj(thisvalue, type, flags) SWIG_V8_NewPointerObj(thisvalue, type, flags) + +#define SWIG_ConvertFunctionPtr(obj, pptr, type) SWIG_V8_ConvertPtr(obj, pptr, type, 0) +#define SWIG_NewFunctionPtrObj(ptr, type) SWIG_V8_NewPointerObj(ptr, type, 0) + +#define SWIG_GetInstancePtr(obj, ptr) SWIG_V8_GetInstancePtr(obj, ptr) + +#if (SWIG_V8_VERSION < 0x031900) +v8::Handle _SWIGV8_wrap_equals(const v8::Arguments &args) { +#else +void _SWIGV8_wrap_equals(const v8::FunctionCallbackInfo& args) { +#endif + v8::HandleScope scope; + v8::Handle jsresult; + void *arg1 = (void *) 0 ; + void *arg2 = (void *) 0 ; + bool result; + int res1; + int res2; + + if(args.Length() != 1) SWIG_exception_fail(SWIG_ERROR, "Illegal number of arguments for equals."); + + res1 = SWIG_GetInstancePtr(args.Holder(), &arg1); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ERROR, "Could not get pointer from 'this' object for equals."); + } + res2 = SWIG_GetInstancePtr(args[0], &arg2); + if (!SWIG_IsOK(res2)) { + SWIG_exception_fail(SWIG_ArgError(res2), "in method '" "equals" "', argument " "1"" of type '" "void *""'"); + } + + result = (bool)(arg1 == arg2); + jsresult = v8::Boolean::New(result); + + SWIGV8_RETURN(jsresult); + goto fail; +fail: + SWIGV8_RETURN(v8::Undefined()); +} + +#if (SWIG_V8_VERSION < 0x031900) +v8::Handle _wrap_getCPtr(const v8::Arguments &args) { +#else +void _wrap_getCPtr(const v8::FunctionCallbackInfo& args) { +#endif + v8::HandleScope scope; + v8::Handle jsresult; + void *arg1 = (void *) 0 ; + long result; + int res1; + + res1 = SWIG_GetInstancePtr(args.Holder(), &arg1); + if (!SWIG_IsOK(res1)) { + SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "getCPtr" "', argument " "1"" of type '" "void *""'"); + } + + result = (long)arg1; + jsresult = v8::Number::New(result); + + SWIGV8_RETURN(jsresult); + goto fail; +fail: + SWIGV8_RETURN(v8::Undefined()); +} + +/* --------------------------------------------------------------------------- + * PackedData object + * + * ---------------------------------------------------------------------------*/ + +class SwigV8PackedData { +public: + SwigV8PackedData(void *data, size_t size, swig_type_info *type): data(data), size(size), type(type) {}; + + ~SwigV8PackedData() { + }; + + void* data; + size_t size; + swig_type_info *type; + + v8::Persistent handle; +}; + +SWIGRUNTIMEINLINE +int SwigV8Packed_Check(v8::Handle valRef) { + v8::HandleScope scope; + v8::Handle objRef = valRef->ToObject(); + if(objRef->InternalFieldCount() < 1) return false; + v8::Handle flag = objRef->GetHiddenValue(v8::String::New("__swig__packed_data__")); + return (flag->IsBoolean() && flag->BooleanValue()); +} + +SWIGRUNTIME +swig_type_info* SwigV8Packed_UnpackData(v8::Handle valRef, void *ptr, size_t size) { + if (SwigV8Packed_Check(valRef)) { + v8::HandleScope scope; + SwigV8PackedData *sobj; + + v8::Handle objRef = valRef->ToObject(); + +#if (SWIG_V8_VERSION < 0x031900) + v8::Handle cdataRef = objRef->GetInternalField(0); + sobj = static_cast(v8::External::Unwrap(cdataRef)); +#else + sobj = static_cast(objRef->GetAlignedPointerFromInternalField(0)); +#endif + if (sobj == NULL || sobj->size != size) return 0; + memcpy(ptr, sobj->data, size); + return sobj->type; + } else { + return 0; + } +} + +SWIGRUNTIME +int SWIGV8_ConvertPacked(v8::Handle valRef, void *ptr, size_t sz, swig_type_info *ty) { + swig_type_info *to = SwigV8Packed_UnpackData(valRef, ptr, sz); + if (!to) return SWIG_ERROR; + if (ty) { + if (to != ty) { + /* check type cast? */ + swig_cast_info *tc = SWIG_TypeCheck(to->name,ty); + if (!tc) return SWIG_ERROR; + } + } + return SWIG_OK; +} + +#if (SWIG_V8_VERSION < 0x031900) +void _wrap_SwigV8PackedData_delete(v8::Persistent< v8::Value > object, void *parameter) +{ + SwigV8PackedData *cdata = static_cast(parameter); +#else +void _wrap_SwigV8PackedData_delete(v8::Isolate *isolate, v8::Persistent< v8::Object > * object, SwigV8PackedData *cdata) +{ +#endif + + delete cdata; + +#if (SWIG_V8_VERSION < 0x031900) + object.Clear(); + object.Dispose(); +#elif (SWIG_V8_VERSION < 0x032100) + object->Dispose(isolate); +#else + object->Dispose(); +#endif +} + +SWIGRUNTIME +v8::Handle SWIGV8_NewPackedObj(void *data, size_t size, swig_type_info *type) { + v8::HandleScope scope; + + SwigV8PackedData* cdata = new SwigV8PackedData(data, size, type); + v8::Handle obj = v8::Object::New(); + + obj->SetHiddenValue(v8::String::New("__swig__packed_data__"), v8::Boolean::New(true)); + +#if (SWIG_V8_VERSION < 0x031900) + obj->SetPointerInInternalField(0, cdata); + cdata->handle = v8::Persistent::New(obj); +#else + obj->SetAlignedPointerInInternalField(0, cdata); + cdata->handle.Reset(v8::Isolate::GetCurrent(), obj); +#endif + +#if (SWIG_V8_VERSION < 0x031900) + cdata->handle.MakeWeak(cdata, _wrap_SwigV8PackedData_delete); + cdata->handle.MarkIndependent(); +#else + cdata->handle.MakeWeak(v8::Isolate::GetCurrent(), cdata, _wrap_SwigV8PackedData_delete); +# if (SWIG_V8_VERSION < 0x032100) + cdata->handle.MarkIndependent(v8::Isolate::GetCurrent()); +# else + cdata->handle.MarkIndependent(); +# endif +#endif + + return scope.Close(obj); +} + +#define SWIG_ConvertMember(obj, ptr, sz, ty) SWIGV8_ConvertPacked(obj, ptr, sz, ty) +#define SWIG_NewMemberObj(ptr, sz, type) SWIGV8_NewPackedObj(ptr, sz, type) + + +/* --------------------------------------------------------------------------- + * Support for IN/OUTPUT typemaps (see Lib/typemaps/inoutlist.swg) + * + * ---------------------------------------------------------------------------*/ + +SWIGRUNTIME +v8::Handle SWIGV8_AppendOutput(v8::Handle result, v8::Handle obj) { + v8::HandleScope scope; + if (result->IsUndefined()) { + result = v8::Array::New(); + } + v8::Handle arr = v8::Handle::Cast(result); + arr->Set(arr->Length(), obj); + + return scope.Close(arr); +} diff --git a/Lib/javascript/v8/javascriptruntime.swg b/Lib/javascript/v8/javascriptruntime.swg new file mode 100644 index 000000000..2e18d19bf --- /dev/null +++ b/Lib/javascript/v8/javascriptruntime.swg @@ -0,0 +1,39 @@ +/* ----------------------------------------------------------------------------- + * javascriptruntime.swg + * + * ----------------------------------------------------------------------------- */ + +%define %swig_v8_define_version(version) +%insert("runtime") %{ +#ifndef SWIG_V8_VERSION +#define SWIG_V8_VERSION version +#endif +%} +%enddef + +#ifdef V8_VERSION +%swig_v8_define_version(V8_VERSION) +#else +// HACK: defining a default version +%swig_v8_define_version(0x031110) +#endif + +#ifdef BUILDING_NODE_EXTENSION +%insert("runtime") %{ +#include +%} +#endif + +%insert(runtime) %{ +#include + +#include +#include +#include +%} + +%insert(runtime) "swigrun.swg"; /* SWIG API */ +%insert(runtime) "swigerrors.swg"; /* SWIG errors */ + +%insert(runtime) "javascriptrun.swg" + diff --git a/Lib/javascript/v8/javascriptstrings.swg b/Lib/javascript/v8/javascriptstrings.swg new file mode 100644 index 000000000..69b6836a8 --- /dev/null +++ b/Lib/javascript/v8/javascriptstrings.swg @@ -0,0 +1,59 @@ + +/* ------------------------------------------------------------ + * utility methods for char strings + * ------------------------------------------------------------ */ +%fragment("SWIG_AsCharPtrAndSize", "header", fragment="SWIG_pchar_descriptor") { +SWIGINTERN int +SWIG_AsCharPtrAndSize(v8::Handle valRef, char** cptr, size_t* psize, int *alloc) +{ + if(valRef->IsString()) { + v8::Handle js_str = valRef->ToString(); + + size_t len = js_str->Utf8Length() + 1; + char* cstr = new char[len]; + js_str->WriteUtf8(cstr, len); + + if(alloc) *alloc = SWIG_NEWOBJ; + if(psize) *psize = len; + if(cptr) *cptr = cstr; + + return SWIG_OK; + } else { + if(valRef->IsObject()) { + v8::Handle obj = valRef->ToObject(); + // try if the object is a wrapped char[] + swig_type_info* pchar_descriptor = SWIG_pchar_descriptor(); + if (pchar_descriptor) { + void* vptr = 0; + if (SWIG_ConvertPtr(obj, &vptr, pchar_descriptor, 0) == SWIG_OK) { + if (cptr) *cptr = (char *) vptr; + if (psize) *psize = vptr ? (strlen((char *)vptr) + 1) : 0; + if (alloc) *alloc = SWIG_OLDOBJ; + return SWIG_OK; + } + } + return SWIG_TypeError; + } else { + return SWIG_TypeError; + } + } +} +} + +%fragment("SWIG_FromCharPtrAndSize","header",fragment="SWIG_pchar_descriptor") { +SWIGINTERNINLINE v8::Handle +SWIG_FromCharPtrAndSize(const char* carray, size_t size) +{ + if (carray) { + if (size > INT_MAX) { + // TODO: handle extra long strings + return v8::Undefined(); + } else { + v8::Handle js_str = v8::String::New(carray, size); + return js_str; + } + } else { + return v8::Undefined(); + } +} +} diff --git a/Lib/javascript/v8/javascripttypemaps.swg b/Lib/javascript/v8/javascripttypemaps.swg new file mode 100644 index 000000000..90317a1c7 --- /dev/null +++ b/Lib/javascript/v8/javascripttypemaps.swg @@ -0,0 +1,43 @@ +/* ------------------------------------------------------------ + * Typemap specializations for Javascript + * ------------------------------------------------------------ */ + +/* ------------------------------------------------------------ + * Fragment section + * ------------------------------------------------------------ */ + +/* Include fundamental fragemt definitions */ +%include + +/* Look for user fragments file. */ +%include + +/* Javascript fragments for fundamental types */ +%include + +/* Javascript fragments for char* strings */ +%include + + +/* ------------------------------------------------------------ + * Unified typemap section + * ------------------------------------------------------------ */ + +/* Javascript types */ + +#define SWIG_Object v8::Handle +#define VOID_Object v8::Undefined() + +/* Overload of the output/constant/exception/dirout handling */ + +/* append output */ +#define SWIG_AppendOutput(result, obj) SWIGV8_AppendOutput(result, obj) + +/* set constant */ +#define SWIG_SetConstant(name, obj) + +/* raise */ +#define SWIG_Raise(obj, type, desc) SWIG_V8_Raise(type) + +/* Include the unified typemap library */ +%include diff --git a/Lib/javascript/v8/node.i b/Lib/javascript/v8/node.i new file mode 100644 index 000000000..8bf9ef061 --- /dev/null +++ b/Lib/javascript/v8/node.i @@ -0,0 +1,12 @@ +%insert("begin") %{ +#ifndef BUILDING_NODE_EXTENSION +#define BUILDING_NODE_EXTENSION +#endif +%} + +%insert("runtime") %{ +// we are including relative to the src folder because of issues +// with other files which might be named "node.h" +#include +%} + diff --git a/Lib/javascript/v8/std_common.i b/Lib/javascript/v8/std_common.i new file mode 100755 index 000000000..cee11e8ca --- /dev/null +++ b/Lib/javascript/v8/std_common.i @@ -0,0 +1,5 @@ +%include + +%apply size_t { std::size_t }; +%apply const size_t& { const std::size_t& }; + diff --git a/Lib/javascript/v8/std_complex.i b/Lib/javascript/v8/std_complex.i new file mode 100644 index 000000000..088a4fe7b --- /dev/null +++ b/Lib/javascript/v8/std_complex.i @@ -0,0 +1,19 @@ +/* + * STD C++ complex typemaps + */ + +%include + +%{ +#include +%} + +/* defining the complex as/from converters */ + +%swig_cplxdbl_convn(std::complex, std::complex, std::real, std::imag) +%swig_cplxflt_convn(std::complex, std::complex, std::real, std::imag) + +/* defining the typemaps */ + +%typemaps_primitive(%checkcode(CPLXDBL), std::complex); +%typemaps_primitive(%checkcode(CPLXFLT), std::complex); diff --git a/Lib/javascript/v8/std_deque.i b/Lib/javascript/v8/std_deque.i new file mode 100644 index 000000000..cb98f6c2f --- /dev/null +++ b/Lib/javascript/v8/std_deque.i @@ -0,0 +1 @@ +%include diff --git a/Lib/javascript/v8/std_except.i b/Lib/javascript/v8/std_except.i new file mode 100644 index 000000000..af98428f6 --- /dev/null +++ b/Lib/javascript/v8/std_except.i @@ -0,0 +1 @@ +%include diff --git a/Lib/javascript/v8/std_map.i b/Lib/javascript/v8/std_map.i new file mode 100755 index 000000000..e7812f38a --- /dev/null +++ b/Lib/javascript/v8/std_map.i @@ -0,0 +1,74 @@ +/* ----------------------------------------------------------------------------- + * std_map.i + * + * SWIG typemaps for std::map + * ----------------------------------------------------------------------------- */ + +%include + +// ------------------------------------------------------------------------ +// std::map +// ------------------------------------------------------------------------ + +%{ +#include +#include +#include +%} + +// exported class + +namespace std { + + template class map { + // add typemaps here + public: + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef K key_type; + typedef T mapped_type; + map(); + map(const map &); + + unsigned int size() const; + bool empty() const; + void clear(); + %extend { + const T& get(const K& key) throw (std::out_of_range) { + std::map::iterator i = self->find(key); + if (i != self->end()) + return i->second; + else + throw std::out_of_range("key not found"); + } + void set(const K& key, const T& x) { + (*self)[key] = x; + } + void del(const K& key) throw (std::out_of_range) { + std::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 K& key) { + std::map::iterator i = self->find(key); + return i != self->end(); + } + } + }; + +// Legacy macros (deprecated) +%define specialize_std_map_on_key(K,CHECK,CONVERT_FROM,CONVERT_TO) +#warning "specialize_std_map_on_key ignored - macro is deprecated and no longer necessary" +%enddef + +%define specialize_std_map_on_value(T,CHECK,CONVERT_FROM,CONVERT_TO) +#warning "specialize_std_map_on_value ignored - macro is deprecated and no longer necessary" +%enddef + +%define specialize_std_map_on_both(K,CHECK_K,CONVERT_K_FROM,CONVERT_K_TO, T,CHECK_T,CONVERT_T_FROM,CONVERT_T_TO) +#warning "specialize_std_map_on_both ignored - macro is deprecated and no longer necessary" +%enddef + +} diff --git a/Lib/javascript/v8/std_pair.i b/Lib/javascript/v8/std_pair.i new file mode 100755 index 000000000..8d6057223 --- /dev/null +++ b/Lib/javascript/v8/std_pair.i @@ -0,0 +1,33 @@ +/* ----------------------------------------------------------------------------- + * std_pair.i + * + * SWIG typemaps for std::pair + * ----------------------------------------------------------------------------- */ + +%include + +// ------------------------------------------------------------------------ +// std::pair +// ------------------------------------------------------------------------ + +%{ +#include +%} + +namespace std { + + template struct pair { + + pair(); + pair(T first, U second); + pair(const pair& p); + + template pair(const pair &p); + + T first; + U second; + }; + + // add specializations here + +} diff --git a/Lib/javascript/v8/std_string.i b/Lib/javascript/v8/std_string.i new file mode 100755 index 000000000..5ad1ead27 --- /dev/null +++ b/Lib/javascript/v8/std_string.i @@ -0,0 +1,79 @@ +/* ----------------------------------------------------------------------------- + * std_string.i + * + * Typemaps for std::string and const std::string&. + * + * To use non-const std::string references use the following %apply: + * %apply const std::string & {std::string &}; + * + * ----------------------------------------------------------------------------- */ + +%{ +#include +%} + +%fragment("SWIGV8_valueToString", "header", fragment="SWIG_AsCharPtrAndSize") { +std::string* SWIGV8_valueToStringPtr(v8::Handle val) { + + if (!val->IsString()) return 0; + + int alloc; + size_t size; + char* chars; + int res = SWIG_AsCharPtrAndSize(val, &chars, &size, &alloc); + + if(res != SWIG_OK) { + v8::ThrowException(v8::Exception::TypeError(v8::String::New("Could not convert to string."))); + return 0; + } + + // copies the data (again) + std::string *str = new std::string(chars); + + if (alloc) delete[] chars; + + return str; +} +} + +%fragment("SWIGV8_stringToValue", "header", fragment="SWIG_FromCharPtrAndSize") { +v8::Handle SWIGV8_stringToValue(const std::string &str) { + return SWIG_FromCharPtrAndSize(str.c_str(), str.length()); +} +} + +namespace std { + %naturalvar string; + + class string; + + %typemap(in, fragment="SWIGV8_valueToString") string (std::string* tmp) + %{ + tmp = SWIGV8_valueToStringPtr($input); + $1 = *tmp; + if (tmp == 0) { v8::ThrowException(v8::Exception::TypeError(v8::String::New("Null pointer."))); goto fail; } + if (tmp) delete tmp; + %} + + %typemap(in, fragment="SWIGV8_valueToString") const string & + %{ + $1 = SWIGV8_valueToStringPtr($input); + if ($1 == 0) { v8::ThrowException(v8::Exception::TypeError(v8::String::New("Null pointer."))); goto fail; } + %} + + %typemap(freearg) const string & + %{ + if ($1) delete $1; + %} + + %typemap(out, fragment="SWIGV8_stringToValue") string + %{ + $result = SWIGV8_stringToValue($1); + %} + + %typemap(out, fragment="SWIGV8_stringToValue") const string & + %{ + $result = SWIGV8_stringToValue(*$1); + %} + +} diff --git a/Lib/javascript/v8/std_vector.i b/Lib/javascript/v8/std_vector.i new file mode 100755 index 000000000..3f29b19c7 --- /dev/null +++ b/Lib/javascript/v8/std_vector.i @@ -0,0 +1,85 @@ +/* ----------------------------------------------------------------------------- + * std_vector.i + * ----------------------------------------------------------------------------- */ + +%include + +%{ +#include +#include +%} + +namespace std { + + template class vector { + public: + typedef size_t size_type; + typedef T value_type; + typedef const value_type& const_reference; + vector(); + vector(size_type n); + size_type size() const; + size_type capacity() const; + void reserve(size_type n); + %rename(isEmpty) empty; + bool empty() const; + void clear(); + %rename(add) push_back; + void push_back(const value_type& x); + %extend { + const_reference get(int i) throw (std::out_of_range) { + int size = int(self->size()); + if (i>=0 && isize()); + if (i>=0 && i class vector { + public: + typedef size_t size_type; + typedef bool value_type; + typedef bool const_reference; + vector(); + vector(size_type n); + size_type size() const; + size_type capacity() const; + void reserve(size_type n); + %rename(isEmpty) empty; + bool empty() const; + void clear(); + %rename(add) push_back; + void push_back(const value_type& x); + %extend { + const_reference get(int i) throw (std::out_of_range) { + int size = int(self->size()); + if (i>=0 && isize()); + if (i>=0 && i +%include +%include +%include +%include + diff --git a/Lib/javascript/v8/typemaps.i b/Lib/javascript/v8/typemaps.i new file mode 100644 index 000000000..d3d8afb19 --- /dev/null +++ b/Lib/javascript/v8/typemaps.i @@ -0,0 +1,148 @@ +/* ----------------------------------------------------------------------------- + * typemaps.i + * + * Pointer handling + * These mappings provide support for input/output arguments and common + * uses for C/C++ pointers. + * ----------------------------------------------------------------------------- */ + +// INPUT typemaps. +// These remap a C pointer to be an "INPUT" value which is passed by value +// instead of reference. + +/* +The following methods can be applied to turn a pointer into a simple +"input" value. That is, instead of passing a pointer to an object, +you would use a real value instead. + + int *INPUT + short *INPUT + long *INPUT + long long *INPUT + unsigned int *INPUT + unsigned short *INPUT + unsigned long *INPUT + unsigned long long *INPUT + unsigned char *INPUT + bool *INPUT + float *INPUT + double *INPUT + +To use these, suppose you had a C function like this : + + double fadd(double *a, double *b) { + return *a+*b; + } + +You could wrap it with SWIG as follows : + + %include + double fadd(double *INPUT, double *INPUT); + +or you can use the %apply directive : + + %include + %apply double *INPUT { double *a, double *b }; + double fadd(double *a, double *b); + +*/ + +// OUTPUT typemaps. These typemaps are used for parameters that +// are output only. The output value is appended to the result as +// a list element. + +/* +The following methods can be applied to turn a pointer into an "output" +value. When calling a function, no input value would be given for +a parameter, but an output value would be returned. In the case of +multiple output values, they are returned in the form of a Python tuple. + + int *OUTPUT + short *OUTPUT + long *OUTPUT + long long *OUTPUT + unsigned int *OUTPUT + unsigned short *OUTPUT + unsigned long *OUTPUT + unsigned long long *OUTPUT + unsigned char *OUTPUT + bool *OUTPUT + float *OUTPUT + double *OUTPUT + +For example, suppose you were trying to wrap the modf() function in the +C math library which splits x into integral and fractional parts (and +returns the integer part in one of its parameters).K: + + double modf(double x, double *ip); + +You could wrap it with SWIG as follows : + + %include + double modf(double x, double *OUTPUT); + +or you can use the %apply directive : + + %include + %apply double *OUTPUT { double *ip }; + double modf(double x, double *ip); + +The Python output of the function would be a tuple containing both +output values. + +*/ + +// INOUT +// Mappings for an argument that is both an input and output +// parameter + +/* +The following methods can be applied to make a function parameter both +an input and output value. This combines the behavior of both the +"INPUT" and "OUTPUT" methods described earlier. Output values are +returned in the form of a Python tuple. + + int *INOUT + short *INOUT + long *INOUT + long long *INOUT + unsigned int *INOUT + unsigned short *INOUT + unsigned long *INOUT + unsigned long long *INOUT + unsigned char *INOUT + bool *INOUT + float *INOUT + double *INOUT + +For example, suppose you were trying to wrap the following function : + + void neg(double *x) { + *x = -(*x); + } + +You could wrap it with SWIG as follows : + + %include + void neg(double *INOUT); + +or you can use the %apply directive : + + %include + %apply double *INOUT { double *x }; + void neg(double *x); + +Unlike C, this mapping does not directly modify the input value (since +this makes no sense in Python). Rather, the modified input value shows +up as the return value of the function. Thus, to apply this function +to a Python variable you might do this : + + x = neg(x) + +Note : previous versions of SWIG used the symbol 'BOTH' to mark +input/output arguments. This is still supported, but will be slowly +phased out in future releases. + +*/ + +%include diff --git a/Lib/typemaps/strings.swg b/Lib/typemaps/strings.swg index e31e5037f..6bac0b98a 100644 --- a/Lib/typemaps/strings.swg +++ b/Lib/typemaps/strings.swg @@ -499,7 +499,7 @@ * --- String fragment methods --- * ------------------------------------------------------------ */ - +#ifndef %_typemap2_string %define %_typemap2_string(StringCode, CharCode, Char, CharName, SWIG_AsCharPtrAndSize, @@ -602,7 +602,7 @@ SWIG_AsVal_dec(Char)(SWIG_Object obj, Char *val) SWIG_DeleteCharArray) %enddef - +#endif /* ------------------------------------------------------------ * String typemaps and fragments, with default allocators diff --git a/Makefile.in b/Makefile.in index 4407d1316..f4d0be077 100644 --- a/Makefile.in +++ b/Makefile.in @@ -84,6 +84,7 @@ skip-uffi = test -n "@SKIP_UFFI@" skip-r = test -n "@SKIP_R@" skip-go = test -n "@SKIP_GO@" skip-d = test -n "@SKIP_D@" +skip-javascript = test -n "@SKIP_JAVASCRIPT@" # Additional dependencies for some tests skip-gcj = test -n "@SKIP_GCJ@" @@ -129,6 +130,7 @@ check-aliveness: @$(skip-r) || ./$(TARGET) -r -help @$(skip-go) || ./$(TARGET) -go -help @$(skip-d) || ./$(TARGET) -d -help + @$(skip-javascript) || ./$(TARGET) -javascript -help check-ccache: test -z "$(ENABLE_CCACHE)" || (cd $(CCACHE) && $(MAKE) check) @@ -139,6 +141,7 @@ check-versions: \ check-perl5-version \ check-python-version \ check-java-version \ + check-javascript-version \ check-android-version \ check-guile-version \ check-mzscheme-version \ @@ -196,7 +199,8 @@ check-examples: \ check-cffi-examples \ check-r-examples \ check-go-examples \ - check-d-examples + check-d-examples \ + check-javascript-examples tcl_examples :=$(shell sed '/^\#/d' $(srcdir)/Examples/tcl/check.list) perl5_examples :=$(shell sed '/^\#/d' $(srcdir)/Examples/perl5/check.list) @@ -221,6 +225,7 @@ cffi_examples := r_examples :=$(shell sed '/^\#/d' $(srcdir)/Examples/r/check.list) go_examples :=$(shell sed '/^\#/d' $(srcdir)/Examples/go/check.list) d_examples :=$(shell sed '/^\#/d' $(srcdir)/Examples/d/check.list) +javascript_examples:=$(shell sed '/^\#/d' $(srcdir)/Examples/javascript/check.list) # all examples check-%-examples : @@ -274,7 +279,8 @@ check-test-suite: \ check-chicken-test-suite \ check-r-test-suite \ check-go-test-suite \ - check-d-test-suite + check-d-test-suite \ + check-javascript-test-suite check-%-test-suite: @if test -z "$(skip-$*)"; then \ @@ -326,7 +332,8 @@ all-test-suite: \ all-chicken-test-suite \ all-r-test-suite \ all-go-test-suite \ - all-d-test-suite + all-d-test-suite \ + all-javascript-test-suite all-%-test-suite: @$(MAKE) $(FLAGS) check-$*-test-suite ACTION=all @@ -354,7 +361,8 @@ broken-test-suite: \ broken-chicken-test-suite \ broken-r-test-suite \ broken-go-test-suite \ - broken-d-test-suite + broken-d-test-suite \ + broken-javascript-test-suite broken-%-test-suite: @$(MAKE) $(FLAGS) check-$*-test-suite ACTION=broken @@ -467,7 +475,8 @@ install-main: @$(INSTALL_PROGRAM) $(TARGET) $(DESTDIR)$(BIN_DIR)/`echo $(TARGET_NOEXE) | sed '$(transform)'`@EXEEXT@ lib-languages = gcj typemaps tcl perl5 python guile java mzscheme ruby php ocaml octave \ - pike chicken csharp modula3 allegrocl clisp lua cffi uffi r go d + pike chicken csharp modula3 allegrocl clisp lua cffi uffi r go d javascript javascript/jsc \ + javascript/v8 lib-modules = std diff --git a/Source/Makefile.am b/Source/Makefile.am index 49d571236..4dbede635 100644 --- a/Source/Makefile.am +++ b/Source/Makefile.am @@ -49,6 +49,7 @@ eswig_SOURCES = CParse/cscanner.c \ Modules/guile.cxx \ Modules/java.cxx \ Modules/lang.cxx \ + Modules/javascript.cxx \ Modules/lua.cxx \ Modules/main.cxx \ Modules/modula3.cxx \ diff --git a/Source/Modules/javascript.cxx b/Source/Modules/javascript.cxx new file mode 100644 index 000000000..eae594727 --- /dev/null +++ b/Source/Modules/javascript.cxx @@ -0,0 +1,2428 @@ +#include "swigmod.h" + +/** + * Enables extra debugging information in typemaps. + */ +bool js_template_enable_debug = false; + +// keywords used for state variables +#define NAME "name" +#define NAME_MANGLED "name_mangled" +#define TYPE "type" +#define TYPE_MANGLED "type_mangled" +#define WRAPPER_NAME "wrapper" +#define IS_IMMUTABLE "is_immutable" +#define IS_STATIC "is_static" +#define IS_ABSTRACT "is_abstract" +#define GETTER "getter" +#define SETTER "setter" +#define PARENT "parent" +#define CTOR "ctor" +#define CTOR_WRAPPERS "ctor_wrappers" +#define CTOR_DISPATCHERS "ctor_dispatchers" +#define DTOR "dtor" +#define ARGCOUNT "wrap:argc" + +// keys for global state variables +#define CREATE_NAMESPACES "create_namespaces" +#define REGISTER_NAMESPACES "register_namespaces" +#define INITIALIZER "initializer" + +// keys for class scoped state variables +#define MEMBER_VARIABLES "member_variables" +#define MEMBER_FUNCTIONS "member_functions" +#define STATIC_FUNCTIONS "static_functions" +#define STATIC_VARIABLES "static_variables" +#define HAS_TEMPLATES "has_templates" + +#define RESET true + +/** + * A convenience class to manage state variables for emitters. + * The implementation delegates to swig Hash DOHs and provides + * named sub-hashes for class, variable, and function states. + */ +class JSEmitterState { + +public: + + JSEmitterState(); + + ~JSEmitterState(); + + DOH *global (); + + DOH *global (const char *key, DOH *initial = 0); + + DOH *clazz(bool reset = false); + + DOH *clazz(const char *key, DOH *initial = 0); + + DOH *function(bool reset = false); + + DOH *function(const char *key, DOH *initial = 0); + + DOH *variable(bool reset = false); + + DOH *variable(const char *key, DOH *initial = 0); + + static int IsSet(DOH *val); + +private: + + DOH *getState(const char *key, bool reset = false); + + Hash *_global; +}; + +/** + * A convenience class that wraps a code snippet used as template + * for code generation. + */ +class Template { + +public: + Template(const String *code); + + Template(const String *code, const String *templateName); + + Template(const Template & other); + + ~Template(); + + String *str(); + + Template & replace(const String *pattern, const String *repl); + + Template & print(DOH *doh); + + Template & pretty_print(DOH *doh); + + void operator=(const Template & t); + + Template & trim(); + +private: + + String *code; + String *templateName; + +}; + +/** + * JSEmitter represents an abstraction of javascript code generators + * for different javascript engines. + **/ +class JSEmitter { + +protected: + + typedef JSEmitterState State; + + enum MarshallingMode { + Setter, + Getter, + Ctor, + Function + }; + +public: + + enum JSEmitterType { + JavascriptCore, + V8 + }; + + JSEmitter(); + + virtual ~ JSEmitter(); + + /** + * Opens output files and temporary output DOHs. + */ + virtual int initialize(Node *n); + + /** + * Writes all collected code into the output file(s). + */ + virtual int dump(Node *n) = 0; + + /** + * Cleans up all open output DOHs. + */ + virtual int close() = 0; + + /** + * Switches the context for code generation. + * + * Classes, global variables and global functions may need to + * be registered in certain static tables. + * This method should be used to switch output DOHs correspondingly. + */ + virtual int switchNamespace(Node *); + + /** + * Invoked at the beginning of the classHandler. + */ + virtual int enterClass(Node *); + + /** + * Invoked at the end of the classHandler. + */ + virtual int exitClass(Node *) { + return SWIG_OK; + }; + + /** + * Invoked at the beginning of the variableHandler. + */ + virtual int enterVariable(Node *); + + /** + * Invoked at the end of the variableHandler. + */ + virtual int exitVariable(Node *) { + return SWIG_OK; + }; + + /** + * Invoked at the beginning of the functionHandler. + */ + virtual int enterFunction(Node *); + + /** + * Invoked at the end of the functionHandler. + */ + virtual int exitFunction(Node *) { + return SWIG_OK; + }; + + /** + * Invoked by functionWrapper callback after call to Language::functionWrapper. + */ + virtual int emitWrapperFunction(Node *n); + + /** + * Invoked from constantWrapper after call to Language::constantWrapper. + **/ + virtual int emitConstant(Node *n); + + /** + * Registers a given code snippet for a given key name. + * + * This method is called by the fragmentDirective handler + * of the JAVASCRIPT language module. + **/ + int registerTemplate(const String *name, const String *code); + + /** + * Retrieve the code template registered for a given name. + */ + Template getTemplate(const String *name); + + State & getState(); + +protected: + + /** + * Generates code for a constructor function. + */ + virtual int emitCtor(Node *n); + + /** + * Generates code for a destructor function. + */ + virtual int emitDtor(Node *n); + + /** + * Generates code for a function. + */ + virtual int emitFunction(Node *n, bool is_member, bool is_static); + + virtual int emitFunctionDispatcher(Node *n, bool /*is_member */ ); + + /** + * Generates code for a getter function. + */ + virtual int emitGetter(Node *n, bool is_member, bool is_static); + + /** + * Generates code for a setter function. + */ + virtual int emitSetter(Node *n, bool is_member, bool is_static); + + virtual void marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) = 0; + + virtual String *emitInputTypemap(Node *n, Parm *params, Wrapper *wrapper, String *arg); + + virtual void marshalOutput(Node *n, ParmList *params, Wrapper *wrapper, String *actioncode, const String *cresult = 0, bool emitReturnVariable = true); + + virtual void emitCleanupCode(Node *n, Wrapper *wrapper, ParmList *params); + + /** + * Helper function to retrieve the first parent class node. + */ + Node *getBaseClass(Node *n); + + Parm *skipIgnoredArgs(Parm *p); + + virtual int createNamespace(String *scope); + + virtual Hash *createNamespaceEntry(const char *name, const char *parent); + + virtual int emitNamespaces() = 0; + + +protected: + + Hash *templates; + + State state; + + // contains context specific data (DOHs) + // to allow generation of namespace related code + // which are switched on namespace change + Hash *namespaces; + Hash *current_namespace; + + String *defaultResultName; + + File *f_wrappers; +}; + +/* factory methods for concrete JSEmitters: */ + +JSEmitter *swig_javascript_create_JSCEmitter(); +JSEmitter *swig_javascript_create_V8Emitter(); + +/********************************************************************** + * JAVASCRIPT: swig module implementation + **********************************************************************/ + +class JAVASCRIPT:public Language { + +public: + + JAVASCRIPT():emitter(NULL) { + } ~JAVASCRIPT() { + delete emitter; + } + + virtual int functionHandler(Node *n); + virtual int globalfunctionHandler(Node *n); + virtual int variableHandler(Node *n); + virtual int globalvariableHandler(Node *n); + virtual int staticmemberfunctionHandler(Node *n); + virtual int classHandler(Node *n); + virtual int functionWrapper(Node *n); + virtual int constantWrapper(Node *n); + virtual void main(int argc, char *argv[]); + virtual int top(Node *n); + + /** + * Registers all %fragments assigned to section "templates". + **/ + virtual int fragmentDirective(Node *n); + +private: + + JSEmitter * emitter; +}; + +/* --------------------------------------------------------------------- + * functionWrapper() + * + * Low level code generator for functions + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::functionWrapper(Node *n) { + + // note: the default implementation only prints a message + // Language::functionWrapper(n); + emitter->emitWrapperFunction(n); + + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * functionHandler() + * + * Function handler for generating wrappers for functions + * --------------------------------------------------------------------- */ +int JAVASCRIPT::functionHandler(Node *n) { + + if (GetFlag(n, "isextension") == 1) { + SetFlag(n, "ismember"); + } + + emitter->enterFunction(n); + Language::functionHandler(n); + emitter->exitFunction(n); + + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * globalfunctionHandler() + * + * Function handler for generating wrappers for functions + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::globalfunctionHandler(Node *n) { + emitter->switchNamespace(n); + Language::globalfunctionHandler(n); + + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * staticmemberfunctionHandler() + * + * Function handler for generating wrappers for static member functions + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::staticmemberfunctionHandler(Node *n) { + /* + * Note: storage=static is removed by Language::staticmemberfunctionHandler. + * So, don't rely on that after here. Instead use the state variable which is + * set by JSEmitter::enterFunction(). + */ + Language::staticmemberfunctionHandler(n); + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * variableHandler() + * + * Function handler for generating wrappers for variables + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::variableHandler(Node *n) { + + emitter->enterVariable(n); + Language::variableHandler(n); + emitter->exitVariable(n); + + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * globalvariableHandler() + * + * Function handler for generating wrappers for global variables + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::globalvariableHandler(Node *n) { + emitter->switchNamespace(n); + Language::globalvariableHandler(n); + + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * constantHandler() + * + * Function handler for generating wrappers for constants + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::constantWrapper(Node *n) { + emitter->switchNamespace(n); + + // Note: callbacks trigger this wrapper handler + // TODO: handle callback declarations + if (Equal(Getattr(n, "kind"), "function")) { + return SWIG_OK; + } + // TODO: the emitter for constants must be implemented in a cleaner way + // currently we treat it like a read-only variable + // however, there is a remaining bug with function pointer constants + // which could be fixed with a cleaner approach + emitter->emitConstant(n); + + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * classHandler() + * + * Function handler for generating wrappers for class + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::classHandler(Node *n) { + emitter->switchNamespace(n); + + emitter->enterClass(n); + Language::classHandler(n); + emitter->exitClass(n); + + return SWIG_OK; +} + +int JAVASCRIPT::fragmentDirective(Node *n) { + + // catch all fragment directives that have "templates" as location + // and register them at the emitter. + String *section = Getattr(n, "section"); + + if (Equal(section, "templates")) { + emitter->registerTemplate(Getattr(n, "value"), Getattr(n, "code")); + } else { + Swig_fragment_register(n); + } + + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * top() + * + * Function handler for processing top node of the parse tree + * Wrapper code generation essentially starts from here + * --------------------------------------------------------------------- */ + +int JAVASCRIPT::top(Node *n) { + emitter->initialize(n); + + Language::top(n); + + emitter->dump(n); + emitter->close(); + + return SWIG_OK; +} + +static const char *usage = (char *) "\ +Javascript Options (available with -javascript)\n\ + -jsc - creates a JavascriptCore extension \n\ + -v8 - creates a v8 extension \n\ + -node - creates a node.js extension \n\ + -debug-codetemplates - generates information about the origin of code templates.\n"; + + +/* --------------------------------------------------------------------- + * main() + * + * Entry point for the JAVASCRIPT module + * --------------------------------------------------------------------- */ + +void JAVASCRIPT::main(int argc, char *argv[]) { + // Set javascript subdirectory in SWIG library + SWIG_library_directory("javascript"); + + int mode = -1; + + for (int i = 1; i < argc; i++) { + if (argv[i]) { + if (strcmp(argv[i], "-v8") == 0) { + Swig_mark_arg(i); + mode = JSEmitter::V8; + SWIG_library_directory("javascript/v8"); + } else if (strcmp(argv[i], "-jsc") == 0) { + Swig_mark_arg(i); + mode = JSEmitter::JavascriptCore; + SWIG_library_directory("javascript/jsc"); + } else if (strcmp(argv[i], "-node") == 0) { + Swig_mark_arg(i); + mode = JSEmitter::V8; + SWIG_library_directory("javascript/v8"); + Preprocessor_define("BUILDING_NODE_EXTENSION 1", 0); + } else if (strcmp(argv[i], "-debug-codetemplates") == 0) { + Swig_mark_arg(i); + js_template_enable_debug = true; + } else if (strcmp(argv[i], "-help") == 0) { + fputs(usage, stdout); + return; + } + } + } + + switch (mode) { + case JSEmitter::V8: + { + emitter = swig_javascript_create_V8Emitter(); + Preprocessor_define("SWIG_JAVASCRIPT_V8 1", 0); + break; + } + case JSEmitter::JavascriptCore: + { + emitter = swig_javascript_create_JSCEmitter(); + Preprocessor_define("SWIG_JAVASCRIPT_JSC 1", 0); + break; + } + default: + { + Printf(stderr, "SWIG Javascript: Unknown emitter type.\n"); + SWIG_exit(-1); + break; + } + } + + // Add a symbol to the parser for conditional compilation + Preprocessor_define("SWIGJAVASCRIPT 1", 0); + + // Add typemap definitions + SWIG_typemap_lang("javascript"); + + // Set configuration file + SWIG_config_file("javascript.swg"); + + allow_overloading(); +} + +/* ----------------------------------------------------------------------------- + * swig_javascript() - Instantiate module + * ----------------------------------------------------------------------------- */ + +static Language *new_swig_javascript() { + return new JAVASCRIPT(); +} + +extern "C" Language *swig_javascript(void) { + return new_swig_javascript(); +} + +/********************************************************************** + * Emitter implementations + **********************************************************************/ + +/* ----------------------------------------------------------------------------- + * JSEmitter() + * ----------------------------------------------------------------------------- */ + +JSEmitter::JSEmitter() +: templates(NewHash()), namespaces(NULL), current_namespace(NULL), defaultResultName(NewString("result")), f_wrappers(NULL) { +} + +/* ----------------------------------------------------------------------------- + * ~JSEmitter() + * ----------------------------------------------------------------------------- */ + +JSEmitter::~JSEmitter() { + Delete(templates); +} + +/* ----------------------------------------------------------------------------- + * JSEmitter::RegisterTemplate() : Registers a code template + * + * Note: this is used only by JAVASCRIPT::fragmentDirective(). + * ----------------------------------------------------------------------------- */ + +int JSEmitter::registerTemplate(const String *name, const String *code) { + if (!State::IsSet(state.global (HAS_TEMPLATES))) { + SetFlag(state.global (), HAS_TEMPLATES); + } + return Setattr(templates, name, code); +} + +/* ----------------------------------------------------------------------------- + * JSEmitter::getTemplate() : Provides a registered code template + * ----------------------------------------------------------------------------- */ + +Template JSEmitter::getTemplate(const String *name) { + String *templ = Getattr(templates, name); + + if (!templ) { + Printf(stderr, "Could not find template %s\n.", name); + SWIG_exit(EXIT_FAILURE); + } + + Template t(templ, name); + return t; +} + +JSEmitterState & JSEmitter::getState() { + return state; +} + +int JSEmitter::initialize(Node * /*n */ ) { + + if (namespaces != NULL) { + Delete(namespaces); + } + namespaces = NewHash(); + Hash *global_namespace = createNamespaceEntry("exports", 0); + + Setattr(namespaces, "::", global_namespace); + current_namespace = global_namespace; + + f_wrappers = NewString(""); + + return SWIG_OK; +} + +/* --------------------------------------------------------------------- + * skipIgnoredArgs() + * --------------------------------------------------------------------- */ + +Parm *JSEmitter::skipIgnoredArgs(Parm *p) { + while (checkAttribute(p, "tmap:in:numinputs", "0")) { + p = Getattr(p, "tmap:in:next"); + } + return p; +} + +/* ----------------------------------------------------------------------------- + * JSEmitter::getBaseClass() : the node of the base class or NULL + * + * Note: the first base class is provided. Multiple inheritance is not + * supported. + * ----------------------------------------------------------------------------- */ + +Node *JSEmitter::getBaseClass(Node *n) { + // retrieve the first base class that is not %ignored + List *baselist = Getattr(n, "bases"); + if (baselist) { + Iterator base = First(baselist); + while (base.item && GetFlag(base.item, "feature:ignore")) { + base = Next(base); + } + return base.item; + } + return NULL; +} + + /* ----------------------------------------------------------------------------- + * JSEmitter::emitWrapperFunction() : dispatches emitter functions. + * + * This allows to have small sized, dedicated emitting functions. + * All state dependent branching is done here. + * ----------------------------------------------------------------------------- */ + +int JSEmitter::emitWrapperFunction(Node *n) { + int ret = SWIG_OK; + + String *kind = Getattr(n, "kind"); + + if (kind) { + + if (Equal(kind, "function") + // HACK: sneaky.ctest revealed that typedef'd (global) functions must be + // detected via the 'view' attribute. + || (Equal(kind, "variable") && Equal(Getattr(n, "view"), "globalfunctionHandler")) + ) { + bool is_member = GetFlag(n, "ismember") | GetFlag(n, "feature:extend"); + bool is_static = GetFlag(state.function(), IS_STATIC); + ret = emitFunction(n, is_member, is_static); + } else if (Cmp(kind, "variable") == 0) { + bool is_static = GetFlag(state.variable(), IS_STATIC); + // HACK: smartpointeraccessed static variables are not treated as statics + if (GetFlag(n, "allocate:smartpointeraccess")) { + is_static = false; + } + + bool is_member = GetFlag(n, "ismember"); + bool is_setter = GetFlag(n, "memberset") || GetFlag(n, "varset"); + bool is_getter = GetFlag(n, "memberget") || GetFlag(n, "varget"); + if (is_setter) { + ret = emitSetter(n, is_member, is_static); + } else if (is_getter) { + ret = emitGetter(n, is_member, is_static); + } else { + Swig_print_node(n); + } + + } else { + Printf(stderr, "Warning: unsupported wrapper function type\n"); + Swig_print_node(n); + ret = SWIG_ERROR; + } + } else { + String *view = Getattr(n, "view"); + + if (Cmp(view, "constructorHandler") == 0) { + ret = emitCtor(n); + } else if (Cmp(view, "destructorHandler") == 0) { + ret = emitDtor(n); + } else { + Printf(stderr, "Warning: unsupported wrapper function type"); + Swig_print_node(n); + ret = SWIG_ERROR; + } + } + + return ret; +} + +int JSEmitter::enterClass(Node *n) { + state.clazz(RESET); + state.clazz(NAME, Getattr(n, "sym:name")); + state.clazz("nspace", current_namespace); + + // Creating a mangled name using the current namespace and the symbol name + String *mangled_name = NewString(""); + Printf(mangled_name, "%s_%s", Getattr(current_namespace, NAME_MANGLED), Getattr(n, "sym:name")); + state.clazz(NAME_MANGLED, SwigType_manglestr(mangled_name)); + Delete(mangled_name); + + state.clazz(TYPE, NewString(Getattr(n, "classtype"))); + + String *type = SwigType_manglestr(Getattr(n, "classtypeobj")); + String *classtype_mangled = NewString(""); + Printf(classtype_mangled, "p%s", type); + state.clazz(TYPE_MANGLED, classtype_mangled); + Delete(type); + + String *ctor_wrapper = NewString("_wrap_new_veto_"); + Append(ctor_wrapper, state.clazz(NAME)); + state.clazz(CTOR, ctor_wrapper); + state.clazz(CTOR_DISPATCHERS, NewString("")); + state.clazz(DTOR, NewString("0")); + + // HACK: assume that a class is abstract + // this is resolved by emitCtor (which is only called for non abstract classes) + SetFlag(state.clazz(), IS_ABSTRACT); + + return SWIG_OK; +} + +int JSEmitter::enterFunction(Node *n) { + state.function(RESET); + state.function(NAME, Getattr(n, "sym:name")); + if (Equal(Getattr(n, "storage"), "static")) { + SetFlag(state.function(), IS_STATIC); + } + return SWIG_OK; +} + +int JSEmitter::enterVariable(Node *n) { + // reset the state information for variables. + state.variable(RESET); + + // Retrieve a pure symbol name. Using 'sym:name' as a basis, as it considers %renamings. + if (Equal(Getattr(n, "view"), "memberconstantHandler")) { + // Note: this is kind of hacky/experimental + // For constants/enums 'sym:name' contains e.g., 'Foo_Hello' instead of 'Hello' + state.variable(NAME, Getattr(n, "memberconstantHandler:sym:name")); + } else { + state.variable(NAME, Swig_scopename_last(Getattr(n, "sym:name"))); + } + + if (Equal(Getattr(n, "storage"), "static")) { + SetFlag(state.variable(), IS_STATIC); + } + + if (!Language::instance()->is_assignable(n)) { + SetFlag(state.variable(), IS_IMMUTABLE); + } + // FIXME: test "arrays_global" does not compile with that as it is not allowed to assign to char[] + if (Equal(Getattr(n, "type"), "a().char")) { + SetFlag(state.variable(), IS_IMMUTABLE); + } + + return SWIG_OK; +} + +int JSEmitter::emitCtor(Node *n) { + + Wrapper *wrapper = NewWrapper(); + + bool is_overloaded = GetFlag(n, "sym:overloaded"); + + Template t_ctor(getTemplate("js_ctor")); + + //String *mangled_name = SwigType_manglestr(Getattr(n, "name")); + String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); + if (is_overloaded) { + t_ctor = getTemplate("js_overloaded_ctor"); + Append(wrap_name, Getattr(n, "sym:overname")); + } + Setattr(n, "wrap:name", wrap_name); + // note: removing the is_abstract flag, as this emitter + // is supposed to be called for non-abstract classes only. + Setattr(state.clazz(), IS_ABSTRACT, 0); + + ParmList *params = Getattr(n, "parms"); + emit_parameter_variables(params, wrapper); + emit_attach_parmmaps(params, wrapper); + // HACK: in test-case `ignore_parameter` emit_attach_parmmaps generated an extra line of applied typemap. + // Deleting wrapper->code here, to reset, and as it seemed to have no side effect elsewhere + Delete(wrapper->code); + wrapper->code = NewString(""); + + Printf(wrapper->locals, "%sresult;", SwigType_str(Getattr(n, "type"), 0)); + + marshalInputArgs(n, params, wrapper, Ctor, true, false); + String *action = emit_action(n); + Printv(wrapper->code, action, "\n", 0); + + emitCleanupCode(n, wrapper, params); + + t_ctor.replace("$jswrapper", wrap_name) + .replace("$jsmangledtype", state.clazz(TYPE_MANGLED)) + .replace("$jslocals", wrapper->locals) + .replace("$jscode", wrapper->code) + .replace("$jsargcount", Getattr(n, ARGCOUNT)) + .pretty_print(f_wrappers); + + Template t_ctor_case(getTemplate("js_ctor_dispatch_case")); + t_ctor_case.replace("$jswrapper", wrap_name) + .replace("$jsargcount", Getattr(n, ARGCOUNT)); + Append(state.clazz(CTOR_DISPATCHERS), t_ctor_case.str()); + + DelWrapper(wrapper); + + // create a dispatching ctor + if (is_overloaded) { + if (!Getattr(n, "sym:nextSibling")) { + String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); + Template t_mainctor(getTemplate("js_ctor_dispatcher")); + t_mainctor.replace("$jswrapper", wrap_name) + .replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsdispatchcases", state.clazz(CTOR_DISPATCHERS)) + .pretty_print(f_wrappers); + state.clazz(CTOR, wrap_name); + } + } else { + state.clazz(CTOR, wrap_name); + } + + return SWIG_OK; +} + +int JSEmitter::emitDtor(Node *n) { + + String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); + + SwigType *type = state.clazz(TYPE); + String *p_classtype = SwigType_add_pointer(state.clazz(TYPE)); + String *ctype = SwigType_lstr(p_classtype, ""); + String *free = NewString(""); + + // (Taken from JSCore implementation.) + /* The if (Extend) block was taken from the Ruby implementation. + * The problem is that in the case of an %extend to create a destructor for a struct to coordinate automatic memory cleanup with the Javascript collector, + * the swig function was not being generated. More specifically: + struct MyData { + %extend { + ~MyData() { + FreeData($self); + } + } + }; + %newobject CreateData; + struct MyData* CreateData(void); + %delobject FreeData; + void FreeData(struct MyData* the_data); + + where the use case is something like: + var my_data = example.CreateData(); + my_data = null; + + This function was not being generated: + SWIGINTERN void delete_MyData(struct MyData *self){ + FreeData(self); + } + + I don't understand fully why it wasn't being generated. It just seems to happen in the Lua generator. + There is a comment about staticmemberfunctionHandler having an inconsistency and I tracked down dome of the SWIGINTERN void delete_* + code to that function in the Language base class. + The Ruby implementation seems to have an explicit check for if(Extend) and explicitly generates the code, so that's what I'm doing here. + The Ruby implementation does other stuff which I omit. + */ + if (Extend) { + String *wrap = Getattr(n, "wrap:code"); + if (wrap) { + Printv(f_wrappers, wrap, NIL); + } + } + + // HACK: this is only for the v8 emitter. maybe set an attribute wrap:action of node + // TODO: generate dtors more similar to other wrappers + // EW: I think this is wrong. delete should only be used when new was used to create. If malloc was used, free needs to be used. + if (SwigType_isarray(type)) { + Printf(free, "delete [] (%s)", ctype); + } else { + Printf(free, "delete (%s)", ctype); + } + + String *destructor_action = Getattr(n, "wrap:action"); + // Adapted from the JSCore implementation. + /* The next challenge is to generate the correct finalize function for JavaScriptCore to call. + Originally, it would use this fragment from javascriptcode.swg + %fragment ("JS_destructordefn", "templates") + %{ + void _wrap_${classname_mangled}_finalize(JSObjectRef thisObject) + { + SWIG_PRV_DATA* t = (SWIG_PRV_DATA*)JSObjectGetPrivate(thisObject); + if(t && t->swigCMemOwn) free ((${type}*)t->swigCObject); + if(t) free(t); + } + %} + + But for the above example case of %extend to define a destructor on a struct, we need to override the system to not call + free ((${type}*)t->swigCObject); + and substitute it with what the user has provided. + To solve this, I created a variation fragment called JS_destructoroverridedefn: + SWIG_PRV_DATA* t = (SWIG_PRV_DATA*)JSObjectGetPrivate(thisObject); + if(t && t->swigCMemOwn) { + ${type}* arg1 = (${type}*)t->swigCObject; + ${destructor_action} + } + if(t) free(t); + + Based on what I saw in the Lua and Ruby modules, I use Getattr(n, "wrap:action") + to decide if the user has a preferred destructor action. + Based on that, I decide which fragment to use. + And in the case of the custom action, I substitute that action in. + I noticed that destructor_action has the form + delete_MyData(arg1); + The explicit arg1 is a little funny, so I structured the fragment to create a temporary variable called arg1 to make the generation easier. + This might suggest this solution misunderstands a more complex case. + + Also, there is a problem where destructor_action is always true for me, even when not requesting %extend as above. + So this code doesn't actually quite work as I expect. The end result is that the code still works because + destructor_action calls free like the original template. The one caveat is the string in destructor_action casts to char* which is wierd. + I think there is a deeper underlying SWIG issue because I don't think it should be char*. However, it doesn't really matter for free. + + Maybe the fix for the destructor_action always true problem is that this is supposed to be embedded in the if(Extend) block above. + But I don't fully understand the conditions of any of these things, and since it works for the moment, I don't want to break more stuff. + */ + if (destructor_action) { + Template t_dtor = getTemplate("js_dtoroverride"); + state.clazz(DTOR, wrap_name); + t_dtor.replace("${classname_mangled}", state.clazz(NAME_MANGLED)) + .replace("$jswrapper", wrap_name) + .replace("$jsfree", free) + .replace("$jstype", ctype); + + t_dtor.replace("${destructor_action}", destructor_action); + Wrapper_pretty_print(t_dtor.str(), f_wrappers); + } else { + Template t_dtor = getTemplate("js_dtor"); + state.clazz(DTOR, wrap_name); + t_dtor.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jswrapper", wrap_name) + .replace("$jsfree", free) + .replace("$jstype", ctype) + .pretty_print(f_wrappers); + } + + Delete(p_classtype); + Delete(ctype); + Delete(free); + + return SWIG_OK; +} + +int JSEmitter::emitGetter(Node *n, bool is_member, bool is_static) { + Wrapper *wrapper = NewWrapper(); + Template t_getter(getTemplate("js_getter")); + + // prepare wrapper name + String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); + Setattr(n, "wrap:name", wrap_name); + state.variable(GETTER, wrap_name); + + // prepare local variables + ParmList *params = Getattr(n, "parms"); + emit_parameter_variables(params, wrapper); + emit_attach_parmmaps(params, wrapper); + + // prepare code part + String *action = emit_action(n); + marshalInputArgs(n, params, wrapper, Getter, is_member, is_static); + marshalOutput(n, params, wrapper, action); + + emitCleanupCode(n, wrapper, params); + + t_getter.replace("$jswrapper", wrap_name) + .replace("$jslocals", wrapper->locals) + .replace("$jscode", wrapper->code) + .pretty_print(f_wrappers); + + DelWrapper(wrapper); + + return SWIG_OK; +} + +int JSEmitter::emitSetter(Node *n, bool is_member, bool is_static) { + + // skip variables that are immutable + if (State::IsSet(state.variable(IS_IMMUTABLE))) { + return SWIG_OK; + } + + Wrapper *wrapper = NewWrapper(); + + Template t_setter(getTemplate("js_setter")); + + // prepare wrapper name + String *wrap_name = Swig_name_wrapper(Getattr(n, "sym:name")); + Setattr(n, "wrap:name", wrap_name); + state.variable(SETTER, wrap_name); + + // prepare local variables + ParmList *params = Getattr(n, "parms"); + emit_parameter_variables(params, wrapper); + emit_attach_parmmaps(params, wrapper); + + // prepare code part + String *action = emit_action(n); + marshalInputArgs(n, params, wrapper, Setter, is_member, is_static); + Append(wrapper->code, action); + + emitCleanupCode(n, wrapper, params); + + t_setter.replace("$jswrapper", wrap_name) + .replace("$jslocals", wrapper->locals) + .replace("$jscode", wrapper->code) + .pretty_print(f_wrappers); + + DelWrapper(wrapper); + + return SWIG_OK; +} + +/* ----------------------------------------------------------------------------- + * JSEmitter::emitConstant() : triggers code generation for constants + * ----------------------------------------------------------------------------- */ + +int JSEmitter::emitConstant(Node *n) { + // HACK: somehow it happened under OSX that before everything started + // a lot of SWIG internal constants were emitted + // This didn't happen on other platforms yet... + // we ignore those premature definitions + if (!State::IsSet(state.global (HAS_TEMPLATES))) { + return SWIG_ERROR; + } + + Wrapper *wrapper = NewWrapper(); + SwigType *type = Getattr(n, "type"); + String *name = Getattr(n, "name"); + String *iname = Getattr(n, "sym:name"); + String *wname = Swig_name_wrapper(name); + String *rawval = Getattr(n, "rawval"); + String *value = rawval ? rawval : Getattr(n, "value"); + + Template t_getter(getTemplate("js_getter")); + + // call the variable methods as a constants are + // registred in same way + enterVariable(n); + state.variable(GETTER, wname); + // TODO: why do we need this? + Setattr(n, "wrap:name", wname); + + // special treatment of member pointers + if (SwigType_type(type) == T_MPOINTER) { + // TODO: this could go into a code-template + String *mpointer_wname = NewString(""); + Printf(mpointer_wname, "_wrapConstant_%s", iname); + Setattr(n, "memberpointer:constant:wrap:name", mpointer_wname); + String *str = SwigType_str(type, mpointer_wname); + Printf(f_wrappers, "static %s = %s;\n", str, value); + Delete(str); + value = mpointer_wname; + } + + marshalOutput(n, 0, wrapper, NewString(""), value, false); + + t_getter.replace("$jswrapper", wname) + .replace("$jslocals", wrapper->locals) + .replace("$jscode", wrapper->code) + .pretty_print(f_wrappers); + + exitVariable(n); + + DelWrapper(wrapper); + + return SWIG_OK; +} + +int JSEmitter::emitFunction(Node *n, bool is_member, bool is_static) { + Wrapper *wrapper = NewWrapper(); + Template t_function(getTemplate("js_function")); + + bool is_overloaded = GetFlag(n, "sym:overloaded"); + + // prepare the function wrapper name + String *iname = Getattr(n, "sym:name"); + String *wrap_name = Swig_name_wrapper(iname); + if (is_overloaded) { + t_function = getTemplate("js_overloaded_function"); + Append(wrap_name, Getattr(n, "sym:overname")); + } + Setattr(n, "wrap:name", wrap_name); + state.function(WRAPPER_NAME, wrap_name); + + // prepare local variables + ParmList *params = Getattr(n, "parms"); + emit_parameter_variables(params, wrapper); + emit_attach_parmmaps(params, wrapper); + + // HACK: in test-case `ignore_parameter` emit_attach_parmmaps generates an extra line of applied typemap. + // Deleting wrapper->code here fixes the problem, and seems to have no side effect elsewhere + Delete(wrapper->code); + wrapper->code = NewString(""); + + marshalInputArgs(n, params, wrapper, Function, is_member, is_static); + String *action = emit_action(n); + + marshalOutput(n, params, wrapper, action); + + emitCleanupCode(n, wrapper, params); + + Replaceall(wrapper->code, "$symname", iname); + + t_function.replace("$jswrapper", wrap_name) + .replace("$jslocals", wrapper->locals) + .replace("$jscode", wrapper->code) + .replace("$jsargcount", Getattr(n, ARGCOUNT)) + .pretty_print(f_wrappers); + + + DelWrapper(wrapper); + + return SWIG_OK; +} + +int JSEmitter::emitFunctionDispatcher(Node *n, bool /*is_member */ ) { + Wrapper *wrapper = NewWrapper(); + + // Generate call list, go to first node + Node *sibl = n; + + while (Getattr(sibl, "sym:previousSibling")) + sibl = Getattr(sibl, "sym:previousSibling"); // go all the way up + + do { + String *siblname = Getattr(sibl, "wrap:name"); + + if (siblname) { + // handle function overloading + Template t_dispatch_case = getTemplate("js_function_dispatch_case"); + t_dispatch_case.replace("$jswrapper", siblname) + .replace("$jsargcount", Getattr(sibl, ARGCOUNT)); + + Append(wrapper->code, t_dispatch_case.str()); + } + + } while ((sibl = Getattr(sibl, "sym:nextSibling"))); + + Template t_function(getTemplate("js_function_dispatcher")); + + // Note: this dispatcher function gets called after the last overloaded function has been created. + // At this time, n.wrap:name contains the name of the last wrapper function. + // To get a valid function name for the dispatcher function we take the last wrapper name and + // substract the extension "sym:overname", + String *wrap_name = NewString(Getattr(n, "wrap:name")); + String *overname = Getattr(n, "sym:overname"); + int l1 = Len(wrap_name); + int l2 = Len(overname); + Delslice(wrap_name, l1 - l2, l1); + + Setattr(n, "wrap:name", wrap_name); + state.function(WRAPPER_NAME, wrap_name); + + t_function.replace("$jslocals", wrapper->locals) + .replace("$jscode", wrapper->code); + + // call this here, to replace all variables + t_function.replace("$jswrapper", wrap_name) + .replace("$jsname", state.function(NAME)) + .pretty_print(f_wrappers); + + // Delete the state variable + DelWrapper(wrapper); + + return SWIG_OK; +} + +String *JSEmitter::emitInputTypemap(Node *n, Parm *p, Wrapper *wrapper, String *arg) { + // Get input typemap for current param + String *tm = Getattr(p, "tmap:in"); + SwigType *type = Getattr(p, "type"); + + if (tm != NULL) { + Replaceall(tm, "$input", arg); + Setattr(p, "emit:input", arg); + // do replacements for built-in variables + if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) { + Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); + } else { + Replaceall(tm, "$disown", "0"); + } + Replaceall(tm, "$symname", Getattr(n, "sym:name")); + Printf(wrapper->code, "%s\n", tm); + } else { + Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(type, 0)); + } + + return tm; +} + +void JSEmitter::marshalOutput(Node *n, ParmList *params, Wrapper *wrapper, String *actioncode, const String *cresult, bool emitReturnVariable) { + SwigType *type = Getattr(n, "type"); + String *tm; + Parm *p; + + // adds a declaration for the result variable + if (emitReturnVariable) + emit_return_variable(n, type, wrapper); + // if not given, use default result identifier ('result') for output typemap + if (cresult == 0) + cresult = defaultResultName; + + tm = Swig_typemap_lookup_out("out", n, cresult, wrapper, actioncode); + bool should_own = GetFlag(n, "feature:new"); + + if (tm) { + Replaceall(tm, "$objecttype", Swig_scopename_last(SwigType_str(SwigType_strip_qualifiers(type), 0))); + + if (should_own) { + Replaceall(tm, "$owner", "SWIG_POINTER_OWN"); + } else { + Replaceall(tm, "$owner", "0"); + } + Append(wrapper->code, tm); + + if (Len(tm) > 0) { + Printf(wrapper->code, "\n"); + } + } else { + Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(type, 0), Getattr(n, "name")); + } + + if (params) { + for (p = params; p;) { + if ((tm = Getattr(p, "tmap:argout"))) { + Replaceall(tm, "$input", Getattr(p, "emit:input")); + Printv(wrapper->code, tm, "\n", NIL); + p = Getattr(p, "tmap:argout:next"); + } else { + p = nextSibling(p); + } + } + } + + Replaceall(wrapper->code, "$result", "jsresult"); +} + +void JSEmitter::emitCleanupCode(Node *n, Wrapper *wrapper, ParmList *params) { + Parm *p; + String *tm; + + for (p = params; p;) { + if ((tm = Getattr(p, "tmap:freearg"))) { + //addThrows(n, "tmap:freearg", p); + Replaceall(tm, "$input", Getattr(p, "emit:input")); + Printv(wrapper->code, tm, "\n", NIL); + p = Getattr(p, "tmap:freearg:next"); + } else { + p = nextSibling(p); + } + } + + if (GetFlag(n, "feature:new")) { + tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0); + if (tm != NIL) { + //addThrows(throws_hash, "newfree", n); + Printv(wrapper->code, tm, "\n", NIL); + } + } + +} + +int JSEmitter::switchNamespace(Node *n) { + // HACK: somehow this gets called when member functions are processed...ignoring + if (GetFlag(n, "ismember")) { + return SWIG_OK; + } + + String *nspace = Getattr(n, "sym:nspace"); + + // if nspace is deactivated, everything goes into the global scope + if (!GetFlag(n, "feature:nspace")) { + current_namespace = Getattr(namespaces, "::"); + return SWIG_OK; + } + + if (nspace == NULL) { + // enums and constants do not have 'sym:nspace' set + // so we try to get the namespace from the qualified name + if (Equal(Getattr(n, "nodeType"), "enumitem")) { + nspace = Swig_scopename_prefix(Getattr(n, "name")); + } + } + + if (nspace == NULL) { + current_namespace = Getattr(namespaces, "::"); + return SWIG_OK; + } + + String *scope = NewString(nspace); + // replace "." with "::" that we can use Swig_scopename_last + Replaceall(scope, ".", "::"); + + // if the scope is not yet registered + // create (parent) namespaces recursively + if (!Getattr(namespaces, scope)) { + createNamespace(scope); + } + current_namespace = Getattr(namespaces, scope); + + return SWIG_OK; +} + +int JSEmitter::createNamespace(String *scope) { + + String *parent_scope = Swig_scopename_prefix(scope); + Hash *parent_namespace; + if (parent_scope == 0) { + parent_namespace = Getattr(namespaces, "::"); + } else if (!Getattr(namespaces, parent_scope)) { + createNamespace(parent_scope); + parent_namespace = Getattr(namespaces, parent_scope); + } else { + parent_namespace = Getattr(namespaces, parent_scope); + } + assert(parent_namespace != 0); + + Hash *new_namespace = createNamespaceEntry(Char(scope), Char(Getattr(parent_namespace, "name"))); + Setattr(namespaces, scope, new_namespace); + + Delete(parent_scope); + return SWIG_OK; +} + +Hash *JSEmitter::createNamespaceEntry(const char *_name, const char *parent) { + Hash *entry = NewHash(); + String *name = NewString(_name); + Setattr(entry, NAME, Swig_scopename_last(name)); + Setattr(entry, NAME_MANGLED, Swig_name_mangle(name)); + Setattr(entry, PARENT, NewString(parent)); + + Delete(name); + return entry; +} + +/********************************************************************** + * JavascriptCore: JSEmitter implementation for JavascriptCore engine + **********************************************************************/ + +class JSCEmitter:public JSEmitter { + +public: + + JSCEmitter(); + + virtual ~ JSCEmitter(); + + virtual int initialize(Node *n); + + virtual int dump(Node *n); + + virtual int close(); + + +protected: + + virtual int enterVariable(Node *n); + + virtual int exitVariable(Node *n); + + virtual int enterFunction(Node *n); + + virtual int exitFunction(Node *n); + + virtual int enterClass(Node *n); + + virtual int exitClass(Node *n); + + virtual void marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static); + + virtual Hash *createNamespaceEntry(const char *name, const char *parent); + + virtual int emitNamespaces(); + +private: + + String *NULL_STR; + String *VETO_SET; + + // output file and major code parts + File *f_wrap_cpp; + File *f_runtime; + File *f_header; + File *f_init; + +}; + +JSCEmitter::JSCEmitter() +: JSEmitter(), NULL_STR(NewString("NULL")), VETO_SET(NewString("JS_veto_set_variable")), f_wrap_cpp(NULL), f_runtime(NULL), f_header(NULL), f_init(NULL) { +} + +JSCEmitter::~JSCEmitter() { + Delete(NULL_STR); + Delete(VETO_SET); +} + + +/* --------------------------------------------------------------------- + * marshalInputArgs() + * + * Process all of the arguments passed into the argv array + * and convert them into C/C++ function arguments using the + * supplied typemaps. + * --------------------------------------------------------------------- */ + +void JSCEmitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) { + Parm *p; + String *tm; + + // determine an offset index, as members have an extra 'this' argument + // except: static members and ctors. + int startIdx = 0; + if (is_member && !is_static && mode != Ctor) { + startIdx = 1; + } + // store number of arguments for argument checks + int num_args = emit_num_arguments(parms) - startIdx; + String *argcount = NewString(""); + Printf(argcount, "%d", num_args); + Setattr(n, ARGCOUNT, argcount); + + // process arguments + int i = 0; + for (p = parms; p; i++) { + String *arg = NewString(""); + String *type = Getattr(p, "type"); + + // ignore varargs + if (SwigType_isvarargs(type)) + break; + + switch (mode) { + case Getter: + case Function: + if (is_member && !is_static && i == 0) { + Printv(arg, "thisObject", 0); + } else { + Printf(arg, "argv[%d]", i - startIdx); + } + break; + case Setter: + if (is_member && !is_static && i == 0) { + Printv(arg, "thisObject", 0); + } else { + Printv(arg, "value", 0); + } + break; + case Ctor: + Printf(arg, "argv[%d]", i); + break; + default: + throw "Illegal state."; + } + tm = emitInputTypemap(n, p, wrapper, arg); + Delete(arg); + if (tm) { + p = Getattr(p, "tmap:in:next"); + } else { + p = nextSibling(p); + } + } +} + +int JSCEmitter::initialize(Node *n) { + + JSEmitter::initialize(n); + + /* Get the output file name */ + String *outfile = Getattr(n, "outfile"); + + /* Initialize I/O */ + f_wrap_cpp = NewFile(outfile, "w", SWIG_output_files()); + if (!f_wrap_cpp) { + FileErrorDisplay(outfile); + SWIG_exit(EXIT_FAILURE); + } + + /* Initialization of members */ + f_runtime = NewString(""); + f_init = NewString(""); + f_header = NewString(""); + + state.global (CREATE_NAMESPACES, NewString("")); + state.global (REGISTER_NAMESPACES, NewString("")); + state.global (INITIALIZER, NewString("")); + + /* Register file targets with the SWIG file handler */ + Swig_register_filebyname("begin", f_wrap_cpp); + Swig_register_filebyname("header", f_header); + Swig_register_filebyname("wrapper", f_wrappers); + Swig_register_filebyname("runtime", f_runtime); + Swig_register_filebyname("init", f_init); + + return SWIG_OK; +} + +int JSCEmitter::dump(Node *n) { + /* Get the module name */ + String *module = Getattr(n, "name"); + + // write the swig banner + Swig_banner(f_wrap_cpp); + + Template initializer_define(getTemplate("js_initializer_define")); + initializer_define.replace("$jsname", module).pretty_print(f_header); + + SwigType_emit_type_table(f_runtime, f_wrappers); + + Printv(f_wrap_cpp, f_runtime, "\n", 0); + Printv(f_wrap_cpp, f_header, "\n", 0); + Printv(f_wrap_cpp, f_wrappers, "\n", 0); + + emitNamespaces(); + + // compose the initializer function using a template + Template initializer(getTemplate("js_initializer")); + initializer.replace("$jsname", module) + .replace("$jsregisterclasses", state.global (INITIALIZER)) + .replace("$jscreatenamespaces", state.global (CREATE_NAMESPACES)) + .replace("$jsregisternamespaces", state.global (REGISTER_NAMESPACES)) + .pretty_print(f_init); + + Printv(f_wrap_cpp, f_init, 0); + + return SWIG_OK; +} + +int JSCEmitter::close() { + Delete(f_runtime); + Delete(f_header); + Delete(f_wrappers); + Delete(f_init); + Delete(namespaces); + Delete(f_wrap_cpp); + return SWIG_OK; +} + +int JSCEmitter::enterFunction(Node *n) { + + JSEmitter::enterFunction(n); + + return SWIG_OK; +} + +int JSCEmitter::exitFunction(Node *n) { + Template t_function = getTemplate("jsc_function_declaration"); + + bool is_member = GetFlag(n, "ismember") | GetFlag(n, "feature:extend"); + bool is_overloaded = GetFlag(n, "sym:overloaded"); + + // handle overloaded functions + if (is_overloaded) { + if (!Getattr(n, "sym:nextSibling")) { + //state.function(WRAPPER_NAME, Swig_name_wrapper(Getattr(n, "name"))); + // create dispatcher + emitFunctionDispatcher(n, is_member); + } else { + //don't register wrappers of overloaded functions in function tables + return SWIG_OK; + } + } + + t_function.replace("$jsname", state.function(NAME)) + .replace("$jswrapper", state.function(WRAPPER_NAME)); + + if (is_member) { + if (GetFlag(state.function(), IS_STATIC)) { + Append(state.clazz(STATIC_FUNCTIONS), t_function.str()); + } else { + Append(state.clazz(MEMBER_FUNCTIONS), t_function.str()); + } + } else { + Append(Getattr(current_namespace, "functions"), t_function.str()); + } + + return SWIG_OK; +} + +int JSCEmitter::enterVariable(Node *n) { + JSEmitter::enterVariable(n); + state.variable(GETTER, NULL_STR); + state.variable(SETTER, VETO_SET); + return SWIG_OK; +} + + +int JSCEmitter::exitVariable(Node *n) { + Template t_variable(getTemplate("jsc_variable_declaration")); + t_variable.replace("$jsname", state.variable(NAME)) + .replace("$jsgetter", state.variable(GETTER)) + .replace("$jssetter", state.variable(SETTER)); + + if (GetFlag(n, "ismember")) { + if (GetFlag(state.variable(), IS_STATIC) + || Equal(Getattr(n, "nodeType"), "enumitem")) { + Append(state.clazz(STATIC_VARIABLES), t_variable.str()); + } else { + Append(state.clazz(MEMBER_VARIABLES), t_variable.str()); + } + } else { + Append(Getattr(current_namespace, "values"), t_variable.str()); + } + + return SWIG_OK; +} + +int JSCEmitter::enterClass(Node *n) { + JSEmitter::enterClass(n); + state.clazz(MEMBER_VARIABLES, NewString("")); + state.clazz(MEMBER_FUNCTIONS, NewString("")); + state.clazz(STATIC_VARIABLES, NewString("")); + state.clazz(STATIC_FUNCTIONS, NewString("")); + + Template t_class_decl = getTemplate("jsc_class_declaration"); + t_class_decl.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .pretty_print(f_wrappers); + + return SWIG_OK; +} + +int JSCEmitter::exitClass(Node *n) { + Template t_class_tables(getTemplate("jsc_class_tables")); + t_class_tables.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsclassvariables", state.clazz(MEMBER_VARIABLES)) + .replace("$jsclassfunctions", state.clazz(MEMBER_FUNCTIONS)) + .replace("$jsstaticclassfunctions", state.clazz(STATIC_FUNCTIONS)) + .replace("$jsstaticclassvariables", state.clazz(STATIC_VARIABLES)) + .pretty_print(f_wrappers); + + /* adds the ctor wrappers at this position */ + // Note: this is necessary to avoid extra forward declarations. + //Append(f_wrappers, state.clazz(CTOR_WRAPPERS)); + + // for abstract classes add a vetoing ctor + if (GetFlag(state.clazz(), IS_ABSTRACT)) { + Template t_veto_ctor(getTemplate("js_veto_ctor")); + t_veto_ctor.replace("$jswrapper", state.clazz(CTOR)) + .replace("$jsname", state.clazz(NAME)) + .pretty_print(f_wrappers); + } + + /* adds a class template statement to initializer function */ + Template t_classtemplate(getTemplate("jsc_class_definition")); + + /* prepare registration of base class */ + String *jsclass_inheritance = NewString(""); + Node *base_class = getBaseClass(n); + if (base_class != NULL) { + Template t_inherit(getTemplate("jsc_class_inherit")); + t_inherit.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsbaseclassmangled", SwigType_manglestr(Getattr(base_class, "name"))) + .pretty_print(jsclass_inheritance); + } else { + Template t_inherit(getTemplate("jsc_class_noinherit")); + t_inherit.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .pretty_print(jsclass_inheritance); + } + + t_classtemplate.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsmangledtype", state.clazz(TYPE_MANGLED)) + .replace("$jsclass_inheritance", jsclass_inheritance) + .replace("$jsctor", state.clazz(CTOR)) + .replace("$jsdtor", state.clazz(DTOR)) + .pretty_print(state.global (INITIALIZER)); + Delete(jsclass_inheritance); + + /* Note: this makes sure that there is a swig_type added for this class */ + SwigType_remember_clientdata(state.clazz(TYPE_MANGLED), NewString("0")); + + /* adds a class registration statement to initializer function */ + Template t_registerclass(getTemplate("jsc_class_registration")); + t_registerclass.replace("$jsname", state.clazz(NAME)) + .replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsnspace", Getattr(state.clazz("nspace"), NAME_MANGLED)) + .pretty_print(state.global (INITIALIZER)); + + return SWIG_OK; +} + +Hash *JSCEmitter::createNamespaceEntry(const char *name, const char *parent) { + Hash *entry = JSEmitter::createNamespaceEntry(name, parent); + Setattr(entry, "functions", NewString("")); + Setattr(entry, "values", NewString("")); + return entry; +} + +int JSCEmitter::emitNamespaces() { + Iterator it; + for (it = First(namespaces); it.item; it = Next(it)) { + Hash *entry = it.item; + String *name = Getattr(entry, NAME); + String *name_mangled = Getattr(entry, NAME_MANGLED); + String *parent = Getattr(entry, PARENT); + String *parent_mangled = Swig_name_mangle(parent); + String *functions = Getattr(entry, "functions"); + String *variables = Getattr(entry, "values"); + + // skip the global namespace which is given by the application + + Template namespace_definition(getTemplate("jsc_nspace_declaration")); + namespace_definition.replace("$jsglobalvariables", variables) + .replace("$jsglobalfunctions", functions) + .replace("$jsnspace", name_mangled) + .pretty_print(f_wrap_cpp); + + Template t_createNamespace(getTemplate("jsc_nspace_definition")); + t_createNamespace.replace("$jsmangledname", name_mangled); + Append(state.global (CREATE_NAMESPACES), t_createNamespace.str()); + + // Don't register 'exports' as namespace. It is return to the application. + if (!Equal("exports", name)) { + Template t_registerNamespace(getTemplate("jsc_nspace_registration")); + t_registerNamespace.replace("$jsmangledname", name_mangled) + .replace("$jsname", name) + .replace("$jsparent", parent_mangled); + Append(state.global (REGISTER_NAMESPACES), t_registerNamespace.str()); + } + + } + + return SWIG_OK; +} + +JSEmitter *swig_javascript_create_JSCEmitter() { + return new JSCEmitter(); +} + +/********************************************************************** + * V8: JSEmitter implementation for V8 engine + **********************************************************************/ + +class V8Emitter:public JSEmitter { + +public: + + V8Emitter(); + + virtual ~ V8Emitter(); + virtual int initialize(Node *n); + virtual int dump(Node *n); + virtual int close(); + virtual int enterClass(Node *n); + virtual int exitClass(Node *n); + virtual int enterVariable(Node *n); + virtual int exitVariable(Node *n); + virtual int exitFunction(Node *n); + +protected: + + virtual void marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static); + virtual int emitNamespaces(); + +private: + + /* built-in parts */ + String *f_runtime; + String *f_header; + String *f_init; + String *f_post_init; + + /* part for class templates */ + String *f_class_templates; + + /* parts for initilizer */ + String *f_init_namespaces; + String *f_init_class_templates; + String *f_init_wrappers; + String *f_init_inheritance; + String *f_init_class_instances; + String *f_init_static_wrappers; + String *f_init_register_classes; + String *f_init_register_namespaces; + + // the output cpp file + File *f_wrap_cpp; + + String *NULL_STR; + String *VETO_SET; + String *moduleName; + +}; + +V8Emitter::V8Emitter() +: JSEmitter(), NULL_STR(NewString("0")), VETO_SET(NewString("JS_veto_set_variable")) { +} + +V8Emitter::~V8Emitter() { + Delete(NULL_STR); + Delete(VETO_SET); +} + +int V8Emitter::initialize(Node *n) { + JSEmitter::initialize(n); + + moduleName = Getattr(n, "name"); + + // Get the output file name + String *outfile = Getattr(n, "outfile"); + f_wrap_cpp = NewFile(outfile, "w", SWIG_output_files()); + if (!f_wrap_cpp) { + FileErrorDisplay(outfile); + SWIG_exit(EXIT_FAILURE); + } + + f_runtime = NewString(""); + f_header = NewString(""); + f_class_templates = NewString(""); + f_init = NewString(""); + f_post_init = NewString(""); + + f_init_namespaces = NewString(""); + f_init_class_templates = NewString(""); + f_init_wrappers = NewString(""); + f_init_inheritance = NewString(""); + f_init_class_instances = NewString(""); + f_init_static_wrappers = NewString(""); + f_init_register_classes = NewString(""); + f_init_register_namespaces = NewString(""); + + // note: this is necessary for built-in generation of swig runtime code + Swig_register_filebyname("begin", f_wrap_cpp); + Swig_register_filebyname("runtime", f_runtime); + Swig_register_filebyname("header", f_header); + Swig_register_filebyname("wrapper", f_wrappers); + Swig_register_filebyname("init", f_init); + Swig_register_filebyname("post-init", f_post_init); + + return SWIG_OK; +} + +int V8Emitter::dump(Node *n) { + /* Get the module name */ + String *module = Getattr(n, "name"); + + // write the swig banner + Swig_banner(f_wrap_cpp); + + Template initializer_define(getTemplate("js_initializer_define")); + initializer_define.replace("$jsname", module).pretty_print(f_header); + + SwigType_emit_type_table(f_runtime, f_wrappers); + + Printv(f_wrap_cpp, f_runtime, "\n", 0); + Printv(f_wrap_cpp, f_header, "\n", 0); + Printv(f_wrap_cpp, f_class_templates, "\n", 0); + Printv(f_wrap_cpp, f_wrappers, "\n", 0); + + emitNamespaces(); + + // compose the initializer function using a template + // filled with sub-parts + Template initializer(getTemplate("js_initializer")); + initializer.replace("$jsname", moduleName) + .replace("$jsv8nspaces", f_init_namespaces) + .replace("$jsv8classtemplates", f_init_class_templates) + .replace("$jsv8wrappers", f_init_wrappers) + .replace("$jsv8inheritance", f_init_inheritance) + .replace("$jsv8classinstances", f_init_class_instances) + .replace("$jsv8staticwrappers", f_init_static_wrappers) + .replace("$jsv8registerclasses", f_init_register_classes) + .replace("$jsv8registernspaces", f_init_register_namespaces); + Printv(f_init, initializer.str(), 0); + + Printv(f_wrap_cpp, f_init, 0); + + Printv(f_wrap_cpp, f_post_init, 0); + + return SWIG_OK; +} + +int V8Emitter::close() { + Delete(f_runtime); + Delete(f_header); + Delete(f_class_templates); + Delete(f_init_namespaces); + Delete(f_init_class_templates); + Delete(f_init_wrappers); + Delete(f_init_inheritance); + Delete(f_init_class_instances); + Delete(f_init_static_wrappers); + Delete(f_init_register_classes); + Delete(f_init_register_namespaces); + Delete(f_init); + Delete(f_post_init); + Delete(f_wrap_cpp); + return SWIG_OK; +} + +int V8Emitter::enterClass(Node *n) { + JSEmitter::enterClass(n); + + // emit declaration of a v8 class template + Template t_decl_class(getTemplate("jsv8_declare_class_template")); + t_decl_class.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .trim() + .pretty_print(f_class_templates); + + return SWIG_OK; +} + +int V8Emitter::exitClass(Node *n) { + if (GetFlag(state.clazz(), IS_ABSTRACT)) { + Template t_veto_ctor(getTemplate("js_veto_ctor")); + t_veto_ctor.replace("$jswrapper", state.clazz(CTOR)) + .replace("$jsname", state.clazz(NAME)) + .pretty_print(f_wrappers); + } + + /* Note: this makes sure that there is a swig_type added for this class */ + String *clientData = NewString(""); + Printf(clientData, "&%s_clientData", state.clazz(NAME_MANGLED)); + + /* Note: this makes sure that there is a swig_type added for this class */ + SwigType_remember_clientdata(state.clazz(TYPE_MANGLED), NewString("0")); + + // emit definition of v8 class template + Template t_def_class = getTemplate("jsv8_define_class_template"); + t_def_class.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsname", state.clazz(NAME)) + .replace("$jsmangledtype", state.clazz(TYPE_MANGLED)) + .replace("$jsdtor", state.clazz(DTOR)) + .trim() + .pretty_print(f_init_class_templates); + + Template t_class_instance = getTemplate("jsv8_create_class_instance"); + t_class_instance.replace("$jsname", state.clazz(NAME)) + .replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsctor", state.clazz(CTOR)) + .trim() + .pretty_print(f_init_class_instances); + + // emit inheritance setup + Node *baseClass = getBaseClass(n); + if (baseClass) { + String *base_name = Getattr(baseClass, "name"); + + Template t_inherit = getTemplate("jsv8_inherit"); + + String *base_name_mangled = SwigType_manglestr(base_name); + t_inherit.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsbaseclass", base_name_mangled) + .trim() + .pretty_print(f_init_inheritance); + Delete(base_name_mangled); + } + // emit registeration of class template + Template t_register = getTemplate("jsv8_register_class"); + t_register.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsname", state.clazz(NAME)) + .replace("$jsparent", Getattr(state.clazz("nspace"), NAME_MANGLED)) + .trim() + .pretty_print(f_init_register_classes); + + return SWIG_OK; +} + +int V8Emitter::enterVariable(Node *n) { + JSEmitter::enterVariable(n); + + state.variable(GETTER, NULL_STR); + state.variable(SETTER, VETO_SET); + + return SWIG_OK; +} + +int V8Emitter::exitVariable(Node *n) { + if (GetFlag(n, "ismember")) { + if (GetFlag(state.variable(), IS_STATIC) || Equal(Getattr(n, "nodeType"), "enumitem")) { + Template t_register = getTemplate("jsv8_register_static_variable"); + t_register.replace("$jsparent", state.clazz(NAME_MANGLED)) + .replace("$jsname", state.variable(NAME)) + .replace("$jsgetter", state.variable(GETTER)) + .replace("$jssetter", state.variable(SETTER)) + .trim().print(f_init_static_wrappers); + } else { + Template t_register = getTemplate("jsv8_register_member_variable"); + t_register.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsname", state.variable(NAME)) + .replace("$jsgetter", state.variable(GETTER)) + .replace("$jssetter", state.variable(SETTER)) + .trim() + .print(f_init_wrappers); + } + } else { + // Note: a global variable is treated like a static variable + // with the parent being a nspace object (instead of class object) + Template t_register = getTemplate("jsv8_register_static_variable"); + t_register.replace("$jsparent", Getattr(current_namespace, NAME_MANGLED)) + .replace("$jsname", state.variable(NAME)) + .replace("$jsgetter", state.variable(GETTER)) + .replace("$jssetter", state.variable(SETTER)) + .trim() + .print(f_init_wrappers); + } + + return SWIG_OK; +} + +int V8Emitter::exitFunction(Node *n) { + bool is_member = GetFlag(n, "ismember") | GetFlag(n, "feature:extend"); + + // create a dispatcher for overloaded functions + bool is_overloaded = GetFlag(n, "sym:overloaded"); + if (is_overloaded) { + if (!Getattr(n, "sym:nextSibling")) { + //state.function(WRAPPER_NAME, Swig_name_wrapper(Getattr(n, "name"))); + emitFunctionDispatcher(n, is_member); + } else { + //don't register wrappers of overloaded functions in function tables + return SWIG_OK; + } + } + // register the function at the specific context + if (is_member) { + if (GetFlag(state.function(), IS_STATIC)) { + Template t_register = getTemplate("jsv8_register_static_function"); + t_register.replace("$jsparent", state.clazz(NAME_MANGLED)) + .replace("$jsname", state.function(NAME)) + .replace("$jswrapper", state.function(WRAPPER_NAME)) + .trim() + .print(f_init_static_wrappers); + } else { + Template t_register = getTemplate("jsv8_register_member_function"); + t_register.replace("$jsmangledname", state.clazz(NAME_MANGLED)) + .replace("$jsname", state.function(NAME)) + .replace("$jswrapper", state.function(WRAPPER_NAME)) + .trim() + .print(f_init_wrappers); + } + } else { + // Note: a global function is treated like a static function + // with the parent being a nspace object instead of class object + Template t_register = getTemplate("jsv8_register_static_function"); + t_register.replace("$jsparent", Getattr(current_namespace, NAME)) + .replace("$jsname", state.function(NAME)) + .replace("$jswrapper", state.function(WRAPPER_NAME)) + .trim() + .pretty_print(f_init_static_wrappers); + } + + return SWIG_OK; +} + +void V8Emitter::marshalInputArgs(Node *n, ParmList *parms, Wrapper *wrapper, MarshallingMode mode, bool is_member, bool is_static) { + Parm *p; + String *tm; + + int startIdx = 0; + if (is_member && !is_static && mode != Ctor) { + startIdx = 1; + } + // store number of arguments for argument checks + int num_args = emit_num_arguments(parms) - startIdx; + String *argcount = NewString(""); + Printf(argcount, "%d", num_args); + Setattr(n, ARGCOUNT, argcount); + + int i = 0; + for (p = parms; p; i++) { + String *arg = NewString(""); + String *type = Getattr(p, "type"); + + // ignore varargs + if (SwigType_isvarargs(type)) + break; + + switch (mode) { + case Getter: + if (is_member && !is_static && i == 0) { + Printv(arg, "info.Holder()", 0); + } else { + Printf(arg, "args[%d]", i - startIdx); + } + break; + case Function: + if (is_member && !is_static && i == 0) { + Printv(arg, "args.Holder()", 0); + } else { + Printf(arg, "args[%d]", i - startIdx); + } + break; + case Setter: + if (is_member && !is_static && i == 0) { + Printv(arg, "info.Holder()", 0); + } else { + Printv(arg, "value", 0); + } + break; + case Ctor: + Printf(arg, "args[%d]", i); + break; + default: + throw "Illegal state."; + } + + tm = emitInputTypemap(n, p, wrapper, arg); + Delete(arg); + + if (tm) { + p = Getattr(p, "tmap:in:next"); + } else { + p = nextSibling(p); + } + } +} + +int V8Emitter::emitNamespaces() { + Iterator it; + for (it = First(namespaces); it.item; it = Next(it)) { + Hash *entry = it.item; + String *name = Getattr(entry, NAME); + String *name_mangled = Getattr(entry, NAME_MANGLED); + String *parent = Getattr(entry, PARENT); + String *parent_mangled = Swig_name_mangle(parent); + + bool do_create = true; + bool do_register = true; + + if (Equal(parent, "")) { + do_register = false; + } + // Note: 'exports' is by convention the name of the object where + // globals are stored into + if (Equal(name, "exports")) { + do_create = false; + } + + if (do_create) { + // create namespace object and register it to the parent scope + Template t_create_ns = getTemplate("jsv8_create_namespace"); + t_create_ns.replace("$jsmangledname", name_mangled) + .trim() + .pretty_print(f_init_namespaces); + } + + if (do_register) { + Template t_register_ns = getTemplate("jsv8_register_namespace"); + t_register_ns.replace("$jsmangledname", name_mangled) + .replace("$jsname", name) + .replace("$jsparent", parent_mangled) + .trim(); + + // prepend in order to achieve reversed order of registration statements + Insert(f_init_register_namespaces, 0, t_register_ns.str()); + } + } + + return SWIG_OK; +} + +JSEmitter *swig_javascript_create_V8Emitter() { + return new V8Emitter(); +} + + +/********************************************************************** + * Helper implementations + **********************************************************************/ + +JSEmitterState::JSEmitterState() +: _global(NewHash()) { + // initialize sub-hashes + Setattr(_global, "class", NewHash()); + Setattr(_global, "function", NewHash()); + Setattr(_global, "variable", NewHash()); +} + +JSEmitterState::~JSEmitterState() { + Delete(_global); +} + +DOH *JSEmitterState::getState(const char *key, bool _new) { + if (_new) { + Hash *hash = NewHash(); + Setattr(_global, key, hash); + } + return Getattr(_global, key); +} + +DOH *JSEmitterState::global () { + return _global; +} + +DOH *JSEmitterState::global (const char *key, DOH *initial) { + if (initial != 0) { + Setattr(_global, key, initial); + } + return Getattr(_global, key); +} + +DOH *JSEmitterState::clazz(bool _new) { + return getState("class", _new); +} + +DOH *JSEmitterState::clazz(const char *key, DOH *initial) { + DOH *c = clazz(); + if (initial != 0) { + Setattr(c, key, initial); + } + return Getattr(c, key); +} + +DOH *JSEmitterState::function(bool _new) { + return getState("function", _new); +} + +DOH *JSEmitterState::function(const char *key, DOH *initial) { + DOH *f = function(); + if (initial != 0) { + Setattr(f, key, initial); + } + return Getattr(f, key); +} + +DOH *JSEmitterState::variable(bool _new) { + return getState("variable", _new); +} + +DOH *JSEmitterState::variable(const char *key, DOH *initial) { + DOH *v = variable(); + if (initial != 0) { + Setattr(v, key, initial); + } + return Getattr(v, key); +} + +/*static*/ +int JSEmitterState::IsSet(DOH *val) { + if (!val) { + return 0; + } else { + const char *cval = Char(val); + if (!cval) + return 0; + return (strcmp(cval, "0") != 0) ? 1 : 0; + } +} + +/* ----------------------------------------------------------------------------- + * Template::Template() : creates a Template class for given template code + * ----------------------------------------------------------------------------- */ + +Template::Template(const String *code_) { + + if (!code_) { + Printf(stdout, "Template code was null. Illegal input for template."); + SWIG_exit(EXIT_FAILURE); + } + code = NewString(code_); + templateName = NewString(""); +} + +Template::Template(const String *code_, const String *templateName_) { + + if (!code_) { + Printf(stdout, "Template code was null. Illegal input for template."); + SWIG_exit(EXIT_FAILURE); + } + + code = NewString(code_); + templateName = NewString(templateName_); +} + + +/* ----------------------------------------------------------------------------- + * Template::~Template() : cleans up of Template. + * ----------------------------------------------------------------------------- */ + +Template::~Template() { + Delete(code); + Delete(templateName); +} + +/* ----------------------------------------------------------------------------- + * String* Template::str() : retrieves the current content of the template. + * ----------------------------------------------------------------------------- */ + +String *Template::str() { + if (js_template_enable_debug) { + String *pre_code = NewString(""); + String *post_code = NewString(""); + String *debug_code = NewString(""); + Printf(pre_code, "/* begin fragment(\"%s\") */", templateName); + Printf(post_code, "/* end fragment(\"%s\") */", templateName); + Printf(debug_code, "%s\n%s\n%s\n", pre_code, code, post_code); + + Delete(code); + Delete(pre_code); + Delete(post_code); + + code = debug_code; + } + return code; +} + +Template & Template::trim() { + const char *str = Char(code); + if (str == 0) + return *this; + + int length = Len(code); + if (length == 0) + return *this; + + int idx; + for (idx = 0; idx < length; ++idx) { + if (str[idx] != ' ' && str[idx] != '\t' && str[idx] != '\r' && str[idx] != '\n') + break; + } + int start_pos = idx; + + for (idx = length - 1; idx >= start_pos; --idx) { + if (str[idx] != ' ' && str[idx] != '\t' && str[idx] != '\r' && str[idx] != '\n') + break; + } + int end_pos = idx; + + int new_length = end_pos - start_pos + 1; + char *newstr = new char[new_length + 1]; + memcpy(newstr, str + start_pos, new_length); + newstr[new_length] = 0; + + Delete(code); + code = NewString(newstr); + delete[]newstr; + + return *this; +} + +/* ----------------------------------------------------------------------------- + * Template& Template::replace(const String* pattern, const String* repl) : + * + * replaces all occurences of a given pattern with a given replacement. + * + * - pattern: the pattern to be replaced + * - repl: the replacement string + * - returns a reference to the Template to allow chaining of methods. + * ----------------------------------------------------------------------------- */ + +Template & Template::replace(const String *pattern, const String *repl) { + Replaceall(code, pattern, repl); + return *this; +} + +Template & Template::print(DOH *doh) { + Printv(doh, str(), 0); + return *this; +} + +Template & Template::pretty_print(DOH *doh) { + Wrapper_pretty_print(str(), doh); + return *this; +} + +Template::Template(const Template & t) { + code = NewString(t.code); + templateName = NewString(t.templateName); +} + +void Template::operator=(const Template & t) { + Delete(code); + Delete(templateName); + code = NewString(t.code); + templateName = NewString(t.templateName); +} diff --git a/Source/Modules/swigmain.cxx b/Source/Modules/swigmain.cxx index 7c9cded70..97b21710a 100644 --- a/Source/Modules/swigmain.cxx +++ b/Source/Modules/swigmain.cxx @@ -51,6 +51,7 @@ extern "C" { Language *swig_r(void); Language *swig_go(void); Language *swig_d(void); + Language *swig_javascript(void); } struct swig_module { @@ -92,6 +93,7 @@ static swig_module modules[] = { {"-tcl8", swig_tcl, 0}, {"-uffi", swig_uffi, "Common Lisp / UFFI"}, {"-xml", swig_xml, "XML"}, + {"-javascript", swig_javascript, "Javascript"}, {NULL, NULL, NULL} }; diff --git a/Tools/javascript/Makefile.in b/Tools/javascript/Makefile.in new file mode 100644 index 000000000..d58412b50 --- /dev/null +++ b/Tools/javascript/Makefile.in @@ -0,0 +1,58 @@ +# ---------------------------------------------------------------- +# Compile a custom javascript interpreter +# ---------------------------------------------------------------- +# +# Note: +# There is no common CLI Javascript interpreter. +# V8 comes with one 'd8' which however does not provide a means +# to load extensions. Therefore, by default we use nodejs as +# environment. +# For testing native v8 and jsc extensions we provide our own +# interpreter (see 'Tools/javascript'). +# +# ---------------------------------------------------------------- +CC = @CC@ +# HACK: under OSX a g++ compiled interpreter is seg-faulting when loading module libraries +# with 'c++' it works... probably some missing flags? +JSCXX = @JSINTERPRETERCXX@ +CFLAGS = @PLATCFLAGS@ +CXXFLAGS = @BOOST_CPPFLAGS@ @PLATCXXFLAGS@ +LINKFLAGS = @JSINTERPRETERLINKFLAGS@ + +ROOT_DIR = @ROOT_DIR@ +JSCFLAGS = @JSCFLAGS@ +JSCXXFLAGS = @JSCXXFLAGS@ +JSINCLUDES = @JSCOREINC@ @JSV8INC@ +JSDYNAMICLINKING = @JSCOREDYNAMICLINKING@ @JSV8DYNAMICLINKING@ +JSLIBRARYPREFIX = @JSLIBRARYPREFIX@ +JSSO =@JSSO@ +JSLDSHARED = @JSLDSHARED@ +JSCXXSHARED = @JSCXXSHARED@ +JSV8ENABLED = @JSV8ENABLED@ +JSCENABLED = @JSCENABLED@ + +# These settings are provided by 'configure' (see '/configure.in') +ifeq (1, $(JSV8ENABLED)) + JS_INTERPRETER_SRC_V8 = v8_shell.cxx + JS_INTERPRETER_ENABLE_V8 = -DENABLE_V8 +endif + +ifeq (1, $(JSCENABLED)) + JS_INTERPRETER_SRC_JSC = jsc_shell.cxx + JS_INTERPRETER_ENABLE_JSC = -DENABLE_JSC +endif + +JS_INTERPRETER_DEFINES = $(JS_INTERPRETER_ENABLE_JSC) $(JS_INTERPRETER_ENABLE_V8) +JS_INTERPRETER_SRC = javascript.cxx js_shell.cxx $(JS_INTERPRETER_SRC_JSC) $(JS_INTERPRETER_SRC_V8) + +JS_INTERPRETER_OBJS = $(JS_INTERPRETER_SRC:.cxx=.o) + +%.o: %.cxx + $(JSCXX) $(JS_INTERPRETER_DEFINES) $(CXXFLAGS) $(JSINCLUDES) -o $@ -c $< + +javascript: $(JS_INTERPRETER_OBJS) + $(JSCXX) $^ $(CXXFLAGS) -o javascript $(JSDYNAMICLINKING) $(LINKFLAGS) + +clean: + rm -f *.o + rm -f javascript diff --git a/Tools/javascript/javascript.cxx b/Tools/javascript/javascript.cxx new file mode 100644 index 000000000..5e7cc0b20 --- /dev/null +++ b/Tools/javascript/javascript.cxx @@ -0,0 +1,66 @@ +#include +#include +#include +#include +#include +#include + +#include "js_shell.h" + +void print_usage() { + std::cout << "javascript [-i] [-jsc|-v8] [-l module] " << std::endl; +} + +int main(int argc, char* argv[]) { + +#if defined(JAVASCRIPT_INTERPRETER_STOP) + std::cout << "Attach your Debugger and press any key to continue" << std::endl; + std::cin.get(); +#endif + + std::string scriptPath = ""; + + bool interactive = false; + JSShell* shell = 0; + + std::vector modulePath; + modulePath.push_back("."); + + for (int idx = 1; idx < argc; ++idx) { + if(strcmp(argv[idx], "-v8") == 0) { + shell = JSShell::Create(JSShell::V8); + } else if(strcmp(argv[idx], "-jsc") == 0) { + shell = JSShell::Create(JSShell::JSC); + } else if(strcmp(argv[idx], "-i") == 0) { + interactive = true; + } else if(strcmp(argv[idx], "-L") == 0) { + modulePath.push_back(argv[++idx]); + } else { + scriptPath = argv[idx]; + } + } + + if (shell == 0) { + shell = JSShell::Create(); + } + + shell->setModulePath(modulePath); + + bool failed = false; + + if(interactive) { + failed = !(shell->RunShell()); + } else { + failed = !(shell->RunScript(scriptPath)); + } + + if (failed) { + delete shell; + printf("FAIL: Error during execution of script.\n"); + return 1; + } + + delete shell; + + return 0; +} diff --git a/Tools/javascript/js_shell.cxx b/Tools/javascript/js_shell.cxx new file mode 100644 index 000000000..539b83d65 --- /dev/null +++ b/Tools/javascript/js_shell.cxx @@ -0,0 +1,156 @@ +#include "js_shell.h" + +#include +#include +#include +#include +#include + +#ifdef __GNUC__ +#ifdef __APPLE__ +#define LIBRARY_EXT ".bundle" +#else +#define LIBRARY_EXT ".so" +#endif +#include +#define LOAD_LIBRARY(name) dlopen(name, RTLD_LAZY) +#define CLOSE_LIBRARY(handle) dlclose(handle) +#define LIBRARY_ERROR dlerror +#define LIBRARYFILE(name) std::string("lib").append(name).append(LIBRARY_EXT) +#else +#error "implement dll loading" +#endif + + +JSShell::~JSShell() { + + for(std::vector::iterator it = loaded_modules.begin(); + it != loaded_modules.end(); ++it) { + HANDLE handle = *it; + CLOSE_LIBRARY(handle); + } + +} + +// TODO: this could be done more intelligent... +// - can we achieve source file relative loading? +// - better path resolution +std::string JSShell::LoadModule(const std::string& name, HANDLE* library) { + + // works only for posix like OSs + size_t pathIdx = name.find_last_of("/"); + + std::string lib_name; + std::string module_name; + + if (pathIdx == std::string::npos) { + module_name = name; + lib_name = std::string(name).append(LIBRARY_EXT); + } else { + std::string path = name.substr(0, pathIdx+1); + module_name = name.substr(pathIdx+1); + lib_name = path.append(module_name).append(LIBRARY_EXT); + } + + std::string lib_path; + HANDLE handle = 0; + + for (int i = 0; i < module_path.size(); ++i) { + lib_path = module_path[i] + "/" + lib_name; + if (access( lib_path.c_str(), F_OK ) != -1) { + handle = LOAD_LIBRARY(lib_path.c_str()); + } + } + + if(handle == 0) { + std::cerr << "Could not find module " << lib_path << ":" + << std::endl << LIBRARY_ERROR() << std::endl; + return 0; + } + + loaded_modules.push_back(handle); + + *library = handle; + + return module_name; +} + +bool JSShell::RunScript(const std::string& scriptPath) { + std::string source = ReadFile(scriptPath); + if(!InitializeEngine()) return false; + + // Node.js compatibility: make `print` available as `console.log()` + ExecuteScript("var console = {}; console.log = print;", ""); + + if(!ExecuteScript(source, scriptPath)) { + return false; + } + + return DisposeEngine(); +} + +bool JSShell::RunShell() { + + if(!InitializeEngine()) return false; + + static const int kBufferSize = 1024; + while (true) { + char buffer[kBufferSize]; + printf("> "); + char* str = fgets(buffer, kBufferSize, stdin); + if (str == NULL) break; + std::string source(str); + ExecuteScript(source, "(shell)"); + } + printf("\n"); + return true; +} + +std::string JSShell::ReadFile(const std::string& fileName) +{ + std::string script; + + std::ifstream file(fileName.c_str()); + if (file.is_open()) { + while ( file.good() ) { + std::string line; + getline(file, line); + script.append(line); + script.append("\n"); + } + file.close(); + } else { + std::cout << "Unable to open file " << fileName << "." << std::endl; + } + + return script; +} + +#ifdef ENABLE_JSC +extern JSShell* JSCShell_Create(); +#endif +#ifdef ENABLE_V8 +extern JSShell* V8Shell_Create(); +#endif + +typedef JSShell*(*ShellFactory)(); + +static ShellFactory js_shell_factories[2] = { +#ifdef ENABLE_JSC +JSCShell_Create, +#else +0, +#endif +#ifdef ENABLE_V8 +V8Shell_Create, +#else +0, +#endif +}; + +JSShell *JSShell::Create(Engine engine) { + if(js_shell_factories[engine] == 0) { + throw "Engine not available."; + } + return js_shell_factories[engine](); +} diff --git a/Tools/javascript/js_shell.h b/Tools/javascript/js_shell.h new file mode 100644 index 000000000..1e2466b96 --- /dev/null +++ b/Tools/javascript/js_shell.h @@ -0,0 +1,53 @@ +#ifndef JS_SHELL_H +#define JS_SHELL_H + +#include +#include + +typedef void* HANDLE; +typedef void* MODULE; + +class JSShell { + +public: + enum Engine { + JSC = 0, + V8 + }; + +public: + + JSShell() {} + + virtual ~JSShell() = 0; + + static JSShell* Create(Engine engine = JSC); + + std::string LoadModule(const std::string& name, HANDLE* library); + + virtual bool RunScript(const std::string& scriptPath); + + virtual bool RunShell(); + + void setModulePath(const std::vector& modulePath) { + module_path = modulePath; + } + +protected: + + virtual bool InitializeEngine() = 0; + + virtual bool ExecuteScript(const std::string& source, const std::string& scriptPath) = 0; + + virtual bool DisposeEngine() = 0; + + static std::string ReadFile(const std::string& fileName); + +protected: + + std::vector loaded_modules; + std::vector module_path; + +}; + +#endif // JS_SHELL_H diff --git a/Tools/javascript/jsc_shell.cxx b/Tools/javascript/jsc_shell.cxx new file mode 100644 index 000000000..292c4042b --- /dev/null +++ b/Tools/javascript/jsc_shell.cxx @@ -0,0 +1,233 @@ +#include + +#include "js_shell.h" + +#include +#include + +#ifdef __GNUC__ +#include +#define LOAD_SYMBOL(handle, name) dlsym(handle, name) +#else +#error "implement dll loading" +#endif + +class JSCShell: public JSShell { + +typedef int (*JSCIntializer)(JSGlobalContextRef context, JSObjectRef *module); + +public: + + JSCShell() {}; + + virtual ~JSCShell(); + +protected: + + virtual bool InitializeEngine(); + + virtual bool ExecuteScript(const std::string& source, const std::string& scriptPath); + + virtual bool DisposeEngine(); + +private: + + JSObjectRef Import(const std::string &moduleName); + + static JSValueRef Print(JSContextRef context, JSObjectRef object, JSObjectRef globalobj, size_t argc, const JSValueRef args[], JSValueRef* ex); + + static JSValueRef Require(JSContextRef context, JSObjectRef object, JSObjectRef globalobj, size_t argc, const JSValueRef args[], JSValueRef* ex); + + static bool RegisterFunction(JSGlobalContextRef context, JSObjectRef object, const char* functionName, JSObjectCallAsFunctionCallback cbFunction); + + static void PrintError(JSContextRef, JSValueRef); + +private: + + JSGlobalContextRef context; +}; + +JSCShell::~JSCShell() { + if(context != 0) { + JSGlobalContextRelease(context); + context = 0; + } +} + +bool JSCShell::InitializeEngine() { + if(context != 0) { + JSGlobalContextRelease(context); + context = 0; + } + // TODO: check for initialization errors + context = JSGlobalContextCreate(NULL); + if(context == 0) return false; + JSObjectRef globalObject = JSContextGetGlobalObject(context); + + // store this for later use + JSClassDefinition __shell_classdef__ = JSClassDefinition(); + + JSClassRef __shell_class__ = JSClassCreate(&__shell_classdef__); + JSObjectRef __shell__ = JSObjectMake(context, __shell_class__, 0); + bool success = JSObjectSetPrivate(__shell__, (void*) (long) this); + if (!success) { + std::cerr << "Could not register the shell in the Javascript context" << std::endl; + return false; + } + JSStringRef shellKey = JSStringCreateWithUTF8CString("__shell__"); + JSObjectSetProperty(context, globalObject, shellKey, __shell__, kJSPropertyAttributeReadOnly, NULL); + JSStringRelease(shellKey); + + JSCShell::RegisterFunction(context, globalObject, "print", JSCShell::Print); + JSCShell::RegisterFunction(context, globalObject, "require", JSCShell::Require); + + return true; +} + +bool JSCShell::ExecuteScript(const std::string& source, const std::string& scriptPath) { + JSStringRef jsScript; + JSStringRef sourceURL; + JSValueRef ex; + jsScript = JSStringCreateWithUTF8CString(source.c_str()); + sourceURL = JSStringCreateWithUTF8CString(scriptPath.c_str()); + JSValueRef jsResult = JSEvaluateScript(context, jsScript, 0, sourceURL, 0, &ex); + JSStringRelease(jsScript); + if (jsResult == NULL && ex != NULL) { + JSCShell::PrintError(context, ex); + return false; + } + return true; +} + +bool JSCShell::DisposeEngine() { + JSGlobalContextRelease(context); + context = 0; + return true; +} + +JSValueRef JSCShell::Print(JSContextRef context, JSObjectRef object, + JSObjectRef globalobj, size_t argc, + const JSValueRef args[], JSValueRef* ex) { + if (argc > 0) + { + JSStringRef string = JSValueToStringCopy(context, args[0], NULL); + size_t numChars = JSStringGetMaximumUTF8CStringSize(string); + char *stringUTF8 = new char[numChars]; + JSStringGetUTF8CString(string, stringUTF8, numChars); + printf("%s\n", stringUTF8); + + delete[] stringUTF8; + } + + return JSValueMakeUndefined(context); +} + +// Attention: this feature should not create too high expectations. +// It is only capable of loading things relative to the execution directory +// and not relative to the parent script. +JSValueRef JSCShell::Require(JSContextRef context, JSObjectRef object, + JSObjectRef globalObj, size_t argc, + const JSValueRef args[], JSValueRef* ex) { + JSObjectRef module; + + JSStringRef shellKey = JSStringCreateWithUTF8CString("__shell__"); + JSValueRef shellAsVal = JSObjectGetProperty(context, globalObj, shellKey, NULL); + JSStringRelease(shellKey); + JSObjectRef shell = JSValueToObject(context, shellAsVal, 0); + JSCShell *_this = (JSCShell*) (long) JSObjectGetPrivate(shell); + + if (argc > 0) + { + JSStringRef string = JSValueToStringCopy(context, args[0], NULL); + size_t numChars = JSStringGetMaximumUTF8CStringSize(string); + char *stringUTF8 = new char[numChars]; + JSStringGetUTF8CString(string, stringUTF8, numChars); + + std::string modulePath(stringUTF8); + module = _this->Import(modulePath); + + delete[] stringUTF8; + } + + if (module) { + return module; + } else { + printf("Ooops.\n"); + return JSValueMakeUndefined(context); + } +} + +JSObjectRef JSCShell::Import(const std::string& module_path) { + + HANDLE library; + std::string module_name = LoadModule(module_path, &library); + + if (library == 0) { + printf("Could not load module."); + return 0; + } + + std::string symname = std::string(module_name).append("_initialize"); + + JSCIntializer init_function = reinterpret_cast((long) LOAD_SYMBOL(library, symname.c_str())); + if(init_function == 0) { + printf("Could not find module's initializer function."); + return 0; + } + + JSObjectRef module; + init_function(context, &module); + + return module; +} + +bool JSCShell::RegisterFunction(JSGlobalContextRef context, JSObjectRef object, + const char* functionName, JSObjectCallAsFunctionCallback callback) { + JSStringRef js_functionName = JSStringCreateWithUTF8CString(functionName); + JSObjectSetProperty(context, object, js_functionName, + JSObjectMakeFunctionWithCallback(context, js_functionName, callback), + kJSPropertyAttributeNone, NULL); + JSStringRelease(js_functionName); + return true; +} + +void JSCShell::PrintError(JSContextRef ctx, JSValueRef err) { + char *buffer; + size_t length; + + JSStringRef string = JSValueToStringCopy(ctx, err, 0); + length = JSStringGetLength(string); + buffer = new char[length+1]; + JSStringGetUTF8CString(string, buffer, length+1); + std::string errMsg(buffer); + JSStringRelease(string); + delete[] buffer; + + JSObjectRef errObj = JSValueToObject(ctx, err, 0); + + if(errObj == 0) { + std::cerr << errMsg << std::endl; + return; + } + + JSStringRef sourceURLKey = JSStringCreateWithUTF8CString("sourceURL"); + JSStringRef sourceURLStr = JSValueToStringCopy(ctx, JSObjectGetProperty(ctx, errObj, sourceURLKey, 0), 0); + length = JSStringGetLength(sourceURLStr); + buffer = new char[length+1]; + JSStringGetUTF8CString(sourceURLStr, buffer, length+1); + std::string sourceURL(buffer); + delete[] buffer; + JSStringRelease(sourceURLStr); + JSStringRelease(sourceURLKey); + + JSStringRef lineKey = JSStringCreateWithUTF8CString("line"); + JSValueRef jsLine = JSObjectGetProperty(ctx, errObj, lineKey, 0); + int line = (int) JSValueToNumber(ctx, jsLine, 0); + JSStringRelease(lineKey); + + std::cerr << sourceURL << ":" << line << ":" << errMsg << std::endl; +} + +JSShell* JSCShell_Create() { + return new JSCShell(); +} diff --git a/Tools/javascript/v8_shell.cxx b/Tools/javascript/v8_shell.cxx new file mode 100755 index 000000000..8a571e0f1 --- /dev/null +++ b/Tools/javascript/v8_shell.cxx @@ -0,0 +1,310 @@ +#include +#include +#include +#include +#include + +#include +#include + +#include "js_shell.h" + +typedef int (*V8ExtensionInitializer) (v8::Handle module); + +class V8Shell: public JSShell { + +public: + V8Shell(); + + virtual ~V8Shell(); + + virtual bool RunScript(const std::string& scriptPath); + + virtual bool RunShell(); + + +protected: + + virtual bool InitializeEngine(); + + virtual bool ExecuteScript(const std::string& source, const std::string& scriptPath); + + virtual bool DisposeEngine(); + +private: + + v8::Handle Import(const std::string& moduleName); + + v8::Persistent CreateShellContext(); + + void ReportException(v8::TryCatch* handler); + + static v8::Handle Print(const v8::Arguments& args); + + static v8::Handle Require(const v8::Arguments& args); + + static v8::Handle Quit(const v8::Arguments& args); + + static v8::Handle Version(const v8::Arguments& args); + + static const char* ToCString(const v8::String::Utf8Value& value); + +protected: + + v8::Persistent context; +}; + +#ifdef __GNUC__ +#include +#define LOAD_SYMBOL(handle, name) dlsym(handle, name) +#else +#error "implement dll loading" +#endif + +V8Shell::V8Shell() +{ +} + +V8Shell::~V8Shell() { + context.Dispose(); + v8::V8::Dispose(); +} + +bool V8Shell::RunScript(const std::string& scriptPath) { + + if (!context.IsEmpty()) { + context.Dispose(); + } + + std::string source = ReadFile(scriptPath); + + context = CreateShellContext(); + if (context.IsEmpty()) { + printf("Could not create context.\n"); + return false; + } + context->Enter(); + //v8::Context::Scope context_scope(context); + v8::HandleScope scope; + + // Store a pointer to this shell for later use + v8::Handle global = context->Global(); + v8::Local __shell__ = v8::External::New((void*) (long) this); + global->SetHiddenValue(v8::String::New("__shell__"), __shell__); + + // Node.js compatibility: make `print` available as `console.log()` + ExecuteScript("var console = {}; console.log = print;", ""); + + if(!ExecuteScript(source, scriptPath)) { + return false; + } + + context->Exit(); + context.Dispose(); + v8::V8::Dispose(); + + return true; +} + +bool V8Shell::RunShell() { + + if (!context.IsEmpty()) { + context.Dispose(); + } + + context = CreateShellContext(); + if (context.IsEmpty()) { + printf("Could not create context.\n"); + return false; + } + + context->Enter(); + + v8::Context::Scope context_scope(context); + + ExecuteScript("var console = {}; console.log = print;", ""); + + static const int kBufferSize = 1024; + while (true) { + char buffer[kBufferSize]; + printf("> "); + char* str = fgets(buffer, kBufferSize, stdin); + if (str == NULL) break; + std::string source(str); + ExecuteScript(source, "(shell)"); + } + printf("\n"); + + context->Exit(); + context.Dispose(); + v8::V8::Dispose(); + + return true; +} + + +bool V8Shell::InitializeEngine() { + return true; +} + +bool V8Shell::ExecuteScript(const std::string& source, const std::string& name) { + v8::HandleScope handle_scope; + v8::TryCatch try_catch; + v8::Handle script = v8::Script::Compile(v8::String::New(source.c_str()), v8::String::New(name.c_str())); + + // Stop if script is empty + if (script.IsEmpty()) { + // Print errors that happened during compilation. + ReportException(&try_catch); + return false; + } + + v8::Handle result = script->Run(); + + // Print errors that happened during execution. + if (try_catch.HasCaught()) { + ReportException(&try_catch); + return false; + } else { + return true; + } +} + +bool V8Shell::DisposeEngine() { + return true; +} + +v8::Persistent V8Shell::CreateShellContext() { + v8::HandleScope scope; + + // Create a template for the global object. + v8::Handle global = v8::ObjectTemplate::New(); + + // Bind global functions + global->Set(v8::String::New("print"), v8::FunctionTemplate::New(V8Shell::Print)); + global->Set(v8::String::New("quit"), v8::FunctionTemplate::New(V8Shell::Quit)); + global->Set(v8::String::New("require"), v8::FunctionTemplate::New(V8Shell::Require)); + global->Set(v8::String::New("version"), v8::FunctionTemplate::New(V8Shell::Version)); + + v8::Persistent _context = v8::Context::New(NULL, global); + + return _context; +} + +v8::Handle V8Shell::Import(const std::string& module_path) +{ + v8::HandleScope scope; + + HANDLE library; + std::string module_name = LoadModule(module_path, &library); + + std::string symname = std::string(module_name).append("_initialize"); + + V8ExtensionInitializer init_function = reinterpret_cast((long) LOAD_SYMBOL(library, symname.c_str())); + + if(init_function == 0) { + printf("Could not find initializer function."); + return v8::Undefined(); + } + + v8::Local module = v8::Object::New(); + init_function(module); + return scope.Close(module); +} + +v8::Handle V8Shell::Print(const v8::Arguments& args) { + bool first = true; + for (int i = 0; i < args.Length(); i++) { + v8::HandleScope handle_scope; + if (first) { + first = false; + } else { + printf(" "); + } + v8::String::Utf8Value str(args[i]); + const char* cstr = V8Shell::ToCString(str); + printf("%s", cstr); + } + printf("\n"); + fflush(stdout); + return v8::Undefined(); +} + +v8::Handle V8Shell::Require(const v8::Arguments& args) { + v8::HandleScope scope; + + if (args.Length() != 1) { + printf("Illegal arguments for `require`"); + }; + + v8::String::Utf8Value str(args[0]); + const char* cstr = V8Shell::ToCString(str); + std::string moduleName(cstr); + + v8::Local global = v8::Context::GetCurrent()->Global(); + v8::Local hidden = global->GetHiddenValue(v8::String::New("__shell__")); + v8::Local __shell__ = v8::Local::Cast(hidden); + V8Shell* _this = (V8Shell*) (long) __shell__->Value(); + + v8::Handle module = _this->Import(moduleName); + + return scope.Close(module); +} + +v8::Handle V8Shell::Quit(const v8::Arguments& args) { + int exit_code = args[0]->Int32Value(); + fflush(stdout); + fflush(stderr); + exit(exit_code); + return v8::Undefined(); +} + +v8::Handle V8Shell::Version(const v8::Arguments& args) { + return v8::String::New(v8::V8::GetVersion()); +} + +void V8Shell::ReportException(v8::TryCatch* try_catch) { + v8::HandleScope handle_scope; + v8::String::Utf8Value exception(try_catch->Exception()); + const char* exception_string = V8Shell::ToCString(exception); + v8::Handle message = try_catch->Message(); + if (message.IsEmpty()) { + // V8 didn't provide any extra information about this error; just + // print the exception. + printf("%s\n", exception_string); + } else { + // Print (filename):(line number): (message). + v8::String::Utf8Value filename(message->GetScriptResourceName()); + const char* filename_string = V8Shell::ToCString(filename); + int linenum = message->GetLineNumber(); + printf("%s:%i: %s\n", filename_string, linenum, exception_string); + // Print line of source code. + v8::String::Utf8Value sourceline(message->GetSourceLine()); + const char* sourceline_string = V8Shell::ToCString(sourceline); + printf("%s\n", sourceline_string); + // Print wavy underline (GetUnderline is deprecated). + int start = message->GetStartColumn(); + for (int i = 0; i < start; i++) { + printf(" "); + } + int end = message->GetEndColumn(); + for (int i = start; i < end; i++) { + printf("^"); + } + printf("\n"); + v8::String::Utf8Value stack_trace(try_catch->StackTrace()); + if (stack_trace.length() > 0) { + const char* stack_trace_string = V8Shell::ToCString(stack_trace); + printf("%s\n", stack_trace_string); + } + } +} + +// Extracts a C string from a V8 Utf8Value. +const char* V8Shell::ToCString(const v8::String::Utf8Value& value) { + return *value ? *value : ""; +} + +JSShell* V8Shell_Create() { + return new V8Shell(); +} diff --git a/Tools/swigconfig.h.cmake b/Tools/swigconfig.h.cmake new file mode 100644 index 000000000..e4f0b42c4 --- /dev/null +++ b/Tools/swigconfig.h.cmake @@ -0,0 +1,89 @@ +/* Define to 1 if the system has the type `bool'. */ +#cmakedefine HAVE_BOOL 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the `dl' library (-ldl). */ +#cmakedefine HAVE_LIBDL 1 + +/* Define to 1 if you have the `dld' library (-ldld). */ +#cmakedefine HAVE_LIBDLD 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_MEMORY_H 1 + +/* Define if popen is available */ +#cmakedefine HAVE_POPEN 1 + +/* Define if rxspencer is available */ +#cmakedefine HAVE_RXSPENCER 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STDINT_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STDLIB_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STRINGS_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_STRING_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the header file. */ +#cmakedefine HAVE_UNISTD_H 1 + +/* Define to 1 if your C compiler doesn't accept -c and -o together. */ +#cmakedefine NO_MINUS_C_MINUS_O 1 + +/* Define to 1 if you have the ANSI C header files. */ +#cmakedefine STDC_HEADERS 1 + +/* Name of package */ +#define PACKAGE "swig" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "http://www.swig.org" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "swig" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "swig @SWIG_VERSION@" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "swig" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "@SWIG_VERSION@" + +/* Compiler that built SWIG */ +#define SWIG_CXX "@SWIG_CXX@" + +/* Directory for SWIG system-independent libraries */ +#define SWIG_LIB "/usr/local/share/swig/2.0.0" + +/* Directory for SWIG system-independent libraries (Unix install on native + Windows) */ +#define SWIG_LIB_WIN_UNIX "C:/cygwin/usr/local/share/swig/2.0.0" + +/* Platform that SWIG is built for */ +#define SWIG_PLATFORM "i686-pc-cygwin" + +/* Version number of package */ +#define VERSION "@SWIG_VERSION@" + +/* Default language */ +#define SWIG_LANG "-tcl" + +/* Deal with Microsoft's attempt at deprecating C standard runtime functions */ +#if defined(_MSC_VER) +# define _CRT_SECURE_NO_DEPRECATE +#endif diff --git a/Tools/swigprinters.gdb b/Tools/swigprinters.gdb new file mode 100644 index 000000000..661aa3ea1 --- /dev/null +++ b/Tools/swigprinters.gdb @@ -0,0 +1,24 @@ +python +import sys +import os + +try: + global SWIG_PRINTER_DIR + sys.path.insert(0, SWIG_PRINTER_DIR) +except NameError: + raise RuntimeError(""" +--------------------------------------------------------- +Change ~/.gdbinit to be able to use swig pretty printers: +> set python SWIG_PRINTER_DIR = /Tools +> source /Tools/swigprinters.gdb +--------------------------------------------------------- +""") + +from swigprinters import register_swig_printers, enableGdbPrintWorkaround, \ + setChildrenRecursionLevel + +#enableGdbPrintWorkaround() +#setChildrenRecursionLevel(2) +register_swig_printers (None) + +end diff --git a/Tools/swigprinters.py b/Tools/swigprinters.py new file mode 100755 index 000000000..741565997 --- /dev/null +++ b/Tools/swigprinters.py @@ -0,0 +1,574 @@ +import gdb +import gdb.types +import itertools +import re + +log_file = None +GDB_FLATTENED_CHILDREN_WORKAROUND = False +CHILDREN_MAX_RECURSION_LEVEL = 0 + +# workaround: don't cast the following DOHs to it's actual type +# to avoid infinite pretty-print loops +cast_black_list = { + 'Hash': set(['parentNode', 'symtab', 'csymtab', 'sym:symtab', 'inherit', 'nextSibling', 'previousSibling']) +} + +def print_(msg): + global log_file; + + if True: + if log_file == None: + log_file = open('swig_gdb.log', 'w') + log_file.write(msg) + + print(msg) + +class SwigStringPrinter: + """ + Pretty print Swig String* types. + """ + + def __init__ (self, typename, val): + self.typename = typename + self.val = val + + try: + self.t_swigstr_ptr = gdb.lookup_type("struct String").pointer() + self.t_doh_base_ptr = gdb.lookup_type("DohBase").pointer() + except Exception as err: + print_("SwigStringPrinter: Could not retrieve gdb types.\n %s.\n"%(str(err))) + + def display_hint(self): + return 'string' + + def to_string(self): + ret = "" + + # Conversion taken from Swig Internals manual: + # http://peregrine.hpc.uwm.edu/Head-node-docs/swig/2.0.4/Devel/internals.html#7 + # (*(struct String *)(((DohBase *)s)->data)).str + + dohbase = None; + str_data = None; + char_ptr = None; + + try: + dohbase = self.val.reinterpret_cast(self.t_doh_base_ptr).dereference() + except Exception as err: + print_("SwigStringPrinter: Could not dereference DOHBase*\n"); + return ""; + + try: + str_data = dohbase['data'].reinterpret_cast(self.t_swigstr_ptr).dereference() + except Exception as err: + print_("SwigStringPrinter: Could not dereference struct String*\n"); + return ""; + + try: + char_ptr = str_data['str'] + except Exception as err: + print_("SwigStringPrinter: Could not access field (struct String).str\n"); + return ""; + + if char_ptr.is_lazy is True: + char_ptr.fetch_lazy () + + try: + ret = char_ptr.string() + except Exception as err: + print_("SwigStringPrinter: Could not convert const char* to string\n"); + return ""; + + return ret + +class SwigIterator: + + def __init__(self): + + self.t_doh_base_ptr = gdb.lookup_type("DohBase").pointer() + self.t_string_ptr = gdb.lookup_type("String").pointer() + self.t_node_ptr = gdb.lookup_type("Node").pointer() + self.t_hash_ptr = gdb.lookup_type("Hash").pointer() + self.t_file_ptr = gdb.lookup_type("File").pointer() + self.t_void_ptr = gdb.lookup_type("void").pointer() + + def cast_doh(self, doh, name = None): + + if doh == 0: + return doh + + doh = doh.reinterpret_cast(self.t_doh_base_ptr); + + val_base = doh.dereference() + val_type = val_base['type'].dereference() + val_typestr = val_type['objname'].string() + + if not name == None and val_typestr in cast_black_list: + blacklist = cast_black_list[val_typestr] + if name in blacklist: + return doh + + if "String" == val_typestr: + doh = doh.reinterpret_cast(self.t_string_ptr) + elif "File" == val_typestr: + doh = doh.reinterpret_cast(self.t_file_ptr) + # BUG: GDB Pyhton can not handle cyclic references yet + # so these casts are deactivated + elif "Hash" == val_typestr: + doh = doh.reinterpret_cast(self.t_hash_ptr) + elif "Node" == val_typestr: + doh = doh.reinterpret_cast(self.t_node_ptr) + + return doh + +class SwigListIterator(SwigIterator): + + def __init__(self, val): + SwigIterator.__init__(self); + + try: + self.valid = False + + self.val = val.reinterpret_cast(self.t_doh_base_ptr) + val_base = self.val.dereference() + val_type = val_base['type'].dereference() + val_typestr = val_type['objname'].string() + #print_("SwigListIterator: constructing iterator for value of type %s"%val_typestr) + + self.t_struct_list_ptr = gdb.lookup_type("struct List").pointer() + + doh_base = self.val.dereference() + self.l = doh_base['data'].reinterpret_cast(self.t_struct_list_ptr).dereference() + + self.address = 0 + self._index = 0 + self.key = 0 + self.item = 0 + + self.address = self.val.dereference().address + + self.is_first = True + self.valid = True + + except Exception as err: + print_("SwigListIterator: Construction failed.\n %s.\n"%(str(err))) + + def __iter__(self): + return self + + def List_first(self): + + self.object = None; + self._index = 0 + self.key = 0 + self.nitems = int(self.l['nitems']) + self.items = self.l['items'] + + if self.nitems > 0: + self.item = self.items[0] + else: + self.stop() + + def List_next(self): + self._index = self._index + 1 + if self._index >= self.nitems: + self.stop() + else: + self.item = self.items[self._index] + + def next(self): + + if not self.valid: + self.stop() + + if self.is_first: + self.is_first = False + try: + self.List_first() + except StopIteration: + raise StopIteration + except Exception as err: + print_("Error during iteration to first node: \n %s \n" %(str(err))) + self.stop() + else: + try: + self.List_next() + except StopIteration: + raise StopIteration + except Exception as err: + print_("Error during iteration to first node: \n %s \n" %(str(err))) + self.stop() + + key_str = "[%d]"%self._index + item = 0 + + try: + item = self.cast_doh(self.item) + except Exception as err: + print_("SwigListIterator(%s): Exception during casting of value doh:\n %s\n" % (str(self.address), str(err)) ) + self.stop() + + return (key_str, item) + + def stop(self): + self.is_first = True + self.item = 0 + self.key = 0 + raise StopIteration + +class SwigHashIterator(SwigIterator): + + def __init__(self, val): + SwigIterator.__init__(self); + + try: + self.valid = False + + self.val = val.reinterpret_cast(self.t_doh_base_ptr) + + self.t_struct_hash_ptr = gdb.lookup_type("struct Hash").pointer() + self.t_struct_hash_node_ptr = gdb.lookup_type("struct HashNode").pointer() + + doh_base = self.val.dereference() + hash_ = doh_base['data'].reinterpret_cast(self.t_struct_hash_ptr).dereference() + self.hashtable = hash_['hashtable'] + self.hashsize = int(hash_['hashsize']) + self.nitems = int(hash_['nitems']) + + self.next_ = 0 + self.address = 0 + self.pos = 0; + self._current = 0 + self.item = 0 + self.key = 0 + self._index = 0 + + self.address = self.val.dereference().address + + self.is_first = True + self.valid = True + + except Exception as err: + print_("SwigHashIterator: Construction failed.\n %s.\n"%(str(err))) + + def __iter__(self): + return self + + def Hash_firstiter(self): + self._current = 0; + self.item = 0; + self.key = 0; + self._index = 0; + + while (self._index < self.hashsize) and (self.hashtable[self._index] == 0): + self._index = self._index+1; + + if self._index >= self.hashsize: + self.stop(); + + self._current = self.hashtable[self._index] + self._current = self._current.reinterpret_cast(self.t_struct_hash_node_ptr); + self.item = self._current['object']; + self.key = self._current['key']; + + self._current = self._current['next']; + + + def Hash_nextiter(self): + if self._current == 0: + self._index = self._index + 1 + while (self._index < self.hashsize) and (self.hashtable[self._index] == 0): + self._index = self._index + 1 + + if self._index >= self.hashsize: + self.item = 0; + self.key = 0; + self._current = 0; + self.stop() + + self._current = self.hashtable[self._index]; + + self._current = self._current.reinterpret_cast(self.t_struct_hash_node_ptr); + self.key = self._current['key']; + self.item = self._current['object']; + + self._current = self._current['next']; + + + def next(self): + + if not self.valid: + self.stop() + + if self.is_first: + self.is_first = False + try: + self.Hash_firstiter() + except StopIteration: + raise StopIteration + except Exception as err: + print_("Error during iteration to first node: \n %s \n" %(str(err))) + self.stop() + else: + try: + self.Hash_nextiter() + except StopIteration: + raise StopIteration + except Exception as err: + print_("Error during iteration to first node: \n %s \n" %(str(err))) + self.stop() + + key_str = "" + item = 0 + try: + string_printer = SwigStringPrinter("String *", self.key) + key_str = string_printer.to_string() + except Exception as err: + print_("SwigHashIterator(%s): Exception during extracting key string:\n %s\n" % (str(self.address), str(err)) ) + self.stop() + + try: + item = self.cast_doh(self.item, key_str) + + except Exception as err: + print_("SwigHashIterator(%s): Exception during casting of value doh:\n %s\n" % (str(self.address), str(err)) ) + self.stop() + + return (key_str, item) + + def stop(self): + self.is_first = True + raise StopIteration + +class AlternateKeyValueIterator(): + + def __init__(self, iterable): + self.it = iterable.__iter__() + self._next = None + self.count = -1 + + def __iter__(self): + return self + + def next(self): + if self._next == None: + key, value = self.it.next() + self._next = value + self.count = self.count + 1 + return ("[%d]"%self.count, key) + else: + value = self._next + self._next = None + return ("[%d]"%self.count, value) + +class NopIterator: + + def __init__(self): + pass + + def __iter__(self): + return self + + def next(self): + raise StopIteration + +class SwigListPrinter: + """ + Pretty print Swig List* types (also ParmList*). + """ + + def __init__ (self, typename, val): + + self.typename = typename + self.val = val + + it = SwigListIterator(val) + self.valid = it.valid + self.address = it.address + + + def display_hint(self): + return 'array' + + def to_string(self): + return "%s(%s)" % (str(self.typename), str(self.address)) + + def children(self): + + if not self.valid: + print_("SwigListPrinter: Invalid state.\n") + return NopIterator() + + try: + it = SwigListIterator(self.val) + return it + except Exception as err: + print_("SwigListPrinter: Error during creation of children iterator. \n %s \n" %(str(err))) + raise err + +class SwigHashPrinter: + """ + Pretty print Swig Hash* types (also Node*). + """ + + def __init__ (self, typename, val): + + self.typename = typename + self.val = val + it = SwigHashIterator(val) + self.valid = it.valid + self.address = it.address + self.level = 0; + + def display_hint(self): + return 'map' + + def to_string(self): + return "%s(%s)" % (str(self.typename), str(self.address)) + + def children(self): + global GDB_FLATTENED_CHILDREN_WORKAROUND + global CHILDREN_MAX_RECURSION_LEVEL + + if not self.valid: + print_("SwigHashPrinter: Invalid state.\n") + return NopIterator() + + if self.level > CHILDREN_MAX_RECURSION_LEVEL: + return NopIterator() + + try: + it = SwigHashIterator(self.val) + if GDB_FLATTENED_CHILDREN_WORKAROUND: + return AlternateKeyValueIterator(it) + return it + except Exception as err: + print_("SwigHashPrinter: Error during creation of children iterator. \n %s \n" %(str(err))) + raise err + +class SwigSimplePrinter: + def __init__ (self, typename, val): + self.typename = typename + self.val = val + + def display_hint(self): + return "string" + + def to_string(self): + return "%s(%s)"%(self.typename, str(self.val.address)) + +class SwigDelegatingPrinter: + + def __init__ (self, typename, val): + t_doh_base_ptr = gdb.lookup_type("DohBase").pointer() + val_base = val.reinterpret_cast(t_doh_base_ptr).dereference() + val_type = val_base['type'].dereference() + val_typestr = val_type['objname'].string() + self.has_children = False + + if val_typestr == "Hash": + self.delegate = SwigHashPrinter(typename, val) + self.has_children = True + elif val_typestr == "List": + self.delegate = SwigListPrinter(typename, val) + self.has_children = True + elif val_typestr == "String": + self.delegate = SwigStringPrinter(typename, val) + else: + self.delegate = SwigSimplePrinter(typename, val) + + def display_hint(self): + return self.delegate.display_hint() + + def to_string(self): + return self.delegate.to_string() + + def children(self): + if not self.has_children: + return NopIterator() + + return self.delegate.children() + +class RxPrinter(object): + def __init__(self, name, function): + super(RxPrinter, self).__init__() + self.name = name + self.function = function + self.enabled = True + + def invoke(self, value): + if not self.enabled: + return None + return self.function(self.name, value) + +# A pretty-printer that conforms to the "PrettyPrinter" protocol from +# gdb.printing. It can also be used directly as an old-style printer. +class Printer(object): + def __init__(self, name): + super(Printer, self).__init__() + self.name = name + self.subprinters = [] + self.lookup = {} + self.enabled = True + self.compiled_rx = re.compile('^([a-zA-Z0-9_: *]+)$') + + def add(self, name, function): + if not self.compiled_rx.match(name): + raise ValueError, 'error: "%s" does not match' % name + + printer = RxPrinter(name, function) + self.subprinters.append(printer) + self.lookup[name] = printer + print('Added pretty printer for %s. ' % (name)) + + def __call__(self, val): + typename = str(val.type) + if typename in self.lookup: + ret = self.lookup[typename].invoke(val) + return ret + + # Cannot find a pretty printer. Return None. + return None + +swig_printer = None + +def register_swig_printers(obj): + global swig_printer + + if obj is None: + obj = gdb + + obj.pretty_printers.append(swig_printer) + +def build_swig_printer(): + global swig_printer + + swig_printer = Printer("swig") + swig_printer.add('String *', SwigStringPrinter) + swig_printer.add('const String *', SwigStringPrinter) + swig_printer.add('SwigType *', SwigStringPrinter) + swig_printer.add('Hash *', SwigHashPrinter) + swig_printer.add('const Hash *', SwigHashPrinter) + swig_printer.add('Node *', SwigHashPrinter) + swig_printer.add('const Node *', SwigHashPrinter) + swig_printer.add('Parm *', SwigHashPrinter) + swig_printer.add('const Parm *', SwigHashPrinter) + swig_printer.add('List *', SwigListPrinter) + swig_printer.add('const List *', SwigListPrinter) + swig_printer.add('ParmList *', SwigDelegatingPrinter) + swig_printer.add('const ParmList *', SwigDelegatingPrinter) + swig_printer.add('File *', SwigDelegatingPrinter) + #swig_printer.add('DOH *', SwigDelegatingPrinter) + #swig_printer.add('const DOH *', SwigDelegatingPrinter) + + print_("Loaded swig printers\n"); + +def enableGdbPrintWorkaround(): + global GDB_FLATTENED_CHILDREN_WORKAROUND + GDB_FLATTENED_CHILDREN_WORKAROUND = True + +def setChildrenRecursionLevel(level): + global CHILDREN_MAX_RECURSION_LEVEL + CHILDREN_MAX_RECURSION_LEVEL = level + +build_swig_printer() diff --git a/configure.ac b/configure.ac index f3414969e..1d5d9ace7 100644 --- a/configure.ac +++ b/configure.ac @@ -1087,6 +1087,231 @@ AC_SUBST(JAVALDSHARED) AC_SUBST(JAVACXXSHARED) AC_SUBST(JAVACFLAGS) +#---------------------------------------------------------------- +# Look for JAVASCRIPT +#---------------------------------------------------------------- +AC_ARG_WITH(javascript, AS_HELP_STRING([--without-javascript], [Disable JAVASCRIPT]), [with_javascript="$withval"], [with_javascript=yes]) + +# First, check for "--without-javascript" or "--with-javascript=no". +if test x"${with_javascript}" = xno -o x"${with_alllang}" = xno ; then + AC_MSG_NOTICE([Disabling Javascript]) + JAVASCRIPT= +else + JAVASCRIPT=1 + + #---------------------------------------------------------------- + # General Javascript settings shared by JSC and V8 + #---------------------------------------------------------------- + + case $host in + *-*-cygwin* | *-*-mingw*) + JSLIBRARYPREFIX="" + ;; + *) + JSLIBRARYPREFIX="lib" + ;; + esac + + case $host in + *-*-darwin*) + JSSO=".dylib" + JSLDSHARED='$(CC) -dynamiclib' + JSCXXSHARED='$(CXX) -dynamiclib' + # HACK: didn't manage to get dynamic module loading working with a g++ compiled interpreter + JSINTERPRETERCXX='c++' + JSINTERPRETERLINKFLAGS='-g -Wl,-search_paths_first -Wl,-headerpad_max_install_names' + ;; + *) + JSSO=$SO + JSLDSHARED='$(LDSHARED)' + JSCXXSHARED='$(CXXSHARED)' + JSINTERPRETERCXX='$(CXX)' + JSINTERPRETERLINKFLAGS='-ldl' + ;; + esac + + #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + # Look for Node.js which is the default javascript engine + # without it, the javascript test-suite will be skipped + #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + AC_CHECK_PROGS(NODEJS, node) + + #---------------------------------------------------------------- + # Look for JavascriptCore (Webkit) settings (JSCOREINCDIR, JSCOREDYNAMICLINKING) + #---------------------------------------------------------------- + + # check for include files + AC_MSG_CHECKING(for include file JavaScriptCore/JavaScript.h) + AC_ARG_WITH(jscoreinc, [ --with-jscinc=path Set location of Javascript include directory], [JSCOREINCDIR="$withval"], [JSCOREINCDIR=]) + + if test -z "$JSCOREINCDIR"; then + JSCOREINCDIR="/usr/include/ /usr/local/include/" + + # Add in default directory for JavaScriptCore headers for Linux and MacOSX + case $host in + *-*-linux*) + JSCOREINCDIR="/usr/include/webkit-1.0/ /usr/include/webkitgtk-1.0/ /usr/local/include/webkit-1.0/JavaScriptCore/ $JSCOREINCDIR" + ;; + *-*-darwin*) + JSCOREINCDIR="/System/Library/Frameworks/JavaScriptCore.framework/Headers/ $JSCOREINCDIR" + ;; + *) + ;; + esac + fi + + for d in $JSCOREINCDIR ; do + if test -r "$d/JavaScriptCore/JavaScript.h" || test -r "$d/JavaScript.h" ; then + AC_MSG_RESULT($d) + JSCOREINCDIR=$d + JSCOREINC=-I\"$d\" + break + fi + done + + if test "$JSCOREINC" = "" ; then + AC_MSG_RESULT(not found) + fi + + # check for JavaScriptCore/Webkit libraries + AC_ARG_WITH(jscorelib,[ --with-jsclib =path Set location of the JavaScriptCore/Webkit library directory],[JSCORELIB="-L$withval"], [JSCORELIB=]) + AC_MSG_CHECKING(for JavaScriptCore/Webkit library) + + # look for the library when not provided + if test -z "$JSCORELIB"; then + case $host in + *-*-linux*) + dirs="/usr/lib/ /usr/local/lib/" + for i in $dirs ; do + if test -r $i/libjavascriptcoregtk-1.0.so; then + AC_MSG_RESULT($i) + JSCORELIB="-L$i -ljavascriptcoregtk-1.0" + break + fi + + if test -r $i/libwebkitgtk-1.0.so; then + AC_MSG_RESULT($i) + JSCORELIB="-L$i -lwebkitgtk-1.0" + break + fi + + if test -r $i/libwebkit-1.0.la; then + AC_MSG_RESULT($i) + JSCORELIB="-L$i -lwebkit-1.0" + break + fi + done + + if test -z "$JSCORELIB"; then + AC_MSG_RESULT(not found) + JSCENABLED=0 + else + JSCOREDYNAMICLINKING="$JSCORELIB" + JSCENABLED=1 + fi + ;; + *-*-darwin*) + JSCOREDYNAMICLINKING="-framework JavaScriptCore" + JSCENABLED=1 + ;; + *) + ;; + esac + fi + + #---------------------------------------------------------------- + # Look for V8 settings (JSV8INCDIR, JSV8DYNAMICLINKING) + #---------------------------------------------------------------- + + # check for include files + AC_MSG_CHECKING(for include file v8.h) + AC_ARG_WITH(jsv8inc, [ --with-v8inc=path Set location of Javascript include directory], [JSV8INCDIR="$withval"]) + + # if not include dir is specified we try to find + if test -z "$JSV8INCDIR"; then + # Add in default directory for JavaScriptCore headers for Linux and MacOSX + case $host in + *-*-linux*) + JSV8INCDIR="/usr/include /usr/local/include/ $JSV8INCDIR" + ;; + *-*-darwin*) + JSV8INCDIR="$JSV8INCDIR" + ;; + *) + ;; + esac + fi + + for d in $JSV8INCDIR ; do + if test -r "$d/v8.h" ; then + JSV8INCDIR=$d + JSV8INC=-I\"$d\" + break + fi + done + + if test "$JSV8INC" = "" ; then + AC_MSG_RESULT(not found) + else + AC_MSG_RESULT($JSV8INCDIR) + fi + + # check for V8 library + AC_MSG_CHECKING(for v8 library) + AC_ARG_WITH(jsv8lib,[ --with-v8lib=path Set location of V8 library directory],[JSV8LIBDIR="$withval"], [JSV8LIB=]) + + v8libdirs="$JSV8LIBDIR /usr/lib/ /usr/local/lib/" + for d in $v8libdirs ; do + if test -r $d/libv8.so; then + JSV8LIBDIR=$d + JSV8LIB="-L$d -lv8" + break + fi + done + + if test "$JSV8LIB" = "" ; then + AC_MSG_RESULT(not found) + JSV8ENABLED=0 + else + AC_MSG_RESULT($JSV8LIBDIR) + JSV8ENABLED=1 + fi + + + # linking options + case $host in + *-*-darwin*) + JSV8DYNAMICLINKING="" # TODO: add osx configuration + ;; + *-*-linux*) + JSV8DYNAMICLINKING="$JSV8LIB" + ;; + *) + JSV8DYNAMICLINKING="" + ;; + esac + +fi + +AC_SUBST(JSCFLAGS) +AC_SUBST(JSCXXFLAGS) +AC_SUBST(JSLIBRARYPREFIX) +AC_SUBST(JSSO) +AC_SUBST(JSLDSHARED) +AC_SUBST(JSCXXSHARED) + +AC_SUBST(JSINTERPRETERCXX) +AC_SUBST(JSINTERPRETERLINKFLAGS) + +AC_SUBST(JSCOREINC) +AC_SUBST(JSCOREDYNAMICLINKING) +AC_SUBST(JSV8INC) +AC_SUBST(JSV8DYNAMICLINKING) + +AC_SUBST(JSCENABLED) +AC_SUBST(JSV8ENABLED) + #---------------------------------------------------------------- # Look for gcj #---------------------------------------------------------------- @@ -2238,6 +2463,11 @@ if test -z "$JAVA" || test -z "$JAVAC" || test -z "$JAVAINC" ; then fi AC_SUBST(SKIP_JAVA) +SKIP_JAVASCRIPT= +if test -z "$JAVASCRIPT" || test -z "$NODEJS"; then + SKIP_JAVASCRIPT="1" +fi +AC_SUBST(SKIP_JAVASCRIPT) SKIP_GUILE= if test -z "$GUILE" || test -z "$GUILE_LIBS" ; then @@ -2421,6 +2651,8 @@ AC_CONFIG_FILES([ Examples/test-suite/d/Makefile Examples/test-suite/guile/Makefile Examples/test-suite/java/Makefile + Examples/test-suite/javascript/Makefile + Tools/javascript/Makefile Examples/test-suite/mzscheme/Makefile Examples/test-suite/ocaml/Makefile Examples/test-suite/octave/Makefile diff --git a/swig-v8/swig-v8.xcodeproj/project.pbxproj b/swig-v8/swig-v8.xcodeproj/project.pbxproj new file mode 100644 index 000000000..d6fcad63b --- /dev/null +++ b/swig-v8/swig-v8.xcodeproj/project.pbxproj @@ -0,0 +1,153 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXGroup section */ + A7E4F27918BDF64900ED77C7 = { + isa = PBXGroup; + children = ( + ); + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXLegacyTarget section */ + A7E4F28018BDF64900ED77C7 /* swig-v8 */ = { + isa = PBXLegacyTarget; + buildArgumentsString = "$(ACTION)"; + buildConfigurationList = A7E4F28318BDF64900ED77C7 /* Build configuration list for PBXLegacyTarget "swig-v8" */; + buildPhases = ( + ); + buildToolPath = /usr/bin/make; + dependencies = ( + ); + name = "swig-v8"; + passBuildSettingsInEnvironment = 1; + productName = "swig-v8"; + }; +/* End PBXLegacyTarget section */ + +/* Begin PBXProject section */ + A7E4F27B18BDF64900ED77C7 /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 0450; + ORGANIZATIONNAME = "Oliver Buchtala"; + }; + buildConfigurationList = A7E4F27E18BDF64900ED77C7 /* Build configuration list for PBXProject "swig-v8" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + ); + mainGroup = A7E4F27918BDF64900ED77C7; + projectDirPath = ""; + projectRoot = ""; + targets = ( + A7E4F28018BDF64900ED77C7 /* swig-v8 */, + ); + }; +/* End PBXProject section */ + +/* Begin XCBuildConfiguration section */ + A7E4F28118BDF64900ED77C7 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ARCHS = "$(ARCHS_STANDARD_64_BIT)"; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_ENABLE_OBJC_EXCEPTIONS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_SYMBOLS_PRIVATE_EXTERN = NO; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.8; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + }; + name = Debug; + }; + A7E4F28218BDF64900ED77C7 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ARCHS = "$(ARCHS_STANDARD_64_BIT)"; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_ENABLE_OBJC_EXCEPTIONS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.8; + SDKROOT = macosx; + }; + name = Release; + }; + A7E4F28418BDF64900ED77C7 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + DEBUGGING_SYMBOLS = YES; + GCC_GENERATE_DEBUGGING_SYMBOLS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + OTHER_CFLAGS = ""; + OTHER_LDFLAGS = ""; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + A7E4F28518BDF64900ED77C7 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + OTHER_CFLAGS = ""; + OTHER_LDFLAGS = ""; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + A7E4F27E18BDF64900ED77C7 /* Build configuration list for PBXProject "swig-v8" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A7E4F28118BDF64900ED77C7 /* Debug */, + A7E4F28218BDF64900ED77C7 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A7E4F28318BDF64900ED77C7 /* Build configuration list for PBXLegacyTarget "swig-v8" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A7E4F28418BDF64900ED77C7 /* Debug */, + A7E4F28518BDF64900ED77C7 /* Release */, + ); + defaultConfigurationIsVisible = 0; + }; +/* End XCConfigurationList section */ + }; + rootObject = A7E4F27B18BDF64900ED77C7 /* Project object */; +} From 57491eaa8189205d0bcd77decd90d2097b1341d5 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Thu, 6 Mar 2014 06:29:00 +0100 Subject: [PATCH 0736/1048] Add 'version' target for javascript. --- Examples/Makefile.in | 35 ++++++++++++++++++++++++++++++++++- configure.ac | 18 ++++++------------ 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/Examples/Makefile.in b/Examples/Makefile.in index c06f09f9a..0cbc5f7f1 100644 --- a/Examples/Makefile.in +++ b/Examples/Makefile.in @@ -656,7 +656,40 @@ javascript_run: javascript_custom_interpreter # TODO: make node configurable and detected via ./configure javascript_run_node: - node runme.js + @NODEJS@ runme.js + +# ----------------------------------------------------------------- +# Version display +# ----------------------------------------------------------------- + +ifeq (, $(ENGINE)) +javascript_version: + @ if [ "@NODEJS@" != "" ]; then \ + echo "Node.js: `(@NODEJS@ --version)`"; \ + else \ + echo "Version depends on the interpreter"; \ + fi +endif + +ifeq (node, $(ENGINE)) +javascript_version: + @NODEJS@ --version +endif + +ifeq (jsc, $(ENGINE)) +javascript_version: + @ if [ "@JSCOREVERSION@" != "" ]; then \ + echo "@JSCOREVERSION@"; \ + else \ + echo "Unknown JavascriptCore version."; \ + fi +endif + +ifeq (v8, $(ENGINE)) +javascript_version: + echo "Unknown v8 version." +endif + # ----------------------------------------------------------------- # Cleaning the javascript examples diff --git a/configure.ac b/configure.ac index 1d5d9ace7..9b1d3205d 100644 --- a/configure.ac +++ b/configure.ac @@ -1145,6 +1145,8 @@ else AC_MSG_CHECKING(for include file JavaScriptCore/JavaScript.h) AC_ARG_WITH(jscoreinc, [ --with-jscinc=path Set location of Javascript include directory], [JSCOREINCDIR="$withval"], [JSCOREINCDIR=]) + JSCOREVERSION= + if test -z "$JSCOREINCDIR"; then JSCOREINCDIR="/usr/include/ /usr/local/include/" @@ -1187,18 +1189,7 @@ else if test -r $i/libjavascriptcoregtk-1.0.so; then AC_MSG_RESULT($i) JSCORELIB="-L$i -ljavascriptcoregtk-1.0" - break - fi - - if test -r $i/libwebkitgtk-1.0.so; then - AC_MSG_RESULT($i) - JSCORELIB="-L$i -lwebkitgtk-1.0" - break - fi - - if test -r $i/libwebkit-1.0.la; then - AC_MSG_RESULT($i) - JSCORELIB="-L$i -lwebkit-1.0" + JSCOREVERSION=`pkg-config --modversion javascriptcoregtk-1.0` break fi done @@ -1306,12 +1297,15 @@ AC_SUBST(JSINTERPRETERLINKFLAGS) AC_SUBST(JSCOREINC) AC_SUBST(JSCOREDYNAMICLINKING) +AC_SUBST(JSCOREVERSION) AC_SUBST(JSV8INC) AC_SUBST(JSV8DYNAMICLINKING) AC_SUBST(JSCENABLED) AC_SUBST(JSV8ENABLED) +AC_SUBST(NODEJS) + #---------------------------------------------------------------- # Look for gcj #---------------------------------------------------------------- From b5aa1df72b071183c71a33a92aa785eb5f6e3549 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Thu, 6 Mar 2014 06:30:36 +0100 Subject: [PATCH 0737/1048] Generalized smoke test configuration. --- Examples/test-suite/common.mk | 33 ++++++++++++++++------ Examples/test-suite/javascript/Makefile.in | 13 ++------- 2 files changed, 26 insertions(+), 20 deletions(-) diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 14f13bed8..fff9cd38a 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -97,8 +97,11 @@ CPP_TEST_BROKEN += \ C_TEST_BROKEN += \ tag_no_clash_with_variable +# Note: this allows to override the global list of tests for the purpose of +# smoke testing to foster shorter test-driven development cycles +ifndef SMOKE_TESTS_ONLY + # C++ test cases. (Can be run individually using: make testcase.cpptest) -ifndef SKIP_CPP_CASES CPP_TEST_CASES += \ abstract_access \ abstract_inherit \ @@ -490,7 +493,11 @@ CPP_TEST_CASES += \ voidtest \ wallkw \ wrapmacro -endif + +endif #SMOKE_TESTS_ONLY + + +ifndef SMOKE_TESTS_ONLY # C++11 test cases. CPP11_TEST_CASES = \ @@ -527,8 +534,12 @@ CPP11_TEST_CASES = \ # cpp11_result_of \ # SWIG does not support # cpp11_strongly_typed_enumerations \ # SWIG not quite getting this right yet in all langs +endif # SMOKE_TESTS_ONLY + # Broken C++11 test cases. -CPP11_TEST_BROKEN = +CPP11_TEST_BROKEN = + +ifndef SMOKE_TESTS_ONLY # # Put all the heavy STD/STL cases here, where they can be skipped if needed @@ -554,17 +565,18 @@ CPP_STD_TEST_CASES += \ template_opaque # li_std_list +endif # SMOKE_TESTS_ONLY -ifndef SKIP_CPP_STD_CASES CPP_TEST_CASES += ${CPP_STD_TEST_CASES} -endif ifneq (,$(HAVE_CXX11_COMPILER)) CPP_TEST_CASES += $(CPP11_TEST_CASES) endif + +ifndef SMOKE_TESTS_ONLY + # C test cases. (Can be run individually using: make testcase.ctest) -ifndef SKIP_C_CASES C_TEST_CASES += \ arrays \ bom_utf8 \ @@ -615,10 +627,12 @@ C_TEST_CASES += \ typemap_subst \ union_parameter \ unions -endif + +endif # SMOKE_TESTS_ONLY + +ifndef SMOKE_TESTS_ONLY # Multi-module C++ test cases . (Can be run individually using make testcase.multicpptest) -ifndef SKIP_MULTI_CPP_CASES MULTI_CPP_TEST_CASES += \ clientdata_prop \ imports \ @@ -627,7 +641,8 @@ MULTI_CPP_TEST_CASES += \ mod \ template_typedef_import \ multi_import -endif + +endif # SMOKE_TESTS_ONLY # Custom tests - tests with additional commandline options wallkw.cpptest: SWIGOPT += -Wallkw diff --git a/Examples/test-suite/javascript/Makefile.in b/Examples/test-suite/javascript/Makefile.in index 49652f0bd..259869f98 100755 --- a/Examples/test-suite/javascript/Makefile.in +++ b/Examples/test-suite/javascript/Makefile.in @@ -15,13 +15,7 @@ else JSENGINE=node endif -# Note: the javascript generator is not ready yet for the real game. -# To be able keep the behavior continously tested that is expected to work already -# we have a 'light' version of the test-suite -# This will be removed and replaced by a list of 'BROKEN_TEST_CASES' when -# the number gets smaller (currently we have about 65 broken tests for JSC, and 85 for V8) - -ifneq (,$(SMOKE)) +ifeq (1,$(SMOKE)) C_TEST_CASES = \ preproc \ @@ -64,10 +58,7 @@ CPP_TEST_CASES = \ using2 \ javascript_unicode -SKIP_CPP_CASES = @SKIP_CPP_CASES@ -SKIP_C_CASES = @SKIP_C_CASES@ -SKIP_CPP_STD_CASES = @SKIP_CPP_STD_CASES@ -SKIP_MULTI_CPP_CASES = @SKIP_MULTI_CPP_CASES@ +SMOKE_TESTS_ONLY=1 endif From f9268f223c0af545a2307ab74caf6ad3af5b9791 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Thu, 6 Mar 2014 06:31:23 +0100 Subject: [PATCH 0738/1048] Development version for travis configuration. --- .travis.yml | 55 +++++++++++++++++++++++++++-------------------------- 1 file changed, 28 insertions(+), 27 deletions(-) diff --git a/.travis.yml b/.travis.yml index 58b3e4ca6..cf4ab32cd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -5,38 +5,38 @@ 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 +# - compiler: gcc +# env: SWIGLANG=csharp +# - compiler: gcc +# env: SWIGLANG=go +# - compiler: gcc +# env: SWIGLANG=guile +# - compiler: gcc +# env: SWIGLANG=java +# - compiler: gcc env: SWIGLANG=javascript ENGINE=node - compiler: gcc env: SWIGLANG=javascript ENGINE=jsc - compiler: gcc env: SWIGLANG=javascript ENGINE=v8 - - 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=python PY3=1 VER=3.3 - - compiler: gcc - env: SWIGLANG=ruby - - compiler: gcc - env: SWIGLANG=tcl +# - 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=python PY3=1 VER=3.3 +# - compiler: gcc +# env: SWIGLANG=ruby +# - compiler: gcc +# env: SWIGLANG=tcl allow_failures: # None before_install: @@ -69,3 +69,4 @@ script: branches: only: - master + - devel From c2f22bb2b82be91d217e4c88820d56ab66c77813 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Thu, 6 Mar 2014 06:32:06 +0100 Subject: [PATCH 0739/1048] Fix regression in custom v8 interpreter. Issue showed up with newer v8 version. --- Tools/javascript/v8_shell.cxx | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/Tools/javascript/v8_shell.cxx b/Tools/javascript/v8_shell.cxx index 8a571e0f1..4c6334f2f 100755 --- a/Tools/javascript/v8_shell.cxx +++ b/Tools/javascript/v8_shell.cxx @@ -49,6 +49,8 @@ private: static const char* ToCString(const v8::String::Utf8Value& value); + virtual bool _ExecuteScript(const std::string& source, const std::string& scriptPath); + protected: v8::Persistent context; @@ -61,14 +63,9 @@ protected: #error "implement dll loading" #endif -V8Shell::V8Shell() -{ -} +V8Shell::V8Shell(){} -V8Shell::~V8Shell() { - context.Dispose(); - v8::V8::Dispose(); -} +V8Shell::~V8Shell() {} bool V8Shell::RunScript(const std::string& scriptPath) { @@ -84,7 +81,17 @@ bool V8Shell::RunScript(const std::string& scriptPath) { return false; } context->Enter(); - //v8::Context::Scope context_scope(context); + + bool success = _ExecuteScript(source, scriptPath); + + context->Exit(); + context.Dispose(); + v8::V8::Dispose(); + + return true; +} + +bool V8Shell::_ExecuteScript(const std::string& source, const std::string& scriptPath) { v8::HandleScope scope; // Store a pointer to this shell for later use @@ -99,10 +106,6 @@ bool V8Shell::RunScript(const std::string& scriptPath) { return false; } - context->Exit(); - context.Dispose(); - v8::V8::Dispose(); - return true; } From e6dd12444cf70a31f731521b1b9a8509facd0a19 Mon Sep 17 00:00:00 2001 From: Oliver Buchtala Date: Thu, 6 Mar 2014 07:37:30 +0100 Subject: [PATCH 0740/1048] Fix travis configuration. --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index cf4ab32cd..f186cb396 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,7 +13,7 @@ matrix: # env: SWIGLANG=guile # - compiler: gcc # env: SWIGLANG=java -# - compiler: gcc + - compiler: gcc env: SWIGLANG=javascript ENGINE=node - compiler: gcc env: SWIGLANG=javascript ENGINE=jsc From 3028b16cee672a796ed0fb4226b127e7a8c493c5 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Thu, 6 Mar 2014 15:24:17 +0400 Subject: [PATCH 0741/1048] Partially disabling old names generation for classes with nspace --- Examples/test-suite/lua/nspace_runme.lua | 10 ++++++++- Examples/test-suite/nspace.i | 6 ++++- Source/Modules/lua.cxx | 28 +++++++++++++----------- 3 files changed, 29 insertions(+), 15 deletions(-) diff --git a/Examples/test-suite/lua/nspace_runme.lua b/Examples/test-suite/lua/nspace_runme.lua index 5d55357c0..049d4ff00 100644 --- a/Examples/test-suite/lua/nspace_runme.lua +++ b/Examples/test-suite/lua/nspace_runme.lua @@ -62,6 +62,14 @@ sc = ns.Outer.SomeClass() assert( sc:GetInner1ColorChannel() ~= sc:GetInner2Channel() ) assert( sc:GetInner1Channel() ~= sc:GetInner2Channel() ) +-- Backward compatibility +assert(ns.Outer.Inner1.Diffuse ~= nil) +-- Enums within class within namespace shouldn't have backward compatible name. Same for static methods +assert(ns.Outer.Inner1.Color_Diffuse == nil) +assert(ns.Outer.Inner1.Color_colorStaticMethod == nil) - +-- Enums and static methods of class marked as %nonspace should have backward compatible name +assert(ns.NoNSpacePlease_noNspaceStaticFunc() == 10) +-- assert(ns.NoNSpacePlease_NoNspace1 == 1) +-- assert(ns.NoNSpacePlease.NoNspace2 == 10) diff --git a/Examples/test-suite/nspace.i b/Examples/test-suite/nspace.i index 58c560412..c595322a7 100644 --- a/Examples/test-suite/nspace.i +++ b/Examples/test-suite/nspace.i @@ -67,7 +67,11 @@ namespace Outer { const Outer::Inner2::Color& col2c) {} }; // Color int Color::staticMemberVariable = 0; - class NoNSpacePlease {}; + class NoNSpacePlease { + public: + enum NoNSpaceEnum { NoNspace1 = 1, NoNspace2 = 10 }; + static int noNspaceStaticFunc() { return 10; } + }; } // Inner2 // Derived class diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index 0a5a00515..e0fb2c2a0 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -103,13 +103,11 @@ static int squash_bases = 0; * 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. + * belongs to as well as into the class scope itself. (only for classes without %nspace given) * 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 int v2_compat_names_generation = 1; // This flag can temporaraly disable backward compatible names generation if v2_compatibiliti is enabled static const int default_api_level = 2; /* NEW LANGUAGE NOTE:*********************************************** @@ -1096,7 +1094,8 @@ public: return SWIG_NOWRAP; } - bool make_v2_compatible = v2_compatibility && getCurrentClass() != 0; + bool make_v2_compatible = v2_compatibility && getCurrentClass() != 0 + && v2_compat_names_generation; if (make_v2_compatible) { // Don't do anything for enums in C mode - they are already @@ -1166,15 +1165,9 @@ public: virtual int enumDeclaration(Node *n) { current[STATIC_CONST] = true; current[ENUM_CONST] = true; - // Drop v2_compatibility if NSpace is given - int old_v2_compatibility = v2_compatibility; - if (getNSpace()) { - v2_compatibility = 0; - } int result = Language::enumDeclaration(n); current[STATIC_CONST] = false; current[ENUM_CONST] = false; - v2_compatibility = old_v2_compatibility; return result; } @@ -1322,12 +1315,21 @@ public: Setattr(instance_cls, "lua:class_instance:static_hash", static_cls); Setattr(static_cls, "lua:class_static:instance_hash", instance_cls); + const int v2_compat_names_generation_old = v2_compat_names_generation; + // If class has %nspace enabled, then generation of backward compatible names + // should be disabled + if (getNSpace()) { + v2_compat_names_generation = 0; + } + /* 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) */ // Generate normal wrappers Language::classHandler(n); + v2_compat_names_generation = v2_compat_names_generation_old; + SwigType_add_pointer(t); // Catch all: eg. a class with only static functions and/or variables will not have 'remembered' @@ -1607,7 +1609,7 @@ public: const int result = Language::staticmemberfunctionHandler(n); registerMethod(n); - if (v2_compatibility && result == SWIG_OK) { + if (v2_compatibility && result == SWIG_OK && v2_compat_names_generation) { Swig_require("lua_staticmemberfunctionHandler", n, "*lua:name", NIL); String *lua_name = Getattr(n, "lua:name"); // Although this function uses Swig_name_member, it actually generates the Lua name, @@ -1652,7 +1654,7 @@ public: if (result == SWIG_OK) { // This will add static member variable to the class namespace with name ClassName_VarName - if (v2_compatibility) { + if (v2_compatibility && v2_compat_names_generation) { Swig_save("lua_staticmembervariableHandler", n, "lua:name", NIL); String *lua_name = Getattr(n, "lua:name"); // Although this function uses Swig_name_member, it actually generates the Lua name, From dbf44fc181b880039c20ba8dd3064e3ae7ee0e97 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Thu, 6 Mar 2014 19:42:57 +0000 Subject: [PATCH 0742/1048] Fix std::map and smart pointers. Fixes problem with method overloading when some methods are added by %extend and others are real methods and using template default parameters with smart pointers. This is noticeable as a regression since 2.0.12 when using the default smart pointer handling for some languages when the smart pointer wraps std::map and other STL containers. Fixes SF Bug 1363 --- CHANGES.current | 6 ++ Examples/test-suite/common.mk | 1 + ...smart_pointer_template_defaults_overload.i | 56 +++++++++++++++++++ Source/Modules/allocate.cxx | 4 +- Source/Modules/lang.cxx | 6 +- Source/Swig/cwrap.c | 4 +- 6 files changed, 70 insertions(+), 7 deletions(-) create mode 100644 Examples/test-suite/smart_pointer_template_defaults_overload.i diff --git a/CHANGES.current b/CHANGES.current index 8e388dee5..529680e7c 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,12 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2014-03-06: wsfulton + Fix SF Bug #1363 - Problem with method overloading when some methods are added by %extend + and others are real methods and using template default parameters with smart pointers. + This is noticeable as a regression since 2.0.12 when using the default smart pointer + handling for some languages when the smart pointer wraps std::map and other STL containers. + 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 diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index b9239315a..e5b61d757 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -347,6 +347,7 @@ CPP_TEST_CASES += \ smart_pointer_simple \ smart_pointer_static \ smart_pointer_template_const_overload \ + smart_pointer_template_defaults_overload \ smart_pointer_templatemethods \ smart_pointer_templatevariables \ smart_pointer_typedef \ diff --git a/Examples/test-suite/smart_pointer_template_defaults_overload.i b/Examples/test-suite/smart_pointer_template_defaults_overload.i new file mode 100644 index 000000000..a1f559ae8 --- /dev/null +++ b/Examples/test-suite/smart_pointer_template_defaults_overload.i @@ -0,0 +1,56 @@ +%module smart_pointer_template_defaults_overload + +// SF Bug #1363 +// Problem with method overloading when some methods are added by %extend and others are real methods +// and using template default parameters with smart pointers. + +%warnfilter(SWIGWARN_LANG_OVERLOAD_IGNORED) Wrap::operator->; +%warnfilter(SWIGWARN_LANG_OVERLOAD_SHADOW) Container::rubout; + +%include +%include + +%inline %{ +template +class Wrap { +T *ptr; +public: + Wrap(T *p) : ptr(p) {} + T const* operator->(void) const { return ptr; } + T* operator->(void) { return ptr; } +}; +%} + +%template(StringDoubleMap) std::map; // erase is generated okay +%template(WrappedMap) Wrap< std::map >; // erase wrappers lead to compile error + +// Above only affects some languages depending on how std::map is implemented. +// Below is a cutdown language independent demonstration of the bug + +%extend Container { + void rubout(int, int) {} +} + +%inline %{ +template class Container { +public: + int rubout() { return 0; } + void rubout(T const &element) {} + static Container* factory() { return new Container(); } + static Container* factory(bool b) { return new Container(); } + static void staticstuff(bool) {} +#ifdef SWIG + %extend { + void rubout(bool) {} + } +#endif +}; +%} + +%extend Container { + void rubout(int) {} +} + +%template(ContainerInt) Container; +%template(WrapContainerInt) Wrap< Container >; + diff --git a/Source/Modules/allocate.cxx b/Source/Modules/allocate.cxx index d3384e1ba..d3618634b 100644 --- a/Source/Modules/allocate.cxx +++ b/Source/Modules/allocate.cxx @@ -421,7 +421,7 @@ class Allocate:public Dispatcher { while (cc) { Node *cp = cc; if (classname) { - Setattr(cp, "classname", classname); + Setattr(cp, "extendsmartclassname", classname); } Setattr(cp, "allocate:smartpointeraccess", "1"); /* If constant, we have to be careful */ @@ -827,7 +827,7 @@ Allocate(): } List *methods = smart_pointer_methods(sc, 0, isconst); Setattr(inclass, "allocate:smartpointer", methods); - Setattr(inclass, "allocate:smartpointerbase", base); + Setattr(inclass, "allocate:smartpointerpointeeclassname", Getattr(sc, "name")); } else { /* Hmmm. The return value is not a pointer. If the type is a value or reference. We're going to chase it to see if another operator->() diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 04304744c..a7b088f00 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -1242,8 +1242,8 @@ int Language::memberfunctionHandler(Node *n) { String *fname = Swig_name_member(NSpace, ClassPrefix, symname); if (Extend && SmartPointer) { - if (!Getattr(n, "classname")) { - Setattr(n, "classname", Getattr(CurrentClass, "allocate:smartpointerbase")); + if (!Getattr(n, "extendsmartclassname")) { + Setattr(n, "extendsmartclassname", Getattr(CurrentClass, "allocate:smartpointerpointeeclassname")); } } // Set up the type for the cast to this class for use when wrapping const director (virtual) methods. @@ -1562,7 +1562,7 @@ int Language::membervariableHandler(Node *n) { int Language::staticmembervariableHandler(Node *n) { Swig_require("staticmembervariableHandler", n, "*name", "*sym:name", "*type", "?value", NIL); String *value = Getattr(n, "value"); - String *classname = !SmartPointer ? (isNonVirtualProtectedAccess(n) ? DirectorClassName : ClassName) : Getattr(CurrentClass, "allocate:smartpointerbase"); + String *classname = !SmartPointer ? (isNonVirtualProtectedAccess(n) ? DirectorClassName : ClassName) : Getattr(CurrentClass, "allocate:smartpointerpointeeclassname"); if (!value || !Getattr(n, "hasconsttype")) { String *name = Getattr(n, "name"); diff --git a/Source/Swig/cwrap.c b/Source/Swig/cwrap.c index 04845f3cf..27eef0ef0 100644 --- a/Source/Swig/cwrap.c +++ b/Source/Swig/cwrap.c @@ -941,7 +941,7 @@ int Swig_MethodToFunction(Node *n, const_String_or_char_ptr nspace, String *clas is_smart_pointer_overload = 1; } else if (Swig_storage_isstatic(n)) { - String *cname = Getattr(n, "classname") ? Getattr(n, "classname") : classname; + String *cname = Getattr(n, "extendsmartclassname") ? Getattr(n, "extendsmartclassname") : classname; String *ctname = SwigType_namestr(cname); self = NewStringf("(*(%s const *)this)->", ctname); is_smart_pointer_overload = 1; @@ -1058,7 +1058,7 @@ int Swig_MethodToFunction(Node *n, const_String_or_char_ptr nspace, String *clas String *defaultargs = Getattr(n, "defaultargs"); String *code = Getattr(n, "code"); - String *cname = Getattr(n, "classname") ? Getattr(n, "classname") : classname; + String *cname = Getattr(n, "extendsmartclassname") ? Getattr(n, "extendsmartclassname") : classname; String *membername = Swig_name_member(nspace, cname, name); String *mangled = Swig_name_mangle(membername); int is_smart_pointer = flags & CWRAP_SMART_POINTER; From b31507a657c6c791e35d3845c4b79a7f08f790ae Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 7 Mar 2014 12:32:07 +0000 Subject: [PATCH 0743/1048] Use proxy class for rvalue reference parameters --- Source/Modules/lang.cxx | 1 + 1 file changed, 1 insertion(+) diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index a7b088f00..6873b0875 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -3237,6 +3237,7 @@ Node *Language::classLookup(const SwigType *s) const { (Len(prefix) == 0) || // simple type (pass by value) (Strcmp(prefix, "p.") == 0) || // pointer (Strcmp(prefix, "r.") == 0) || // reference + (Strcmp(prefix, "z.") == 0) || // rvalue reference SwigType_prefix_is_simple_1D_array(prefix); // Simple 1D array (not arrays of pointers/references) // Also accept pointer by const reference, not non-const pointer reference if (!acceptable_prefix && (Strcmp(prefix, "r.p.") == 0)) { From e897733b081d920c893b53dce8b37e937f86cde3 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Fri, 7 Mar 2014 13:15:53 +0000 Subject: [PATCH 0744/1048] Fix missing fragments in Ruby wstring typemaps --- Lib/ruby/rubywstrings.swg | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Lib/ruby/rubywstrings.swg b/Lib/ruby/rubywstrings.swg index bb44fbc6e..b6dd937a5 100644 --- a/Lib/ruby/rubywstrings.swg +++ b/Lib/ruby/rubywstrings.swg @@ -11,7 +11,7 @@ * utility methods for wchar_t strings * ------------------------------------------------------------ */ -%fragment("SWIG_AsWCharPtrAndSize","header",fragment="",fragment="SWIG_pwchar_descriptor") { +%fragment("SWIG_AsWCharPtrAndSize","header",fragment="",fragment="SWIG_pwchar_descriptor",fragment="SWIG_AsCharPtrAndSize") { SWIGINTERN int SWIG_AsWCharPtrAndSize(VALUE obj, wchar_t **cptr, size_t *psize, int *alloc) { @@ -50,7 +50,7 @@ SWIG_AsWCharPtrAndSize(VALUE obj, wchar_t **cptr, size_t *psize, int *alloc) } } -%fragment("SWIG_FromWCharPtrAndSize","header",fragment="",fragment="SWIG_pwchar_descriptor") { +%fragment("SWIG_FromWCharPtrAndSize","header",fragment="",fragment="SWIG_pwchar_descriptor",fragment="SWIG_FromCharPtrAndSize") { SWIGINTERNINLINE VALUE SWIG_FromWCharPtrAndSize(const wchar_t * carray, size_t size) { From 7f45cbd1783e204a49bba0a4ee7e75a15bd8ec5b Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 8 Mar 2014 12:02:08 +0000 Subject: [PATCH 0745/1048] Reorganise broken C++11 testcases --- Examples/test-suite/common.mk | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index e5b61d757..1d8a4f04f 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -493,7 +493,7 @@ CPP_TEST_CASES += \ # C++11 test cases. CPP11_TEST_CASES = \ - cpp11_alternate_function_syntax \ + cpp11_alternate_function_syntax \ cpp11_constexpr \ cpp11_decltype \ cpp11_default_delete \ @@ -517,17 +517,17 @@ CPP11_TEST_CASES = \ cpp11_template_double_brackets \ cpp11_template_explicit \ cpp11_template_typedefs \ - cpp11_uniform_initialization \ + cpp11_uniform_initialization \ cpp11_unrestricted_unions \ cpp11_userdefined_literals \ - cpp11_variadic_templates +# Broken C++11 test cases. +CPP11_TEST_BROKEN = \ # cpp11_hash_tables \ # not fully implemented yet # cpp11_result_of \ # SWIG does not support # cpp11_strongly_typed_enumerations \ # SWIG not quite getting this right yet in all langs +# cpp11_variadic_templates \ # Broken for some languages (such as Java) -# Broken C++11 test cases. -CPP11_TEST_BROKEN = # # Put all the heavy STD/STL cases here, where they can be skipped if needed From 504c2030bb03198281df1597aaee177ae5d68b38 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 8 Mar 2014 12:04:19 +0000 Subject: [PATCH 0746/1048] Change in default behaviour wrapping C++ bool for Python. Only a Python True or False will now work for C++ bool parameters. This fixes overloading bool with other types. --- CHANGES.current | 56 ++++++++++++ Examples/test-suite/common.mk | 1 + Examples/test-suite/overload_bool.i | 19 ++++ .../python/li_std_vector_extra_runme.py | 8 +- .../test-suite/python/overload_bool_runme.py | 55 ++++++++++++ .../test-suite/python/primitive_ref_runme.py | 2 +- .../python/reference_global_vars_runme.py | 8 +- .../test-suite/python/std_containers_runme.py | 2 +- .../test-suite/ruby/overload_bool_runme.rb | 88 +++++++++++++++++++ Lib/python/pyprimtypes.swg | 19 ++++ Lib/python/pytypemaps.swg | 4 +- 11 files changed, 251 insertions(+), 11 deletions(-) create mode 100644 Examples/test-suite/overload_bool.i create mode 100644 Examples/test-suite/python/overload_bool_runme.py create mode 100755 Examples/test-suite/ruby/overload_bool_runme.rb diff --git a/CHANGES.current b/CHANGES.current index 529680e7c..9b0642ef4 100644 --- a/CHANGES.current +++ b/CHANGES.current @@ -5,6 +5,62 @@ See the RELEASENOTES file for a summary of changes in each release. Version 3.0.0 (in progress) ============================ +2014-03-06: wsfulton + [Python] Change in default behaviour wrapping C++ bool. Only a Python True or False + will now work for C++ bool parameters. This fixes overloading bool with other types. + Python 2.3 minimum is now required for wrapping bool. + + When wrapping: + + const char* overloaded(bool value) { return "bool"; } + const char* overloaded(int value) { return "int"; } + + Previous behaviour: + >>> overloaded(False) + 'int' + >>> overloaded(True) + 'int' + >>> overloaded(0) + 'int' + + Now we get the expected behaviour: + >>> overloaded(False) + 'bool' + >>> overloaded(0) + 'int' + + The consequence is when wrapping bool in non-overloaded functions: + + const char* boolfunction(bool value) { return value ? "true" : "false"; } + + The previous behaviour was very Pythonic: + >>> boolfunction("") + 'false' + >>> boolfunction("hi") + 'true' + >>> boolfunction(12.34) + 'true' + >>> boolfunction(0) + 'false' + >>> boolfunction(1) + 'true' + + Now the new behaviour more along the lines of C++ due to stricter type checking. The + above calls result in an exception and need to be explicitly converted into a bool as + follows: + >>> boolfunction(0) + Traceback (most recent call last): + File "", line 1, in + TypeError: in method 'boolfunction', argument 1 of type 'bool' + >>> boolfunction(bool(0)) + 'false' + + The old behaviour can be resurrected by passing the -DSWIG_PYTHON_LEGACY_BOOL command line + parameter when executing SWIG. Typemaps can of course be written to customise the behaviour + for specific parameters. + + *** POTENTIAL INCOMPATIBILITY *** + 2014-03-06: wsfulton Fix SF Bug #1363 - Problem with method overloading when some methods are added by %extend and others are real methods and using template default parameters with smart pointers. diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 1d8a4f04f..4466558fb 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -294,6 +294,7 @@ CPP_TEST_CASES += \ operator_pointer_ref \ operbool \ ordering \ + overload_bool \ overload_copy \ overload_extend \ overload_method \ diff --git a/Examples/test-suite/overload_bool.i b/Examples/test-suite/overload_bool.i new file mode 100644 index 000000000..d48bfc299 --- /dev/null +++ b/Examples/test-suite/overload_bool.i @@ -0,0 +1,19 @@ +%module overload_bool + +%inline %{ +const char* overloaded(bool value) { return "bool"; } +const char* overloaded(int value) { return "int"; } +const char* overloaded(const char *value) { return "string"; } + +const char* boolfunction(bool value) { return value ? "true" : "false"; } +const char* intfunction(int value) { return "int"; } + + +// Const references +const char* overloaded_ref(bool const& value) { return "bool"; } +const char* overloaded_ref(int const& value) { return "int"; } +const char* overloaded_ref(const char *value) { return "string"; } + +const char* boolfunction_ref(bool const& value) { return value ? "true" : "false"; } +const char* intfunction_ref(int const& value) { return "int"; } +%} diff --git a/Examples/test-suite/python/li_std_vector_extra_runme.py b/Examples/test-suite/python/li_std_vector_extra_runme.py index 8900d7298..d24d36cb6 100644 --- a/Examples/test-suite/python/li_std_vector_extra_runme.py +++ b/Examples/test-suite/python/li_std_vector_extra_runme.py @@ -17,10 +17,10 @@ halve_in_place(dv) bv = BoolVector(4) -bv[0]= 1 -bv[1]= 0 -bv[2]= 4 -bv[3]= 0 +bv[0]= bool(1) +bv[1]= bool(0) +bv[2]= bool(4) +bv[3]= bool(0) if bv[0] != bv[2]: raise RuntimeError,"bad std::vector mapping" diff --git a/Examples/test-suite/python/overload_bool_runme.py b/Examples/test-suite/python/overload_bool_runme.py new file mode 100644 index 000000000..ed7d1b5a1 --- /dev/null +++ b/Examples/test-suite/python/overload_bool_runme.py @@ -0,0 +1,55 @@ +import overload_bool + +# Overloading bool, int, string +if overload_bool.overloaded(True) != "bool": + raise RuntimeError("wrong!") +if overload_bool.overloaded(False) != "bool": + raise RuntimeError("wrong!") + +if overload_bool.overloaded(0) != "int": + raise RuntimeError("wrong!") +if overload_bool.overloaded(1) != "int": + raise RuntimeError("wrong!") +if overload_bool.overloaded(2) != "int": + raise RuntimeError("wrong!") + +if overload_bool.overloaded("1234") != "string": + raise RuntimeError("wrong!") + +# Test bool masquerading as int +if overload_bool.intfunction(True) != "int": + raise RuntimeError("wrong!") +if overload_bool.intfunction(False) != "int": + raise RuntimeError("wrong!") + +# Test int masquerading as bool +# Not possible + + +############################################# + +# Overloading bool, int, string +if overload_bool.overloaded_ref(True) != "bool": + raise RuntimeError("wrong!") +if overload_bool.overloaded_ref(False) != "bool": + raise RuntimeError("wrong!") + +if overload_bool.overloaded_ref(0) != "int": + raise RuntimeError("wrong!") +if overload_bool.overloaded_ref(1) != "int": + raise RuntimeError("wrong!") +if overload_bool.overloaded_ref(2) != "int": + raise RuntimeError("wrong!") + +if overload_bool.overloaded_ref("1234") != "string": + raise RuntimeError("wrong!") + +# Test bool masquerading as int +if overload_bool.intfunction_ref(True) != "int": + raise RuntimeError("wrong!") +if overload_bool.intfunction_ref(False) != "int": + raise RuntimeError("wrong!") + +# Test int masquerading as bool +# Not possible + diff --git a/Examples/test-suite/python/primitive_ref_runme.py b/Examples/test-suite/python/primitive_ref_runme.py index 7ce872a62..f3a640389 100644 --- a/Examples/test-suite/python/primitive_ref_runme.py +++ b/Examples/test-suite/python/primitive_ref_runme.py @@ -30,7 +30,7 @@ if ref_float(3.5) != 3.5: if ref_double(3.5) != 3.5: raise RuntimeError -if ref_bool(1) != 1: +if ref_bool(True) != True: raise RuntimeError if ref_char('x') != 'x': diff --git a/Examples/test-suite/python/reference_global_vars_runme.py b/Examples/test-suite/python/reference_global_vars_runme.py index aa42ff50b..98aaec5fe 100644 --- a/Examples/test-suite/python/reference_global_vars_runme.py +++ b/Examples/test-suite/python/reference_global_vars_runme.py @@ -5,12 +5,12 @@ if getconstTC().num != 33: raise RuntimeError # primitive reference variables -cvar.var_bool = createref_bool(0) -if value_bool(cvar.var_bool) != 0: +cvar.var_bool = createref_bool(False) +if value_bool(cvar.var_bool) != False: raise RuntimeError -cvar.var_bool = createref_bool(1) -if value_bool(cvar.var_bool) != 1: +cvar.var_bool = createref_bool(True) +if value_bool(cvar.var_bool) != True: raise RuntimeError cvar.var_char = createref_char('w') diff --git a/Examples/test-suite/python/std_containers_runme.py b/Examples/test-suite/python/std_containers_runme.py index bed59bb29..f90c98405 100644 --- a/Examples/test-suite/python/std_containers_runme.py +++ b/Examples/test-suite/python/std_containers_runme.py @@ -46,7 +46,7 @@ for i in range(0,len(m)): if m[i][j] != im[i][j]: raise RuntimeError, "bad getslice" -m = ((1,0,1),(1,1),(1,1)) +m = ((True,False,True),(True,True),(True,True)) im = std_containers.midentb(m) for i in range(0,len(m)): for j in range(0,len(m[i])): diff --git a/Examples/test-suite/ruby/overload_bool_runme.rb b/Examples/test-suite/ruby/overload_bool_runme.rb new file mode 100755 index 000000000..8b7568e94 --- /dev/null +++ b/Examples/test-suite/ruby/overload_bool_runme.rb @@ -0,0 +1,88 @@ +#!/usr/bin/env ruby +# +# Put description here +# +# +# +# +# + +require 'swig_assert' + +require 'overload_bool' + +include Overload_bool + +# Overloading bool, int, string +if overloaded(true) != "bool" + raise RuntimeError, "wrong!" +end +if overloaded(false) != "bool" + raise RuntimeError, "wrong!" +end + +if overloaded(0) != "int" + raise RuntimeError, "wrong!" +end +if overloaded(1) != "int" + raise RuntimeError, "wrong!" +end +if overloaded(2) != "int" + raise RuntimeError, "wrong!" +end + +if overloaded("1234") != "string" + raise RuntimeError, "wrong!" +end + +# Test bool masquerading as integer +# Not possible + +# Test int masquerading as bool +if boolfunction(0) != "false" + raise RuntimeError, "wrong!" +end +if boolfunction(1) != "true" + raise RuntimeError, "wrong!" +end +if boolfunction(2) != "true" + raise RuntimeError, "wrong!" +end + +############################################# + +# Overloading bool, int, string +if overloaded_ref(true) != "bool" + raise RuntimeError, "wrong!" +end +if overloaded_ref(false) != "bool" + raise RuntimeError, "wrong!" +end + +if overloaded_ref(0) != "int" + raise RuntimeError, "wrong!" +end +if overloaded_ref(1) != "int" + raise RuntimeError, "wrong!" +end +if overloaded_ref(2) != "int" + raise RuntimeError, "wrong!" +end + +if overloaded_ref("1234") != "string" + raise RuntimeError, "wrong!" +end + +# Test bool masquerading as integer +# Not possible + +# Test int masquerading as bool +if boolfunction_ref(0) != "false" + raise RuntimeError, "wrong!" +end +if boolfunction_ref(1) != "true" + raise RuntimeError, "wrong!" +end +if boolfunction_ref(2) != "true" + raise RuntimeError, "wrong!" +end diff --git a/Lib/python/pyprimtypes.swg b/Lib/python/pyprimtypes.swg index 66ff104a6..30bb64f66 100644 --- a/Lib/python/pyprimtypes.swg +++ b/Lib/python/pyprimtypes.swg @@ -12,6 +12,8 @@ SWIGINTERNINLINE PyObject* } } +#ifdef SWIG_PYTHON_LEGACY_BOOL +// Default prior to SWIG 3.0.0 %fragment(SWIG_AsVal_frag(bool),"header", fragment=SWIG_AsVal_frag(long)) { SWIGINTERN int @@ -24,6 +26,23 @@ SWIG_AsVal_dec(bool)(PyObject *obj, bool *val) return SWIG_OK; } } +#else +%fragment(SWIG_AsVal_frag(bool),"header", + fragment=SWIG_AsVal_frag(long)) { +SWIGINTERN int +SWIG_AsVal_dec(bool)(PyObject *obj, bool *val) +{ + int r; + if (!PyBool_Check(obj)) + return SWIG_ERROR; + r = PyObject_IsTrue(obj); + if (r == -1) + return SWIG_ERROR; + if (val) *val = r ? true : false; + return SWIG_OK; +} +} +#endif /* int */ diff --git a/Lib/python/pytypemaps.swg b/Lib/python/pytypemaps.swg index 5c6abb01e..2341980f2 100644 --- a/Lib/python/pytypemaps.swg +++ b/Lib/python/pytypemaps.swg @@ -5,9 +5,11 @@ /* ------------------------------------------------------------ * Fragment section * ------------------------------------------------------------ */ -/* bool is dangerous in Python, change precedence */ +#ifdef SWIG_PYTHON_LEGACY_BOOL +// Default prior to SWIG 3.0.0 #undef SWIG_TYPECHECK_BOOL %define SWIG_TYPECHECK_BOOL 10000 %enddef +#endif /* Include fundamental fragment definitions */ %include From ddbf439db9e65ec4243fa71f1c036bd7d56f1624 Mon Sep 17 00:00:00 2001 From: Artem Serebriyskiy Date: Wed, 12 Mar 2014 18:00:15 +0400 Subject: [PATCH 0747/1048] Working around some of the SWIG internal issues with enums --- Examples/test-suite/lua/nspace_runme.lua | 8 ++++++-- Examples/test-suite/nspace.i | 2 ++ Source/Modules/lua.cxx | 11 +++++++++++ 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/Examples/test-suite/lua/nspace_runme.lua b/Examples/test-suite/lua/nspace_runme.lua index 049d4ff00..21f88e2af 100644 --- a/Examples/test-suite/lua/nspace_runme.lua +++ b/Examples/test-suite/lua/nspace_runme.lua @@ -70,6 +70,10 @@ assert(ns.Outer.Inner1.Color_colorStaticMethod == nil) -- Enums and static methods of class marked as %nonspace should have backward compatible name assert(ns.NoNSpacePlease_noNspaceStaticFunc() == 10) --- assert(ns.NoNSpacePlease_NoNspace1 == 1) --- assert(ns.NoNSpacePlease.NoNspace2 == 10) +assert(ns.Outer.Inner2.NoNSpacePlease_NoNspace == nil) +-- ReallyNoNSpaceEnum is wrapped into %nonspace and thus handled correctly. +-- NoNSpaceEnum is not (although both of them are in %nonspace-wrapped class) and thus +-- handled rather unexpectedly +assert(ns.NoNSpacePlease_ReallyNoNspace1 == 1) +assert(ns.NoNSpacePlease.ReallyNoNspace2 == 10) diff --git a/Examples/test-suite/nspace.i b/Examples/test-suite/nspace.i index c595322a7..1520b3652 100644 --- a/Examples/test-suite/nspace.i +++ b/Examples/test-suite/nspace.i @@ -10,6 +10,7 @@ SWIG_JAVABODY_PROXY(public, public, SWIGTYPE) %nspace; %nonspace Outer::Inner2::NoNSpacePlease; +%nonspace Outer::Inner2::NoNSpacePlease::ReallyNoNSpaceEnum; %copyctor; %ignore Outer::Inner2::Color::Color(); @@ -70,6 +71,7 @@ namespace Outer { class NoNSpacePlease { public: enum NoNSpaceEnum { NoNspace1 = 1, NoNspace2 = 10 }; + enum ReallyNoNSpaceEnum { ReallyNoNspace1 = 1, ReallyNoNspace2 = 10 }; static int noNspaceStaticFunc() { return 10; } }; } // Inner2 diff --git a/Source/Modules/lua.cxx b/Source/Modules/lua.cxx index e0fb2c2a0..002c6eb3a 100644 --- a/Source/Modules/lua.cxx +++ b/Source/Modules/lua.cxx @@ -1165,9 +1165,20 @@ public: virtual int enumDeclaration(Node *n) { current[STATIC_CONST] = true; current[ENUM_CONST] = true; + // There is some slightly specific behaviour with enums. Basically, + // their NSpace may be tracked separately. The code below tries to work around + // this issue to some degree. + // The idea is the same as in classHandler - to drop old names generation if + // enum is in class in namespace. + const int v2_compat_names_generation_old = v2_compat_names_generation; + if (getNSpace() || + ( Getattr(n, "sym:nspace") != 0 && Len(Getattr(n, "sym:nspace")) > 0 ) ) { + v2_compat_names_generation = 0; + } int result = Language::enumDeclaration(n); current[STATIC_CONST] = false; current[ENUM_CONST] = false; + v2_compat_names_generation = v2_compat_names_generation_old; return result; } From e18044185e152a5f634ecb146312b20baf7b273e Mon Sep 17 00:00:00 2001 From: Vladimir Kalinin Date: Thu, 13 Mar 2014 14:57:17 +0400 Subject: [PATCH 0748/1048] fixes for director class naming when nested classes are used --- Examples/test-suite/common.mk | 1 + .../csharp/nested_directors_runme.cs | 20 +++++++++++ Examples/test-suite/nested_directors.i | 35 +++++++++++++++++++ Source/Modules/csharp.cxx | 20 ----------- Source/Modules/lang.cxx | 10 +++--- Source/Swig/cwrap.c | 26 +++----------- Source/Swig/swig.h | 2 +- 7 files changed, 67 insertions(+), 47 deletions(-) create mode 100644 Examples/test-suite/csharp/nested_directors_runme.cs create mode 100644 Examples/test-suite/nested_directors.i diff --git a/Examples/test-suite/common.mk b/Examples/test-suite/common.mk index 4466558fb..f2a2242b7 100644 --- a/Examples/test-suite/common.mk +++ b/Examples/test-suite/common.mk @@ -284,6 +284,7 @@ CPP_TEST_CASES += \ naturalvar_more \ naturalvar_onoff \ nested_class \ + nested_directors \ nested_comment \ nested_scope \ nested_workaround \ diff --git a/Examples/test-suite/csharp/nested_directors_runme.cs b/Examples/test-suite/csharp/nested_directors_runme.cs new file mode 100644 index 000000000..32a8df953 --- /dev/null +++ b/Examples/test-suite/csharp/nested_directors_runme.cs @@ -0,0 +1,20 @@ +using System; +using nested_directorsNamespace; +#pragma warning disable 219 + +public class CNested : Base.Nest { + public override bool GetValue() {return true;} +} +public class CSub : Sub { + protected override bool GetValue() { return base.GetValue(); } + public bool Test(){ return GetValue(); } +} + +public class runme { + static void Main() { + CNested n = new CNested(); + CSub s = new CSub(); + if (!s.Test()) + throw new Exception("Sub.GetValue"); + } +} diff --git a/Examples/test-suite/nested_directors.i b/Examples/test-suite/nested_directors.i new file mode 100644 index 000000000..a25d85d46 --- /dev/null +++ b/Examples/test-suite/nested_directors.i @@ -0,0 +1,35 @@ +%module(directors="1", allprotected="1") nested_directors + +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Base::Nest; +%warnfilter(SWIGWARN_PARSE_NAMED_NESTED_CLASS) Sub::IListener; + +%feature("director") Base; +%feature("director") Sub; +%feature("director") Base::Nest; + +%inline %{ +namespace NN { +class Base { +public: + virtual ~Base(){} + class Nest { + public: + virtual ~Nest(){} + virtual bool GetValue(){ return false; } + }; +protected: + virtual bool DoNothing() = 0; +}; + +class Sub : public Base { +public: + class IListener { + }; +public: + virtual ~Sub(){} +protected: + void DoSomething(){} + virtual bool GetValue() const { return true; } +}; +} +%} diff --git a/Source/Modules/csharp.cxx b/Source/Modules/csharp.cxx index 4a105aa16..298056b7b 100644 --- a/Source/Modules/csharp.cxx +++ b/Source/Modules/csharp.cxx @@ -203,26 +203,6 @@ public: 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() * ------------------------------------------------------------ */ diff --git a/Source/Modules/lang.cxx b/Source/Modules/lang.cxx index 6873b0875..5ea79f0ab 100644 --- a/Source/Modules/lang.cxx +++ b/Source/Modules/lang.cxx @@ -2373,6 +2373,7 @@ int Language::classDeclaration(Node *n) { String *oldDirectorClassName = DirectorClassName; String *oldNSpace = NSpace; Node *oldCurrentClass = CurrentClass; + int dir = 0; String *kind = Getattr(n, "kind"); String *name = Getattr(n, "name"); @@ -2424,7 +2425,6 @@ int Language::classDeclaration(Node *n) { /* Call classHandler() here */ if (!ImportMode) { - int dir = 0; if (directorsEnabled()) { int ndir = GetFlag(n, "feature:director"); int nndir = GetFlag(n, "feature:nodirector"); @@ -2481,7 +2481,9 @@ int Language::classDeclaration(Node *n) { ClassPrefix = oldClassPrefix; Delete(ClassName); ClassName = oldClassName; - Delete(DirectorClassName); + if (dir) { + Delete(DirectorClassName); + } DirectorClassName = oldDirectorClassName; return SWIG_OK; } @@ -2749,7 +2751,7 @@ int Language::constructorHandler(Node *n) { Setattr(n, "handled_as_constructor", "1"); } - Swig_ConstructorToFunction(n, NSpace, ClassType, none_comparison, director_ctor, CPlusPlus, Getattr(n, "template") ? 0 : Extend); + Swig_ConstructorToFunction(n, NSpace, ClassType, none_comparison, director_ctor, CPlusPlus, Getattr(n, "template") ? 0 : Extend, DirectorClassName); Setattr(n, "sym:name", mrename); functionWrapper(n); Delete(mrename); @@ -2771,7 +2773,7 @@ int Language::copyconstructorHandler(Node *n) { String *director_ctor = get_director_ctor_code(n, director_ctor_code, director_prot_ctor_code, abstracts); - Swig_ConstructorToFunction(n, NSpace, ClassType, none_comparison, director_ctor, CPlusPlus, Getattr(n, "template") ? 0 : Extend); + Swig_ConstructorToFunction(n, NSpace, ClassType, none_comparison, director_ctor, CPlusPlus, Getattr(n, "template") ? 0 : Extend, DirectorClassName); Setattr(n, "sym:name", mrename); functionWrapper(n); Delete(mrename); diff --git a/Source/Swig/cwrap.c b/Source/Swig/cwrap.c index 27eef0ef0..ec0acfa77 100644 --- a/Source/Swig/cwrap.c +++ b/Source/Swig/cwrap.c @@ -1181,23 +1181,14 @@ Node *Swig_directormap(Node *module, String *type) { * This function creates a C wrapper for a C constructor function. * ----------------------------------------------------------------------------- */ -int Swig_ConstructorToFunction(Node *n, const_String_or_char_ptr nspace, String *classname, String *none_comparison, String *director_ctor, int cplus, int flags) { - ParmList *parms; - Parm *prefix_args; +int Swig_ConstructorToFunction(Node *n, const_String_or_char_ptr nspace, String *classname, String *none_comparison, String *director_ctor, int cplus, int flags, String *directorname) { Parm *p; ParmList *directorparms; SwigType *type; - int use_director; - String *directorScope = NewString(nspace); - - Replace(directorScope, NSPACE_SEPARATOR, "_", DOH_REPLACE_ANY); - - use_director = Swig_directorclass(n); - - parms = CopyParmList(nonvoid_parms(Getattr(n, "parms"))); - + int use_director = Swig_directorclass(n); + ParmList *parms = CopyParmList(nonvoid_parms(Getattr(n, "parms"))); /* Prepend the list of prefix_args (if any) */ - prefix_args = Getattr(n, "director:prefix_args"); + Parm *prefix_args = Getattr(n, "director:prefix_args"); if (prefix_args != NIL) { Parm *p2, *p3; @@ -1250,18 +1241,11 @@ int Swig_ConstructorToFunction(Node *n, const_String_or_char_ptr nspace, String if (use_director) { Node *parent = Swig_methodclass(n); int abstract = Getattr(parent, "abstracts") != 0; - String *name = Getattr(parent, "sym:name"); - String *directorname; String *action = NewStringEmpty(); String *tmp_none_comparison = Copy(none_comparison); String *director_call; String *nodirector_call; - if (Len(directorScope) > 0) - directorname = NewStringf("SwigDirector_%s_%s", directorScope, name); - else - directorname = NewStringf("SwigDirector_%s", name); - Replaceall(tmp_none_comparison, "$arg", "arg1"); director_call = Swig_cppconstructor_director_call(directorname, directorparms); @@ -1300,7 +1284,6 @@ int Swig_ConstructorToFunction(Node *n, const_String_or_char_ptr nspace, String Setattr(n, "wrap:action", action); Delete(tmp_none_comparison); Delete(action); - Delete(directorname); } else { String *call = Swig_cppconstructor_call(classname, parms); String *cres = Swig_cresult(type, Swig_cresult_name(), call); @@ -1322,7 +1305,6 @@ int Swig_ConstructorToFunction(Node *n, const_String_or_char_ptr nspace, String if (directorparms != parms) Delete(directorparms); Delete(parms); - Delete(directorScope); return SWIG_OK; } diff --git a/Source/Swig/swig.h b/Source/Swig/swig.h index 95d9189b3..5334a29f0 100644 --- a/Source/Swig/swig.h +++ b/Source/Swig/swig.h @@ -374,7 +374,7 @@ extern int ParmList_is_compactdefargs(ParmList *p); /* --- Transformations --- */ extern int Swig_MethodToFunction(Node *n, const_String_or_char_ptr nspace, String *classname, int flags, SwigType *director_type, int is_director); - extern int Swig_ConstructorToFunction(Node *n, const_String_or_char_ptr nspace, String *classname, String *none_comparison, String *director_ctor, int cplus, int flags); + extern int Swig_ConstructorToFunction(Node *n, const_String_or_char_ptr nspace, String *classname, String *none_comparison, String *director_ctor, int cplus, int flags, String *directorname); extern int Swig_DestructorToFunction(Node *n, const_String_or_char_ptr nspace, String *classname, int cplus, int flags); extern int Swig_MembersetToFunction(Node *n, String *classname, int flags); extern int Swig_MembergetToFunction(Node *n, String *classname, int flags); From 348caba6e5d77d72d6f588f65deed9cfb9988a4f Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Sat, 8 Mar 2014 21:52:38 +0000 Subject: [PATCH 0749/1048] Add note about cplusplusout for nested_struct testcase --- Examples/test-suite/nested_structs.i | 1 + 1 file changed, 1 insertion(+) diff --git a/Examples/test-suite/nested_structs.i b/Examples/test-suite/nested_structs.i index 44ff994ba..f4f7a275a 100644 --- a/Examples/test-suite/nested_structs.i +++ b/Examples/test-suite/nested_structs.i @@ -33,6 +33,7 @@ int getInside1Val(struct Outer *n) { return n->inside1.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). +See cparse_cplusplusout / Swig_cparse_cplusplusout in the Source. */ %inline %{ int nestedByVal(struct Named s); From e186dc13b7a2c31eeea8e4918504ff85b7244765 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 10 Mar 2014 07:07:39 +0000 Subject: [PATCH 0750/1048] C++11 constexpr variables support added --- Doc/Manual/CPlusPlus11.html | 21 ++++++++++---------- Examples/test-suite/cpp11_constexpr.i | 28 ++++++++++++++++++++++++--- Source/CParse/parser.y | 2 +- 3 files changed, 36 insertions(+), 15 deletions(-) diff --git a/Doc/Manual/CPlusPlus11.html b/Doc/Manual/CPlusPlus11.html index 86a042d78..585a70e63 100644 --- a/Doc/Manual/CPlusPlus11.html +++ b/Doc/Manual/CPlusPlus11.html @@ -107,7 +107,7 @@ For example, ignore the move constructor:

        -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: +The plan is to ignore move constructors 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:

        @@ -120,20 +120,19 @@ example.i:18: Warning 503: Can't wrap 'operator =' unless renamed to a valid ide

        7.2.2 Generalized constant expressions

        -

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

        +

        SWIG parses and identifies the keyword constexpr, but cannot fully utilise it. +These C++ compile time constants are usable as runtime constants from the target languages. +Below shows example usage for assigning a C++ compile time constant from a compile time constant function: +

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

        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
        -
        +

        +When either of these is used from a target language, a runtime call is made to obtain the underlying constant. +

        7.2.3 Extern template

        diff --git a/Examples/test-suite/cpp11_constexpr.i b/Examples/test-suite/cpp11_constexpr.i index 95fe5fa2b..412b8132a 100644 --- a/Examples/test-suite/cpp11_constexpr.i +++ b/Examples/test-suite/cpp11_constexpr.i @@ -4,9 +4,31 @@ %module cpp11_constexpr %inline %{ -class TestClass { -public: - constexpr int func() { return 10; } +constexpr int AAA = 10; +constexpr const int BBB = 20; +constexpr int CCC() { return 30; } +constexpr const int DDD() { return 40; } + +constexpr int XXX() { return 10; } +constexpr int YYY = XXX() + 100; + +struct ConstExpressions { + static constexpr const int JJJ = 100; + static constexpr int KKK = 200; + static const int LLL = 300; + constexpr int MMM() { return 400; } + constexpr const int NNN() { return 500; } }; %} +%{ +int Array10[AAA]; +int Array20[BBB]; +int Array30[CCC()]; +int Array40[DDD()]; +int Array100[ConstExpressions::JJJ]; +int Array200[ConstExpressions::KKK]; +int Array300[ConstExpressions::LLL]; +//int Array400[ConstExpressions::MMM()]; +//int Array500[ConstExpressions::NNN()]; +%} diff --git a/Source/CParse/parser.y b/Source/CParse/parser.y index 1bd351560..0ed438e90 100644 --- a/Source/CParse/parser.y +++ b/Source/CParse/parser.y @@ -412,7 +412,7 @@ static void add_symbols(Node *n) { } else { ty = type; } - if (!SwigType_ismutable(ty)) { + if (!SwigType_ismutable(ty) || (storage && Strstr(storage, "constexpr"))) { SetFlag(n,"hasconsttype"); SetFlag(n,"feature:immutable"); } From 3fb973644eaf939ef6100a03d926aafe93a7a7de Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 10 Mar 2014 07:19:16 +0000 Subject: [PATCH 0751/1048] More C++11 doc tweaks --- Doc/Manual/CPlusPlus11.html | 42 +++++++++---------- Examples/test-suite/cpp11_template_explicit.i | 4 ++ 2 files changed, 25 insertions(+), 21 deletions(-) diff --git a/Doc/Manual/CPlusPlus11.html b/Doc/Manual/CPlusPlus11.html index 585a70e63..4317c189e 100644 --- a/Doc/Manual/CPlusPlus11.html +++ b/Doc/Manual/CPlusPlus11.html @@ -137,19 +137,14 @@ When either of these is used from a target language, a runtime call is made to o

        7.2.3 Extern template

        -

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

        - +

        SWIG correctly parses the keywords extern template. +However, this template instantiation suppression in a translation unit has no relevance for SWIG. +SWIG only uses %template for instantiating and wrapping templates.

        -extern template class std::vector<MyClass>; // explicit instantiation
        -
        -...
        -
        -class MyClass {
        -public:
        -  int a;
        -  int b;
        -};
        +template class std::vector<int>; // C++03 explicit instantiation in C++
        +extern template class std::vector<int>; // C++11 explicit instantiation suppression in C++
        +%template(VectorInt) std::vector<int>; // SWIG instantiation
         

        7.2.4 Initializer lists

        @@ -272,7 +267,7 @@ public:

        -Any attempt at passing in values from the target language will be ignored and replaced by {10, 20, 30, 40, 50}. +Any attempt at passing in values from the target language will be ignored and be 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. @@ -468,7 +463,7 @@ struct DerivedStruct : BaseStruct {

        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.

        +

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

        7.2.12 Strongly typed enumerations

        @@ -479,7 +474,8 @@ 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, +This is because the required nested class support in SWIG is new and has not yet been incorporated into the wrapping of these strongly typed enum classes. +This is usually not a problem, however, there may be some name clashes. For example, the following code:

        @@ -521,6 +517,10 @@ class AllColors {
         };
         
        +

        +Expect to see this improved in a future version of SWIG. +

        +

        7.2.13 Double angle brackets

        @@ -541,22 +541,22 @@ For example:

         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; }
        +  //implicit converting constructor
        +  TestClass(U const &val) { t=val.u; }
        +  // explicit constructor
        +  explicit TestClass(V const &val) { t=val.v; }
         
        -        int t;
        +  int t;
         };
         
        diff --git a/Examples/test-suite/cpp11_template_explicit.i b/Examples/test-suite/cpp11_template_explicit.i index 80a30d283..83b16583c 100644 --- a/Examples/test-suite/cpp11_template_explicit.i +++ b/Examples/test-suite/cpp11_template_explicit.i @@ -20,5 +20,9 @@ extern template class std::vector; template class std::vector; extern template class std::vector; + +template class std::vector; +extern template class std::vector; %} +%template(VectorInt) std::vector; From adc3cfeb571f8dd6d072bbab52eebda0bf612656 Mon Sep 17 00:00:00 2001 From: William S Fulton Date: Mon, 10 Mar 2014 18:55:57 +0000 Subject: [PATCH 0752/1048] More C++11 doc and test improvements --- Doc/Manual/CPlusPlus11.html | 32 ++++++++++++++++--- .../cpp11_inheriting_constructors.i | 11 +++++++ 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/Doc/Manual/CPlusPlus11.html b/Doc/Manual/CPlusPlus11.html index 4317c189e..d79c3172e 100644 --- a/Doc/Manual/CPlusPlus11.html +++ b/Doc/Manual/CPlusPlus11.html @@ -138,13 +138,13 @@ When either of these is used from a target language, a runtime call is made to o

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

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

        7.2.4 Initializer lists

        @@ -400,7 +400,8 @@ auto square(float a, float b) -> decltype(a);

        -SWIG is able to handle constructor delegation, such as: +There are three parts to object construction improvement. +The first improvement is constructor delegation such as the following:

        @@ -418,7 +419,13 @@ public:
         

        -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: +where peer constructors can be called. SWIG handles this without any issue. +

        + +

        +The second improvement is constructor inheritance via a using declaration. +This is parsed correctly, but the additional constructors are not currently added to the derived proxy class in the target language. +An example is shown below:

          @@ -135,10 +135,10 @@ be unhappy to see some enterprising folk use this work to add to it.

          -

          17.1 Basics

          +

          18.1 Basics

          -

          17.1.1 Running SWIG

          +

          18.1.1 Running SWIG

          @@ -360,7 +360,7 @@ need to link in the Allegro shared library. The library you create from the C++ wrapper will be what you then load into Allegro CL.

          -

          17.1.2 Command Line Options

          +

          18.1.2 Command Line Options

          @@ -396,7 +396,7 @@ See Section 17.5 Identifier converter functions for more details.

          -

          17.1.3 Inserting user code into generated files

          +

          18.1.3 Inserting user code into generated files

          @@ -436,7 +436,7 @@ Note that the block %{ ... %} is effectively a shortcut for

          -

          17.2 Wrapping Overview

          +

          18.2 Wrapping Overview

          @@ -446,7 +446,7 @@ New users to SWIG are encouraged to read interested in generating an interface to C++.

          -

          17.2.1 Function Wrapping

          +

          18.2.1 Function Wrapping

          @@ -499,7 +499,7 @@ interested in generating an interface to C++.

        -

        17.2.2 Foreign Wrappers

        +

        18.2.2 Foreign Wrappers

        @@ -512,7 +512,7 @@ interested in generating an interface to C++. typemap.

        -

        17.2.3 FFI Wrappers

        +

        18.2.3 FFI Wrappers

        @@ -593,7 +593,7 @@ char *xxx(); ff:def-foreign-call's.

        -

        17.2.4 Non-overloaded Defuns

        +

        18.2.4 Non-overloaded Defuns

        @@ -606,7 +606,7 @@ char *xxx(); this function can be manipulated via the lout typemap.

        -

        17.2.5 Overloaded Defuns

        +

        18.2.5 Overloaded Defuns

        @@ -622,7 +622,7 @@ char *xxx(); can be manipulated via the lout typemap.

        -

        17.2.6 What about constant and variable access?

        +

        18.2.6 What about constant and variable access?

        @@ -635,7 +635,7 @@ char *xxx(); into the foreign module.

        -

        17.2.7 Object Wrapping

        +

        18.2.7 Object Wrapping

        @@ -657,7 +657,7 @@ char *xxx(); foreign function interface.

        -

        17.3 Wrapping Details

        +

        18.3 Wrapping Details

        @@ -665,7 +665,7 @@ char *xxx(); translated into lisp.

        -

        17.3.1 Namespaces

        +

        18.3.1 Namespaces

        @@ -742,7 +742,7 @@ namespace car { function such as (car '(1 2 3).

        -

        17.3.2 Constants

        +

        18.3.2 Constants

        @@ -803,7 +803,7 @@ namespace car { not use the -nocwrap command-line option.

        -

        17.3.3 Variables

        +

        18.3.3 Variables

        @@ -881,7 +881,7 @@ globalvar> (globalvar.nnn::glob_float) -

        17.3.4 Enumerations

        +

        18.3.4 Enumerations

        @@ -957,7 +957,7 @@ EXPORT const int ACL_ENUM___FOO3__SWIG_0 = FOO3; -

        17.3.5 Arrays

        +

        18.3.5 Arrays

        @@ -1105,10 +1105,10 @@ namespace BAR { -

        17.3.6 Classes and Structs and Unions (oh my!)

        +

        18.3.6 Classes and Structs and Unions (oh my!)

        -

        17.3.6.1 CLOS wrapping of

        +

        18.3.6.1 CLOS wrapping of

        @@ -1123,7 +1123,7 @@ namespace BAR { integer values.

        -

        17.3.6.2 CLOS Inheritance

        +

        18.3.6.2 CLOS Inheritance

        @@ -1136,7 +1136,7 @@ namespace BAR { parameter.

        -

        17.3.6.3 Member fields and functions

        +

        18.3.6.3 Member fields and functions

        @@ -1152,7 +1152,7 @@ namespace BAR { the interface does nothing for friend directives,

        -

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

        +

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

        @@ -1170,11 +1170,11 @@ namespace BAR { use the more robust wrapper functions.

        -

        17.3.7 Templates

        +

        18.3.7 Templates

        -

        17.3.7.1 Generating wrapper code for templates

        +

        18.3.7.1 Generating wrapper code for templates

        @@ -1187,7 +1187,7 @@ namespace BAR { directive.

        -

        17.3.7.2 Implicit Template instantiation

        +

        18.3.7.2 Implicit Template instantiation

        @@ -1197,7 +1197,7 @@ namespace BAR { class schema.

        -

        17.3.8 Typedef, Templates, and Synonym Types

        +

        18.3.8 Typedef, Templates, and Synonym Types

        @@ -1277,7 +1277,7 @@ synonym> -

        17.3.8.1 Choosing a primary type

        +

        18.3.8.1 Choosing a primary type

        @@ -1298,7 +1298,7 @@ synonym> -

        17.3.9 Function overloading/Parameter defaulting

        +

        18.3.9 Function overloading/Parameter defaulting

        @@ -1461,7 +1461,7 @@ overload> -

        17.3.10 Operator wrapping and Operator overloading

        +

        18.3.10 Operator wrapping and Operator overloading

        @@ -1607,7 +1607,7 @@ opoverload> -

        17.3.11 Varargs

        +

        18.3.11 Varargs

        @@ -1628,7 +1628,7 @@ opoverload> with other ways such functions can be wrapped.

        -

        17.3.12 C++ Exceptions

        +

        18.3.12 C++ Exceptions

        @@ -1640,7 +1640,7 @@ opoverload> implemented.

        -

        17.3.13 Pass by value, pass by reference

        +

        18.3.13 Pass by value, pass by reference

        @@ -1652,7 +1652,7 @@ opoverload> newly defined types.

        -

        17.4 Typemaps

        +

        18.4 Typemaps

        @@ -1663,7 +1663,7 @@ opoverload> on Typemaps for more information.

        -

        17.4.1 Code Generation in the C++ Wrapper

        +

        18.4.1 Code Generation in the C++ Wrapper

        @@ -1693,7 +1693,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) -

        17.4.1.1 IN Typemap

        +

        18.4.1.1 IN Typemap

        @@ -1728,7 +1728,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) -

        17.4.1.2 OUT Typemap

        +

        18.4.1.2 OUT Typemap

        @@ -1752,7 +1752,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) -

        17.4.1.3 CTYPE Typemap

        +

        18.4.1.3 CTYPE Typemap

        @@ -1784,7 +1784,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) these common typemaps here.

        -

        17.4.2 Code generation in Lisp wrappers

        +

        18.4.2 Code generation in Lisp wrappers

        @@ -1803,7 +1803,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) 16.3.1 Namespaces for details.

        -

        17.4.2.1 LIN Typemap

        +

        18.4.2.1 LIN Typemap

        @@ -1846,7 +1846,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) -

        17.4.2.2 LOUT Typemap

        +

        18.4.2.2 LOUT Typemap

        @@ -1889,7 +1889,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) -

        17.4.2.3 FFITYPE Typemap

        +

        18.4.2.3 FFITYPE Typemap

        @@ -1939,7 +1939,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) -

        17.4.2.4 LISPTYPE Typemap

        +

        18.4.2.4 LISPTYPE Typemap

        @@ -1959,7 +1959,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) -

        17.4.2.5 LISPCLASS Typemap

        +

        18.4.2.5 LISPCLASS Typemap

        @@ -1983,7 +1983,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) -

        17.4.3 Modifying SWIG behavior using typemaps

        +

        18.4.3 Modifying SWIG behavior using typemaps

        @@ -2017,10 +2017,10 @@ return-val wrapper-name(parm0, parm1, ..., parmN) -

        17.5 Identifier Converter functions

        +

        18.5 Identifier Converter functions

        -

        17.5.1 Creating symbols in the lisp environment

        +

        18.5.1 Creating symbols in the lisp environment

        @@ -2041,11 +2041,11 @@ return-val wrapper-name(parm0, parm1, ..., parmN) of arguments.

        -

        17.5.2 Existing identifier-converter functions

        +

        18.5.2 Existing identifier-converter functions

        Two basic identifier routines have been defined. -

        17.5.2.1 identifier-convert-null

        +

        18.5.2.1 identifier-convert-null

        @@ -2054,7 +2054,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) strings, from which a symbol will be created.

        -

        17.5.2.2 identifier-convert-lispify

        +

        18.5.2.2 identifier-convert-lispify

        @@ -2063,7 +2063,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) same symbol transformations.

        -

        17.5.2.3 Default identifier to symbol conversions

        +

        18.5.2.3 Default identifier to symbol conversions

        @@ -2072,7 +2072,7 @@ return-val wrapper-name(parm0, parm1, ..., parmN) default naming conventions.

        -

        17.5.3 Defining your own identifier-converter

        +

        18.5.3 Defining your own identifier-converter

        @@ -2128,7 +2128,7 @@ indicating the number of arguments passed to the routine indicated by this identifier.

        -

        17.5.4 Instructing SWIG to use a particular identifier-converter

        +

        18.5.4 Instructing SWIG to use a particular identifier-converter

        diff --git a/Doc/Manual/Android.html b/Doc/Manual/Android.html index e02271169..e62139797 100644 --- a/Doc/Manual/Android.html +++ b/Doc/Manual/Android.html @@ -5,7 +5,7 @@ -

        18 SWIG and Android

        +

        19 SWIG and Android

          @@ -30,7 +30,7 @@ This chapter describes SWIG's support of Android. -

          18.1 Overview

          +

          19.1 Overview

          @@ -40,10 +40,10 @@ Everything in the Java chapter applies to generating cod This chapter contains a few Android specific notes and examples.

          -

          18.2 Android examples

          +

          19.2 Android examples

          -

          18.2.1 Examples introduction

          +

          19.2.1 Examples introduction

          @@ -76,7 +76,7 @@ $ android list targets The following examples are shipped with SWIG under the Examples/android directory and include a Makefile to build and install each example.

          -

          18.2.2 Simple C example

          +

          19.2.2 Simple C example

          @@ -398,7 +398,7 @@ Run the app again and this time you will see the output pictured below, showing

          Android screenshot of SwigSimple example
          -

          18.2.3 C++ class example

          +

          19.2.3 C++ class example

          @@ -746,7 +746,7 @@ Run the app to see the result of calling the C++ code from Java:

          Android screenshot of SwigClass example
          -

          18.2.4 Other examples

          +

          19.2.4 Other examples

          @@ -758,7 +758,7 @@ Note that the 'extend' example is demonstrates the directors feature. Normally C++ exception handling and the STL is not available by default in the version of g++ shipped with Android, but this example turns these features on as described in the next section.

          -

          18.3 C++ STL

          +

          19.3 C++ STL

          diff --git a/Doc/Manual/Arguments.html b/Doc/Manual/Arguments.html index 1ae9a6d2f..3b7713686 100644 --- a/Doc/Manual/Arguments.html +++ b/Doc/Manual/Arguments.html @@ -6,7 +6,7 @@ -

          9 Argument Handling

          +

          10 Argument Handling

            @@ -42,7 +42,7 @@ return multiple values through the arguments of a function. This chapter describes some of the techniques for doing this.

            -

            9.1 The typemaps.i library

            +

            10.1 The typemaps.i library

            @@ -50,7 +50,7 @@ This section describes the typemaps.i library file--commonly used to change certain properties of argument conversion.

            -

            9.1.1 Introduction

            +

            10.1.1 Introduction

            @@ -194,7 +194,7 @@ else. To clear a typemap, the %clear directive should be used. For e

          -

          9.1.2 Input parameters

          +

          10.1.2 Input parameters

          @@ -247,7 +247,7 @@ When the function is used in the scripting language interpreter, it will work li result = add(3,4)

        -

        9.1.3 Output parameters

        +

        10.1.3 Output parameters

        @@ -314,7 +314,7 @@ iresult, dresult = foo(3.5, 2) -

        9.1.4 Input/Output parameters

        +

        10.1.4 Input/Output parameters

        @@ -379,7 +379,7 @@ rather than directly overwriting the value of the original input object. SWIG. Backwards compatibility is preserved, but deprecated.

        -

        9.1.5 Using different names

        +

        10.1.5 Using different names

        @@ -413,7 +413,7 @@ Typemap declarations are lexically scoped so a typemap takes effect from the poi file or a matching %clear declaration.

        -

        9.2 Applying constraints to input values

        +

        10.2 Applying constraints to input values

        @@ -423,7 +423,7 @@ insure that a value is positive, or that a pointer is non-NULL. This can be accomplished including the constraints.i library file.

        -

        9.2.1 Simple constraint example

        +

        10.2.1 Simple constraint example

        @@ -449,7 +449,7 @@ the arguments violate the constraint condition, a scripting language exception will be raised. As a result, it is possible to catch bad values, prevent mysterious program crashes and so on.

        -

        9.2.2 Constraint methods

        +

        10.2.2 Constraint methods

        @@ -465,7 +465,7 @@ NONNULL Non-NULL pointer (pointers only). -

        9.2.3 Applying constraints to new datatypes

        +

        10.2.3 Applying constraints to new datatypes

        diff --git a/Doc/Manual/CPlusPlus11.html b/Doc/Manual/CPlusPlus11.html index ed2edd630..ce9174254 100644 --- a/Doc/Manual/CPlusPlus11.html +++ b/Doc/Manual/CPlusPlus11.html @@ -23,6 +23,7 @@

      1. Lambda functions and expressions
      2. Alternate function syntax
      3. Object construction improvement +
      4. Explicit overrides and final
      5. Null pointer constant
      6. Strongly typed enumerations
      7. Double angle brackets @@ -36,13 +37,16 @@
      8. Explicitly defaulted functions and deleted functions
      9. Type long long int
      10. Static assertions -
      11. Allow sizeof to work on members of classes without an explicit object +
      12. Allow sizeof to work on members of classes without an explicit object
      13. Exception specifications and noexcept +
      14. Control and query object alignment +
      15. Attributes
      16. Standard library changes
        • Threading facilities -
        • Tuple types and hash tables +
        • Tuple types +
        • Hash tables
        • Regular expressions
        • General-purpose smart pointers
        • Extensible random number facility @@ -86,7 +90,7 @@ for example the typical usage of it in the move constructor and move assignment
           class MyClass {
           ...
          -  std::vector numbers;
          +  std::vector<int> numbers;
           public:
             MyClass(MyClass &&other) : numbers(std::move(other.numbers)) {}
             MyClass & operator=(MyClass &&other) {
          @@ -459,7 +463,8 @@ public:
           };
           
          -

          Explicit overrides and final

          +

          7.2.11 Explicit overrides and final

          +

          The special identifiers final and override can be used on methods and destructors, @@ -482,12 +487,12 @@ struct DerivedStruct : BaseStruct { -

          7.2.11 Null pointer constant

          +

          7.2.12 Null pointer constant

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

          -

          7.2.12 Strongly typed enumerations

          +

          7.2.13 Strongly typed enumerations

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

          @@ -543,7 +548,7 @@ class AllColors { Expect to see this improved in a future version of SWIG.

          -

          7.2.13 Double angle brackets

          +

          7.2.14 Double angle brackets

          SWIG correctly parses the symbols >> as closing the @@ -554,7 +559,7 @@ shift operator >> otherwise.

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

          7.2.14 Explicit conversion operators

          +

          7.2.15 Explicit conversion operators

          SWIG correctly parses the keyword explicit for operators in addition to constructors now. @@ -597,7 +602,7 @@ Conversion operators either with or without explicit need renaming to a them available as a normal proxy method.

          -

          7.2.15 Alias templates

          +

          7.2.16 Alias templates

          @@ -650,7 +655,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.17 Unrestricted unions

          SWIG fully supports any type inside a union even if it does not @@ -676,7 +681,7 @@ union P { } p1; -

          7.2.17 Variadic templates

          +

          7.2.18 Variadic templates

          SWIG supports the variadic templates syntax (inside the <> @@ -711,7 +716,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.19 New string literals

          SWIG supports wide string and Unicode string constants and raw string literals.

          @@ -741,7 +746,7 @@ Note: There is a bug currently where SWIG's preprocessor incorrectly parses an o inside raw string literals.

          -

          7.2.19 User-defined literals

          +

          7.2.20 User-defined literals

          @@ -808,7 +813,7 @@ OutputType var2 = 1234_suffix; OutputType var3 = 3.1416_suffix; -

          7.2.20 Thread-local storage

          +

          7.2.21 Thread-local storage

          SWIG correctly parses the thread_local keyword. For example, variables @@ -828,7 +833,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 Explicitly defaulted functions and deleted functions

          +

          7.2.22 Explicitly defaulted functions and deleted functions

          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. @@ -866,12 +871,12 @@ This is a C++ compile time check and SWIG does not make any attempt to detect if so in this case it is entirely possible to pass an int instead of a double to f from Java, Python etc.

          -

          7.2.22 Type long long int

          +

          7.2.23 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.24 Static assertions

          @@ -886,7 +891,7 @@ struct Check { }; -

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

          +

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

          @@ -907,7 +912,7 @@ const int SIZE = sizeof(A::member); // does not work with C++03. Okay with C++11 8 -

          7.2.25 Exception specifications and noexcept

          +

          7.2.26 Exception specifications and noexcept

          @@ -923,7 +928,8 @@ int noex2(int) noexcept(true); int noex3(int, bool) noexcept(false); -

          Control and query object alignment

          +

          7.2.27 Control and query object alignment

          +

          An alignof operator is used mostly within C++ to return alignment in number of bytes, but could be used to initialize a variable as shown below. @@ -954,7 +960,8 @@ Use the preprocessor to work around this for now: -

          Attributes

          +

          7.2.28 Attributes

          +

          Attributes such as those shown below, are not yet supported and will give a syntax error. @@ -979,26 +986,28 @@ SWIG target languages offer their own threading facilities so there is limited u

          7.3.2 Tuple types

          +

          SWIG does not provide library files for the new tuple types yet. Variadic template support requires further work to provide substantial tuple wrappers.

          -

          7.3.2 Hash tables

          +

          7.3.3 Hash tables

          +

          The new hash tables in the STL are unordered_set, unordered_multiset, unordered_map, unordered_multimap. These are not available in SWIG, but in principle should be easily implemented by adapting the current STL containers.

          -

          7.3.3 Regular expressions

          +

          7.3.4 Regular expressions

          While SWIG could provide wrappers for the new C++11 regular expressions classes, there is little need as the target languages have their own regular expression facilities.

          -

          7.3.4 General-purpose smart pointers

          +

          7.3.5 General-purpose smart pointers

          @@ -1007,12 +1016,12 @@ Please see the shared_ptr smart po There is no special smart pointer handling available for std::weak_ptr and std::unique_ptr yet.

          -

          7.3.5 Extensible random number facility

          +

          7.3.6 Extensible random number facility

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

          -

          7.3.6 Wrapper reference

          +

          7.3.7 Wrapper reference

          @@ -1023,7 +1032,7 @@ Users would need to write their own typemaps if wrapper references are being use

          -

          7.3.7 Polymorphous wrappers for function objects

          +

          7.3.8 Polymorphous wrappers for function objects

          @@ -1054,7 +1063,7 @@ t = Test() b = t(1,2) # invoke C++ function object -

          7.3.8 Type traits for metaprogramming

          +

          7.3.9 Type traits for metaprogramming

          The type_traits functions to support C++ metaprogramming is useful at compile time and is aimed specifically at C++ development:

          @@ -1104,7 +1113,7 @@ Then the appropriate algorithm can be called for the subset of types given by th 2 -

          7.3.9 Uniform method for computing return type of function objects

          +

          7.3.10 Uniform method for computing return type of function objects

          diff --git a/Doc/Manual/CSharp.html b/Doc/Manual/CSharp.html index 6ee33ac68..7f53423fc 100644 --- a/Doc/Manual/CSharp.html +++ b/Doc/Manual/CSharp.html @@ -5,7 +5,7 @@ -

          19 SWIG and C#

          +

          20 SWIG and C#

            @@ -52,7 +52,7 @@ -

            19.1 Introduction

            +

            20.1 Introduction

            @@ -72,13 +72,14 @@ 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 Compatibility

            +

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

            +

            20.2 Differences to the Java module

            @@ -491,7 +492,7 @@ Windows users can also get the examples working using a Cygwin or MinGW environment for automatic configuration of the example makefiles. Any one of the three C# compilers (Portable.NET, Mono or Microsoft) can be detected from within a Cygwin or Mingw environment if installed in your path. -

            19.3 Void pointers

            +

            20.3 Void pointers

            @@ -509,7 +510,7 @@ void * f(void *v);

          -

          19.4 C# Arrays

          +

          20.4 C# Arrays

          @@ -521,7 +522,7 @@ with one of the following three approaches; namely the SWIG C arrays library, P/ pinned arrays.

          -

          19.4.1 The SWIG C arrays library

          +

          20.4.1 The SWIG C arrays library

          @@ -558,7 +559,7 @@ example.print_array(c.cast()); // Pass to C -

          19.4.2 Managed arrays using P/Invoke default array marshalling

          +

          20.4.2 Managed arrays using P/Invoke default array marshalling

          @@ -685,7 +686,7 @@ and intermediary class method -

          19.4.3 Managed arrays using pinning

          +

          20.4.3 Managed arrays using pinning

          @@ -780,7 +781,7 @@ public static extern void myArrayCopy(global::System.IntPtr jarg1, global::Syste -

          19.5 C# Exceptions

          +

          20.5 C# Exceptions

          @@ -877,7 +878,7 @@ set so should only be used when a C# exception is not created.

          -

          19.5.1 C# exception example using "check" typemap

          +

          20.5.1 C# exception example using "check" typemap

          @@ -1059,7 +1060,7 @@ method and C# code does not handle pending exceptions via the canthrow attribute Actually it will issue this warning for any function beginning with SWIG_CSharpSetPendingException.

          -

          19.5.2 C# exception example using %exception

          +

          20.5.2 C# exception example using %exception

          @@ -1124,7 +1125,7 @@ The managed code generated does check for the pending exception as mentioned ear -

          19.5.3 C# exception example using exception specifications

          +

          20.5.3 C# exception example using exception specifications

          @@ -1181,7 +1182,7 @@ SWIGEXPORT void SWIGSTDCALL CSharp_evensonly(int jarg1) { Multiple catch handlers are generated should there be more than one exception specifications declared.

          -

          19.5.4 Custom C# ApplicationException example

          +

          20.5.4 Custom C# ApplicationException example

          @@ -1315,7 +1316,7 @@ try { -

          19.6 C# Directors

          +

          20.6 C# Directors

          @@ -1328,7 +1329,7 @@ The following sections provide information on the C# director implementation and However, the Java directors section should also be read in order to gain more insight into directors.

          -

          19.6.1 Directors example

          +

          20.6.1 Directors example

          @@ -1449,7 +1450,7 @@ CSharpDerived - UIntMethod(123) -

          19.6.2 Directors implementation

          +

          20.6.2 Directors implementation

          @@ -1632,7 +1633,7 @@ void SwigDirector_Base::BaseBoolMethod(Base const &b, bool flag) { -

          19.6.3 Director caveats

          +

          20.6.3 Director caveats

          @@ -1680,7 +1681,7 @@ However, a call from C# to CSharpDefaults.DefaultMethod() will of cours should pass the call on to CSharpDefaults.DefaultMethod(int)using the C++ default value, as shown above.

          -

          19.7 Multiples modules

          +

          20.7 Multiples modules

          @@ -1715,7 +1716,7 @@ the [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrows if you don't want users to easily stumble upon these so called 'internal workings' of the wrappers.

          -

          19.8 C# Typemap examples

          +

          20.8 C# Typemap examples

          This section includes a few examples of typemaps. For more examples, you @@ -1723,7 +1724,7 @@ might look at the files "csharp.swg" and "typemaps.i" in the SWIG library. -

          19.8.1 Memory management when returning references to member variables

          +

          20.8.1 Memory management when returning references to member variables

          @@ -1847,7 +1848,7 @@ public class Bike : global::System.IDisposable { Note the addReference call.

          -

          19.8.2 Memory management for objects passed to the C++ layer

          +

          20.8.2 Memory management for objects passed to the C++ layer

          @@ -1966,7 +1967,7 @@ The 'cscode' typemap simply adds in the specified code into the C# proxy class. -

          19.8.3 Date marshalling using the csin typemap and associated attributes

          +

          20.8.3 Date marshalling using the csin typemap and associated attributes

          @@ -2252,7 +2253,7 @@ public class example { -

          19.8.4 A date example demonstrating marshalling of C# properties

          +

          20.8.4 A date example demonstrating marshalling of C# properties

          @@ -2352,7 +2353,7 @@ Some points to note:

        • The 'csin' typemap has 'pre', 'post' and 'cshin' attributes, and these are all ignored in the property set. The code in these attributes must instead be replicated within the 'csvarin' typemap. The line creating the temp$csinput variable is such an example; it is identical to what is in the 'pre' attribute.
        -

        19.8.5 Date example demonstrating the 'pre' and 'post' typemap attributes for directors

        +

        20.8.5 Date example demonstrating the 'pre' and 'post' typemap attributes for directors

        @@ -2414,7 +2415,7 @@ Pay special attention to the memory management issues, using these attributes.

        -

        19.8.6 Turning wrapped classes into partial classes

        +

        20.8.6 Turning wrapped classes into partial classes

        @@ -2514,7 +2515,7 @@ demonstrating that the class contains methods calling both unmanaged code - The following example is an alternative approach to adding managed code to the generated proxy class.

        -

        19.8.7 Extending proxy classes with additional C# code

        +

        20.8.7 Extending proxy classes with additional C# code

        @@ -2553,7 +2554,7 @@ public class ExtendMe : global::System.IDisposable { -

        19.8.8 Underlying type for enums

        +

        20.8.8 Underlying type for enums

        diff --git a/Doc/Manual/Chicken.html b/Doc/Manual/Chicken.html index 4e43b9b90..82861c31c 100644 --- a/Doc/Manual/Chicken.html +++ b/Doc/Manual/Chicken.html @@ -8,7 +8,7 @@ -

        20 SWIG and Chicken

        +

        21 SWIG and Chicken

          @@ -72,7 +72,7 @@

          -

          20.1 Preliminaries

          +

          21.1 Preliminaries

          @@ -89,7 +89,7 @@ directory for the basic steps to run SWIG CHICKEN.

          -

          20.1.1 Running SWIG in C mode

          +

          21.1.1 Running SWIG in C mode

          @@ -122,7 +122,7 @@ object files and linked into your project.

          -

          20.1.2 Running SWIG in C++ mode

          +

          21.1.2 Running SWIG in C++ mode

          @@ -151,10 +151,10 @@ object files and linked into your project.

          -

          20.2 Code Generation

          +

          21.2 Code Generation

          -

          20.2.1 Naming Conventions

          +

          21.2.1 Naming Conventions

          @@ -170,7 +170,7 @@ %rename SWIG directive in the SWIG interface file.

          -

          20.2.2 Modules

          +

          21.2.2 Modules

          @@ -192,7 +192,7 @@ (uses modulename)) CHICKEN Scheme form.

          -

          20.2.3 Constants and Variables

          +

          21.2.3 Constants and Variables

          @@ -229,7 +229,7 @@ for info on how to apply the %feature.

          -

          20.2.4 Functions

          +

          21.2.4 Functions

          @@ -248,7 +248,7 @@ parameters). The return values can then be accessed with (call-with-values).

          -

          20.2.5 Exceptions

          +

          21.2.5 Exceptions

          The SWIG chicken module has support for exceptions thrown from @@ -290,7 +290,7 @@

        -

        20.3 TinyCLOS

        +

        21.3 TinyCLOS

        @@ -333,7 +333,7 @@

        -

        20.4 Linkage

        +

        21.4 Linkage

        @@ -354,7 +354,7 @@

        -

        20.4.1 Static binary or shared library linked at compile time

        +

        21.4.1 Static binary or shared library linked at compile time

        We can easily use csc to build a static binary.

        @@ -395,7 +395,7 @@ in which case the test script does not need to be linked with example.so. The t be run with csi.

        -

        20.4.2 Building chicken extension libraries

        +

        21.4.2 Building chicken extension libraries

        Building a shared library like in the above section only works if the library @@ -453,7 +453,7 @@ distributed and used by anyone, even if SWIG is not installed.

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

        -

        20.4.3 Linking multiple SWIG modules with TinyCLOS

        +

        21.4.3 Linking multiple SWIG modules with TinyCLOS

        Linking together multiple modules that share type information using the %import @@ -477,7 +477,7 @@ with (declare (uses ...)). To create an extension library or an egg, just create a module_load.scm file that (declare (uses ...)) all the modules.

        -

        20.5 Typemaps

        +

        21.5 Typemaps

        @@ -486,7 +486,7 @@ all the modules.

        Lib/chicken/chicken.swg.

        -

        20.6 Pointers

        +

        21.6 Pointers

        @@ -519,7 +519,7 @@ all the modules.

        type. flags is either zero or SWIG_POINTER_DISOWN (see below).

        -

        20.6.1 Garbage collection

        +

        21.6.1 Garbage collection

        If the owner flag passed to SWIG_NewPointerObj is 1, NewPointerObj will add a @@ -550,7 +550,7 @@ all the modules.

        must be called manually.

        -

        20.7 Unsupported features and known problems

        +

        21.7 Unsupported features and known problems

        -

        20.7.1 TinyCLOS problems with Chicken version <= 1.92

        +

        21.7.1 TinyCLOS problems with Chicken version <= 1.92

        In Chicken versions equal to or below 1.92, TinyCLOS has a limitation such that generic methods do not properly work on methods diff --git a/Doc/Manual/Contents.html b/Doc/Manual/Contents.html index 77280c8bc..de64429cb 100644 --- a/Doc/Manual/Contents.html +++ b/Doc/Manual/Contents.html @@ -262,7 +262,61 @@ -

        7 Preprocessing

        +

        7 SWIG and C++11

        + + + + + +

        8 Preprocessing

        @@ -285,7 +339,7 @@
        -

        8 SWIG library

        +

        9 SWIG library

        @@ -311,6 +365,7 @@
      17. std::vector
      18. STL exceptions
      19. shared_ptr smart pointer +
      20. auto_ptr smart pointer
      21. Utility Libraries
      22. Accessing protected members
      23. Common customization features @@ -987,7 +1046,7 @@ -

        25 SWIG and Common Lisp

        +

        26 SWIG and Common Lisp

        @@ -1010,7 +1069,7 @@
        -

        26 SWIG and Lua

        +

        27 SWIG and Lua

        @@ -1029,8 +1088,11 @@
      24. Functions
      25. Global variables
      26. Constants and enums +
      27. Pointers -
      28. Structures +
      29. Structures
      30. C++ classes
      31. C++ inheritance
      32. Pointers, references, values, and arrays @@ -1041,17 +1103,26 @@
      33. C++ templates
      34. C++ Smart Pointers
      35. C++ Exceptions +
      36. Namespaces + +
      37. Compatibility Note +
      38. Typemaps -
      39. Writing typemaps +
      40. Writing typemaps
      41. Customization of your Bindings @@ -1069,7 +1140,7 @@ -

        27 SWIG and Modula-3

        +

        28 SWIG and Modula-3

        @@ -1107,7 +1178,7 @@
        -

        28 SWIG and MzScheme/Racket

        +

        29 SWIG and MzScheme/Racket

        @@ -1119,7 +1190,7 @@
        -

        29 SWIG and Ocaml

        +

        30 SWIG and Ocaml

        @@ -1170,7 +1241,7 @@
        -

        30 SWIG and Octave

        +

        31 SWIG and Octave

        @@ -1206,7 +1277,7 @@
        -

        31 SWIG and Perl5

        +

        32 SWIG and Perl5

        @@ -1269,11 +1340,20 @@
      42. Modifying the proxy methods
      43. Adding additional Perl code +
      44. Cross language polymorphism + -

        32 SWIG and PHP

        +

        33 SWIG and PHP

        @@ -1313,7 +1393,7 @@
        -

        33 SWIG and Pike

        +

        34 SWIG and Pike

        @@ -1337,7 +1417,7 @@
        -

        34 SWIG and Python

        +

        35 SWIG and Python

        @@ -1437,6 +1517,12 @@
      45. %feature("docstring")
      46. Python Packages +
      47. Python 3 Support
        • Function annotation @@ -1447,7 +1533,7 @@ -

          35 SWIG and R

          +

          36 SWIG and R

          @@ -1463,7 +1549,7 @@
          -

          36 SWIG and Ruby

          +

          37 SWIG and Ruby

          @@ -1597,7 +1683,7 @@
          -

          37 SWIG and Tcl

          +

          38 SWIG and Tcl

          @@ -1663,7 +1749,7 @@
          -

          38 Extending SWIG to support new languages

          +

          39 Extending SWIG to support new languages

          diff --git a/Doc/Manual/Contract.html b/Doc/Manual/Contract.html index de390fba4..35bc874ef 100644 --- a/Doc/Manual/Contract.html +++ b/Doc/Manual/Contract.html @@ -6,7 +6,7 @@ -

          12 Contracts

          +

          13 Contracts

            @@ -38,7 +38,7 @@ When one of the rules is violated by a script, a runtime exception is generated rather than having the program continue to execute.

            -

            12.1 The %contract directive

            +

            13.1 The %contract directive

            @@ -94,7 +94,7 @@ RuntimeError: Contract violation: require: (arg1>=0)

          -

          12.2 %contract and classes

          +

          13.2 %contract and classes

          @@ -173,7 +173,7 @@ specified for the derived class all must hold. In the above example, this means that both the arguments to Spam::bar must be positive.

          -

          12.3 Constant aggregation and %aggregate_check

          +

          13.3 Constant aggregation and %aggregate_check

          @@ -262,7 +262,7 @@ Regrettably, there is no automatic way to perform similar checks with enums valu release.

          -

          12.4 Notes

          +

          13.4 Notes

          diff --git a/Doc/Manual/Customization.html b/Doc/Manual/Customization.html index f420f42d6..a0a89c042 100644 --- a/Doc/Manual/Customization.html +++ b/Doc/Manual/Customization.html @@ -6,7 +6,7 @@ -

          11 Customization Features

          +

          12 Customization Features

            @@ -45,7 +45,7 @@ of exception handling is presented. Then, a more general-purpose customization mechanism known as "features" is described.

            -

            11.1 Exception handling with %exception

            +

            12.1 Exception handling with %exception

            @@ -100,7 +100,7 @@ for exception handling. That directive is deprecated--%exception provides the same functionality, but is substantially more flexible.

            -

            11.1.1 Handling exceptions in C code

            +

            12.1.1 Handling exceptions in C code

            @@ -166,7 +166,7 @@ Each target language has its own approach to creating a runtime error/exception and for Perl it is the croak method shown above.

            -

            11.1.2 Exception handling with longjmp()

            +

            12.1.2 Exception handling with longjmp()

            @@ -240,7 +240,7 @@ Note: This implementation is only intended to illustrate the general idea. To m modify it to handle nested try declarations.

            -

            11.1.3 Handling C++ exceptions

            +

            12.1.3 Handling C++ exceptions

            @@ -275,7 +275,7 @@ class OutOfMemory {};

          -

          11.1.4 Exception handlers for variables

          +

          12.1.4 Exception handlers for variables

          @@ -300,7 +300,7 @@ The %allowexception feature works like any other feature and so can be

          -

          11.1.5 Defining different exception handlers

          +

          12.1.5 Defining different exception handlers

          @@ -437,7 +437,7 @@ declarations. However, it never really worked that well and the new %exception directive is much better.

          -

          11.1.6 Special variables for %exception

          +

          12.1.6 Special variables for %exception

          @@ -540,7 +540,7 @@ Below shows the expansions for the 1st of the overloaded something wrap -

          11.1.7 Using The SWIG exception library

          +

          12.1.7 Using The SWIG exception library

          @@ -595,7 +595,7 @@ SWIG_NullReferenceError The SWIG_exception() function can also be used in typemaps.

          -

          11.2 Object ownership and %newobject

          +

          12.2 Object ownership and %newobject

          @@ -752,7 +752,7 @@ char *strdup(const char *s); The results might not be what you expect.

          -

          11.3 Features and the %feature directive

          +

          12.3 Features and the %feature directive

          @@ -834,7 +834,7 @@ The following are all equivalent: The syntax in the first variation will generate the { } delimiters used whereas the other variations will not.

          -

          11.3.1 Feature attributes

          +

          12.3.1 Feature attributes

          @@ -875,7 +875,7 @@ In the following example, MyExceptionClass is the name of the Java clas Further details can be obtained from the Java exception handling section.

          -

          11.3.2 Feature flags

          +

          12.3.2 Feature flags

          @@ -973,7 +973,7 @@ in the swig.swg Library file. The following shows the alternative synta The concept of clearing features is discussed next.

          -

          11.3.3 Clearing features

          +

          12.3.3 Clearing features

          @@ -1066,7 +1066,7 @@ The three macros below show this for the "except" feature: -

          11.3.4 Features and default arguments

          +

          12.3.4 Features and default arguments

          @@ -1141,7 +1141,7 @@ specifying or not specifying default arguments in a feature is not applicable as in SWIG-1.3.23 when the approach to wrapping methods with default arguments was changed.

          -

          11.3.5 Feature example

          +

          12.3.5 Feature example

          diff --git a/Doc/Manual/D.html b/Doc/Manual/D.html index 43fa69196..47dab50f1 100644 --- a/Doc/Manual/D.html +++ b/Doc/Manual/D.html @@ -6,7 +6,7 @@ -

          21 SWIG and D

          +

          22 SWIG and D

            @@ -41,7 +41,7 @@ -

            21.1 Introduction

            +

            22.1 Introduction

            From the D Programming Language web site: D is a systems programming language. Its focus is on combining the power and high performance of C and C++ with the programmer productivity of modern languages like Ruby and Python. [...] The D language is statically typed and compiles directly to machine code. As such, it is not very surprising that D is able to directly interface with C libraries. Why would a SWIG module for D be needed then in the first place?

            @@ -53,7 +53,7 @@

            To help addressing these issues, the SWIG C# module has been forked to support D. Is has evolved quite a lot since then, but there are still many similarities, so if you do not find what you are looking for on this page, it might be worth having a look at the chapter on C# (and also on Java, since the C# module was in turn forked from it).

            -

            21.2 Command line invocation

            +

            22.2 Command line invocation

            To activate the D module, pass the -d option to SWIG at the command line. The same standard command line switches as with any other language module are available, plus the following D specific ones:

            @@ -83,10 +83,10 @@ -

            21.3 Typemaps

            +

            22.3 Typemaps

            -

            21.3.1 C# <-> D name comparison

            +

            22.3.1 C# <-> D name comparison

            If you already know the SWIG C# module, you might find the following name comparison table useful:

            @@ -112,7 +112,7 @@
          -

          21.3.2 ctype, imtype, dtype

          +

          22.3.2 ctype, imtype, dtype

          Mapping of types between the C/C++ library, the C/C++ library wrapper exposing the C functions, the D wrapper module importing these functions and the D proxy code.

          @@ -120,7 +120,7 @@

          The ctype typemap is used to determine the types to use in the C wrapper functions. The types from the imtype typemap are used in the extern(C) declarations of these functions in the intermediary D module. The dtype typemap contains the D types used in the D proxy module/class.

          -

          21.3.3 in, out, directorin, directorout

          +

          22.3.3 in, out, directorin, directorout

          Used for converting between the types for C/C++ and D when generating the code for the wrapper functions (on the C++ side).

          @@ -130,7 +130,7 @@

          The directorin typemap is used to convert parameters to the type used in the D director callback function, its return value is processed by directorout (see below).

          -

          21.3.4 din, dout, ddirectorin, ddirectorout

          +

          22.3.4 din, dout, ddirectorin, ddirectorout

          Typemaps for code generation in D proxy and type wrapper classes.

          @@ -157,13 +157,13 @@ dtype DClass.method(dtype a) -

          21.3.5 typecheck typemaps

          +

          22.3.5 typecheck typemaps

          Because, unlike many scripting languages supported by SWIG, D does not need any dynamic dispatch helper to access an overloaded function, the purpose of these is merely to issue a warning for overloaded C++ functions that cannot be overloaded in D (as more than one C++ type maps to a single D type).

          -

          21.3.6 Code injection typemaps

          +

          22.3.6 Code injection typemaps

          These typemaps are used for generating the skeleton of proxy classes for C++ types.

          @@ -175,7 +175,7 @@

          dconstructor, ddestructor, ddispose and ddispose_derived are used to generate the class constructor, destructor and dispose() method, respectively. The auxiliary code for handling the pointer to the C++ object is stored in dbody and dbody_derived. You can override them for specific types.

          -

          21.3.7 Special variable macros

          +

          22.3.7 Special variable macros

          The standard SWIG special variables are available for use within typemaps as described in the Typemaps documentation, for example $1, $input, $result etc.

          @@ -295,7 +295,7 @@ $importtype(AnotherInterface) -

          21.4 %features

          +

          22.4 %features

          The D module defines a number of directives which modify the SWIG features set globally or for a specific declaration:

          @@ -325,7 +325,7 @@ struct A { -

          21.5 Pragmas

          +

          22.5 Pragmas

          There are a few SWIG pragmas specific to the D module, which you can use to influence the D code SWIG generates:

          @@ -364,7 +364,7 @@ struct A { -

          21.6 D Exceptions

          +

          22.6 D Exceptions

          Out of the box, C++ exceptions are fundamentally incompatible to their equivalent in the D world and cannot simply be propagated to a calling D method. There is, however, an easy way to solve this problem: Just catch the exception in the C/C++ wrapper layer, pass the contents to D, and make the wrapper code rethrow the exception in the D world.

          @@ -374,7 +374,7 @@ struct A {

          As this feature is implemented in exactly the same way it is for C#, please see the C# documentation for a more detailed explanation.

          -

          21.7 D Directors

          +

          22.7 D Directors

          When the directors feature is activated, SWIG generates extra code on both the C++ and the D side to enable cross-language polymorphism. Essentially, this means that if you subclass a proxy class in D, C++ code can access any overridden virtual methods just as if you created a derived class in C++.

          @@ -383,16 +383,16 @@ struct A {

          -

          21.8 Other features

          +

          22.8 Other features

          -

          21.8.1 Extended namespace support (nspace)

          +

          22.8.1 Extended namespace support (nspace)

          By default, SWIG flattens all C++ namespaces into a single target language namespace, but as for Java and C#, the nspace feature is supported for D. If it is active, C++ namespaces are mapped to D packages/modules. Note, however, that like for the other languages, free variables and functions are not supported yet; currently, they are all allows written to the main proxy D module.

          -

          21.8.2 Native pointer support

          +

          22.8.2 Native pointer support

          Contrary to many of the scripting languages supported by SWIG, D fully supports C-style pointers. The D module thus includes a custom mechanism to wrap C pointers directly as D pointers where applicable, that is, if the type that is pointed to is represented the same in C and D (on the bit-level), dubbed a primitive type below.

          @@ -404,7 +404,7 @@ struct A {

          To determine if a type should be considered primitive, the cprimitive attribute on its dtype attribute is used. For example, the dtype typemap for float has cprimitive="1", so the code from the nativepointer attribute is taken into account e.g. for float ** or the function pointer float (*)(float *).

          -

          21.8.3 Operator overloading

          +

          22.8.3 Operator overloading

          The D module comes with basic operator overloading support for both D1 and D2. There are, however, a few limitations arising from conceptual differences between C++ and D:

          @@ -416,7 +416,7 @@ struct A {

          There are also some cases where the operators can be translated to D, but the differences in the implementation details are big enough that a rather involved scheme would be required for automatic wrapping them, which has not been implemented yet. This affects, for example, the array subscript operator, [], in combination with assignments - while operator [] in C++ simply returns a reference which is then written to, D resorts to a separate opIndexAssign method -, or implicit casting (which was introduced in D2 via alias this). Despite the lack of automatic support, manually handling these cases should be perfectly possible.

          -

          21.8.4 Running the test-suite

          +

          22.8.4 Running the test-suite

          As with any other language, the SWIG test-suite can be built for D using the *-d-test-suite targets of the top-level Makefile. By default, D1 is targeted, to build it with D2, use the optional D_VERSION variable, e.g. make check-d-test-suite D_VERSION=2.

          @@ -424,14 +424,14 @@ struct A {

          Note: If you want to use GDC on Linux or another platform which requires you to link libdl for dynamically loading the shared library, you might have to add -ldl manually to the d_compile target in Examples/Makefile, because GDC does not currently honor the pragma(lib,...) statement.

          -

          21.9 D Typemap examples

          +

          22.9 D Typemap examples

          There are no D-specific typemap examples yet. However, with the above name comparison table, you should be able to get an idea what can be done by looking at the corresponding C# section.

          -

          21.10 Work in progress and planned features

          +

          22.10 Work in progress and planned features

          There are a couple of features which are not implemented yet, but would be very useful and might be added in the near future:

          diff --git a/Doc/Manual/Extending.html b/Doc/Manual/Extending.html index a8c15fe03..5cd89a280 100644 --- a/Doc/Manual/Extending.html +++ b/Doc/Manual/Extending.html @@ -6,7 +6,7 @@ -

          38 Extending SWIG to support new languages

          +

          39 Extending SWIG to support new languages

            @@ -75,7 +75,7 @@ -

            38.1 Introduction

            +

            39.1 Introduction

            @@ -91,7 +91,7 @@ Also, this chapter is not meant to be a hand-holding tutorial. As a starting po you should probably look at one of SWIG's existing modules.

            -

            38.2 Prerequisites

            +

            39.2 Prerequisites

            @@ -121,7 +121,7 @@ obvious, but almost all SWIG directives as well as the low-level generation of wrapper code are driven by C++ datatypes.

            -

            38.3 The Big Picture

            +

            39.3 The Big Picture

            @@ -158,7 +158,7 @@ role in making the system work. For example, both typemaps and declaration anno based on pattern matching and interact heavily with the underlying type system.

            -

            38.4 Execution Model

            +

            39.4 Execution Model

            @@ -203,7 +203,7 @@ latter stage of compilation. The next few sections briefly describe some of these stages.

            -

            38.4.1 Preprocessing

            +

            39.4.1 Preprocessing

            @@ -284,7 +284,7 @@ been expanded as well as everything else that goes into the low-level construction of the wrapper code.

            -

            38.4.2 Parsing

            +

            39.4.2 Parsing

            @@ -385,7 +385,7 @@ returning a foo and taking types a and b as arguments).

            -

            38.4.3 Parse Trees

            +

            39.4.3 Parse Trees

            @@ -640,7 +640,7 @@ $ swig -c++ -python -debug-module 4 example.i

          -

          38.4.4 Attribute namespaces

          +

          39.4.4 Attribute namespaces

          @@ -659,7 +659,7 @@ that matches the name of the target language. For example, python:foo perl:foo.

          -

          38.4.5 Symbol Tables

          +

          39.4.5 Symbol Tables

          @@ -750,7 +750,7 @@ example.i:5. Previous declaration is foo_i(int ) -

          38.4.6 The %feature directive

          +

          39.4.6 The %feature directive

          @@ -806,7 +806,7 @@ For example, the exception code above is simply stored without any modifications.

          -

          38.4.7 Code Generation

          +

          39.4.7 Code Generation

          @@ -928,7 +928,7 @@ public : The role of these functions is described shortly.

          -

          38.4.8 SWIG and XML

          +

          39.4.8 SWIG and XML

          @@ -941,7 +941,7 @@ internal data structures, it may be useful to keep XML in the back of your mind as a model.

          -

          38.5 Primitive Data Structures

          +

          39.5 Primitive Data Structures

          @@ -987,7 +987,7 @@ typedef Hash Typetab; -

          38.5.1 Strings

          +

          39.5.1 Strings

          @@ -1128,7 +1128,7 @@ Returns the number of replacements made (if any). -

          38.5.2 Hashes

          +

          39.5.2 Hashes

          @@ -1205,7 +1205,7 @@ Returns the list of hash table keys. -

          38.5.3 Lists

          +

          39.5.3 Lists

          @@ -1294,7 +1294,7 @@ If t is not a standard object, it is assumed to be a char * and is used to create a String object. -

          38.5.4 Common operations

          +

          39.5.4 Common operations

          The following operations are applicable to all datatypes. @@ -1349,7 +1349,7 @@ objects and report errors. Gets the line number associated with x. -

          38.5.5 Iterating over Lists and Hashes

          +

          39.5.5 Iterating over Lists and Hashes

          To iterate over the elements of a list or a hash table, the following functions are used: @@ -1394,7 +1394,7 @@ for (j = First(j); j.item; j= Next(j)) { -

          38.5.6 I/O

          +

          39.5.6 I/O

          Special I/O functions are used for all internal I/O. These operations @@ -1531,7 +1531,7 @@ Similarly, the preprocessor and parser all operate on string-files. -

          38.6 Navigating and manipulating parse trees

          +

          39.6 Navigating and manipulating parse trees

          Parse trees are built as collections of hash tables. Each node is a hash table in which @@ -1665,7 +1665,7 @@ Deletes a node from the parse tree. Deletion reconnects siblings and properly u the parent so that sibling nodes are unaffected. -

          38.7 Working with attributes

          +

          39.7 Working with attributes

          @@ -1782,7 +1782,7 @@ the attribute is optional. Swig_restore() must always be called after function. -

          38.8 Type system

          +

          39.8 Type system

          @@ -1791,7 +1791,7 @@ pointers, references, and pointers to members. A detailed discussion of type theory is impossible here. However, let's cover the highlights.

          -

          38.8.1 String encoding of types

          +

          39.8.1 String encoding of types

          @@ -1892,7 +1892,7 @@ make the final type, the two parts are just joined together using string concatenation.

          -

          38.8.2 Type construction

          +

          39.8.2 Type construction

          @@ -2061,7 +2061,7 @@ Returns the prefix of a type. For example, if ty is ty is unmodified. -

          38.8.3 Type tests

          +

          39.8.3 Type tests

          @@ -2148,7 +2148,7 @@ Checks if ty is a varargs type. Checks if ty is a templatized type. -

          38.8.4 Typedef and inheritance

          +

          39.8.4 Typedef and inheritance

          @@ -2250,7 +2250,7 @@ Fully reduces ty according to typedef rules. Resulting datatype will consist only of primitive typenames. -

          38.8.5 Lvalues

          +

          39.8.5 Lvalues

          @@ -2287,7 +2287,7 @@ Literal y; // type = 'Literal', ltype='p.char' -

          38.8.6 Output functions

          +

          39.8.6 Output functions

          @@ -2349,7 +2349,7 @@ SWIG, but is most commonly associated with type-descriptor objects that appear in wrappers (e.g., SWIGTYPE_p_double). -

          38.9 Parameters

          +

          39.9 Parameters

          @@ -2448,7 +2448,7 @@ included. Used to emit prototypes. Returns the number of required (non-optional) arguments in p. -

          38.10 Writing a Language Module

          +

          39.10 Writing a Language Module

          @@ -2463,7 +2463,7 @@ describes the creation of a minimal Python module. You should be able to extra this to other languages.

          -

          38.10.1 Execution model

          +

          39.10.1 Execution model

          @@ -2473,7 +2473,7 @@ the parsing of command line options, all aspects of code generation are controll different methods of the Language that must be defined by your module.

          -

          38.10.2 Starting out

          +

          39.10.2 Starting out

          @@ -2581,7 +2581,7 @@ that activates your module. For example, swig -python foo.i. The messages from your new module should appear.

          -

          38.10.3 Command line options

          +

          39.10.3 Command line options

          @@ -2640,7 +2640,7 @@ to mark the option as valid. If you forget to do this, SWIG will terminate wit unrecognized command line option error.

          -

          38.10.4 Configuration and preprocessing

          +

          39.10.4 Configuration and preprocessing

          @@ -2689,7 +2689,7 @@ an implementation file python.cxx and a configuration file python.swg.

          -

          38.10.5 Entry point to code generation

          +

          39.10.5 Entry point to code generation

          @@ -2747,7 +2747,7 @@ int Python::top(Node *n) { -

          38.10.6 Module I/O and wrapper skeleton

          +

          39.10.6 Module I/O and wrapper skeleton

          @@ -2896,7 +2896,7 @@ functionWrapper : void Shape_y_set(Shape *self,double y) -

          38.10.7 Low-level code generators

          +

          39.10.7 Low-level code generators

          @@ -3050,7 +3050,7 @@ but without the typemaps, there is still work to do.

          -

          38.10.8 Configuration files

          +

          39.10.8 Configuration files

          @@ -3194,7 +3194,7 @@ politely displays the ignoring language message. -

          38.10.9 Runtime support

          +

          39.10.9 Runtime support

          @@ -3203,7 +3203,7 @@ Discuss the kinds of functions typically needed for SWIG runtime support (e.g. the SWIG files that implement those functions.

          -

          38.10.10 Standard library files

          +

          39.10.10 Standard library files

          @@ -3222,7 +3222,7 @@ The following are the minimum that are usually supported: Please copy these and modify for any new language.

          -

          38.10.11 User examples

          +

          39.10.11 User examples

          @@ -3251,7 +3251,7 @@ during this process, see the section on .

          -

          38.10.12 Test driven development and the test-suite

          +

          39.10.12 Test driven development and the test-suite

          @@ -3310,7 +3310,7 @@ It is therefore essential that the runtime tests are written in a manner that di but error/exception out with an error message on stderr on failure.

          -

          38.10.12.1 Running the test-suite

          +

          39.10.12.1 Running the test-suite

          @@ -3502,7 +3502,7 @@ It can be run in the same way as the other language test-suites, replacing [lang The test cases used and the way it works is described in Examples/test-suite/errors/Makefile.in.

          -

          38.10.13 Documentation

          +

          39.10.13 Documentation

          @@ -3534,7 +3534,7 @@ Some topics that you'll want to be sure to address include: if available.

        -

        38.10.14 Prerequisites for adding a new language module to the SWIG distribution

        +

        39.10.14 Prerequisites for adding a new language module to the SWIG distribution

        @@ -3591,7 +3591,7 @@ should be added should there be an area not already covered by the existing tests.

        -

        38.10.15 Coding style guidelines

        +

        39.10.15 Coding style guidelines

        @@ -3615,7 +3615,7 @@ The generated C/C++ code should also follow this style as close as possible. How should be avoided as unlike the SWIG developers, users will never have consistent tab settings.

        -

        38.11 Debugging Options

        +

        39.11 Debugging Options

        @@ -3642,7 +3642,7 @@ There are various command line options which can aid debugging a SWIG interface The complete list of command line options for SWIG are available by running swig -help.

        -

        38.12 Guide to parse tree nodes

        +

        39.12 Guide to parse tree nodes

        @@ -4050,7 +4050,7 @@ extern "X" { ... } declaration. -

        38.13 Further Development Information

        +

        39.13 Further Development Information

        diff --git a/Doc/Manual/Go.html b/Doc/Manual/Go.html index 226acaabf..f970b02e8 100644 --- a/Doc/Manual/Go.html +++ b/Doc/Manual/Go.html @@ -5,7 +5,7 @@ -

        22 SWIG and Go

        +

        23 SWIG and Go

          @@ -43,7 +43,7 @@ the Go programming language see golang.org.

          -

          22.1 Overview

          +

          23.1 Overview

          @@ -67,7 +67,7 @@ checking and runtime library are not used with Go. This should be borne in mind when reading the rest of the SWIG documentation.

          -

          22.2 Running SWIG with Go

          +

          23.2 Running SWIG with Go

          @@ -76,7 +76,7 @@ default SWIG will generate code for the gc compilers. To generate code for gccgo, you should also use the -gccgo option.

          -

          22.2.1 Additional Commandline Options

          +

          23.2.1 Additional Commandline Options

          @@ -150,7 +150,7 @@ swig -go -help -

          22.2.2 Go Output Files

          +

          23.2.2 Go Output Files

          When generating Go code, SWIG will generate the following @@ -226,7 +226,7 @@ this: % go tool 6l main.6

        -

        22.3 A tour of basic C/C++ wrapping

        +

        23.3 A tour of basic C/C++ wrapping

        @@ -236,7 +236,7 @@ modifications have to occur. This section briefly covers the essential aspects of this wrapping.

        -

        22.3.1 Go Package Name

        +

        23.3.1 Go Package Name

        @@ -246,7 +246,7 @@ directive. You may override this by using SWIG's -package command line option.

        -

        22.3.2 Go Names

        +

        23.3.2 Go Names

        @@ -278,7 +278,7 @@ followed by that name, and the destructor will be named Delete followed by that name.

        -

        22.3.3 Go Constants

        +

        23.3.3 Go Constants

        @@ -286,7 +286,7 @@ C/C++ constants created via #define or the %constant directive become Go constants, declared with a const declaration. -

        22.3.4 Go Enumerations

        +

        23.3.4 Go Enumerations

        @@ -296,7 +296,7 @@ usual). The values of the enumeration will become variables in Go; code should avoid modifying those variables.

        -

        22.3.5 Go Classes

        +

        23.3.5 Go Classes

        @@ -374,7 +374,7 @@ returns a go interface. If the returned pointer can be null, you can check for this by calling the Swigcptr() method.

        -

        22.3.5.1 Go Class Inheritance

        +

        23.3.5.1 Go Class Inheritance

        @@ -386,7 +386,7 @@ Doing the reverse will require an explicit type assertion, which will be checked dynamically.

        -

        22.3.6 Go Templates

        +

        23.3.6 Go Templates

        @@ -394,7 +394,7 @@ In order to use C++ templates in Go, you must tell SWIG to create wrappers for a particular template instantation. To do this, use the %template directive. -

        22.3.7 Go Director Classes

        +

        23.3.7 Go Director Classes

        @@ -437,7 +437,7 @@ method defined in Go. The Go code may of course call other methods on itself, and those methods may be defined either in Go or in C++.

        -

        22.3.8 Default Go primitive type mappings

        +

        23.3.8 Default Go primitive type mappings

        @@ -544,7 +544,7 @@ that typemap, or add new values, to control how C/C++ types are mapped into Go types.

        -

        22.3.9 Output arguments

        +

        23.3.9 Output arguments

        Because of limitations in the way output arguments are processed in swig, @@ -597,7 +597,7 @@ void f(char *output); -

        22.3.10 Adding additional go code

        +

        23.3.10 Adding additional go code

        Often the APIs generated by swig are not very natural in go, especially if diff --git a/Doc/Manual/Guile.html b/Doc/Manual/Guile.html index 17e3a3fab..4c1126c7f 100644 --- a/Doc/Manual/Guile.html +++ b/Doc/Manual/Guile.html @@ -8,7 +8,7 @@ -

        23 SWIG and Guile

        +

        24 SWIG and Guile

          @@ -47,7 +47,7 @@

          This section details guile-specific support in SWIG. -

          23.1 Supported Guile Versions

          +

          24.1 Supported Guile Versions

          @@ -61,7 +61,7 @@ improved performance. This is currently not tested with swig so your mileage may vary. To be safe set environment variable GUILE_AUTO_COMPILE to 0 when using swig generated guile code. -

          23.2 Meaning of "Module"

          +

          24.2 Meaning of "Module"

          @@ -69,7 +69,7 @@ There are three different concepts of "module" involved, defined separately for SWIG, Guile, and Libtool. To avoid horrible confusion, we explicitly prefix the context, e.g., "guile-module". -

          23.3 Old GH Guile API

          +

          24.3 Old GH Guile API

          Guile 1.8 and older could be interfaced using two different api's, the SCM @@ -80,7 +80,7 @@ or the GH API. The GH interface to guile is deprecated. Read more about why in version of SWIG that can still generate guile GH wrapper code is 2.0.9. Please use that version if you really need the GH wrapper code. -

          23.4 Linkage

          +

          24.4 Linkage

          @@ -88,7 +88,7 @@ Guile support is complicated by a lack of user community cohesiveness, which manifests in multiple shared-library usage conventions. A set of policies implementing a usage convention is called a linkage. -

          23.4.1 Simple Linkage

          +

          24.4.1 Simple Linkage

          @@ -193,7 +193,7 @@ placed between the define-module form and the SWIG_init via a preprocessor define to avoid symbol clashes. For this case, however, passive linkage is available. -

          23.4.2 Passive Linkage

          +

          24.4.2 Passive Linkage

          Passive linkage is just like simple linkage, but it generates an @@ -203,7 +203,7 @@ package name (see below).

          You should use passive linkage rather than simple linkage when you are using multiple modules. -

          23.4.3 Native Guile Module Linkage

          +

          24.4.3 Native Guile Module Linkage

          SWIG can also generate wrapper code that does all the Guile module @@ -244,7 +244,7 @@ Newer Guile versions have a shorthand procedure for this:

        -

        23.4.4 Old Auto-Loading Guile Module Linkage

        +

        24.4.4 Old Auto-Loading Guile Module Linkage

        Guile used to support an autoloading facility for object-code @@ -270,7 +270,7 @@ option, SWIG generates an exported module initialization function with an appropriate name. -

        23.4.5 Hobbit4D Linkage

        +

        24.4.5 Hobbit4D Linkage

        @@ -295,7 +295,7 @@ my/lib/libfoo.so.X.Y.Z and friends. This scheme is still very experimental; the (hobbit4d link) conventions are not well understood.

        -

        23.5 Underscore Folding

        +

        24.5 Underscore Folding

        @@ -307,7 +307,7 @@ complained so far. %rename to specify the Guile name of the wrapped functions and variables (see CHANGES). -

        23.6 Typemaps

        +

        24.6 Typemaps

        @@ -399,7 +399,7 @@ constant will appear as a scheme variable. See Features and the %feature directive for info on how to apply the %feature.

        -

        23.7 Representation of pointers as smobs

        +

        24.7 Representation of pointers as smobs

        @@ -420,7 +420,7 @@ representing the expected pointer type. See also If the Scheme object passed was not a SWIG smob representing a compatible pointer, a wrong-type-arg exception is raised. -

        23.7.1 Smobs

        +

        24.7.1 Smobs

        @@ -439,7 +439,7 @@ structure describing this type. If a generated GOOPS module has been loaded, sm the corresponding GOOPS class.

        -

        23.7.2 Garbage Collection

        +

        24.7.2 Garbage Collection

        Garbage collection is a feature of Guile since version 1.6. As SWIG now requires Guile > 1.8, @@ -453,7 +453,7 @@ is exactly like described in 23.8 Exception Handling +

        24.8 Exception Handling

        @@ -479,7 +479,7 @@ mapping: The default when not specified here is to use "swig-error". See Lib/exception.i for details. -

        23.9 Procedure documentation

        +

        24.9 Procedure documentation

        If invoked with the command-line option -procdoc @@ -514,7 +514,7 @@ like this: typemap argument doc. See Lib/guile/typemaps.i for details. -

        23.10 Procedures with setters

        +

        24.10 Procedures with setters

        For global variables, SWIG creates a single wrapper procedure @@ -542,7 +542,7 @@ struct members, the procedures (struct-member-get pointer) and (struct-member-set pointer value) are not generated. -

        23.11 GOOPS Proxy Classes

        +

        24.11 GOOPS Proxy Classes

        SWIG can also generate classes and generic functions for use with @@ -688,7 +688,7 @@ Notice that <Foo> is used before it is defined. The fix is to just put th %import "foo.h" before the %inline block.

        -

        23.11.1 Naming Issues

        +

        24.11.1 Naming Issues

        As you can see in the example above, there are potential naming conflicts. The default exported @@ -725,7 +725,7 @@ guile-modules. For example,

        (use-modules ((Test) #:renamer (symbol-prefix-proc 'goops:))) -

        23.11.2 Linking

        +

        24.11.2 Linking

        The guile-modules generated above all need to be linked together. GOOPS support requires diff --git a/Doc/Manual/Java.html b/Doc/Manual/Java.html index 3144341e1..fb8e5d694 100644 --- a/Doc/Manual/Java.html +++ b/Doc/Manual/Java.html @@ -5,7 +5,7 @@ -

        24 SWIG and Java

        +

        25 SWIG and Java

      48. Accessing protected members
      49. Common customization features @@ -157,7 +157,7 @@ It covers most SWIG features, but certain low-level details are covered in less

        -

        24.1 Overview

        +

        25.1 Overview

        @@ -192,7 +192,7 @@ Various customisation tips and techniques using SWIG directives are covered. The latter sections cover the advanced techniques of using typemaps for complete control of the wrapping process.

        -

        24.2 Preliminaries

        +

        25.2 Preliminaries

        @@ -212,7 +212,7 @@ This is the commonly used method to load JNI code so your system will more than Android uses Java JNI and also works with SWIG. Please read the Android chapter in conjunction with this one if you are targeting Android.

        -

        24.2.1 Running SWIG

        +

        25.2.1 Running SWIG

        @@ -271,7 +271,7 @@ The following sections have further practical examples and details on how you mi compiling and using the generated files.

        -

        24.2.2 Additional Commandline Options

        +

        25.2.2 Additional Commandline Options

        @@ -308,7 +308,7 @@ swig -java -help Their use will become clearer by the time you have finished reading this section on SWIG and Java.

        -

        24.2.3 Getting the right header files

        +

        25.2.3 Getting the right header files

        @@ -323,7 +323,7 @@ They are usually in directories like this:

        The exact location may vary on your machine, but the above locations are typical.

        -

        24.2.4 Compiling a dynamic module

        +

        25.2.4 Compiling a dynamic module

        @@ -360,7 +360,7 @@ The name of the shared library output file is important. If the name of your SWIG module is "example", the name of the corresponding shared library file should be "libexample.so" (or equivalent depending on your machine, see Dynamic linking problems for more information). The name of the module is specified using the %module directive or -module command line option.

        -

        24.2.5 Using your module

        +

        25.2.5 Using your module

        @@ -395,7 +395,7 @@ $ If it doesn't work have a look at the following section which discusses problems loading the shared library.

        -

        24.2.6 Dynamic linking problems

        +

        25.2.6 Dynamic linking problems

        @@ -482,7 +482,7 @@ The following section also contains some C++ specific linking problems and solut

        -

        24.2.7 Compilation problems and compiling with C++

        +

        25.2.7 Compilation problems and compiling with C++

        @@ -534,7 +534,7 @@ Finally make sure the version of JDK header files matches the version of Java th

        -

        24.2.8 Building on Windows

        +

        25.2.8 Building on Windows

        @@ -543,7 +543,7 @@ You will want to produce a DLL that can be loaded by the Java Virtual Machine. This section covers the process of using SWIG with Microsoft Visual C++ 6 although the procedure may be similar with other compilers. In order for everything to work, you will need to have a JDK installed on your machine in order to read the JNI header files.

        -

        24.2.8.1 Running SWIG from Visual Studio

        +

        25.2.8.1 Running SWIG from Visual Studio

        @@ -582,7 +582,7 @@ To run the native code in the DLL (example.dll), make sure that it is in your pa If the library fails to load have a look at Dynamic linking problems.

        -

        24.2.8.2 Using NMAKE

        +

        25.2.8.2 Using NMAKE

        @@ -641,7 +641,7 @@ Of course you may want to make changes for it to work for C++ by adding in the -

        -

        24.3 A tour of basic C/C++ wrapping

        +

        25.3 A tour of basic C/C++ wrapping

        @@ -651,7 +651,7 @@ variables are wrapped with JavaBean type getters and setters and so forth. This section briefly covers the essential aspects of this wrapping.

        -

        24.3.1 Modules, packages and generated Java classes

        +

        25.3.1 Modules, packages and generated Java classes

        @@ -687,7 +687,7 @@ swig -java -package com.bloggs.swig -outdir com/bloggs/swig example.i SWIG won't create the directory, so make sure it exists beforehand.

        -

        24.3.2 Functions

        +

        25.3.2 Functions

        @@ -721,7 +721,7 @@ System.out.println(example.fact(4)); -

        24.3.3 Global variables

        +

        25.3.3 Global variables

        @@ -808,7 +808,7 @@ extern char *path; // Read-only (due to %immutable) -

        24.3.4 Constants

        +

        25.3.4 Constants

        @@ -948,7 +948,7 @@ Or if you decide this practice isn't so bad and your own class implements ex

        -

        24.3.5 Enumerations

        +

        25.3.5 Enumerations

        @@ -962,7 +962,7 @@ The final two approaches use simple integers for each enum item. Before looking at the various approaches for wrapping named C/C++ enums, anonymous enums are considered.

        -

        24.3.5.1 Anonymous enums

        +

        25.3.5.1 Anonymous enums

        @@ -1025,7 +1025,7 @@ As in the case of constants, you can access them through either the module class

        -

        24.3.5.2 Typesafe enums

        +

        25.3.5.2 Typesafe enums

        @@ -1119,7 +1119,7 @@ When upgrading to JDK 1.5 or later, proper Java enums could be used instead, wit The following section details proper Java enum generation.

        -

        24.3.5.3 Proper Java enums

        +

        25.3.5.3 Proper Java enums

        @@ -1172,7 +1172,7 @@ The additional support methods need not be generated if none of the enum items h Simpler Java enums for enums without initializers section.

        -

        24.3.5.4 Type unsafe enums

        +

        25.3.5.4 Type unsafe enums

        @@ -1220,7 +1220,7 @@ Note that unlike typesafe enums, this approach requires users to mostly use diff Thus the upgrade path to proper enums provided in JDK 1.5 is more painful.

        -

        24.3.5.5 Simple enums

        +

        25.3.5.5 Simple enums

        @@ -1239,7 +1239,7 @@ SWIG-1.3.21 and earlier versions wrapped all enums using this approach. The type unsafe approach is preferable to this one and this simple approach is only included for backwards compatibility with these earlier versions of SWIG.

        -

        24.3.6 Pointers

        +

        25.3.6 Pointers

        @@ -1327,7 +1327,7 @@ C-style cast may return a bogus result whereas as the C++-style cast will return a NULL pointer if the conversion can't be performed.

        -

        24.3.7 Structures

        +

        25.3.7 Structures

        @@ -1495,7 +1495,7 @@ x.setA(3); // Modify x.a - this is the same as b.f.a -

        24.3.8 C++ classes

        +

        25.3.8 C++ classes

        @@ -1558,7 +1558,7 @@ int bar = Spam.getBar(); -

        24.3.9 C++ inheritance

        +

        25.3.9 C++ inheritance

        @@ -1619,7 +1619,7 @@ Note that Java does not support multiple inheritance so any multiple inheritance A warning is given when multiple inheritance is detected and only the first base class is used.

        -

        24.3.10 Pointers, references, arrays and pass by value

        +

        25.3.10 Pointers, references, arrays and pass by value

        @@ -1674,7 +1674,7 @@ to hold the result and a pointer is returned (Java will release this memory when the returned object's finalizer is run by the garbage collector).

        -

        24.3.10.1 Null pointers

        +

        25.3.10.1 Null pointers

        @@ -1698,7 +1698,7 @@ For spam1 and spam4 above the Java null gets translat The converse also occurs, that is, NULL pointers are translated into null Java objects when returned from a C/C++ function.

        -

        24.3.11 C++ overloaded functions

        +

        25.3.11 C++ overloaded functions

        @@ -1813,7 +1813,7 @@ void spam(unsigned short); // Ignored -

        24.3.12 C++ default arguments

        +

        25.3.12 C++ default arguments

        @@ -1856,7 +1856,7 @@ Further details on default arguments and how to restore this approach are given

        -

        24.3.13 C++ namespaces

        +

        25.3.13 C++ namespaces

        @@ -1946,7 +1946,7 @@ If the resulting use of the nspace feature and hence packages results in a proxy you will need to open up the visibility for the pointer constructor and getCPtr method from the default 'protected' to 'public' with the SWIG_JAVABODY_PROXY macro. See Java code typemaps.

        -

        24.3.14 C++ templates

        +

        25.3.14 C++ templates

        @@ -1995,7 +1995,7 @@ Obviously, there is more to template wrapping than shown in this example. More details can be found in the SWIG and C++ chapter.

        -

        24.3.15 C++ Smart Pointers

        +

        25.3.15 C++ Smart Pointers

        @@ -2079,7 +2079,7 @@ Foo f = p.__deref__(); // Returns underlying Foo * -

        24.4 Further details on the generated Java classes

        +

        25.4 Further details on the generated Java classes

        @@ -2094,7 +2094,7 @@ Finally enum classes are covered. First, the crucial intermediary JNI class is considered.

        -

        24.4.1 The intermediary JNI class

        +

        25.4.1 The intermediary JNI class

        @@ -2214,7 +2214,7 @@ If name is the same as modulename then the module class name g from modulename to modulenameModule.

        -

        24.4.1.1 The intermediary JNI class pragmas

        +

        25.4.1.1 The intermediary JNI class pragmas

        @@ -2296,7 +2296,7 @@ For example, let's change the intermediary JNI class access to just the default All the methods in the intermediary JNI class will then not be callable outside of the package as the method modifiers have been changed from public access to default access. This is useful if you want to prevent users calling these low level functions.

        -

        24.4.2 The Java module class

        +

        25.4.2 The Java module class

        @@ -2327,7 +2327,7 @@ example.egg(new Foo()); The primary reason for having the module class wrapping the calls in the intermediary JNI class is to implement static type checking. In this case only a Foo can be passed to the egg function, whereas any long can be passed to the egg function in the intermediary JNI class.

        -

        24.4.2.1 The Java module class pragmas

        +

        25.4.2.1 The Java module class pragmas

        @@ -2378,7 +2378,7 @@ See The intermediary JNI class pragmas secti

        -

        24.4.3 Java proxy classes

        +

        25.4.3 Java proxy classes

        @@ -2454,7 +2454,7 @@ int y = f.spam(5, new Foo()); -

        24.4.3.1 Memory management

        +

        25.4.3.1 Memory management

        @@ -2616,7 +2616,7 @@ and

        -

        24.4.3.2 Inheritance

        +

        25.4.3.2 Inheritance

        @@ -2732,7 +2732,7 @@ However, true cross language polymorphism can be achieved using the 24.4.3.3 Proxy classes and garbage collection +

        25.4.3.3 Proxy classes and garbage collection

        @@ -2815,7 +2815,7 @@ The section on Java typemaps details how to specify See the How to Handle Java Finalization's Memory-Retention Issues article for alternative approaches to managing memory by avoiding finalizers altogether.

        -

        24.4.3.4 The premature garbage collection prevention parameter for proxy class marshalling

        +

        25.4.3.4 The premature garbage collection prevention parameter for proxy class marshalling

        @@ -2937,7 +2937,7 @@ For example: Compatibility note: The generation of this additional parameter did not occur in versions prior to SWIG-1.3.30.

        -

        24.4.3.5 Single threaded applications and thread safety

        +

        25.4.3.5 Single threaded applications and thread safety

        @@ -3025,7 +3025,7 @@ for (int i=0; i<100000; i++) { -

        24.4.4 Type wrapper classes

        +

        25.4.4 Type wrapper classes

        @@ -3112,7 +3112,7 @@ public static void spam(SWIGTYPE_p_int x, SWIGTYPE_p_int y, int z) { ... } -

        24.4.5 Enum classes

        +

        25.4.5 Enum classes

        @@ -3121,7 +3121,7 @@ The Enumerations section discussed these but om The following sub-sections detail the various types of enum classes that can be generated.

        -

        24.4.5.1 Typesafe enum classes

        +

        25.4.5.1 Typesafe enum classes

        @@ -3205,7 +3205,7 @@ The swigValue method is used for marshalling in the other direction. The toString method is overridden so that the enum name is available.

        -

        24.4.5.2 Proper Java enum classes

        +

        25.4.5.2 Proper Java enum classes

        @@ -3283,7 +3283,7 @@ These needn't be generated if the enum being wrapped does not have any initializ Simpler Java enums for enums without initializers section describes how typemaps can be used to achieve this.

        -

        24.4.5.3 Type unsafe enum classes

        +

        25.4.5.3 Type unsafe enum classes

        @@ -3314,7 +3314,7 @@ public final class Beverage { -

        24.5 Cross language polymorphism using directors

        +

        25.5 Cross language polymorphism using directors

        @@ -3336,7 +3336,7 @@ The upshot is that C++ classes can be extended in Java and from C++ these extens Neither C++ code nor Java code needs to know where a particular method is implemented: the combination of proxy classes, director classes, and C wrapper functions transparently takes care of all the cross-language method routing.

        -

        24.5.1 Enabling directors

        +

        25.5.1 Enabling directors

        @@ -3404,7 +3404,7 @@ public: -

        24.5.2 Director classes

        +

        25.5.2 Director classes

        @@ -3431,7 +3431,7 @@ If the correct implementation is in Java, the Java API is used to call the metho

        -

        24.5.3 Overhead and code bloat

        +

        25.5.3 Overhead and code bloat

        @@ -3449,7 +3449,7 @@ This situation can be optimized by selectively enabling director methods (using

        -

        24.5.4 Simple directors example

        +

        25.5.4 Simple directors example

        @@ -3514,7 +3514,7 @@ DirectorDerived::upcall_method() invoked. -

        24.5.5 Director threading issues

        +

        25.5.5 Director threading issues

        @@ -3534,7 +3534,7 @@ Macros can be defined on the commandline when compiling your C++ code, or altern -

        24.5.6 Director performance tuning

        +

        25.5.6 Director performance tuning

        @@ -3555,7 +3555,8 @@ 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

        +

        25.5.7 Java exceptions from directors

        +

        With directors routing method calls to Java, and proxies routing them @@ -3716,6 +3717,7 @@ this potential fate. 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: +

        @@ -3729,7 +3731,6 @@ unexpected exceptions, the default handling can be changed with:
         %}
         
        -

        Alternatively an exception compatible with the existing director method exception specifications can be thrown. Assuming that all @@ -3862,7 +3863,7 @@ See the Exception handling with %exception an section for more on converting C++ exceptions to Java exceptions.

        -

        24.6 Accessing protected members

        +

        25.6 Accessing protected members

        @@ -3958,7 +3959,7 @@ class MyProtectedBase extends ProtectedBase -

        24.7 Common customization features

        +

        25.7 Common customization features

        @@ -3970,7 +3971,7 @@ be awkward. This section describes some common SWIG features that are used to improve the interface to existing C/C++ code.

        -

        24.7.1 C/C++ helper functions

        +

        25.7.1 C/C++ helper functions

        @@ -4036,7 +4037,7 @@ hard to implement. It is possible to improve on this using Java code, typemaps, customization features as covered in later sections, but sometimes helper functions are a quick and easy solution to difficult cases.

        -

        24.7.2 Class extension with %extend

        +

        25.7.2 Class extension with %extend

        @@ -4099,7 +4100,7 @@ Vector(2,3,4) in any way---the extensions only show up in the Java interface.

        -

        24.7.3 Exception handling with %exception and %javaexception

        +

        25.7.3 Exception handling with %exception and %javaexception

        @@ -4258,7 +4259,7 @@ to raise exceptions. See the SWIG Library ch The typemap example Handling C++ exception specifications as Java exceptions provides further exception handling capabilities.

        -

        24.7.4 Method access with %javamethodmodifiers

        +

        25.7.4 Method access with %javamethodmodifiers

        @@ -4284,7 +4285,7 @@ protected static void protect_me() { -

        24.8 Tips and techniques

        +

        25.8 Tips and techniques

        @@ -4294,7 +4295,7 @@ strings and arrays. This chapter discusses the common techniques for solving these problems.

        -

        24.8.1 Input and output parameters using primitive pointers and references

        +

        25.8.1 Input and output parameters using primitive pointers and references

        @@ -4468,7 +4469,7 @@ void foo(Bar *OUTPUT); will not have the intended effect since typemaps.i does not define an OUTPUT rule for Bar.

        -

        24.8.2 Simple pointers

        +

        25.8.2 Simple pointers

        @@ -4534,7 +4535,7 @@ System.out.println("3 + 4 = " + result); See the SWIG Library chapter for further details.

        -

        24.8.3 Wrapping C arrays with Java arrays

        +

        25.8.3 Wrapping C arrays with Java arrays

        @@ -4601,7 +4602,7 @@ Please be aware that the typemaps in this library are not efficient as all the e There is an alternative approach using the SWIG array library and this is covered in the next section.

        -

        24.8.4 Unbounded C Arrays

        +

        25.8.4 Unbounded C Arrays

        @@ -4746,7 +4747,7 @@ well suited for applications in which you need to create buffers, package binary data, etc.

        -

        24.8.5 Binary data vs Strings

        +

        25.8.5 Binary data vs Strings

        @@ -4790,7 +4791,7 @@ len: 5 data: 68 69 0 6a 6b -

        24.8.6 Overriding new and delete to allocate from Java heap

        +

        25.8.6 Overriding new and delete to allocate from Java heap

        @@ -4907,7 +4908,7 @@ model and use these functions in place of malloc and free in your own code.

        -

        24.9 Java typemaps

        +

        25.9 Java typemaps

        @@ -4928,7 +4929,7 @@ Before proceeding, it should be stressed that typemaps are not a required part of using SWIG---the default wrapping behavior is enough in most cases. Typemaps are only used if you want to change some aspect of the generated code. -

        24.9.1 Default primitive type mappings

        +

        25.9.1 Default primitive type mappings

        @@ -5080,7 +5081,7 @@ However, the mappings allow the full range of values for each C type from Java.

        -

        24.9.2 Default typemaps for non-primitive types

        +

        25.9.2 Default typemaps for non-primitive types

        @@ -5095,7 +5096,7 @@ So in summary, the C/C++ pointer to non-primitive types is cast into the 64 bit The Java type is either the proxy class or type wrapper class.

        -

        24.9.3 Sixty four bit JVMs

        +

        25.9.3 Sixty four bit JVMs

        @@ -5108,7 +5109,7 @@ Unfortunately it won't of course hold true for JNI code.

        -

        24.9.4 What is a typemap?

        +

        25.9.4 What is a typemap?

        @@ -5231,7 +5232,7 @@ int c = example.count('e',"Hello World"); -

        24.9.5 Typemaps for mapping C/C++ types to Java types

        +

        25.9.5 Typemaps for mapping C/C++ types to Java types

        @@ -5491,7 +5492,7 @@ These are listed below: -

        24.9.6 Java typemap attributes

        +

        25.9.6 Java typemap attributes

        @@ -5537,7 +5538,7 @@ The "javain" typemap has the optional 'pre', 'post' and 'pgcppname' attributes. Note that when the 'pre' or 'post' attributes are specified and the associated type is used in a constructor, a constructor helper function is generated. This is necessary as the Java proxy constructor wrapper makes a call to a support constructor using a this call. In Java the this call must be the first statement in the constructor body. The constructor body thus calls the helper function and the helper function instead makes the JNI call, ensuring the 'pre' code is called before the JNI call is made. There is a Date marshalling example showing 'pre', 'post' and 'pgcppname' attributes in action.

        -

        24.9.7 Java special variables

        +

        25.9.7 Java special variables

        @@ -5688,7 +5689,7 @@ This special variable expands to the intermediary class name. Usually this is th unless the jniclassname attribute is specified in the %module directive.

        -

        24.9.8 Typemaps for both C and C++ compilation

        +

        25.9.8 Typemaps for both C and C++ compilation

        @@ -5725,7 +5726,7 @@ If you do not intend your code to be targeting both C and C++ then your typemaps

        -

        24.9.9 Java code typemaps

        +

        25.9.9 Java code typemaps

        @@ -5963,7 +5964,7 @@ to make the method and constructor public: -

        24.9.10 Director specific typemaps

        +

        25.9.10 Director specific typemaps

        @@ -6227,7 +6228,7 @@ The basic strategy here is to provide a default package typemap for the majority -

        24.10 Typemap Examples

        +

        25.10 Typemap Examples

        @@ -6237,7 +6238,7 @@ the SWIG library.

        -

        24.10.1 Simpler Java enums for enums without initializers

        +

        25.10.1 Simpler Java enums for enums without initializers

        @@ -6316,7 +6317,7 @@ This would be done by using the original versions of these typemaps in "enums.sw

        -

        24.10.2 Handling C++ exception specifications as Java exceptions

        +

        25.10.2 Handling C++ exception specifications as Java exceptions

        @@ -6441,7 +6442,7 @@ We could alternatively have used %rename to rename what() into

        -

        24.10.3 NaN Exception - exception handling for a particular type

        +

        25.10.3 NaN Exception - exception handling for a particular type

        @@ -6596,7 +6597,7 @@ If we were a martyr to the JNI cause, we could replace the succinct code within If we had, we would have put it in the "in" typemap which, like all JNI and Java typemaps, also supports the 'throws' attribute.

        -

        24.10.4 Converting Java String arrays to char **

        +

        25.10.4 Converting Java String arrays to char **

        @@ -6740,7 +6741,7 @@ Lastly the "jni", "jtype" and "jstype" typemaps are also required to specify what Java types to use.

        -

        24.10.5 Expanding a Java object to multiple arguments

        +

        25.10.5 Expanding a Java object to multiple arguments

        @@ -6822,7 +6823,7 @@ example.foo(new String[]{"red", "green", "blue", "white"}); -

        24.10.6 Using typemaps to return arguments

        +

        25.10.6 Using typemaps to return arguments

        @@ -6940,7 +6941,7 @@ $ java runme 1 12.0 340.0 -

        24.10.7 Adding Java downcasts to polymorphic return types

        +

        25.10.7 Adding Java downcasts to polymorphic return types

        @@ -7146,7 +7147,7 @@ SWIG usually generates code which constructs the proxy classes using Java code a Note that the JNI code above uses a number of string lookups to call a constructor, whereas this would not occur using byte compiled Java code.

        -

        24.10.8 Adding an equals method to the Java classes

        +

        25.10.8 Adding an equals method to the Java classes

        @@ -7190,7 +7191,7 @@ System.out.println("foo1? " + foo1.equals(foo2)); -

        24.10.9 Void pointers and a common Java base class

        +

        25.10.9 Void pointers and a common Java base class

        @@ -7249,7 +7250,7 @@ This example contains some useful functionality which you may want in your code.

      50. It also has a function which effectively implements a cast from the type of the proxy/type wrapper class to a void pointer. This is necessary for passing a proxy class or a type wrapper class to a function that takes a void pointer. -

        24.10.10 Struct pointer to pointer

        +

        25.10.10 Struct pointer to pointer

        @@ -7429,7 +7430,7 @@ The C functional interface has been completely morphed into an object-oriented i the Butler class would behave much like any pure Java class and feel more natural to Java users.

        -

        24.10.11 Memory management when returning references to member variables

        +

        25.10.11 Memory management when returning references to member variables

        @@ -7552,7 +7553,7 @@ public class Bike { Note the addReference call.

        -

        24.10.12 Memory management for objects passed to the C++ layer

        +

        25.10.12 Memory management for objects passed to the C++ layer

        @@ -7668,7 +7669,7 @@ The 'javacode' typemap simply adds in the specified code into the Java proxy cla -

        24.10.13 Date marshalling using the javain typemap and associated attributes

        +

        25.10.13 Date marshalling using the javain typemap and associated attributes

        @@ -7845,7 +7846,7 @@ A few things to note: -

        24.11 Living with Java Directors

        +

        25.11 Living with Java Directors

        @@ -8026,10 +8027,10 @@ public abstract class UserVisibleFoo extends Foo {

      -

      24.12 Odds and ends

      +

      25.12 Odds and ends

      -

      24.12.1 JavaDoc comments

      +

      25.12.1 JavaDoc comments

      @@ -8085,7 +8086,7 @@ public class Barmy { -

      24.12.2 Functional interface without proxy classes

      +

      25.12.2 Functional interface without proxy classes

      @@ -8146,7 +8147,7 @@ All destructors have to be called manually for example the delete_Foo(foo) -

      24.12.3 Using your own JNI functions

      +

      25.12.3 Using your own JNI functions

      @@ -8196,7 +8197,7 @@ This directive is only really useful if you want to mix your own hand crafted JN

      -

      24.12.4 Performance concerns and hints

      +

      25.12.4 Performance concerns and hints

      @@ -8217,7 +8218,7 @@ However, you will have to be careful about memory management and make sure that This method normally calls the C++ destructor or free() for C code.

      -

      24.12.5 Debugging

      +

      25.12.5 Debugging

      @@ -8239,7 +8240,7 @@ The -verbose:jni and -verbose:gc are also useful options for monitoring code beh

      -

      24.13 Java Examples

      +

      25.13 Java Examples

      diff --git a/Doc/Manual/Library.html b/Doc/Manual/Library.html index 7510c8686..740988e71 100644 --- a/Doc/Manual/Library.html +++ b/Doc/Manual/Library.html @@ -6,7 +6,7 @@ -

      8 SWIG library

      +

      9 SWIG library

        @@ -59,7 +59,7 @@ Alternative libraries provide similar functionality. Please read this chapter carefully if you used the old libraries.

        -

        8.1 The %include directive and library search path

        +

        9.1 The %include directive and library search path

        @@ -91,7 +91,7 @@ Set the environment variable to hold an alternative library directory. The directories that are searched are displayed when using -verbose commandline option.

        -

        8.2 C Arrays and Pointers

        +

        9.2 C Arrays and Pointers

        @@ -103,7 +103,7 @@ pointers as class-like objects. Since these functions provide direct access to memory, their use is potentially unsafe and you should exercise caution.

        -

        8.2.1 cpointer.i

        +

        9.2.1 cpointer.i

        @@ -319,7 +319,7 @@ In this example, the function int_to_uint() would be used to cast type Note: When working with simple pointers, typemaps can often be used to provide more seamless operation.

        -

        8.2.2 carrays.i

        +

        9.2.2 carrays.i

        @@ -497,7 +497,7 @@ you should consider using a special array object rather than a bare pointer. used with types of char or char *.

        -

        8.2.3 cmalloc.i

        +

        9.2.3 cmalloc.i

        @@ -658,7 +658,7 @@ Now, in a script:

      -

      8.2.4 cdata.i

      +

      9.2.4 cdata.i

      @@ -760,7 +760,7 @@ char *cdata_name(type* ptr, int nitems) Clearly they are unsafe.

      -

      8.3 C String Handling

      +

      9.3 C String Handling

      @@ -780,7 +780,7 @@ morality. The modules in this section provide basic functionality for manipulating raw C strings.

      -

      8.3.1 Default string handling

      +

      9.3.1 Default string handling

      @@ -821,7 +821,7 @@ interpreter and lead to a crash). Furthermore, the default behavior does not work well with binary data. Instead, strings are assumed to be NULL-terminated.

      -

      8.3.2 Passing binary data

      +

      9.3.2 Passing binary data

      @@ -863,7 +863,7 @@ In the wrapper function, the passed string will be expanded to a pointer and len The (char *STRING, int LENGTH) multi-argument typemap is also available in addition to (char *STRING, size_t LENGTH).

      -

      8.3.3 Using %newobject to release memory

      +

      9.3.3 Using %newobject to release memory

      @@ -904,7 +904,7 @@ however, you may need to provide your own "newfree" typemap for other types. See Object ownership and %newobject for more details.

      -

      8.3.4 cstring.i

      +

      9.3.4 cstring.i

      @@ -1364,7 +1364,7 @@ structure or class instead.

    52. -

      8.4 STL/C++ Library

      +

      9.4 STL/C++ Library

      @@ -1402,7 +1402,7 @@ Please look for the library files in the appropriate language library directory.

      -

      8.4.1 std::string

      +

      9.4.1 std::string

      @@ -1486,7 +1486,7 @@ void foo(string s, const String &t); // std_string typemaps still applie -

      8.4.2 std::vector

      +

      9.4.2 std::vector

      @@ -1665,7 +1665,7 @@ if you want to make their head explode. details and the public API exposed to the interpreter vary.

      -

      8.4.3 STL exceptions

      +

      9.4.3 STL exceptions

      @@ -1715,7 +1715,7 @@ The %exception directive can be used by placing the following code befo Any thrown STL exceptions will then be gracefully handled instead of causing a crash.

      -

      8.4.4 shared_ptr smart pointer

      +

      9.4.4 shared_ptr smart pointer

      @@ -1904,7 +1904,8 @@ Adding the missing %shared_ptr macros will fix this:

      -

      8.4.5 auto_ptr smart pointer

      +

      9.4.5 auto_ptr smart pointer

      +

      While std::auto_ptr is deprecated in C++11, some existing code may @@ -1952,10 +1953,10 @@ int value = k.getValue(); -

      8.5 Utility Libraries

      +

      9.5 Utility Libraries

      -

      8.5.1 exception.i

      +

      9.5.1 exception.i

      diff --git a/Doc/Manual/Lisp.html b/Doc/Manual/Lisp.html index 09e410185..7ea9139ac 100644 --- a/Doc/Manual/Lisp.html +++ b/Doc/Manual/Lisp.html @@ -6,7 +6,7 @@ -

      25 SWIG and Common Lisp

      +

      26 SWIG and Common Lisp

        @@ -41,7 +41,7 @@ Lisp, Common Foreign Function Interface(CFFI), CLisp and UFFI foreign function interfaces.

        -

        25.1 Allegro Common Lisp

        +

        26.1 Allegro Common Lisp

        @@ -50,7 +50,7 @@ here

        -

        25.2 Common Foreign Function Interface(CFFI)

        +

        26.2 Common Foreign Function Interface(CFFI)

        @@ -77,7 +77,7 @@ swig -cffi -module module-name file-name files and the various things which you can do with them.

        -

        25.2.1 Additional Commandline Options

        +

        26.2.1 Additional Commandline Options

        @@ -118,7 +118,7 @@ swig -cffi -help -

        25.2.2 Generating CFFI bindings

        +

        26.2.2 Generating CFFI bindings

        As we mentioned earlier the ideal way to use SWIG is to use interface @@ -392,7 +392,7 @@ The feature intern_function ensures that all C names are
      -

      25.2.3 Generating CFFI bindings for C++ code

      +

      26.2.3 Generating CFFI bindings for C++ code

      This feature to SWIG (for CFFI) is very new and still far from @@ -568,7 +568,7 @@ If you have any questions, suggestions, patches, etc., related to CFFI module feel free to contact us on the SWIG mailing list, and also please add a "[CFFI]" tag in the subject line. -

      25.2.4 Inserting user code into generated files

      +

      26.2.4 Inserting user code into generated files

      @@ -608,7 +608,7 @@ Note that the block %{ ... %} is effectively a shortcut for

      -

      25.3 CLISP

      +

      26.3 CLISP

      @@ -638,7 +638,7 @@ swig -clisp -module module-name file-name interface file for the CLISP module. The CLISP module tries to produce code which is both human readable and easily modifyable.

      -

      25.3.1 Additional Commandline Options

      +

      26.3.1 Additional Commandline Options

      @@ -671,7 +671,7 @@ and global variables will be created otherwise only definitions for
      -

      25.3.2 Details on CLISP bindings

      +

      26.3.2 Details on CLISP bindings

      @@ -795,7 +795,7 @@ struct bar { -

      25.4 UFFI

      +

      26.4 UFFI

      diff --git a/Doc/Manual/Lua.html b/Doc/Manual/Lua.html index e7d1a5b1b..f0415d8d6 100644 --- a/Doc/Manual/Lua.html +++ b/Doc/Manual/Lua.html @@ -6,7 +6,7 @@ -

      26 SWIG and Lua

      +

      27 SWIG and Lua

    53. Typemaps -
    54. Writing typemaps +
    55. Writing typemaps
    56. Customization of your Bindings @@ -73,14 +85,14 @@ Lua is an extension programming language designed to support general procedural 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

      -

      26.1 Preliminaries

      +

      27.1 Preliminaries

      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

      +

      27.2 Running SWIG

      @@ -128,7 +140,7 @@ $ swig -lua -eluac example.i The -elua option puts all the C function wrappers and variable get/set wrappers in rotables. It also generates a metatable which will control the access to these variables from eLua. It also offers a significant amount of module size compression. On the other hand, the -eluac option puts all the wrappers in a single rotable. With this option, no matter how huge the module, it will consume no additional microcontroller SRAM (crass compression). There is a catch though: Metatables are not generated with -eluac. To access any value from eLua, one must directly call the wrapper function associated with that value.

      -

      26.2.1 Additional command line options

      +

      27.2.1 Additional command line options

      @@ -169,7 +181,7 @@ swig -lua -help -

      26.2.2 Compiling and Linking and Interpreter

      +

      27.2.2 Compiling and Linking and Interpreter

      @@ -240,7 +252,7 @@ LUALIB_API int ( luaopen_mod )(lua_State *L ); More information on building and configuring eLua can be found here: http://www.eluaproject.net/doc/v0.8/en_building.html

      -

      26.2.3 Compiling a dynamic module

      +

      27.2.3 Compiling a dynamic module

      @@ -308,7 +320,7 @@ Is quite obvious (Go back and consult the Lua documents on how to enable loadlib -

      26.2.4 Using your module

      +

      27.2.4 Using your module

      @@ -326,19 +338,19 @@ $ ./my_lua >

    57. -

      26.3 A tour of basic C/C++ wrapping

      +

      27.3 A tour of basic C/C++ wrapping

      By default, SWIG tries to build a very natural Lua interface to your C/C++ code. This section briefly covers the essential aspects of this wrapping.

      -

      26.3.1 Modules

      +

      27.3.1 Modules

      The SWIG module directive specifies the name of the Lua module. If you specify `module example', then everything is wrapped into a Lua table 'example' containing all the functions and variables. When choosing a module name, make sure you don't use the same name as a built-in Lua command or standard module name.

      -

      26.3.2 Functions

      +

      27.3.2 Functions

      @@ -379,7 +391,7 @@ It is also possible to rename the module with an assignment. 24 -

      26.3.3 Global variables

      +

      27.3.3 Global variables

      @@ -467,7 +479,7 @@ If you have used the -eluac option for your eLua module, you will have In general, functions of the form "variable_get()" and "variable_set()" are automatically generated by SWIG for use with -eluac.

      -

      26.3.4 Constants and enums

      +

      27.3.4 Constants and enums

      @@ -502,7 +514,9 @@ If you're using eLua and have used -elua or -eluac to generate Hello World -

      Constants/enums and classes/structures

      +

      27.3.4.1 Constants/enums and classes/structures

      + +

      Enums are exported into a class table. For example, given some enums:

      @@ -556,7 +570,7 @@ If the -no-old-metatable-bindings option is used, then these old-style 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

      +

      27.3.5 Pointers

      @@ -594,7 +608,7 @@ Lua enforces the integrity of its userdata, so it is virtually impossible to cor nil -

      26.3.6 Structures

      +

      27.3.6 Structures

      @@ -698,7 +712,7 @@ For eLua with the -eluac option, structure manipulation has to be perfo In general, functions of the form "new_struct()", "struct_member_get()", "struct_member_set()" and "free_struct()" are automatically generated by SWIG for each structure defined in C. (Please note: This doesn't apply for modules generated with the -elua option)

      -

      26.3.7 C++ classes

      +

      27.3.7 C++ classes

      @@ -770,7 +784,7 @@ 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

      +

      27.3.8 C++ inheritance

      @@ -795,7 +809,7 @@ then the function spam() accepts a Foo pointer or a pointer to any clas

      It is safe to use multiple inheritance with SWIG.

      -

      26.3.9 Pointers, references, values, and arrays

      +

      27.3.9 Pointers, references, values, and arrays

      @@ -826,7 +840,7 @@ Foo spam7();

      then all three functions will return a pointer to some Foo object. Since the third function (spam7) returns a value, newly allocated memory is used to hold the result and a pointer is returned (Lua will release this memory when the return value is garbage collected). The other two are pointers which are assumed to be managed by the C code and so will not be garbage collected.

      -

      26.3.10 C++ overloaded functions

      +

      27.3.10 C++ overloaded functions

      @@ -912,7 +926,7 @@ Please refer to the "SWIG and C++" chapter for more information about overloadin

      Dealing with the Lua coercion mechanism, the priority is roughly (integers, floats, strings, userdata). But it is better to rename the functions rather than rely upon the ordering.

      -

      26.3.11 C++ operators

      +

      27.3.11 C++ operators

      @@ -1024,7 +1038,7 @@ It is also possible to overload the operator[], but currently this cann }; -

      26.3.12 Class extension with %extend

      +

      27.3.12 Class extension with %extend

      @@ -1080,7 +1094,7 @@ true Extend works with both C and C++ code, on classes and structs. It does not modify the underlying object in any way---the extensions only show up in the Lua interface. The only item to take note of is the code has to use the '$self' instead of 'this', and that you cannot access protected/private members of the code (as you are not officially part of the class).

      -

      26.3.13 Using %newobject to release memory

      +

      27.3.13 Using %newobject to release memory

      If you have a function that allocates memory like this,

      @@ -1104,7 +1118,7 @@ char *foo();

      This will release the allocated memory.

      -

      26.3.14 C++ templates

      +

      27.3.14 C++ templates

      @@ -1139,7 +1153,7 @@ In Lua:

      Obviously, there is more to template wrapping than shown in this example. More details can be found in the SWIG and C++ chapter. Some more complicated examples will appear later.

      -

      26.3.15 C++ Smart Pointers

      +

      27.3.15 C++ Smart Pointers

      @@ -1191,7 +1205,7 @@ If you ever need to access the underlying pointer returned by operator->( > f = p:__deref__() -- Returns underlying Foo * -

      26.3.16 C++ Exceptions

      +

      27.3.16 C++ Exceptions

      @@ -1334,7 +1348,9 @@ and the "Exception handling add exception specification to functions or globally (respectively).

      -

      26.3.17 Namespaces

      +

      27.3.17 Namespaces

      + +

      Since SWIG-3.0.0 C++ namespaces are supported via the %nspace feature.

      @@ -1379,7 +1395,9 @@ Now, from Lua usage is as follows: 19 > -

      Compatibility Note

      +

      27.3.17.1 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):

      @@ -1391,8 +1409,12 @@ If SWIG is running in backward compatible way, i.e. without -no-old-metatabl 11 > -

      Compatibility Note

      -

      Names

      +

      27.3.18 Compatibility Note

      + + +

      27.3.18.1 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. Those names are in a form $classname_$symbolname and are added to the scope surrounding the class. @@ -1434,7 +1456,9 @@ surrounding scope without any prefixing. Pretending that Test2 is a struct, not > -

      Inheritance

      +

      27.3.18.2 Inheritance

      + +

      The internal organization of inheritance has changed. Consider the following C++ code:

      %module example
      @@ -1473,12 +1497,12 @@ function
       >
       
      -

      26.4 Typemaps

      +

      27.4 Typemaps

      This section explains what typemaps are and how to use them. The default wrapping behaviour of SWIG is enough in most cases. However sometimes SWIG may need a little additional assistance to know which typemap to apply to provide the best wrapping. This section will be explaining how to use typemaps to best effect

      -

      26.4.1 What is a typemap?

      +

      27.4.1 What is a typemap?

      A typemap is nothing more than a code generation rule that is attached to a specific C datatype. For example, to convert integers from Lua to C, you might define a typemap like this:

      @@ -1506,7 +1530,7 @@ Received an integer : 6 720 -

      26.4.2 Using typemaps

      +

      27.4.2 Using typemaps

      There are many ready written typemaps built into SWIG for all common types (int, float, short, long, char*, enum and more), which SWIG uses automatically, with no effort required on your part.

      @@ -1559,7 +1583,7 @@ void swap(int *sx, int *sy);

      Note: C++ references must be handled exactly the same way. However SWIG will automatically wrap a const int& as an input parameter (since that it obviously input).

      -

      26.4.3 Typemaps and arrays

      +

      27.4.3 Typemaps and arrays

      Arrays present a challenge for SWIG, because like pointers SWIG does not know whether these are input or output values, nor @@ -1623,7 +1647,7 @@ and Lua tables to be 1..N, (the indexing follows the norm for the language). In

      Note: SWIG also can support arrays of pointers in a similar manner.

      -

      26.4.4 Typemaps and pointer-pointer functions

      +

      27.4.4 Typemaps and pointer-pointer functions

      Several C++ libraries use a pointer-pointer functions to create its objects. These functions require a pointer to a pointer which is then filled with the pointer to the new object. Microsoft's COM and DirectX as well as many other libraries have this kind of function. An example is given below:

      @@ -1657,7 +1681,7 @@ int Create_Math(iMath** pptr); // its creator (assume it mallocs) ptr=nil -- the iMath* will be GC'ed as normal -

      26.5 Writing typemaps

      +

      27.5 Writing typemaps

      This section describes how you can modify SWIG's default wrapping behavior for various C/C++ datatypes using the %typemap directive. This is an advanced topic that assumes familiarity with the Lua C API as well as the material in the "Typemaps" chapter.

      @@ -1666,7 +1690,7 @@ ptr=nil -- the iMath* will be GC'ed as normal

      Before proceeding, you should read the previous section on using typemaps, and look at the existing typemaps found in luatypemaps.swg and typemaps.i. These are both well documented and fairly easy to read. You should not attempt to write your own typemaps until you have read and can understand both of these files (they may well also give you an idea to base your work on).

      -

      26.5.1 Typemaps you can write

      +

      27.5.1 Typemaps you can write

      There are many different types of typemap that can be written, the full list can be found in the "Typemaps" chapter. However the following are the most commonly used ones.

      @@ -1679,7 +1703,7 @@ ptr=nil -- the iMath* will be GC'ed as normal (the syntax for the typecheck is different from the typemap, see typemaps for details). -

      26.5.2 SWIG's Lua-C API

      +

      27.5.2 SWIG's Lua-C API

      This section explains the SWIG specific Lua-C API. It does not cover the main Lua-C api, as this is well documented and not worth covering.

      @@ -1728,7 +1752,7 @@ This macro, when called within the context of a SWIG wrapped function, will disp
      Similar to SWIG_fail_arg, except that it will display the swig_type_info information instead.
      -

      26.6 Customization of your Bindings

      +

      27.6 Customization of your Bindings

      @@ -1737,7 +1761,7 @@ This section covers adding of some small extra bits to your module to add the la -

      26.6.1 Writing your own custom wrappers

      +

      27.6.1 Writing your own custom wrappers

      @@ -1756,7 +1780,7 @@ int native_function(lua_State*L) // my native code The %native directive in the above example, tells SWIG that there is a function int native_function(lua_State*L); which is to be added into the module under the name 'my_func'. SWIG will not add any wrapper for this function, beyond adding it into the function table. How you write your code is entirely up to you.

      -

      26.6.2 Adding additional Lua code

      +

      27.6.2 Adding additional Lua code

      @@ -1794,7 +1818,7 @@ Good uses for this feature is adding of new code, or writing helper functions to See Examples/lua/arrays for an example of this code.

      -

      26.7 Details on the Lua binding

      +

      27.7 Details on the Lua binding

      @@ -1805,7 +1829,7 @@ See Examples/lua/arrays for an example of this code.

      -

      26.7.1 Binding global data into the module.

      +

      27.7.1 Binding global data into the module.

      @@ -1865,7 +1889,7 @@ end

      That way when you call 'a=example.Foo', the interpreter looks at the table 'example' sees that there is no field 'Foo' and calls __index. This will in turn check in '.get' table and find the existence of 'Foo' and then return the value of the C function call 'Foo_get()'. Similarly for the code 'example.Foo=10', the interpreter will check the table, then call the __newindex which will then check the '.set' table and call the C function 'Foo_set(10)'.

      -

      26.7.2 Userdata and Metatables

      +

      27.7.2 Userdata and Metatables

      @@ -1945,7 +1969,7 @@ Note: Both the opaque structures (like the FILE*) and normal wrapped classes/str

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

      -

      26.7.3 Memory management

      +

      27.7.3 Memory management

      diff --git a/Doc/Manual/Modula3.html b/Doc/Manual/Modula3.html index 329127a0f..0bf9f2995 100644 --- a/Doc/Manual/Modula3.html +++ b/Doc/Manual/Modula3.html @@ -5,7 +5,7 @@ -

      27 SWIG and Modula-3

      +

      28 SWIG and Modula-3

        @@ -54,7 +54,7 @@ especially typemaps.

        -

        27.1 Overview

        +

        28.1 Overview

        @@ -84,7 +84,7 @@ FFTW

    -

    27.1.1 Motivation

    +

    28.1.1 Motivation

    @@ -131,10 +131,10 @@ functions), but it doesn't allow you to easily integrate a Modula-3 module into a C/C++ project.

    -

    27.2 Conception

    +

    28.2 Conception

    -

    27.2.1 Interfaces to C libraries

    +

    28.2.1 Interfaces to C libraries

    @@ -283,7 +283,7 @@ and the principal type must be renamed (%typemap).

    -

    27.2.2 Interfaces to C++ libraries

    +

    28.2.2 Interfaces to C++ libraries

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

    -

    27.3 Preliminaries

    +

    28.3 Preliminaries

    -

    27.3.1 Compilers

    +

    28.3.1 Compilers

    @@ -400,7 +400,7 @@ For testing examples I use Critical Mass cm3.

    -

    27.3.2 Additional Commandline Options

    +

    28.3.2 Additional Commandline Options

    @@ -477,10 +477,10 @@ Instead generate templates for some basic typemaps. -

    27.4 Modula-3 typemaps

    +

    28.4 Modula-3 typemaps

    -

    27.4.1 Inputs and outputs

    +

    28.4.1 Inputs and outputs

    @@ -694,7 +694,7 @@ consist of the following parts: -

    27.4.2 Subranges, Enumerations, Sets

    +

    28.4.2 Subranges, Enumerations, Sets

    @@ -746,7 +746,7 @@ that I'd like to automate.

    -

    27.4.3 Objects

    +

    28.4.3 Objects

    @@ -759,7 +759,7 @@ is not really useful, yet.

    -

    27.4.4 Imports

    +

    28.4.4 Imports

    @@ -792,7 +792,7 @@ IMPORT M3toC; -

    27.4.5 Exceptions

    +

    28.4.5 Exceptions

    @@ -816,7 +816,7 @@ you should declare %typemap("m3wrapinconv:throws") blah * %{OSError.E%}.

    -

    27.4.6 Example

    +

    28.4.6 Example

    @@ -863,10 +863,10 @@ where almost everything is generated by a typemap: -

    27.5 More hints to the generator

    +

    28.5 More hints to the generator

    -

    27.5.1 Features

    +

    28.5.1 Features

    @@ -903,7 +903,7 @@ where almost everything is generated by a typemap:
    -

    27.5.2 Pragmas

    +

    28.5.2 Pragmas

    @@ -926,7 +926,7 @@ where almost everything is generated by a typemap:
    -

    27.6 Remarks

    +

    28.6 Remarks

      diff --git a/Doc/Manual/Modules.html b/Doc/Manual/Modules.html index c44341e56..551fd0750 100644 --- a/Doc/Manual/Modules.html +++ b/Doc/Manual/Modules.html @@ -6,7 +6,7 @@ -

      15 Working with Modules

      +

      16 Working with Modules

        @@ -23,7 +23,7 @@ -

        15.1 Modules Introduction

        +

        16.1 Modules Introduction

        @@ -77,7 +77,7 @@ where you want to create a collection of modules. Each module in the collection is created via separate invocations of SWIG.

        -

        15.2 Basics

        +

        16.2 Basics

        @@ -176,7 +176,7 @@ in parallel from multiple threads as SWIG provides no locking - for more on that issue, read on.

        -

        15.3 The SWIG runtime code

        +

        16.3 The SWIG runtime code

        @@ -242,7 +242,7 @@ can peacefully coexist. So the type structures are separated by the is empty. Only modules compiled with the same pair will share type information.

        -

        15.4 External access to the runtime

        +

        16.4 External access to the runtime

        As described in The run-time type checker, @@ -279,7 +279,7 @@ SWIG_TYPE_TABLE to be the same as the module whose types you are trying to access.

        -

        15.5 A word of caution about static libraries

        +

        16.5 A word of caution about static libraries

        @@ -290,7 +290,7 @@ into it. This is very often NOT what you want and it can lead to unexpect behavior. When working with dynamically loadable modules, you should try to work exclusively with shared libraries.

        -

        15.6 References

        +

        16.6 References

        @@ -298,7 +298,7 @@ Due to the complexity of working with shared libraries and multiple modules, it an outside reference. John Levine's "Linkers and Loaders" is highly recommended.

        -

        15.7 Reducing the wrapper file size

        +

        16.7 Reducing the wrapper file size

        diff --git a/Doc/Manual/Mzscheme.html b/Doc/Manual/Mzscheme.html index 3b49a2974..40173d720 100644 --- a/Doc/Manual/Mzscheme.html +++ b/Doc/Manual/Mzscheme.html @@ -8,7 +8,7 @@ -

        28 SWIG and MzScheme/Racket

        +

        29 SWIG and MzScheme/Racket

          @@ -24,7 +24,7 @@

          This section contains information on SWIG's support of Racket, formally known as MzScheme. -

          28.1 Creating native structures

          +

          29.1 Creating native structures

          @@ -65,7 +65,7 @@ Then in scheme, you can use regular struct access procedures like

        -

        28.2 Simple example

        +

        29.2 Simple example

        @@ -166,7 +166,7 @@ Some points of interest:

      • The above requests mzc to create an extension using the CGC garbage-collector. The alternative -- the 3m collector -- has generally better performance, but work is still required for SWIG to emit code which is compatible with it.
      -

      28.3 External documentation

      +

      29.3 External documentation

      diff --git a/Doc/Manual/Ocaml.html b/Doc/Manual/Ocaml.html index 2eef3ad4d..ec46d6e50 100644 --- a/Doc/Manual/Ocaml.html +++ b/Doc/Manual/Ocaml.html @@ -6,7 +6,7 @@ -

      29 SWIG and Ocaml

      +

      30 SWIG and Ocaml

        @@ -80,7 +80,7 @@ If you're not familiar with the Objective Caml language, you can visit The Ocaml Website.

        -

        29.1 Preliminaries

        +

        30.1 Preliminaries

        @@ -99,7 +99,7 @@ file Examples/Makefile illustrate how to compile and link SWIG modules that will be loaded dynamically. This has only been tested on Linux so far.

        -

        29.1.1 Running SWIG

        +

        30.1.1 Running SWIG

        @@ -122,7 +122,7 @@ you will compile the file example_wrap.c with ocamlc or the resulting .ml and .mli files as well, and do the final link with -custom (not needed for native link).

        -

        29.1.2 Compiling the code

        +

        30.1.2 Compiling the code

        @@ -158,7 +158,7 @@ the user more freedom with respect to custom typing.

      -

      29.1.3 The camlp4 module

      +

      30.1.3 The camlp4 module

      @@ -234,7 +234,7 @@ let b = C_string (getenv "PATH") -

      29.1.4 Using your module

      +

      30.1.4 Using your module

      @@ -248,7 +248,7 @@ When linking any ocaml bytecode with your module, use the -custom option is not needed when you build native code.

      -

      29.1.5 Compilation problems and compiling with C++

      +

      30.1.5 Compilation problems and compiling with C++

      @@ -259,7 +259,7 @@ liberal with pointer types may not compile under the C++ compiler. Most code meant to be compiled as C++ will not have problems.

      -

      29.2 The low-level Ocaml/C interface

      +

      30.2 The low-level Ocaml/C interface

      @@ -360,7 +360,7 @@ is that you must append them to the return list with swig_result = caml_list_a signature for a function that uses value in this way.

      -

      29.2.1 The generated module

      +

      30.2.1 The generated module

      @@ -394,7 +394,7 @@ it describes the output SWIG will generate for class definitions. -

      29.2.2 Enums

      +

      30.2.2 Enums

      @@ -457,7 +457,7 @@ val x : Enum_test.c_obj = C_enum `a

      -

      29.2.2.1 Enum typing in Ocaml

      +

      30.2.2.1 Enum typing in Ocaml

      @@ -470,10 +470,10 @@ functions imported from different modules. You must convert values to master values using the swig_val function before sharing them with another module.

      -

      29.2.3 Arrays

      +

      30.2.3 Arrays

      -

      29.2.3.1 Simple types of bounded arrays

      +

      30.2.3.1 Simple types of bounded arrays

      @@ -494,7 +494,7 @@ arrays of simple types with known bounds in your code, but this only works for arrays whose bounds are completely specified.

      -

      29.2.3.2 Complex and unbounded arrays

      +

      30.2.3.2 Complex and unbounded arrays

      @@ -507,7 +507,7 @@ SWIG can't predict which of these methods will be used in the array, so you have to specify it for yourself in the form of a typemap.

      -

      29.2.3.3 Using an object

      +

      30.2.3.3 Using an object

      @@ -521,7 +521,7 @@ Consider writing an object when the ending condition of your array is complex, such as using a required sentinel, etc.

      -

      29.2.3.4 Example typemap for a function taking float * and int

      +

      30.2.3.4 Example typemap for a function taking float * and int

      @@ -572,7 +572,7 @@ void printfloats( float *tab, int len ); -

      29.2.4 C++ Classes

      +

      30.2.4 C++ Classes

      @@ -615,7 +615,7 @@ the underlying pointer, so using create_[x]_from_ptr alters the returned value for the same object.

      -

      29.2.4.1 STL vector and string Example

      +

      30.2.4.1 STL vector and string Example

      @@ -695,7 +695,7 @@ baz # -

      29.2.4.2 C++ Class Example

      +

      30.2.4.2 C++ Class Example

      @@ -725,7 +725,7 @@ public: }; -

      29.2.4.3 Compiling the example

      +

      30.2.4.3 Compiling the example

      @@ -743,7 +743,7 @@ bash-2.05a$ ocamlmktop -custom swig.cmo -I `camlp4 -where` \
         -L$QTPATH/lib -cclib -lqt
       
      -

      29.2.4.4 Sample Session

      +

      30.2.4.4 Sample Session

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

      -

      29.2.5 Director Classes

      +

      30.2.5 Director Classes

      -

      29.2.5.1 Director Introduction

      +

      30.2.5.1 Director Introduction

      @@ -800,7 +800,7 @@ class foo { };

      -

      29.2.5.2 Overriding Methods in Ocaml

      +

      30.2.5.2 Overriding Methods in Ocaml

      @@ -828,7 +828,7 @@ In this example, I'll examine the objective caml code involved in providing an overloaded class. This example is contained in Examples/ocaml/shapes.

      -

      29.2.5.3 Director Usage Example

      +

      30.2.5.3 Director Usage Example

      @@ -887,7 +887,7 @@ in a more effortless style in ocaml, while leaving the "engine" part of the program in C++.

      -

      29.2.5.4 Creating director objects

      +

      30.2.5.4 Creating director objects

      @@ -928,7 +928,7 @@ object from causing a core dump, as long as the object is destroyed properly.

      -

      29.2.5.5 Typemaps for directors, directorin, directorout, directorargout

      +

      30.2.5.5 Typemaps for directors, directorin, directorout, directorargout

      @@ -939,7 +939,7 @@ well as a function return value in the same way you provide function arguments, and to receive arguments the same way you normally receive function returns.

      -

      29.2.5.6 directorin typemap

      +

      30.2.5.6 directorin typemap

      @@ -950,7 +950,7 @@ code receives when you are called. In general, a simple directorin typ can use the same body as a simple out typemap.

      -

      29.2.5.7 directorout typemap

      +

      30.2.5.7 directorout typemap

      @@ -961,7 +961,7 @@ for the same type, except when there are special requirements for object ownership, etc.

      -

      29.2.5.8 directorargout typemap

      +

      30.2.5.8 directorargout typemap

      @@ -978,7 +978,7 @@ In the event that you don't specify all of the necessary values, integral values will read zero, and struct or object returns have undefined results.

      -

      29.2.6 Exceptions

      +

      30.2.6 Exceptions

      diff --git a/Doc/Manual/Octave.html b/Doc/Manual/Octave.html index 42c6526b7..bc6873c4b 100644 --- a/Doc/Manual/Octave.html +++ b/Doc/Manual/Octave.html @@ -8,7 +8,7 @@ -

      30 SWIG and Octave

      +

      31 SWIG and Octave

        @@ -55,7 +55,7 @@ More information can be found at O Also, there are a dozen or so examples in the Examples/octave directory, and hundreds in the test suite (Examples/test-suite and Examples/test-suite/octave).

        -

        30.1 Preliminaries

        +

        31.1 Preliminaries

        @@ -63,7 +63,7 @@ As of SWIG 3.0.0, the Octave module has been tested with Octave versions 3.0.5, 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

        +

        31.2 Running SWIG

        @@ -95,7 +95,7 @@ The -c++ option is also required when wrapping C++ code: This creates a C++ source file "example_wrap.cpp". A C++ file is generated even when wrapping C code as Octave is itself written in C++ and requires wrapper code to be in the same language. The generated C++ source file contains the low-level wrappers that need to be compiled and linked with the rest of your C/C++ application (in this case, the gcd implementation) to create an extension module.

        -

        30.2.1 Command-line options

        +

        31.2.1 Command-line options

        @@ -118,7 +118,7 @@ The special name "." loads C global variables into the module namespace, i.e. al The -opprefix options sets the prefix of the names of global/friend operator functions.

        -

        30.2.2 Compiling a dynamic module

        +

        31.2.2 Compiling a dynamic module

        @@ -145,7 +145,7 @@ $ mkoctfile example_wrap.cpp example.c

        octave:1> swigexample
        -

        30.2.3 Using your module

        +

        31.2.3 Using your module

        @@ -163,10 +163,10 @@ octave:4> swigexample.cvar.Foo=4; octave:5> swigexample.cvar.Foo ans = 4

      -

      30.3 A tour of basic C/C++ wrapping

      +

      31.3 A tour of basic C/C++ wrapping

      -

      30.3.1 Modules

      +

      31.3.1 Modules

      @@ -211,7 +211,7 @@ octave:4> swigexample.gcd(4,6) ans = 2 -

      30.3.2 Functions

      +

      31.3.2 Functions

      @@ -228,7 +228,7 @@ int fact(int n);

      octave:1> swigexample.fact(4)
       24 
      -

      30.3.3 Global variables

      +

      31.3.3 Global variables

      @@ -281,7 +281,7 @@ octave:2> swigexample.PI=3.142; octave:3> swigexample.PI ans = 3.1420 -

      30.3.4 Constants and enums

      +

      31.3.4 Constants and enums

      @@ -303,7 +303,7 @@ swigexample.SCONST="Hello World" swigexample.SUNDAY=0 .... -

      30.3.5 Pointers

      +

      31.3.5 Pointers

      @@ -350,7 +350,7 @@ octave:2> f=swigexample.fopen("not there","r"); error: value on right hand side of assignment is undefined error: evaluating assignment expression near line 2, column 2 -

      30.3.6 Structures and C++ classes

      +

      31.3.6 Structures and C++ classes

      @@ -485,7 +485,7 @@ ans = 1 Depending on the ownership setting of a swig_ref, it may call C++ destructors when its reference count goes to zero. See the section on memory management below for details.

      -

      30.3.7 C++ inheritance

      +

      31.3.7 C++ inheritance

      @@ -494,7 +494,7 @@ This information contains the full class hierarchy. When an indexing operation ( the tree is walked to find a match in the current class as well as any of its bases. The lookup is then cached in the swig_ref.

      -

      30.3.8 C++ overloaded functions

      +

      31.3.8 C++ overloaded functions

      @@ -504,7 +504,7 @@ The dispatch function selects which overload to call (if any) based on the passe typecheck typemaps are used to analyze each argument, as well as assign precedence. See the chapter on typemaps for details.

      -

      30.3.9 C++ operators

      +

      31.3.9 C++ operators

      @@ -608,7 +608,7 @@ On the C++ side, the default mappings are as follows: Octave can also utilise friend (i.e. non-member) operators with a simple %rename: see the example in the Examples/octave/operator directory.

      -

      30.3.10 Class extension with %extend

      +

      31.3.10 Class extension with %extend

      @@ -638,7 +638,7 @@ octave:3> printf("%s\n",a); octave:4> a.__str() 4 -

      30.3.11 C++ templates

      +

      31.3.11 C++ templates

      @@ -715,14 +715,14 @@ ans = -

      30.3.12 C++ Smart Pointers

      +

      31.3.12 C++ Smart Pointers

      C++ smart pointers are fully supported as in other modules.

      -

      30.3.13 Directors (calling Octave from C++ code)

      +

      31.3.13 Directors (calling Octave from C++ code)

      @@ -803,14 +803,14 @@ c-side routine called octave-side routine called -

      30.3.14 Threads

      +

      31.3.14 Threads

      The use of threads in wrapped Director code is not supported; i.e., an Octave-side implementation of a C++ class must be called from the Octave interpreter's thread. Anything fancier (apartment/queue model, whatever) is left to the user. Without anything fancier, this amounts to the limitation that Octave must drive the module... like, for example, an optimization package that calls Octave to evaluate an objective function.

      -

      30.3.15 Memory management

      +

      31.3.15 Memory management

      @@ -844,14 +844,14 @@ The %newobject directive may be used to control this behavior for pointers retur In the case where one wishes for the C++ side to own an object that was created in Octave (especially a Director object), one can use the __disown() method to invert this logic. Then letting the Octave reference count go to zero will not destroy the object, but destroying the object will invalidate the Octave-side object if it still exists (and call destructors of other C++ bases in the case of multiple inheritance/subclass()'ing).

      -

      30.3.16 STL support

      +

      31.3.16 STL support

      Various STL library files are provided for wrapping STL containers.

      -

      30.3.17 Matrix typemaps

      +

      31.3.17 Matrix typemaps

      diff --git a/Doc/Manual/Perl5.html b/Doc/Manual/Perl5.html index 9e577b08b..010eb48df 100644 --- a/Doc/Manual/Perl5.html +++ b/Doc/Manual/Perl5.html @@ -6,7 +6,7 @@ -

      31 SWIG and Perl5

      +

      32 SWIG and Perl5

        @@ -96,7 +96,7 @@ later. We're no longer testing regularly with older versions, but Perl 5.6 seems to mostly work, while older versions don't.

        -

        31.1 Overview

        +

        32.1 Overview

        @@ -117,7 +117,7 @@ described. Advanced customization features, typemaps, and other options are found near the end of the chapter.

        -

        31.2 Preliminaries

        +

        32.2 Preliminaries

        @@ -142,7 +142,7 @@ To build the module, you will need to compile the file example_wrap.c and link it with the rest of your program.

        -

        31.2.1 Getting the right header files

        +

        32.2.1 Getting the right header files

        @@ -174,7 +174,7 @@ $ perl -e 'use Config; print "$Config{archlib}\n";'

      -

      31.2.2 Compiling a dynamic module

      +

      32.2.2 Compiling a dynamic module

      @@ -207,7 +207,7 @@ the target should be named `example.so', `example.sl', or the appropriate dynamic module name on your system.

      -

      31.2.3 Building a dynamic module with MakeMaker

      +

      32.2.3 Building a dynamic module with MakeMaker

      @@ -241,7 +241,7 @@ the preferred approach to compilation. More information about MakeMaker can be found in "Programming Perl, 2nd ed." by Larry Wall, Tom Christiansen, and Randal Schwartz.

      -

      31.2.4 Building a static version of Perl

      +

      32.2.4 Building a static version of Perl

      @@ -310,7 +310,7 @@ added to it. Depending on your machine, you may need to link with additional libraries such as -lsocket, -lnsl, -ldl, etc.

      -

      31.2.5 Using the module

      +

      32.2.5 Using the module

      @@ -463,7 +463,7 @@ system configuration (this requires root access and you will need to read the man pages).

      -

      31.2.6 Compilation problems and compiling with C++

      +

      32.2.6 Compilation problems and compiling with C++

      @@ -606,7 +606,7 @@ have to find the macro that conflicts and add an #undef into the .i file. Pleas any conflicting macros you find to swig-user mailing list.

      -

      31.2.7 Compiling for 64-bit platforms

      +

      32.2.7 Compiling for 64-bit platforms

      @@ -633,7 +633,7 @@ also introduce problems on platforms that support more than one linking standard (e.g., -o32 and -n32 on Irix).

      -

      31.3 Building Perl Extensions under Windows

      +

      32.3 Building Perl Extensions under Windows

      @@ -644,7 +644,7 @@ section assumes you are using SWIG with Microsoft Visual C++ although the procedure may be similar with other compilers.

      -

      31.3.1 Running SWIG from Developer Studio

      +

      32.3.1 Running SWIG from Developer Studio

      @@ -707,7 +707,7 @@ print "$a\n"; -

      31.3.2 Using other compilers

      +

      32.3.2 Using other compilers

      @@ -715,7 +715,7 @@ SWIG is known to work with Cygwin and may work with other compilers on Windows. For general hints and suggestions refer to the Windows chapter.

      -

      31.4 The low-level interface

      +

      32.4 The low-level interface

      @@ -725,7 +725,7 @@ can be used to control your application. However, it is also used to construct more user-friendly proxy classes as described in the next section.

      -

      31.4.1 Functions

      +

      32.4.1 Functions

      @@ -748,7 +748,7 @@ use example; $a = &example::fact(2); -

      31.4.2 Global variables

      +

      32.4.2 Global variables

      @@ -818,7 +818,7 @@ extern char *path; // Declared later in the input -

      31.4.3 Constants

      +

      32.4.3 Constants

      @@ -858,7 +858,7 @@ print example::FOO,"\n"; -

      31.4.4 Pointers

      +

      32.4.4 Pointers

      @@ -967,7 +967,7 @@ as XS and xsubpp. Given the advancement of the SWIG typesystem and the SWIG and XS, this is no longer supported.

      -

      31.4.5 Structures

      +

      32.4.5 Structures

      @@ -1101,7 +1101,7 @@ void Bar_f_set(Bar *b, Foo *val) { -

      31.4.6 C++ classes

      +

      32.4.6 C++ classes

      @@ -1166,7 +1166,7 @@ provides direct access to C++ objects. A higher level interface using Perl prox can be built using these low-level accessors. This is described shortly.

      -

      31.4.7 C++ classes and type-checking

      +

      32.4.7 C++ classes and type-checking

      @@ -1202,7 +1202,7 @@ If necessary, the type-checker also adjusts the value of the pointer (as is nece multiple inheritance is used).

      -

      31.4.8 C++ overloaded functions

      +

      32.4.8 C++ overloaded functions

      @@ -1246,7 +1246,7 @@ example::Spam_foo_d($s,3.14); Please refer to the "SWIG Basics" chapter for more information.

      -

      31.4.9 Operators

      +

      32.4.9 Operators

      @@ -1273,7 +1273,7 @@ The following C++ operators are currently supported by the Perl module:

    • operator or
    • -

      31.4.10 Modules and packages

      +

      32.4.10 Modules and packages

      @@ -1368,7 +1368,7 @@ print Foo::fact(4),"\n"; # Call a function in package FooBar --> -

      31.5 Input and output parameters

      +

      32.5 Input and output parameters

      @@ -1587,7 +1587,7 @@ print "$c\n"; Note: The REFERENCE feature is only currently supported for numeric types (integers and floating point).

      -

      31.6 Exception handling

      +

      32.6 Exception handling

      @@ -1752,7 +1752,7 @@ This is still supported, but it is deprecated. The newer %exception di functionality, but it has additional capabilities that make it more powerful.

      -

      31.7 Remapping datatypes with typemaps

      +

      32.7 Remapping datatypes with typemaps

      @@ -1769,7 +1769,7 @@ Typemaps are only used if you want to change some aspect of the primitive C-Perl interface.

      -

      31.7.1 A simple typemap example

      +

      32.7.1 A simple typemap example

      @@ -1873,7 +1873,7 @@ example::count("e","Hello World"); -

      31.7.2 Perl5 typemaps

      +

      32.7.2 Perl5 typemaps

      @@ -1978,7 +1978,7 @@ Return of C++ member data (all languages). Check value of input parameter. -

      31.7.3 Typemap variables

      +

      32.7.3 Typemap variables

      @@ -2049,7 +2049,7 @@ properly assigned. The Perl name of the wrapper function being created. -

      31.7.4 Useful functions

      +

      32.7.4 Useful functions

      @@ -2118,7 +2118,7 @@ int sv_isa(SV *, char *0; -

      31.8 Typemap Examples

      +

      32.8 Typemap Examples

      @@ -2127,7 +2127,7 @@ might look at the files "perl5.swg" and "typemaps.i" in the SWIG library.

      -

      31.8.1 Converting a Perl5 array to a char **

      +

      32.8.1 Converting a Perl5 array to a char **

      @@ -2219,7 +2219,7 @@ print @$b,"\n"; # Print it out -

      31.8.2 Return values

      +

      32.8.2 Return values

      @@ -2248,7 +2248,7 @@ can be done using the EXTEND() macro as in: } -

      31.8.3 Returning values from arguments

      +

      32.8.3 Returning values from arguments

      @@ -2302,7 +2302,7 @@ print "multout(7,13) = @r\n"; ($x,$y) = multout(7,13); -

      31.8.4 Accessing array structure members

      +

      32.8.4 Accessing array structure members

      @@ -2365,7 +2365,7 @@ the "in" typemap in the previous section would be used to convert an to copy the converted array into a C data structure.

      -

      31.8.5 Turning Perl references into C pointers

      +

      32.8.5 Turning Perl references into C pointers

      @@ -2430,7 +2430,7 @@ print "$c\n"; -

      31.8.6 Pointer handling

      +

      32.8.6 Pointer handling

      @@ -2509,7 +2509,7 @@ For example: -

      31.9 Proxy classes

      +

      32.9 Proxy classes

      @@ -2525,7 +2525,7 @@ to the underlying code. This section describes the implementation details of the proxy interface.

      -

      31.9.1 Preliminaries

      +

      32.9.1 Preliminaries

      @@ -2547,7 +2547,7 @@ SWIG creates a collection of high-level Perl wrappers. In your scripts, you wil high level wrappers. The wrappers, in turn, interact with the low-level procedural module.

      -

      31.9.2 Structure and class wrappers

      +

      32.9.2 Structure and class wrappers

      @@ -2673,7 +2673,7 @@ $v->DESTROY(); -

      31.9.3 Object Ownership

      +

      32.9.3 Object Ownership

      @@ -2760,7 +2760,7 @@ counting, garbage collection, or advanced features one might find in sophisticated languages.

      -

      31.9.4 Nested Objects

      +

      32.9.4 Nested Objects

      @@ -2813,7 +2813,7 @@ $p->{f}->{x} = 0.0; %${$p->{v}} = ( x=>0, y=>0, z=>0); -

      31.9.5 Proxy Functions

      +

      32.9.5 Proxy Functions

      @@ -2847,7 +2847,7 @@ This function replaces the original function, but operates in an identical manner.

      -

      31.9.6 Inheritance

      +

      32.9.6 Inheritance

      @@ -2923,7 +2923,7 @@ particular, inheritance of data members is extremely tricky (and I'm not even sure if it really works).

      -

      31.9.7 Modifying the proxy methods

      +

      32.9.7 Modifying the proxy methods

      @@ -2951,7 +2951,7 @@ public: }; -

      31.10 Adding additional Perl code

      +

      32.10 Adding additional Perl code

      @@ -3002,7 +3002,7 @@ set_transform($im, $a); -

      31.11 Cross language polymorphism

      +

      32.11 Cross language polymorphism

      @@ -3036,7 +3036,7 @@ proxy classes, director classes, and C wrapper functions takes care of all the cross-language method routing transparently.

      -

      31.11.1 Enabling directors

      +

      32.11.1 Enabling directors

      @@ -3126,7 +3126,7 @@ sub one { -

      31.11.2 Director classes

      +

      32.11.2 Director classes

      @@ -3206,7 +3206,7 @@ so there is no need for the extra overhead involved with routing the calls through Perl.

      -

      31.11.3 Ownership and object destruction

      +

      32.11.3 Ownership and object destruction

      @@ -3255,7 +3255,7 @@ sub DESTROY { -

      31.11.4 Exception unrolling

      +

      32.11.4 Exception unrolling

      @@ -3311,7 +3311,7 @@ Swig::DirectorMethodException is thrown, Perl will register the exception as soon as the C wrapper function returns.

      -

      31.11.5 Overhead and code bloat

      +

      32.11.5 Overhead and code bloat

      @@ -3345,7 +3345,7 @@ directive) for only those methods that are likely to be extended in Perl.

      -

      31.11.6 Typemaps

      +

      32.11.6 Typemaps

      diff --git a/Doc/Manual/Php.html b/Doc/Manual/Php.html index 19bfab6ba..493c861f8 100644 --- a/Doc/Manual/Php.html +++ b/Doc/Manual/Php.html @@ -7,7 +7,7 @@ -

      32 SWIG and PHP

      +

      33 SWIG and PHP

        @@ -79,7 +79,7 @@ your extension into php directly, you will need the complete PHP source tree available.

        -

        32.1 Generating PHP Extensions

        +

        33.1 Generating PHP Extensions

        @@ -126,7 +126,7 @@ and it doesn't play nicely with package system. We don't recommend this approach, or provide explicit support for it.

        -

        32.1.1 Building a loadable extension

        +

        33.1.1 Building a loadable extension

        @@ -141,7 +141,7 @@ least work for Linux though): gcc -shared example_wrap.o -o example.so

      -

      32.1.2 Using PHP Extensions

      +

      33.1.2 Using PHP Extensions

      @@ -172,7 +172,7 @@ attempts to do the dl() call for you: include("example.php"); -

      32.2 Basic PHP interface

      +

      33.2 Basic PHP interface

      @@ -183,7 +183,7 @@ other symbols unless care is taken to %rename them. At present SWIG doesn't have support for the namespace feature added in PHP 5.3.

      -

      32.2.1 Constants

      +

      33.2.1 Constants

      @@ -260,7 +260,7 @@ is treated as true by the if test, when the value of the intended constant would be treated as false!

      -

      32.2.2 Global Variables

      +

      33.2.2 Global Variables

      @@ -309,7 +309,7 @@ undefined. At this time SWIG does not support custom accessor methods.

      -

      32.2.3 Functions

      +

      33.2.3 Functions

      @@ -362,7 +362,7 @@ print $s; # The value of $s was not changed. --> -

      32.2.4 Overloading

      +

      33.2.4 Overloading

      @@ -418,7 +418,7 @@ taking the integer argument.

      --> -

      32.2.5 Pointers and References

      +

      33.2.5 Pointers and References

      @@ -563,7 +563,7 @@ PHP in a number of ways: by using unset on an existing variable, or assigning NULL to a variable.

      -

      32.2.6 Structures and C++ classes

      +

      33.2.6 Structures and C++ classes

      @@ -624,7 +624,7 @@ Would be used in the following way from PHP5: Member variables and methods are accessed using the -> operator.

      -

      32.2.6.1 Using -noproxy

      +

      33.2.6.1 Using -noproxy

      @@ -650,7 +650,7 @@ Complex_im_set($obj,$d); Complex_im_get($obj); -

      32.2.6.2 Constructors and Destructors

      +

      33.2.6.2 Constructors and Destructors

      @@ -691,7 +691,7 @@ the programmer can either reassign the variable or call unset($v)

      -

      32.2.6.3 Static Member Variables

      +

      33.2.6.3 Static Member Variables

      @@ -734,7 +734,7 @@ Ko::threats(10); echo "There have now been " . Ko::threats() . " threats\n"; -

      32.2.6.4 Static Member Functions

      +

      33.2.6.4 Static Member Functions

      @@ -756,7 +756,7 @@ Ko::threats(); -

      32.2.7 PHP Pragmas, Startup and Shutdown code

      +

      33.2.7 PHP Pragmas, Startup and Shutdown code

      @@ -844,7 +844,7 @@ The %rinit and %rshutdown statements are very similar but inse into the request init (PHP_RINIT_FUNCTION) and request shutdown (PHP_RSHUTDOWN_FUNCTION) code respectively.

      -

      32.3 Cross language polymorphism

      +

      33.3 Cross language polymorphism

      @@ -879,7 +879,7 @@ wrapper functions takes care of all the cross-language method routing transparently.

      -

      32.3.1 Enabling directors

      +

      33.3.1 Enabling directors

      @@ -968,7 +968,7 @@ class MyFoo extends Foo { -

      32.3.2 Director classes

      +

      33.3.2 Director classes

      @@ -1048,7 +1048,7 @@ so there is no need for the extra overhead involved with routing the calls through PHP.

      -

      32.3.3 Ownership and object destruction

      +

      33.3.3 Ownership and object destruction

      @@ -1104,7 +1104,7 @@ In this example, we are assuming that FooContainer will take care of deleting all the Foo pointers it contains at some point.

      -

      32.3.4 Exception unrolling

      +

      33.3.4 Exception unrolling

      @@ -1163,7 +1163,7 @@ Swig::DirectorMethodException is thrown, PHP will register the exception as soon as the C wrapper function returns.

      -

      32.3.5 Overhead and code bloat

      +

      33.3.5 Overhead and code bloat

      @@ -1196,7 +1196,7 @@ optimized by selectively enabling director methods (using the %feature directive) for only those methods that are likely to be extended in PHP.

      -

      32.3.6 Typemaps

      +

      33.3.6 Typemaps

      @@ -1210,7 +1210,7 @@ need to be supported.

      -

      32.3.7 Miscellaneous

      +

      33.3.7 Miscellaneous

      Director typemaps for STL classes are mostly in place, and hence you diff --git a/Doc/Manual/Pike.html b/Doc/Manual/Pike.html index 8c1eb2d36..3ede1a992 100644 --- a/Doc/Manual/Pike.html +++ b/Doc/Manual/Pike.html @@ -6,7 +6,7 @@ -

      33 SWIG and Pike

      +

      34 SWIG and Pike

        @@ -46,10 +46,10 @@ least, make sure you read the "SWIG Basics" chapter.

        -

        33.1 Preliminaries

        +

        34.1 Preliminaries

        -

        33.1.1 Running SWIG

        +

        34.1.1 Running SWIG

        @@ -94,7 +94,7 @@ can use the -o option:

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

        33.1.2 Getting the right header files

        +

        34.1.2 Getting the right header files

        @@ -114,7 +114,7 @@ You're looking for files with the names global.h, program.h and so on.

        -

        33.1.3 Using your module

        +

        34.1.3 Using your module

        @@ -129,10 +129,10 @@ Pike v7.4 release 10 running Hilfe v3.5 (Incremental Pike Frontend) (1) Result: 24

      -

      33.2 Basic C/C++ Mapping

      +

      34.2 Basic C/C++ Mapping

      -

      33.2.1 Modules

      +

      34.2.1 Modules

      @@ -143,7 +143,7 @@ concerned), SWIG's %module directive doesn't really have any significance.

      -

      33.2.2 Functions

      +

      34.2.2 Functions

      @@ -168,7 +168,7 @@ exactly as you'd expect it to: (1) Result: 24 -

      33.2.3 Global variables

      +

      34.2.3 Global variables

      @@ -197,7 +197,7 @@ will result in two functions, Foo_get() and Foo_set(): (3) Result: 3.141590 -

      33.2.4 Constants and enumerated types

      +

      34.2.4 Constants and enumerated types

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

      -

      33.2.5 Constructors and Destructors

      +

      34.2.5 Constructors and Destructors

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

      -

      33.2.6 Static Members

      +

      34.2.6 Static Members

      diff --git a/Doc/Manual/Preprocessor.html b/Doc/Manual/Preprocessor.html index 8fcbe9206..d5c41dde7 100644 --- a/Doc/Manual/Preprocessor.html +++ b/Doc/Manual/Preprocessor.html @@ -6,7 +6,7 @@ -

      7 Preprocessing

      +

      8 Preprocessing

        @@ -37,7 +37,7 @@ However, a number of modifications and enhancements have been made. This chapter describes some of these modifications.

        -

        7.1 File inclusion

        +

        8.1 File inclusion

        @@ -63,7 +63,7 @@ By default, the #include is ignored unless you run SWIG with the is that you often don't want SWIG to try and wrap everything included in standard header system headers and auxiliary files. -

        7.2 File imports

        +

        8.2 File imports

        @@ -92,7 +92,7 @@ The -importall directive tells SWIG to follow all #include sta as imports. This might be useful if you want to extract type definitions from system header files without generating any wrappers. -

        7.3 Conditional Compilation

        +

        8.3 Conditional Compilation

        @@ -152,7 +152,7 @@ SWIG (except for the symbol `SWIG' which is only defined within the SWIG compiler).

        -

        7.4 Macro Expansion

        +

        8.4 Macro Expansion

        @@ -207,7 +207,7 @@ like #x. This is a non-standard SWIG extension.

      -

      7.5 SWIG Macros

      +

      8.5 SWIG Macros

      @@ -253,7 +253,7 @@ many of SWIG's advanced features and libraries are built using this mechanism (s support).

      -

      7.6 C99 and GNU Extensions

      +

      8.6 C99 and GNU Extensions

      @@ -309,14 +309,14 @@ interface building. However, they are used internally to implement a number of SWIG directives and are provided to make SWIG more compatible with C99 code.

      -

      7.7 Preprocessing and delimiters

      +

      8.7 Preprocessing and delimiters

      The preprocessor handles { }, " " and %{ %} delimiters differently.

      -

      7.7.1 Preprocessing and %{ ... %} & " ... " delimiters

      +

      8.7.1 Preprocessing and %{ ... %} & " ... " delimiters

      @@ -341,7 +341,7 @@ the contents of the %{ ... %} block are copied without modification to the output (including all preprocessor directives).

      -

      7.7.2 Preprocessing and { ... } delimiters

      +

      8.7.2 Preprocessing and { ... } delimiters

      @@ -383,7 +383,7 @@ to actually go into the wrapper file, prefix the preprocessor directives with % and leave the preprocessor directive in the code.

      -

      7.8 Preprocessor and Typemaps

      +

      8.8 Preprocessor and Typemaps

      @@ -454,7 +454,7 @@ would generate

      -

      7.9 Viewing preprocessor output

      +

      8.9 Viewing preprocessor output

      @@ -464,7 +464,7 @@ Instead the results after the preprocessor has run are displayed. This might be useful as an aid to debugging and viewing the results of macro expansions.

      -

      7.10 The #error and #warning directives

      +

      8.10 The #error and #warning directives

      diff --git a/Doc/Manual/Python.html b/Doc/Manual/Python.html index 522412fc8..dcfd7427e 100644 --- a/Doc/Manual/Python.html +++ b/Doc/Manual/Python.html @@ -6,7 +6,7 @@ -

      34 SWIG and Python

      +

      35 SWIG and Python

        @@ -106,10 +106,10 @@
    • Python Packages
    • Python 3 Support
        @@ -141,7 +141,7 @@ very least, make sure you read the "SWIG Basics" chapter.

        -

        34.1 Overview

        +

        35.1 Overview

        @@ -168,10 +168,10 @@ described followed by a discussion of low-level implementation details.

        -

        34.2 Preliminaries

        +

        35.2 Preliminaries

        -

        34.2.1 Running SWIG

        +

        35.2.1 Running SWIG

        @@ -269,7 +269,7 @@ The following sections have further practical examples and details on how you might go about compiling and using the generated files.

        -

        34.2.2 Using distutils

        +

        35.2.2 Using distutils

        @@ -361,7 +361,7 @@ This same approach works on all platforms if the appropriate compiler is install can even build extensions to the standard Windows Python using MingGW)

        -

        34.2.3 Hand compiling a dynamic module

        +

        35.2.3 Hand compiling a dynamic module

        @@ -409,7 +409,7 @@ module actually consists of two files; socket.py and

        -

        34.2.4 Static linking

        +

        35.2.4 Static linking

        @@ -488,7 +488,7 @@ If using static linking, you might want to rely on a different approach (perhaps using distutils).

        -

        34.2.5 Using your module

        +

        35.2.5 Using your module

        @@ -645,7 +645,7 @@ system configuration (this requires root access and you will need to read the man pages).

        -

        34.2.6 Compilation of C++ extensions

        +

        35.2.6 Compilation of C++ extensions

        @@ -737,7 +737,7 @@ erratic program behavior. If working with lots of software components, you might want to investigate using a more formal standard such as COM.

        -

        34.2.7 Compiling for 64-bit platforms

        +

        35.2.7 Compiling for 64-bit platforms

        @@ -774,7 +774,7 @@ and -m64 allow you to choose the desired binary format for your python extension.

        -

        34.2.8 Building Python Extensions under Windows

        +

        35.2.8 Building Python Extensions under Windows

        @@ -903,7 +903,7 @@ SWIG Wiki.

        -

        34.3 A tour of basic C/C++ wrapping

        +

        35.3 A tour of basic C/C++ wrapping

        @@ -912,7 +912,7 @@ to your C/C++ code. Functions are wrapped as functions, classes are wrapped as This section briefly covers the essential aspects of this wrapping.

        -

        34.3.1 Modules

        +

        35.3.1 Modules

        @@ -925,7 +925,7 @@ module name, make sure you don't use the same name as a built-in Python command or standard module name.

        -

        34.3.2 Functions

        +

        35.3.2 Functions

        @@ -949,7 +949,7 @@ like you think it does: >>>

    • -

      34.3.3 Global variables

      +

      35.3.3 Global variables

      @@ -1087,7 +1087,7 @@ that starts with a leading underscore. SWIG does not create cvar if there are no global variables in a module.

      -

      34.3.4 Constants and enums

      +

      35.3.4 Constants and enums

      @@ -1127,7 +1127,7 @@ other object. Unfortunately, there is no easy way for SWIG to generate code that prevents this. You will just have to be careful.

      -

      34.3.5 Pointers

      +

      35.3.5 Pointers

      @@ -1268,7 +1268,7 @@ C-style cast may return a bogus result whereas as the C++-style cast will return None if the conversion can't be performed.

      -

      34.3.6 Structures

      +

      35.3.6 Structures

      @@ -1457,7 +1457,7 @@ everything works just like you would expect. For example: -

      34.3.7 C++ classes

      +

      35.3.7 C++ classes

      @@ -1546,7 +1546,7 @@ they are accessed through cvar like this: -

      34.3.8 C++ inheritance

      +

      35.3.8 C++ inheritance

      @@ -1601,7 +1601,7 @@ then the function spam() accepts Foo * or a pointer to any cla It is safe to use multiple inheritance with SWIG.

      -

      34.3.9 Pointers, references, values, and arrays

      +

      35.3.9 Pointers, references, values, and arrays

      @@ -1662,7 +1662,7 @@ treated as a returning value, and it will follow the same allocation/deallocation process.

      -

      34.3.10 C++ overloaded functions

      +

      35.3.10 C++ overloaded functions

      @@ -1785,7 +1785,7 @@ first declaration takes precedence. Please refer to the "SWIG and C++" chapter for more information about overloading.

      -

      34.3.11 C++ operators

      +

      35.3.11 C++ operators

      @@ -1874,7 +1874,7 @@ Also, be aware that certain operators don't map cleanly to Python. For instance overloaded assignment operators don't map to Python semantics and will be ignored.

      -

      34.3.12 C++ namespaces

      +

      35.3.12 C++ namespaces

      @@ -1941,7 +1941,7 @@ utilizes thousands of small deeply nested namespaces each with identical symbol names, well, then you get what you deserve.

      -

      34.3.13 C++ templates

      +

      35.3.13 C++ templates

      @@ -1995,7 +1995,7 @@ Some more complicated examples will appear later.

      -

      34.3.14 C++ Smart Pointers

      +

      35.3.14 C++ Smart Pointers

      @@ -2079,7 +2079,7 @@ simply use the __deref__() method. For example: -

      34.3.15 C++ reference counted objects

      +

      35.3.15 C++ reference counted objects

      @@ -2088,7 +2088,7 @@ Python examples of memory management using referencing counting.

      -

      34.4 Further details on the Python class interface

      +

      35.4 Further details on the Python class interface

      @@ -2111,7 +2111,7 @@ the -builtin option are in the Built-in section.

      -

      34.4.1 Proxy classes

      +

      35.4.1 Proxy classes

      @@ -2200,7 +2200,7 @@ you can attach new Python methods to the class and you can even inherit from it by Python built-in types until Python 2.2).

      -

      34.4.2 Built-in Types

      +

      35.4.2 Built-in Types

      @@ -2244,7 +2244,7 @@ please refer to the python documentation:

      http://docs.python.org/extending/newtypes.html

      -

      34.4.2.1 Limitations

      +

      35.4.2.1 Limitations

      Use of the -builtin option implies a couple of limitations: @@ -2412,7 +2412,7 @@ assert(issubclass(B.Derived, A.Base)) -

      34.4.2.2 Operator overloads -- use them!

      +

      35.4.2.2 Operator overloads -- use them!

      The entire justification for the -builtin option is improved @@ -2513,7 +2513,7 @@ structs.

      -

      34.4.3 Memory management

      +

      35.4.3 Memory management

      NOTE: Although this section refers to proxy objects, everything here also applies @@ -2708,7 +2708,7 @@ It is also possible to deal with situations like this using typemaps--an advanced topic discussed later.

      -

      34.4.4 Python 2.2 and classic classes

      +

      35.4.4 Python 2.2 and classic classes

      @@ -2745,7 +2745,7 @@ class itself. In Python-2.1 and earlier, they have to be accessed as a global function or through an instance (see the earlier section).

      -

      34.5 Cross language polymorphism

      +

      35.5 Cross language polymorphism

      @@ -2779,7 +2779,7 @@ proxy classes, director classes, and C wrapper functions takes care of all the cross-language method routing transparently.

      -

      34.5.1 Enabling directors

      +

      35.5.1 Enabling directors

      @@ -2869,7 +2869,7 @@ class MyFoo(mymodule.Foo): -

      34.5.2 Director classes

      +

      35.5.2 Director classes

      @@ -2951,7 +2951,7 @@ so there is no need for the extra overhead involved with routing the calls through Python.

      -

      34.5.3 Ownership and object destruction

      +

      35.5.3 Ownership and object destruction

      @@ -3018,7 +3018,7 @@ deleting all the Foo pointers it contains at some point. Note that no hard references to the Foo objects remain in Python.

      -

      34.5.4 Exception unrolling

      +

      35.5.4 Exception unrolling

      @@ -3077,7 +3077,7 @@ Swig::DirectorMethodException is thrown, Python will register the exception as soon as the C wrapper function returns.

      -

      34.5.5 Overhead and code bloat

      +

      35.5.5 Overhead and code bloat

      @@ -3111,7 +3111,7 @@ directive) for only those methods that are likely to be extended in Python.

      -

      34.5.6 Typemaps

      +

      35.5.6 Typemaps

      @@ -3125,7 +3125,7 @@ need to be supported.

      -

      34.5.7 Miscellaneous

      +

      35.5.7 Miscellaneous

      @@ -3172,7 +3172,7 @@ methods that return const references.

      -

      34.6 Common customization features

      +

      35.6 Common customization features

      @@ -3185,7 +3185,7 @@ This section describes some common SWIG features that are used to improve your the interface to an extension module.

      -

      34.6.1 C/C++ helper functions

      +

      35.6.1 C/C++ helper functions

      @@ -3266,7 +3266,7 @@ hard to implement. It is possible to clean this up using Python code, typemaps, customization features as covered in later sections.

      -

      34.6.2 Adding additional Python code

      +

      35.6.2 Adding additional Python code

      @@ -3494,7 +3494,7 @@ The same applies for overloaded constructors.

      -

      34.6.3 Class extension with %extend

      +

      35.6.3 Class extension with %extend

      @@ -3583,7 +3583,7 @@ Vector(12,14,16) in any way---the extensions only show up in the Python interface.

      -

      34.6.4 Exception handling with %exception

      +

      35.6.4 Exception handling with %exception

      @@ -3709,7 +3709,7 @@ The language-independent exception.i library file can also be used to raise exceptions. See the SWIG Library chapter.

      -

      34.7 Tips and techniques

      +

      35.7 Tips and techniques

      @@ -3719,7 +3719,7 @@ strings, binary data, and arrays. This chapter discusses the common techniques solving these problems.

      -

      34.7.1 Input and output parameters

      +

      35.7.1 Input and output parameters

      @@ -3932,7 +3932,7 @@ void foo(Bar *OUTPUT); may not have the intended effect since typemaps.i does not define an OUTPUT rule for Bar.

      -

      34.7.2 Simple pointers

      +

      35.7.2 Simple pointers

      @@ -4001,7 +4001,7 @@ If you replace %pointer_functions() by %pointer_class(type,name)SWIG Library chapter for further details.

      -

      34.7.3 Unbounded C Arrays

      +

      35.7.3 Unbounded C Arrays

      @@ -4063,7 +4063,7 @@ well suited for applications in which you need to create buffers, package binary data, etc.

      -

      34.7.4 String handling

      +

      35.7.4 String handling

      @@ -4132,7 +4132,7 @@ If you need to return binary data, you might use the also be used to extra binary data from arbitrary pointers.

      -

      34.8 Typemaps

      +

      35.8 Typemaps

      @@ -4149,7 +4149,7 @@ Typemaps are only used if you want to change some aspect of the primitive C-Python interface or if you want to elevate your guru status.

      -

      34.8.1 What is a typemap?

      +

      35.8.1 What is a typemap?

      @@ -4265,7 +4265,7 @@ parameter is omitted): -

      34.8.2 Python typemaps

      +

      35.8.2 Python typemaps

      @@ -4306,7 +4306,7 @@ a look at the SWIG library version 1.3.20 or so.

      -

      34.8.3 Typemap variables

      +

      35.8.3 Typemap variables

      @@ -4377,7 +4377,7 @@ properly assigned. The Python name of the wrapper function being created. -

      34.8.4 Useful Python Functions

      +

      35.8.4 Useful Python Functions

      @@ -4505,7 +4505,7 @@ write me -

      34.9 Typemap Examples

      +

      35.9 Typemap Examples

      @@ -4514,7 +4514,7 @@ might look at the files "python.swg" and "typemaps.i" in the SWIG library.

      -

      34.9.1 Converting Python list to a char **

      +

      35.9.1 Converting Python list to a char **

      @@ -4594,7 +4594,7 @@ memory allocation is used to allocate memory for the array, the the C function.

      -

      34.9.2 Expanding a Python object into multiple arguments

      +

      35.9.2 Expanding a Python object into multiple arguments

      @@ -4673,7 +4673,7 @@ to supply the argument count. This is automatically set by the typemap code. F -

      34.9.3 Using typemaps to return arguments

      +

      35.9.3 Using typemaps to return arguments

      @@ -4761,7 +4761,7 @@ function can now be used as follows: >>> -

      34.9.4 Mapping Python tuples into small arrays

      +

      35.9.4 Mapping Python tuples into small arrays

      @@ -4810,7 +4810,7 @@ array, such an approach would not be recommended for huge arrays, but for small structures, this approach works fine.

      -

      34.9.5 Mapping sequences to C arrays

      +

      35.9.5 Mapping sequences to C arrays

      @@ -4899,7 +4899,7 @@ static int convert_darray(PyObject *input, double *ptr, int size) { -

      34.9.6 Pointer handling

      +

      35.9.6 Pointer handling

      @@ -4996,7 +4996,7 @@ class object (if applicable). -

      34.10 Docstring Features

      +

      35.10 Docstring Features

      @@ -5024,7 +5024,7 @@ of your users much simpler.

      -

      34.10.1 Module docstring

      +

      35.10.1 Module docstring

      @@ -5058,7 +5058,7 @@ layout of controls on a panel, etc. to be loaded from an XML file." -

      34.10.2 %feature("autodoc")

      +

      35.10.2 %feature("autodoc")

      @@ -5086,7 +5086,7 @@ four levels for autodoc controlled by the value given to the feature, %feature("autodoc", "level"). The four values for level are covered in the following sub-sections. -

      34.10.2.1 %feature("autodoc", "0")

      +

      35.10.2.1 %feature("autodoc", "0")

      @@ -5115,7 +5115,7 @@ def function_name(*args, **kwargs): -

      34.10.2.2 %feature("autodoc", "1")

      +

      35.10.2.2 %feature("autodoc", "1")

      @@ -5140,7 +5140,7 @@ def function_name(*args, **kwargs): -

      34.10.2.3 %feature("autodoc", "2")

      +

      35.10.2.3 %feature("autodoc", "2")

      @@ -5200,7 +5200,7 @@ def function_name(*args, **kwargs): -

      34.10.2.4 %feature("autodoc", "3")

      +

      35.10.2.4 %feature("autodoc", "3")

      @@ -5225,7 +5225,7 @@ def function_name(*args, **kwargs): -

      34.10.2.5 %feature("autodoc", "docstring")

      +

      35.10.2.5 %feature("autodoc", "docstring")

      @@ -5244,7 +5244,7 @@ void GetPosition(int* OUTPUT, int* OUTPUT); -

      34.10.3 %feature("docstring")

      +

      35.10.3 %feature("docstring")

      @@ -5276,7 +5276,8 @@ with more than one line. -

      34.11 Python Packages

      +

      35.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, @@ -5333,7 +5334,8 @@ users may need to use special features such as the package option in th %module directive or import related command line options. These are explained in the following sections.

      -

      34.11.1 Setting the Python package

      +

      35.11.1 Setting the Python package

      +

      Using the package option in the %module directive allows you @@ -5386,7 +5388,8 @@ pkg1/pkg2/_foo.so # (shared library built from C/C++ code generated by SWI -

      34.11.2 Absolute and relative imports

      +

      35.11.2 Absolute and relative imports

      +

      Suppose, we have the following hierarchy of files:

      @@ -5524,7 +5527,8 @@ 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

      +

      35.11.3 Enforcing absolute import semantics

      +

      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 @@ -5560,7 +5564,8 @@ from __future__ import absolute_import -

      34.11.4 Importing from __init__.py

      +

      35.11.4 Importing from __init__.py

      +

      Imports in __init__.py are handy when you want to populate a package's namespace with names imported from other modules. In SWIG based @@ -5670,7 +5675,7 @@ effect (note, that the Python 2 case also needs the -relativeimport workaround).

      -

      34.12 Python 3 Support

      +

      35.12 Python 3 Support

      @@ -5697,7 +5702,7 @@ The following are Python 3.0 new features that are currently supported by SWIG.

      -

      34.12.1 Function annotation

      +

      35.12.1 Function annotation

      @@ -5730,7 +5735,7 @@ For detailed usage of function annotation, see PEP 3107.

      -

      34.12.2 Buffer interface

      +

      35.12.2 Buffer interface

      @@ -5882,7 +5887,7 @@ modify the buffer. -

      34.12.3 Abstract base classes

      +

      35.12.3 Abstract base classes

      diff --git a/Doc/Manual/R.html b/Doc/Manual/R.html index ceea32146..ce9523ced 100644 --- a/Doc/Manual/R.html +++ b/Doc/Manual/R.html @@ -6,7 +6,7 @@ -

      35 SWIG and R

      +

      36 SWIG and R

        @@ -33,7 +33,7 @@ compile and run an R interface to QuantLib running on Mandriva Linux with gcc. The R bindings also work on Microsoft Windows using Visual C++.

        -

        35.1 Bugs

        +

        36.1 Bugs

        @@ -45,7 +45,7 @@ Currently the following features are not implemented or broken:

      • C Array wrappings
      -

      35.2 Using R and SWIG

      +

      36.2 Using R and SWIG

      @@ -119,7 +119,7 @@ Without it, inheritance of wrapped objects may fail. These two files can be loaded in any order

      -

      35.3 Precompiling large R files

      +

      36.3 Precompiling large R files

      In cases where the R file is large, one make save a lot of loading @@ -137,7 +137,7 @@ will save a large amount of loading time. -

      35.4 General policy

      +

      36.4 General policy

      @@ -146,7 +146,7 @@ wrapping over the underlying functions and rely on the R type system to provide R syntax.

      -

      35.5 Language conventions

      +

      36.5 Language conventions

      @@ -155,7 +155,7 @@ and [ are overloaded to allow for R syntax (one based indices and slices)

      -

      35.6 C++ classes

      +

      36.6 C++ classes

      @@ -167,7 +167,7 @@ keep track of the pointer object which removes the necessity for a lot of the proxy class baggage you see in other languages.

      -

      35.7 Enumerations

      +

      36.7 Enumerations

      diff --git a/Doc/Manual/Ruby.html b/Doc/Manual/Ruby.html index 6ff98ca23..3fc45834d 100644 --- a/Doc/Manual/Ruby.html +++ b/Doc/Manual/Ruby.html @@ -7,7 +7,7 @@ -

      36 SWIG and Ruby

      +

      37 SWIG and Ruby

        @@ -144,7 +144,7 @@

        This chapter describes SWIG's support of Ruby.

        -

        36.1 Preliminaries

        +

        37.1 Preliminaries

        SWIG 1.3 is known to work with Ruby versions 1.6 and later. @@ -159,7 +159,7 @@ read the "SWIG Basics" chapter. It is also assumed that the reader has a basic understanding of Ruby.

        -

        36.1.1 Running SWIG

        +

        37.1.1 Running SWIG

        To build a Ruby module, run SWIG using the -ruby @@ -183,7 +183,7 @@ if compiling a C++ extension) that contains all of the code needed to build a Ruby extension module. To finish building the module, you need to compile this file and link it with the rest of your program.

        -

        36.1.2 Getting the right header files

        +

        37.1.2 Getting the right header files

        In order to compile the wrapper code, the compiler needs the ruby.h @@ -206,7 +206,7 @@ installed, you can run Ruby to find out. For example:

      -

      36.1.3 Compiling a dynamic module

      +

      37.1.3 Compiling a dynamic module

      Ruby extension modules are typically compiled into shared @@ -279,7 +279,7 @@ manual pages for your compiler and linker to determine the correct set of options. You might also check the SWIG Wiki for additional information.

      -

      36.1.4 Using your module

      +

      37.1.4 Using your module

      Ruby module names must be capitalized, @@ -309,7 +309,7 @@ begins with:

      will result in an extension module using the feature name "example" and Ruby module name "Example".

      -

      36.1.5 Static linking

      +

      37.1.5 Static linking

      An alternative approach to dynamic linking is to rebuild the @@ -324,7 +324,7 @@ finding the Ruby source, adding an entry to the ext/Setup file, adding your directory to the list of extensions in the file, and finally rebuilding Ruby.

      -

      36.1.6 Compilation of C++ extensions

      +

      37.1.6 Compilation of C++ extensions

      On most machines, C++ extension modules should be linked @@ -356,7 +356,7 @@ $libs = append_library($libs, "supc++") create_makefile('example')

      -

      36.2 Building Ruby Extensions under Windows 95/NT

      +

      37.2 Building Ruby Extensions under Windows 95/NT

      Building a SWIG extension to Ruby under Windows 95/NT is @@ -381,7 +381,7 @@ order to build extensions, you may need to download the source distribution to the Ruby package, as you will need the Ruby header files.

      -

      36.2.1 Running SWIG from Developer Studio

      +

      37.2.1 Running SWIG from Developer Studio

      If you are developing your application within Microsoft @@ -445,13 +445,13 @@ Foo = 3.0 -

      36.3 The Ruby-to-C/C++ Mapping

      +

      37.3 The Ruby-to-C/C++ Mapping

      This section describes the basics of how SWIG maps C or C++ declarations in your SWIG interface files to Ruby constructs.

      -

      36.3.1 Modules

      +

      37.3.1 Modules

      The SWIG %module directive specifies @@ -523,7 +523,7 @@ option to wrap everything into the global module, take care that the names of your constants, classes and methods don't conflict with any of Ruby's built-in names.

      -

      36.3.2 Functions

      +

      37.3.2 Functions

      Global functions are wrapped as Ruby module methods. For @@ -557,7 +557,7 @@ irb(main):002:0> Example.fact(4) 24 -

      36.3.3 Variable Linking

      +

      37.3.3 Variable Linking

      C/C++ global variables are wrapped as a pair of singleton @@ -619,7 +619,7 @@ directive. For example:

      effect until it is explicitly disabled using %mutable.

      -

      36.3.4 Constants

      +

      37.3.4 Constants

      C/C++ constants are wrapped as module constants initialized @@ -647,7 +647,7 @@ irb(main):002:0> Example::PI 3.14159 -

      36.3.5 Pointers

      +

      37.3.5 Pointers

      "Opaque" pointers to arbitrary C/C++ types (i.e. types that @@ -671,7 +671,7 @@ returns an instance of an internally generated Ruby class:

      A NULL pointer is always represented by the Ruby nil object.

      -

      36.3.6 Structures

      +

      37.3.6 Structures

      C/C++ structs are wrapped as Ruby classes, with accessor @@ -776,7 +776,7 @@ void Bar_f_set(Bar *b, Foo *val) { } -

      36.3.7 C++ classes

      +

      37.3.7 C++ classes

      Like structs, C++ classes are wrapped by creating a new Ruby @@ -831,7 +831,7 @@ Ale 3 -

      36.3.8 C++ Inheritance

      +

      37.3.8 C++ Inheritance

      The SWIG type-checker is fully aware of C++ inheritance. @@ -984,7 +984,7 @@ inherit from both Base1 and Base2 (i.e. they exhibit "Duck Typing").

      -

      36.3.9 C++ Overloaded Functions

      +

      37.3.9 C++ Overloaded Functions

      C++ overloaded functions, methods, and constructors are @@ -1074,7 +1074,7 @@ arises--in this case, the first declaration takes precedence.

      Please refer to the "SWIG and C++" chapter for more information about overloading.

      -

      36.3.10 C++ Operators

      +

      37.3.10 C++ Operators

      For the most part, overloaded operators are handled @@ -1116,7 +1116,7 @@ c = Example.add_complex(a, b) is discussed in the section on operator overloading.

      -

      36.3.11 C++ namespaces

      +

      37.3.11 C++ namespaces

      SWIG is aware of C++ namespaces, but namespace names do not @@ -1173,7 +1173,7 @@ and create extension modules for each namespace separately. If your program utilizes thousands of small deeply nested namespaces each with identical symbol names, well, then you get what you deserve.

      -

      36.3.12 C++ templates

      +

      37.3.12 C++ templates

      C++ templates don't present a huge problem for SWIG. However, @@ -1215,7 +1215,7 @@ irb(main):004:0> p.second 4 -

      36.3.13 C++ Standard Template Library (STL)

      +

      37.3.13 C++ Standard Template Library (STL)

      On a related note, the standard SWIG library contains a @@ -1308,7 +1308,7 @@ puts v shown in these examples. More details can be found in the SWIG and C++ chapter.

      -

      36.3.14 C++ STL Functors

      +

      37.3.14 C++ STL Functors

      Some containers in the STL allow you to modify their default @@ -1369,7 +1369,7 @@ b -

      36.3.15 C++ STL Iterators

      +

      37.3.15 C++ STL Iterators

      The STL is well known for the use of iterators. There @@ -1452,7 +1452,7 @@ i

      If you'd rather have STL classes without any iterators, you should define -DSWIG_NO_EXPORT_ITERATOR_METHODS when running swig.

      -

      36.3.16 C++ Smart Pointers

      +

      37.3.16 C++ Smart Pointers

      In certain C++ programs, it is common to use classes that @@ -1517,7 +1517,7 @@ method. For example:

      irb(main):004:0> f = p.__deref__() # Returns underlying Foo *
      -

      36.3.17 Cross-Language Polymorphism

      +

      37.3.17 Cross-Language Polymorphism

      SWIG's Ruby module supports cross-language polymorphism @@ -1526,7 +1526,7 @@ module. Rather than duplicate the information presented in the 36.3.17.1 Exception Unrolling +

      37.3.17.1 Exception Unrolling

      Whenever a C++ director class routes one of its virtual @@ -1549,7 +1549,7 @@ method is "wrapped" using the rb_rescue2() function from Ruby's C API. If any Ruby exception is raised, it will be caught here and a C++ exception is raised in its place.

      -

      36.4 Naming

      +

      37.4 Naming

      Ruby has several common naming conventions. Constants are @@ -1587,7 +1587,7 @@ generated by SWIG, it is turned off by default in SWIG 1.3.28. However, it is planned to become the default option in future releases.

      -

      36.4.1 Defining Aliases

      +

      37.4.1 Defining Aliases

      It's a fairly common practice in the Ruby built-ins and @@ -1657,7 +1657,7 @@ matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

      -

      36.4.2 Predicate Methods

      +

      37.4.2 Predicate Methods

      Ruby methods that return a boolean value and end in a @@ -1706,7 +1706,7 @@ using SWIG's "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

      -

      36.4.3 Bang Methods

      +

      37.4.3 Bang Methods

      Ruby methods that modify an object in-place and end in an @@ -1738,7 +1738,7 @@ using SWIG's "features" mechanism and so the same name matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

      -

      36.4.4 Getters and Setters

      +

      37.4.4 Getters and Setters

      Often times a C++ library will expose properties through @@ -1773,7 +1773,7 @@ irb(main):003:0> puts foo.value %rename("value=") Foo::setValue(int value); -

      36.5 Input and output parameters

      +

      37.5 Input and output parameters

      A common problem in some C programs is handling parameters @@ -1912,10 +1912,10 @@ void get_dimensions(Matrix *m, int *rows, int*columns);

      r, c = Example.get_dimensions(m)
      -

      36.6 Exception handling

      +

      37.6 Exception handling

      -

      36.6.1 Using the %exception directive

      +

      37.6.1 Using the %exception directive

      The SWIG %exception directive can be @@ -2024,7 +2024,7 @@ methods and functions named getitem and setitem. limited to C++ exception handling. See the chapter on Customization Features for more examples.

      -

      36.6.2 Handling Ruby Blocks

      +

      37.6.2 Handling Ruby Blocks

      One of the highlights of Ruby and most of its standard library @@ -2091,7 +2091,7 @@ a special in typemap, like:

      For more information on typemaps, see Typemaps.

      -

      36.6.3 Raising exceptions

      +

      37.6.3 Raising exceptions

      There are three ways to raise exceptions from C++ code to @@ -2248,7 +2248,7 @@ function. The first argument passed to rb_raise() is the exception type. You can raise a custom exception type or one of the built-in Ruby exception types.

      -

      36.6.4 Exception classes

      +

      37.6.4 Exception classes

      Starting with SWIG 1.3.28, the Ruby module supports the %exceptionclass @@ -2285,7 +2285,7 @@ end

      For another example look at swig/Examples/ruby/exception_class.

      -

      36.7 Typemaps

      +

      37.7 Typemaps

      This section describes how you can modify SWIG's default @@ -2300,7 +2300,7 @@ a required part of using SWIG---the default wrapping behavior is enough in most cases. Typemaps are only used if you want to change some aspect of the primitive C-Ruby interface.

      -

      36.7.1 What is a typemap?

      +

      37.7.1 What is a typemap?

      A typemap is nothing more than a code generation rule that is @@ -2457,7 +2457,7 @@ to be used as follows (notice how the length parameter is omitted):

      2 -

      36.7.2 Typemap scope

      +

      37.7.2 Typemap scope

      Once defined, a typemap remains in effect for all of the @@ -2503,7 +2503,7 @@ where the class itself is defined. For example:

      }; -

      36.7.3 Copying a typemap

      +

      37.7.3 Copying a typemap

      A typemap is copied by using assignment. For example:

      @@ -2545,7 +2545,7 @@ rules as for %apply (char *buf, int len) { (char *buffer, int size) }; // Multiple arguments -

      36.7.4 Deleting a typemap

      +

      37.7.4 Deleting a typemap

      A typemap can be deleted by simply defining no code. For @@ -2570,7 +2570,7 @@ defined by typemaps, clearing a fundamental type like int will make that type unusable unless you also define a new set of typemaps immediately after the clear operation.

      -

      36.7.5 Placement of typemaps

      +

      37.7.5 Placement of typemaps

      Typemap declarations can be declared in the global scope, @@ -2641,13 +2641,13 @@ In this example, this is done using the class declaration class string .

      -

      36.7.6 Ruby typemaps

      +

      37.7.6 Ruby typemaps

      The following list details all of the typemap methods that can be used by the Ruby module:

      -

      36.7.6.1 "in" typemap

      +

      37.7.6.1 "in" typemap

      Converts Ruby objects to input @@ -2714,7 +2714,7 @@ arguments to be specified. For example:

      At this time, only zero or one arguments may be converted.

      -

      36.7.6.2 "typecheck" typemap

      +

      37.7.6.2 "typecheck" typemap

      The "typecheck" typemap is used to support overloaded @@ -2736,7 +2736,7 @@ program uses overloaded methods, you should also define a collection of "typecheck" typemaps. More details about this follow in a later section on "Typemaps and Overloading."

      -

      36.7.6.3 "out" typemap

      +

      37.7.6.3 "out" typemap

      Converts return value of a C function @@ -2787,7 +2787,7 @@ version of the C datatype matched by the typemap.

      -

      36.7.6.4 "arginit" typemap

      +

      37.7.6.4 "arginit" typemap

      The "arginit" typemap is used to set the initial value of a @@ -2802,7 +2802,7 @@ applications. For example:

      } -

      36.7.6.5 "default" typemap

      +

      37.7.6.5 "default" typemap

      The "default" typemap is used to turn an argument into a @@ -2827,7 +2827,7 @@ arguments that follow must have default values. See the 36.7.6.6 "check" typemap +

      37.7.6.6 "check" typemap

      The "check" typemap is used to supply value checking code @@ -2842,7 +2842,7 @@ arguments have been converted. For example:

      } -

      36.7.6.7 "argout" typemap

      +

      37.7.6.7 "argout" typemap

      The "argout" typemap is used to return values from arguments. @@ -2896,7 +2896,7 @@ some function like SWIG_Ruby_AppendOutput.

      See the typemaps.i library for examples.

      -

      36.7.6.8 "freearg" typemap

      +

      37.7.6.8 "freearg" typemap

      The "freearg" typemap is used to cleanup argument data. It is @@ -2923,7 +2923,7 @@ This code is also placed into a special variable $cleanup that may be used in other typemaps whenever a wrapper function needs to abort prematurely.

      -

      36.7.6.9 "newfree" typemap

      +

      37.7.6.9 "newfree" typemap

      The "newfree" typemap is used in conjunction with the %newobject @@ -2947,7 +2947,7 @@ string *foo();

      See Object ownership and %newobject for further details.

      -

      36.7.6.10 "memberin" typemap

      +

      37.7.6.10 "memberin" typemap

      The "memberin" typemap is used to copy data from an @@ -2965,21 +2965,21 @@ example:

      already provides a default implementation for arrays, strings, and other objects.

      -

      36.7.6.11 "varin" typemap

      +

      37.7.6.11 "varin" typemap

      The "varin" typemap is used to convert objects in the target language to C for the purposes of assigning to a C/C++ global variable. This is implementation specific.

      -

      36.7.6.12 "varout" typemap

      +

      37.7.6.12 "varout" typemap

      The "varout" typemap is used to convert a C/C++ object to an object in the target language when reading a C/C++ global variable. This is implementation specific.

      -

      36.7.6.13 "throws" typemap

      +

      37.7.6.13 "throws" typemap

      The "throws" typemap is only used when SWIG parses a C++ @@ -3020,7 +3020,7 @@ specification yet they do throw exceptions, SWIG cannot know how to deal with them. For a neat way to handle these, see the Exception handling with %exception section.

      -

      36.7.6.14 directorin typemap

      +

      37.7.6.14 directorin typemap

      Converts C++ objects in director @@ -3079,7 +3079,7 @@ referring to the class itself. -

      36.7.6.15 directorout typemap

      +

      37.7.6.15 directorout typemap

      Converts Ruby objects in director @@ -3152,7 +3152,7 @@ exception.

      -

      36.7.6.16 directorargout typemap

      +

      37.7.6.16 directorargout typemap

      Output argument processing in director @@ -3210,19 +3210,19 @@ referring to the instance of the class itself -

      36.7.6.17 ret typemap

      +

      37.7.6.17 ret typemap

      Cleanup of function return values

      -

      36.7.6.18 globalin typemap

      +

      37.7.6.18 globalin typemap

      Setting of C global variables

      -

      36.7.7 Typemap variables

      +

      37.7.7 Typemap variables

      @@ -3272,7 +3272,7 @@ so that their values can be properly assigned.

      The Ruby name of the wrapper function being created.
      -

      36.7.8 Useful Functions

      +

      37.7.8 Useful Functions

      When you write a typemap, you usually have to work directly @@ -3287,7 +3287,7 @@ stick to the swig functions instead of the native Ruby functions. That should help you avoid having to rewrite a lot of typemaps across multiple languages.

      -

      36.7.8.1 C Datatypes to Ruby Objects

      +

      37.7.8.1 C Datatypes to Ruby Objects

      @@ -3329,7 +3329,7 @@ SWIG_From_float(float)
      -

      36.7.8.2 Ruby Objects to C Datatypes

      +

      37.7.8.2 Ruby Objects to C Datatypes

      Here, while the Ruby versions return the value directly, the SWIG @@ -3397,7 +3397,7 @@ versions do not, but return a status value to indicate success (SWIG_OK -

      36.7.8.3 Macros for VALUE

      +

      37.7.8.3 Macros for VALUE

      RSTRING_LEN(str)

      @@ -3420,7 +3420,7 @@ versions do not, but return a status value to indicate success (SWIG_OK
      pointer to array storage
      -

      36.7.8.4 Exceptions

      +

      37.7.8.4 Exceptions

      void rb_raise(VALUE exception, const char *fmt, @@ -3499,7 +3499,7 @@ message to standard error if Ruby was invoked with the -w flag. The given format string fmt and remaining arguments are interpreted as with printf(). -

      36.7.8.5 Iterators

      +

      37.7.8.5 Iterators

      void rb_iter_break()

      @@ -3545,14 +3545,14 @@ VALUE), VALUE value)

      Equivalent to Ruby's throw.
      -

      36.7.9 Typemap Examples

      +

      37.7.9 Typemap Examples

      This section includes a few examples of typemaps. For more examples, you might look at the examples in the Example/ruby directory.

      -

      36.7.10 Converting a Ruby array to a char **

      +

      37.7.10 Converting a Ruby array to a char **

      A common problem in many C programs is the processing of @@ -3617,7 +3617,7 @@ array. Since dynamic memory allocation is used to allocate memory for the array, the "freearg" typemap is used to later release this memory after the execution of the C function.

      -

      36.7.11 Collecting arguments in a hash

      +

      37.7.11 Collecting arguments in a hash

      Ruby's solution to the "keyword arguments" capability of some @@ -3831,7 +3831,7 @@ memory leak. Fortunately, this typemap is a lot easier to write:

      program that uses the extension, can be found in the Examples/ruby/hashargs directory of the SWIG distribution.

      -

      36.7.12 Pointer handling

      +

      37.7.12 Pointer handling

      Occasionally, it might be necessary to convert pointer values @@ -3890,7 +3890,7 @@ For example:

      } -

      36.7.12.1 Ruby Datatype Wrapping

      +

      37.7.12.1 Ruby Datatype Wrapping

      VALUE Data_Wrap_Struct(VALUE class, void @@ -3917,7 +3917,7 @@ as above. type c-type from the data object obj and assigns that pointer to ptr. -

      36.7.13 Example: STL Vector to Ruby Array

      +

      37.7.13 Example: STL Vector to Ruby Array

      Another use for macros and type maps is to create a Ruby array @@ -4009,7 +4009,7 @@ STL with ruby, you are advised to use the standard swig STL library, which does much more than this. Refer to the section called the C++ Standard Template Library. -

      36.8 Docstring Features

      +

      37.8 Docstring Features

      @@ -4043,7 +4043,7 @@ generate ri documentation from a c wrap file, you could do:

      $ rdoc -r file_wrap.c -

      36.8.1 Module docstring

      +

      37.8.1 Module docstring

      @@ -4073,7 +4073,7 @@ layout of controls on a panel, etc. to be loaded from an XML file." %module(docstring=DOCSTRING) xrc -

      36.8.2 %feature("autodoc")

      +

      37.8.2 %feature("autodoc")

      Since SWIG does know everything about the function it wraps, @@ -4094,7 +4094,7 @@ several options for autodoc controlled by the value given to the feature, described below.

      -

      36.8.2.1 %feature("autodoc", "0")

      +

      37.8.2.1 %feature("autodoc", "0")

      @@ -4118,7 +4118,7 @@ Then Ruby code like this will be generated: ... -

      36.8.2.2 %feature("autodoc", "1")

      +

      37.8.2.2 %feature("autodoc", "1")

      @@ -4138,7 +4138,7 @@ this: ... -

      36.8.2.3 %feature("autodoc", "2")

      +

      37.8.2.3 %feature("autodoc", "2")

      @@ -4150,7 +4150,7 @@ parameter types with the "2" option will result in Ruby code like this:

      -

      36.8.2.4 %feature("autodoc", "3")

      +

      37.8.2.4 %feature("autodoc", "3")

      @@ -4171,7 +4171,7 @@ Parameters: bar - Bar -

      36.8.2.5 %feature("autodoc", "docstring")

      +

      37.8.2.5 %feature("autodoc", "docstring")

      @@ -4187,7 +4187,7 @@ generated string. For example: void GetPosition(int* OUTPUT, int* OUTPUT); -

      36.8.3 %feature("docstring")

      +

      37.8.3 %feature("docstring")

      @@ -4198,10 +4198,10 @@ docstring associated with classes, function or methods are output. If an item already has an autodoc string then it is combined with the docstring and they are output together.

      -

      36.9 Advanced Topics

      +

      37.9 Advanced Topics

      -

      36.9.1 Operator overloading

      +

      37.9.1 Operator overloading

      SWIG allows operator overloading with, by using the %extend @@ -4382,7 +4382,7 @@ separate method for handling inequality since Ruby parses the expression a != b as !(a == b).

      -

      36.9.2 Creating Multi-Module Packages

      +

      37.9.2 Creating Multi-Module Packages

      The chapter on Working @@ -4508,7 +4508,7 @@ irb(main):005:0> c.getX() 5.0 -

      36.9.3 Specifying Mixin Modules

      +

      37.9.3 Specifying Mixin Modules

      The Ruby language doesn't support multiple inheritance, but @@ -4575,7 +4575,7 @@ matching rules used for other kinds of features apply (see the chapter on "Customization Features") for more details).

      -

      36.10 Memory Management

      +

      37.10 Memory Management

      One of the most common issues in generating SWIG bindings for @@ -4598,7 +4598,7 @@ to C++ (or vice versa) depending on what function or methods are invoked. Clearly, developing a SWIG wrapper requires a thorough understanding of how the underlying library manages memory.

      -

      36.10.1 Mark and Sweep Garbage Collector

      +

      37.10.1 Mark and Sweep Garbage Collector

      Ruby uses a mark and sweep garbage collector. When the garbage @@ -4630,7 +4630,7 @@ any memory has been allocated in creating the underlying C struct or C++ struct, then a "free" function must be defined that deallocates this memory.

      -

      36.10.2 Object Ownership

      +

      37.10.2 Object Ownership

      As described above, memory management depends on clearly @@ -4775,7 +4775,7 @@ public:

      This code can be seen in swig/examples/ruby/tracking.

      -

      36.10.3 Object Tracking

      +

      37.10.3 Object Tracking

      The remaining parts of this section will use the class library @@ -5000,7 +5000,7 @@ However, if you implement your own free functions (see below) you may also have to call the SWIG_RubyRemoveTracking and RubyUnlinkObjects methods.

      -

      36.10.4 Mark Functions

      +

      37.10.4 Mark Functions

      With a bit more testing, we see that our class library still @@ -5129,7 +5129,7 @@ irb(main):016:0>

      This code can be seen in swig/examples/ruby/mark_function.

      -

      36.10.5 Free Functions

      +

      37.10.5 Free Functions

      By default, SWIG creates a "free" function that is called when @@ -5296,7 +5296,7 @@ been freed, and thus raises a runtime exception.

      This code can be seen in swig/examples/ruby/free_function.

      -

      36.10.6 Embedded Ruby and the C++ Stack

      +

      37.10.6 Embedded Ruby and the C++ Stack

      As has been said, the Ruby GC runs and marks objects before diff --git a/Doc/Manual/SWIGPlus.html b/Doc/Manual/SWIGPlus.html index aa02b2dee..f9558994b 100644 --- a/Doc/Manual/SWIGPlus.html +++ b/Doc/Manual/SWIGPlus.html @@ -4972,6 +4972,7 @@ public:

      6.27 Nested classes

      +

      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.) diff --git a/Doc/Manual/Tcl.html b/Doc/Manual/Tcl.html index 9b9cd7218..45eebbf5e 100644 --- a/Doc/Manual/Tcl.html +++ b/Doc/Manual/Tcl.html @@ -6,7 +6,7 @@ -

      37 SWIG and Tcl

      +

      38 SWIG and Tcl

        @@ -83,7 +83,7 @@ Tcl 8.0 or a later release. Earlier releases of SWIG supported Tcl 7.x, but this is no longer supported.

        -

        37.1 Preliminaries

        +

        38.1 Preliminaries

        @@ -109,7 +109,7 @@ build a Tcl extension module. To finish building the module, you need to compile this file and link it with the rest of your program.

        -

        37.1.1 Getting the right header files

        +

        38.1.1 Getting the right header files

        @@ -127,7 +127,7 @@ this is the case, you should probably make a symbolic link so that tcl.h -

        37.1.2 Compiling a dynamic module

        +

        38.1.2 Compiling a dynamic module

        @@ -163,7 +163,7 @@ The name of the module is specified using the %module directive or the -module command line option.

        -

        37.1.3 Static linking

        +

        38.1.3 Static linking

        @@ -229,7 +229,7 @@ minimal in most situations (and quite frankly not worth the extra hassle in the opinion of this author).

        -

        37.1.4 Using your module

        +

        38.1.4 Using your module

        @@ -357,7 +357,7 @@ to the default system configuration (this requires root access and you will need the man pages).

        -

        37.1.5 Compilation of C++ extensions

        +

        38.1.5 Compilation of C++ extensions

        @@ -440,7 +440,7 @@ erratic program behavior. If working with lots of software components, you might want to investigate using a more formal standard such as COM.

        -

        37.1.6 Compiling for 64-bit platforms

        +

        38.1.6 Compiling for 64-bit platforms

        @@ -467,7 +467,7 @@ also introduce problems on platforms that support more than one linking standard (e.g., -o32 and -n32 on Irix).

        -

        37.1.7 Setting a package prefix

        +

        38.1.7 Setting a package prefix

        @@ -486,7 +486,7 @@ option will append the prefix to the name when creating a command and call it "Foo_bar".

        -

        37.1.8 Using namespaces

        +

        38.1.8 Using namespaces

        @@ -508,7 +508,7 @@ When the -namespace option is used, objects in the module are always accessed with the namespace name such as Foo::bar.

        -

        37.2 Building Tcl/Tk Extensions under Windows 95/NT

        +

        38.2 Building Tcl/Tk Extensions under Windows 95/NT

        @@ -519,7 +519,7 @@ covers the process of using SWIG with Microsoft Visual C++. although the procedure may be similar with other compilers.

        -

        37.2.1 Running SWIG from Developer Studio

        +

        38.2.1 Running SWIG from Developer Studio

        @@ -577,7 +577,7 @@ MSDOS > tclsh80 %

      -

      37.2.2 Using NMAKE

      +

      38.2.2 Using NMAKE

      @@ -640,7 +640,7 @@ to get you started. With a little practice, you'll be making lots of Tcl extensions.

      -

      37.3 A tour of basic C/C++ wrapping

      +

      38.3 A tour of basic C/C++ wrapping

      @@ -651,7 +651,7 @@ classes. This section briefly covers the essential aspects of this wrapping.

      -

      37.3.1 Modules

      +

      38.3.1 Modules

      @@ -685,7 +685,7 @@ To fix this, supply an extra argument to load like this: -

      37.3.2 Functions

      +

      38.3.2 Functions

      @@ -710,7 +710,7 @@ like you think it does: % -

      37.3.3 Global variables

      +

      38.3.3 Global variables

      @@ -790,7 +790,7 @@ extern char *path; // Read-only (due to %immutable) -

      37.3.4 Constants and enums

      +

      38.3.4 Constants and enums

      @@ -874,7 +874,7 @@ When an identifier name is given, it is used to perform an implicit hash-table l conversion. This allows the global statement to be omitted.

      -

      37.3.5 Pointers

      +

      38.3.5 Pointers

      @@ -970,7 +970,7 @@ C-style cast may return a bogus result whereas as the C++-style cast will return None if the conversion can't be performed.

      -

      37.3.6 Structures

      +

      38.3.6 Structures

      @@ -1252,7 +1252,7 @@ Note: Tcl only destroys the underlying object if it has ownership. See the memory management section that appears shortly.

      -

      37.3.7 C++ classes

      +

      38.3.7 C++ classes

      @@ -1319,7 +1319,7 @@ In Tcl, the static member is accessed as follows: -

      37.3.8 C++ inheritance

      +

      38.3.8 C++ inheritance

      @@ -1368,7 +1368,7 @@ For instance: It is safe to use multiple inheritance with SWIG.

      -

      37.3.9 Pointers, references, values, and arrays

      +

      38.3.9 Pointers, references, values, and arrays

      @@ -1422,7 +1422,7 @@ to hold the result and a pointer is returned (Tcl will release this memory when the return value is garbage collected).

      -

      37.3.10 C++ overloaded functions

      +

      38.3.10 C++ overloaded functions

      @@ -1545,7 +1545,7 @@ first declaration takes precedence. Please refer to the "SWIG and C++" chapter for more information about overloading.

      -

      37.3.11 C++ operators

      +

      38.3.11 C++ operators

      @@ -1647,7 +1647,7 @@ There are ways to make this operator appear as part of the class using the % Keep reading.

      -

      37.3.12 C++ namespaces

      +

      38.3.12 C++ namespaces

      @@ -1711,7 +1711,7 @@ utilizes thousands of small deeply nested namespaces each with identical symbol names, well, then you get what you deserve.

      -

      37.3.13 C++ templates

      +

      38.3.13 C++ templates

      @@ -1763,7 +1763,7 @@ More details can be found in the SWIG and C++ -

      37.3.14 C++ Smart Pointers

      +

      38.3.14 C++ Smart Pointers

      @@ -1847,7 +1847,7 @@ simply use the __deref__() method. For example: -

      37.4 Further details on the Tcl class interface

      +

      38.4 Further details on the Tcl class interface

      @@ -1860,7 +1860,7 @@ of low-level details were omitted. This section provides a brief overview of how the proxy classes work.

      -

      37.4.1 Proxy classes

      +

      38.4.1 Proxy classes

      @@ -1925,7 +1925,7 @@ function. This allows objects to be encapsulated objects that look a lot like as shown in the last section.

      -

      37.4.2 Memory management

      +

      38.4.2 Memory management

      @@ -2113,7 +2113,7 @@ typemaps--an advanced topic discussed later.

      -

      37.5 Input and output parameters

      +

      38.5 Input and output parameters

      @@ -2301,7 +2301,7 @@ set c [lindex $dim 1] -

      37.6 Exception handling

      +

      38.6 Exception handling

      @@ -2435,7 +2435,7 @@ Since SWIG's exception handling is user-definable, you are not limited to C++ ex See the chapter on "Customization Features" for more examples.

      -

      37.7 Typemaps

      +

      38.7 Typemaps

      @@ -2452,7 +2452,7 @@ Typemaps are only used if you want to change some aspect of the primitive C-Tcl interface.

      -

      37.7.1 What is a typemap?

      +

      38.7.1 What is a typemap?

      @@ -2569,7 +2569,7 @@ parameter is omitted): -

      37.7.2 Tcl typemaps

      +

      38.7.2 Tcl typemaps

      @@ -2707,7 +2707,7 @@ Initialize an argument to a value before any conversions occur. Examples of these methods will appear shortly.

      -

      37.7.3 Typemap variables

      +

      38.7.3 Typemap variables

      @@ -2778,7 +2778,7 @@ properly assigned. The Tcl name of the wrapper function being created. -

      37.7.4 Converting a Tcl list to a char **

      +

      38.7.4 Converting a Tcl list to a char **

      @@ -2840,7 +2840,7 @@ argv[2] = Larry 3 -

      37.7.5 Returning values in arguments

      +

      38.7.5 Returning values in arguments

      @@ -2882,7 +2882,7 @@ result, a Tcl function using these typemaps will work like this : % -

      37.7.6 Useful functions

      +

      38.7.6 Useful functions

      @@ -2959,7 +2959,7 @@ int Tcl_IsShared(Tcl_Obj *obj); -

      37.7.7 Standard typemaps

      +

      38.7.7 Standard typemaps

      @@ -3043,7 +3043,7 @@ work) -

      37.7.8 Pointer handling

      +

      38.7.8 Pointer handling

      @@ -3119,7 +3119,7 @@ For example: -

      37.8 Turning a SWIG module into a Tcl Package.

      +

      38.8 Turning a SWIG module into a Tcl Package.

      @@ -3191,7 +3191,7 @@ As a final note, most SWIG examples do not yet use the to use the load command instead.

      -

      37.9 Building new kinds of Tcl interfaces (in Tcl)

      +

      38.9 Building new kinds of Tcl interfaces (in Tcl)

      @@ -3290,7 +3290,7 @@ danger of blowing something up (although it is easily accomplished with an out of bounds array access).

      -

      37.9.1 Proxy classes

      +

      38.9.1 Proxy classes

      @@ -3411,7 +3411,7 @@ short, but clever Tcl script can be combined with SWIG to do many interesting things.

      -

      37.10 Tcl/Tk Stubs

      +

      38.10 Tcl/Tk Stubs

      diff --git a/Doc/Manual/Typemaps.html b/Doc/Manual/Typemaps.html index 20ad085f8..cba524149 100644 --- a/Doc/Manual/Typemaps.html +++ b/Doc/Manual/Typemaps.html @@ -6,7 +6,7 @@ -

      10 Typemaps

      +

      11 Typemaps

        @@ -95,7 +95,7 @@ -

        10.1 Introduction

        +

        11.1 Introduction

        @@ -112,7 +112,7 @@ to re-read the earlier chapters if you have found your way to this chapter with only a vague idea of what SWIG already does by default.

        -

        10.1.1 Type conversion

        +

        11.1.1 Type conversion

        @@ -205,7 +205,7 @@ to read the extension documentation for your favorite language to know how it works (an exercise left to the reader).

        -

        10.1.2 Typemaps

        +

        11.1.2 Typemaps

        @@ -306,7 +306,7 @@ parts of the generated wrapper functions. Because arbitrary code can be insert possible to completely change the way in which values are converted.

        -

        10.1.3 Pattern matching

        +

        11.1.3 Pattern matching

        @@ -408,7 +408,7 @@ In this case, a single input object is expanded into a pair of C arguments. Thi provides a hint to the unusual variable naming scheme involving $1, $2, and so forth.

        -

        10.1.4 Reusing typemaps

        +

        11.1.4 Reusing typemaps

        @@ -464,7 +464,7 @@ typedef int size_t; then SWIG already knows that the int typemaps apply. You don't have to do anything.

        -

        10.1.5 What can be done with typemaps?

        +

        11.1.5 What can be done with typemaps?

        @@ -576,7 +576,7 @@ typemaps that expand upon this list. For example, the Java module defines a var aspects of the Java bindings. Consult language specific documentation for further details.

        -

        10.1.6 What can't be done with typemaps?

        +

        11.1.6 What can't be done with typemaps?

        @@ -639,7 +639,7 @@ void wrap_foo(char *s, int x) {

      -

      10.1.7 Similarities to Aspect Oriented Programming

      +

      11.1.7 Similarities to Aspect Oriented Programming

      @@ -657,7 +657,7 @@ SWIG can also be viewed as has having a second set of aspects based around %exception are also cross-cutting concerns as they encapsulate code that can be used to add logging or exception handling to any function.

      -

      10.1.8 The rest of this chapter

      +

      11.1.8 The rest of this chapter

      @@ -677,14 +677,14 @@ of "The C Programming Language" by Kernighan and Ritchie or "The C++ Programming Language" by Stroustrup before going any further.

      -

      10.2 Typemap specifications

      +

      11.2 Typemap specifications

      This section describes the behavior of the %typemap directive itself.

      -

      10.2.1 Defining a typemap

      +

      11.2.1 Defining a typemap

      @@ -797,7 +797,7 @@ Admittedly, it's not the most readable syntax at first glance. However, the pur individual pieces will become clear.

      -

      10.2.2 Typemap scope

      +

      11.2.2 Typemap scope

      @@ -847,7 +847,7 @@ class Foo { -

      10.2.3 Copying a typemap

      +

      11.2.3 Copying a typemap

      @@ -905,7 +905,7 @@ The patterns for %apply follow the same rules as for %typemap. -

      10.2.4 Deleting a typemap

      +

      11.2.4 Deleting a typemap

      @@ -938,7 +938,7 @@ For example: after the clear operation.

      -

      10.2.5 Placement of typemaps

      +

      11.2.5 Placement of typemaps

      @@ -1018,7 +1018,7 @@ It should be noted that for scoping to work, SWIG has to know that stringclass string.

      -

      10.3 Pattern matching rules

      +

      11.3 Pattern matching rules

      @@ -1026,7 +1026,7 @@ The section describes the pattern matching rules by which C/C++ datatypes are as The matching rules can be observed in practice by using the debugging options also described.

      -

      10.3.1 Basic matching rules

      +

      11.3.1 Basic matching rules

      @@ -1125,7 +1125,7 @@ void F(int x[1000]); // int [ANY] rule (typemap 5) stripped all qualifiers in one step.

      -

      10.3.2 Typedef reductions matching

      +

      11.3.2 Typedef reductions matching

      @@ -1300,7 +1300,7 @@ void go(Struct aStruct); -

      10.3.3 Default typemap matching rules

      +

      11.3.3 Default typemap matching rules

      @@ -1438,7 +1438,7 @@ Finally the best way to view the typemap matching rules in action is via the -

      10.3.4 Multi-arguments typemaps

      +

      11.3.4 Multi-arguments typemaps

      @@ -1468,7 +1468,7 @@ but all subsequent arguments must match exactly.

      -

      10.3.5 Matching rules compared to C++ templates

      +

      11.3.5 Matching rules compared to C++ templates

      @@ -1627,7 +1627,7 @@ are similar to those for specialized template handling.

      -

      10.3.6 Debugging typemap pattern matching

      +

      11.3.6 Debugging typemap pattern matching

      @@ -1840,7 +1840,7 @@ Also the types may be displayed slightly differently - char const * and

    -

    10.4 Code generation rules

    +

    11.4 Code generation rules

    @@ -1848,7 +1848,7 @@ This section describes rules by which typemap code is inserted into the generated wrapper code.

    -

    10.4.1 Scope

    +

    11.4.1 Scope

    @@ -1926,7 +1926,7 @@ a block scope when it is emitted. This sometimes results in a less complicated Note that only the third of the three typemaps have the typemap code passed through the SWIG preprocessor.

    -

    10.4.2 Declaring new local variables

    +

    11.4.2 Declaring new local variables

    @@ -2077,7 +2077,7 @@ each type must have its own local variable declaration. -

    10.4.3 Special variables

    +

    11.4.3 Special variables

    @@ -2329,7 +2329,7 @@ Another approach, which only works for arrays is to use the $1_basetype -

    10.4.4 Special variable macros

    +

    11.4.4 Special variable macros

    @@ -2341,7 +2341,7 @@ it is done during the SWIG parsing/compilation stages. The following special variable macros are available across all language modules.

    -

    10.4.4.1 $descriptor(type)

    +

    11.4.4.1 $descriptor(type)

    @@ -2352,7 +2352,7 @@ For example, $descriptor(std::vector<int> *) will expand into Run-time type checker usage section.

    -

    10.4.4.2 $typemap(method, typepattern)

    +

    11.4.4.2 $typemap(method, typepattern)

    @@ -2409,7 +2409,7 @@ The result is the following expansion -

    10.5 Common typemap methods

    +

    11.5 Common typemap methods

    @@ -2417,7 +2417,7 @@ The set of typemaps recognized by a language module may vary. However, the following typemap methods are nearly universal:

    -

    10.5.1 "in" typemap

    +

    11.5.1 "in" typemap

    @@ -2477,7 +2477,7 @@ Usually numinputs is not specified, whereupon the default value is 1, t is the same as the old "ignore" typemap.

    -

    10.5.2 "typecheck" typemap

    +

    11.5.2 "typecheck" typemap

    @@ -2503,7 +2503,7 @@ If you define new "in" typemaps and your program uses overloaded method "typecheck" typemaps. More details about this follow in the Typemaps and overloading section.

    -

    10.5.3 "out" typemap

    +

    11.5.3 "out" typemap

    @@ -2534,7 +2534,7 @@ $symname - Name of function/method being wrapped The "out" typemap supports an optional attribute flag called "optimal". This is for code optimisation and is detailed in the Optimal code generation when returning by value section.

    -

    10.5.4 "arginit" typemap

    +

    11.5.4 "arginit" typemap

    @@ -2553,7 +2553,7 @@ For example: -

    10.5.5 "default" typemap

    +

    11.5.5 "default" typemap

    @@ -2586,7 +2586,7 @@ See the Default/optional arguments sec for further information on default argument wrapping.

    -

    10.5.6 "check" typemap

    +

    11.5.6 "check" typemap

    @@ -2605,7 +2605,7 @@ converted. For example: -

    10.5.7 "argout" typemap

    +

    11.5.7 "argout" typemap

    @@ -2651,7 +2651,7 @@ return values are often appended to return value of the function. See the typemaps.i library file for examples.

    -

    10.5.8 "freearg" typemap

    +

    11.5.8 "freearg" typemap

    @@ -2684,7 +2684,7 @@ be used in other typemaps whenever a wrapper function needs to abort prematurely.

    -

    10.5.9 "newfree" typemap

    +

    11.5.9 "newfree" typemap

    @@ -2713,7 +2713,7 @@ string *foo(); See Object ownership and %newobject for further details.

    -

    10.5.10 "memberin" typemap

    +

    11.5.10 "memberin" typemap

    @@ -2735,7 +2735,7 @@ It is rarely necessary to write "memberin" typemaps---SWIG already provides a default implementation for arrays, strings, and other objects.

    -

    10.5.11 "varin" typemap

    +

    11.5.11 "varin" typemap

    @@ -2743,7 +2743,7 @@ The "varin" typemap is used to convert objects in the target language to C for t purposes of assigning to a C/C++ global variable. This is implementation specific.

    -

    10.5.12 "varout" typemap

    +

    11.5.12 "varout" typemap

    @@ -2751,7 +2751,7 @@ The "varout" typemap is used to convert a C/C++ object to an object in the targe language when reading a C/C++ global variable. This is implementation specific.

    -

    10.5.13 "throws" typemap

    +

    11.5.13 "throws" typemap

    @@ -2797,7 +2797,7 @@ Note that if your methods do not have an exception specification yet they do thr For a neat way to handle these, see the Exception handling with %exception section.

    -

    10.6 Some typemap examples

    +

    11.6 Some typemap examples

    @@ -2805,7 +2805,7 @@ This section contains a few examples. Consult language module documentation for more examples.

    -

    10.6.1 Typemaps for arrays

    +

    11.6.1 Typemaps for arrays

    @@ -3064,7 +3064,7 @@ Now, you will find that member access is quite nice: useless and has since been eliminated. To return structure members, simply use the "out" typemap.

    -

    10.6.2 Implementing constraints with typemaps

    +

    11.6.2 Implementing constraints with typemaps

    @@ -3112,7 +3112,7 @@ a NULL pointer. As a result, SWIG can often prevent a potential segmentation faults or other run-time problems by raising an exception rather than blindly passing values to the underlying C/C++ program.

    -

    10.7 Typemaps for multiple target languages

    +

    11.7 Typemaps for multiple target languages

    @@ -3142,7 +3142,7 @@ The example above also shows a common approach of issuing a warning for an as ye %typemap(ruby,in) int "$1 = NUM2INT($input);".

    -

    10.8 Optimal code generation when returning by value

    +

    11.8 Optimal code generation when returning by value

    @@ -3331,7 +3331,7 @@ example.i:7: Warning 475: optimal attribute usage in the out typemap. However, it doesn't always get it right, for example when $1 is within some commented out code.

    -

    10.9 Multi-argument typemaps

    +

    11.9 Multi-argument typemaps

    @@ -3598,7 +3598,7 @@ with non-consecutive C/C++ arguments; a workaround such as a helper function re- the arguments to make them consecutive will need to be written.

    -

    10.10 Typemap warnings

    +

    11.10 Typemap warnings

    @@ -3607,7 +3607,7 @@ See the information in the issuing warnings

    -

    10.11 Typemap fragments

    +

    11.11 Typemap fragments

    @@ -3860,7 +3860,7 @@ fragment usage unless a desire to really get to grips with some powerful but tricky macro and fragment usage that is used in parts of the SWIG typemap library.

    -

    10.11.1 Fragment type specialization

    +

    11.11.1 Fragment type specialization

    @@ -3893,7 +3893,7 @@ struct A { -

    10.11.2 Fragments and automatic typemap specialization

    +

    11.11.2 Fragments and automatic typemap specialization

    @@ -3939,7 +3939,7 @@ The interested (or very brave) reader can take a look at the fragments.swg file

    -

    10.12 The run-time type checker

    +

    11.12 The run-time type checker

    @@ -3965,7 +3965,7 @@ language modules.