1 /* -----------------------------------------------------------------------------
2  * This file is part of SWIG, which is licensed as a whole under version 3
3  * (or any later version) of the GNU General Public License. Some additional
4  * terms also apply to certain portions of SWIG. The full details of the SWIG
5  * license and copyrights can be found in the LICENSE and COPYRIGHT files
6  * included with the SWIG source code as distributed by the SWIG developers
7  * and at http://www.swig.org/legal.html.
8  *
9  * python.cxx
10  *
11  * Python language module for SWIG.
12  * ----------------------------------------------------------------------------- */
13 
14 #include "swigmod.h"
15 #include <limits.h>
16 #include "cparse.h"
17 #include <ctype.h>
18 #include <errno.h>
19 #include "pydoc.h"
20 
21 #include <stdint.h>
22 
23 #define PYSHADOW_MEMBER  0x2
24 #define WARN_PYTHON_MULTIPLE_INH 405
25 
26 #define PYTHON_INT_MAX (2147483647)
27 #define PYTHON_INT_MIN (-2147483647-1)
28 
29 static String *const_code = 0;
30 static String *module = 0;
31 static String *package = 0;
32 static String *mainmodule = 0;
33 static String *interface = 0;
34 static String *global_name = 0;
35 static int shadow = 1;
36 static int use_kw = 0;
37 static int director_method_index = 0;
38 static int builtin = 0;
39 
40 static File *f_begin = 0;
41 static File *f_runtime = 0;
42 static File *f_runtime_h = 0;
43 static File *f_header = 0;
44 static File *f_wrappers = 0;
45 static File *f_directors = 0;
46 static File *f_directors_h = 0;
47 static File *f_init = 0;
48 static File *f_shadow_py = 0;
49 static String *f_shadow = 0;
50 static String *f_shadow_begin = 0;
51 static Hash *f_shadow_imports = 0;
52 static String *f_shadow_after_begin = 0;
53 static String *f_shadow_stubs = 0;
54 static Hash *builtin_getset = 0;
55 static Hash *builtin_closures = 0;
56 static Hash *class_members = 0;
57 static File *f_builtins = 0;
58 static String *builtin_tp_init = 0;
59 static String *builtin_methods = 0;
60 static String *builtin_default_unref = 0;
61 static String *builtin_closures_code = 0;
62 
63 static String *methods;
64 static String *methods_proxydocs;
65 static String *class_name;
66 static String *shadow_indent = 0;
67 static int in_class = 0;
68 static int no_header_file = 0;
69 static int max_bases = 0;
70 static int builtin_bases_needed = 0;
71 
72 static int py3 = 0;
73 
74 /* C++ Support + Shadow Classes */
75 
76 static int have_constructor;
77 static int have_repr;
78 static String *real_classname;
79 
80 /* Thread Support */
81 static int threads = 0;
82 static int nothreads = 0;
83 
84 /* Other options */
85 static int dirvtable = 0;
86 static int doxygen = 0;
87 static int fastunpack = 1;
88 static int fastproxy = 0;
89 static int olddefs = 0;
90 static int castmode = 0;
91 static int extranative = 0;
92 static int nortti = 0;
93 static int relativeimport = 0;
94 
95 /* flags for the make_autodoc function */
96 enum autodoc_t {
97   AUTODOC_CLASS,
98   AUTODOC_CTOR,
99   AUTODOC_DTOR,
100   AUTODOC_STATICFUNC,
101   AUTODOC_FUNC,
102   AUTODOC_METHOD,
103   AUTODOC_CONST,
104   AUTODOC_VAR
105 };
106 
107 
108 static const char *usage1 = "\
109 Python Options (available with -python)\n\
110      -builtin        - Create Python built-in types rather than proxy classes, for better performance\n\
111      -castmode       - Enable the casting mode, which allows implicit cast between types in Python\n\
112      -debug-doxygen-parser     - Display doxygen parser module debugging information\n\
113      -debug-doxygen-translator - Display doxygen translator module debugging information\n\
114      -dirvtable      - Generate a pseudo virtual table for directors for faster dispatch\n\
115      -doxygen        - Convert C++ doxygen comments to pydoc comments in proxy classes\n\
116      -extranative    - Return extra native wrappers for C++ std containers wherever possible\n\
117      -fastproxy      - Use fast proxy mechanism for member methods\n\
118      -globals <name> - Set <name> used to access C global variable (default: 'cvar')\n\
119      -interface <mod>- Set low-level C/C++ module name to <mod> (default: module name prefixed by '_')\n\
120      -keyword        - Use keyword arguments\n";
121 static const char *usage2 = "\
122      -nofastunpack   - Use traditional UnpackTuple method to parse the argument functions\n\
123      -noh            - Don't generate the output header file\n";
124 static const char *usage3 = "\
125      -noproxy        - Don't generate proxy classes\n\
126      -nortti         - Disable the use of the native C++ RTTI with directors\n\
127      -nothreads      - Disable thread support for the entire interface\n\
128      -olddefs        - Keep the old method definitions when using -fastproxy\n\
129      -py3            - Generate code with Python 3 specific features and syntax\n\
130      -relativeimport - Use relative Python imports\n\
131      -threads        - Add thread support for all the interface\n\
132      -O              - Enable the following optimization options:\n\
133                          -fastdispatch -fastproxy -fvirtual\n\
134 \n";
135 
getSlot(Node * n=NULL,const char * key=NULL,String * default_slot=NULL)136 static String *getSlot(Node *n = NULL, const char *key = NULL, String *default_slot = NULL) {
137   static String *zero = NewString("0");
138   String *val = n && key && *key ? Getattr(n, key) : NULL;
139   return val ? val : default_slot ? default_slot : zero;
140 }
141 
printSlot(File * f,String * slotval,const char * slotname,const char * functype=NULL)142 static void printSlot(File *f, String *slotval, const char *slotname, const char *functype = NULL) {
143   String *slotval_override = 0;
144   if (functype && Strcmp(slotval, "0") == 0)
145     slotval = slotval_override = NewStringf("(%s) %s", functype, slotval);
146   int len = Len(slotval);
147   int fieldwidth = len > 41 ? (len > 61 ? 0 : 61 - len) : 41 - len;
148   Printf(f, "    %s,%*s/* %s */\n", slotval, fieldwidth, "", slotname);
149   Delete(slotval_override);
150 }
151 
getClosure(String * functype,String * wrapper,int funpack=0)152 static String *getClosure(String *functype, String *wrapper, int funpack = 0) {
153   static const char *functypes[] = {
154     "unaryfunc", "SWIGPY_UNARYFUNC_CLOSURE",
155     "destructor", "SWIGPY_DESTRUCTOR_CLOSURE",
156     "inquiry", "SWIGPY_INQUIRY_CLOSURE",
157     "getiterfunc", "SWIGPY_GETITERFUNC_CLOSURE",
158     "binaryfunc", "SWIGPY_BINARYFUNC_CLOSURE",
159     "ternaryfunc", "SWIGPY_TERNARYFUNC_CLOSURE",
160     "ternarycallfunc", "SWIGPY_TERNARYCALLFUNC_CLOSURE",
161     "lenfunc", "SWIGPY_LENFUNC_CLOSURE",
162     "ssizeargfunc", "SWIGPY_SSIZEARGFUNC_CLOSURE",
163     "ssizessizeargfunc", "SWIGPY_SSIZESSIZEARGFUNC_CLOSURE",
164     "ssizeobjargproc", "SWIGPY_SSIZEOBJARGPROC_CLOSURE",
165     "ssizessizeobjargproc", "SWIGPY_SSIZESSIZEOBJARGPROC_CLOSURE",
166     "objobjproc", "SWIGPY_OBJOBJPROC_CLOSURE",
167     "objobjargproc", "SWIGPY_OBJOBJARGPROC_CLOSURE",
168     "reprfunc", "SWIGPY_REPRFUNC_CLOSURE",
169     "hashfunc", "SWIGPY_HASHFUNC_CLOSURE",
170     "iternextfunc", "SWIGPY_ITERNEXTFUNC_CLOSURE",
171     NULL
172   };
173 
174   static const char *funpack_functypes[] = {
175     "unaryfunc", "SWIGPY_UNARYFUNC_CLOSURE",
176     "destructor", "SWIGPY_DESTRUCTOR_CLOSURE",
177     "inquiry", "SWIGPY_INQUIRY_CLOSURE",
178     "getiterfunc", "SWIGPY_GETITERFUNC_CLOSURE",
179     "ternaryfunc", "SWIGPY_TERNARYFUNC_CLOSURE",
180     "ternarycallfunc", "SWIGPY_TERNARYCALLFUNC_CLOSURE",
181     "lenfunc", "SWIGPY_LENFUNC_CLOSURE",
182     "ssizeargfunc", "SWIGPY_FUNPACK_SSIZEARGFUNC_CLOSURE",
183     "ssizessizeargfunc", "SWIGPY_SSIZESSIZEARGFUNC_CLOSURE",
184     "ssizeobjargproc", "SWIGPY_SSIZEOBJARGPROC_CLOSURE",
185     "ssizessizeobjargproc", "SWIGPY_SSIZESSIZEOBJARGPROC_CLOSURE",
186     "objobjproc", "SWIGPY_FUNPACK_OBJOBJPROC_CLOSURE",
187     "objobjargproc", "SWIGPY_OBJOBJARGPROC_CLOSURE",
188     "reprfunc", "SWIGPY_REPRFUNC_CLOSURE",
189     "hashfunc", "SWIGPY_HASHFUNC_CLOSURE",
190     "iternextfunc", "SWIGPY_ITERNEXTFUNC_CLOSURE",
191     NULL
192   };
193 
194   if (!functype)
195     return NULL;
196   char *c = Char(functype);
197   int i;
198   if (funpack) {
199     for (i = 0; funpack_functypes[i] != NULL; i += 2) {
200       if (!strcmp(c, funpack_functypes[i]))
201 	return NewStringf("%s(%s)", funpack_functypes[i + 1], wrapper);
202     }
203   } else {
204     for (i = 0; functypes[i] != NULL; i += 2) {
205       if (!strcmp(c, functypes[i]))
206 	return NewStringf("%s(%s)", functypes[i + 1], wrapper);
207     }
208   }
209   return NULL;
210 }
211 
212 class PYTHON:public Language {
213 public:
PYTHON()214   PYTHON() {
215     /* Add code to manage protected constructors and directors */
216     director_prot_ctor_code = NewString("");
217     Printv(director_prot_ctor_code,
218 	   "if ( $comparison ) { /* subclassed */\n",
219 	   "  $director_new \n",
220 	   "} else {\n", "  SWIG_SetErrorMsg(PyExc_RuntimeError,\"accessing abstract class or protected constructor\"); \n", "  SWIG_fail;\n", "}\n", NIL);
221     director_multiple_inheritance = 1;
222     director_language = 1;
223   }
224 
~PYTHON()225   ~PYTHON() {
226     delete doxygenTranslator;
227   }
228 
229   /* ------------------------------------------------------------
230    * Thread Implementation
231    * ------------------------------------------------------------ */
threads_enable(Node * n) const232   int threads_enable(Node *n) const {
233     return threads && !GetFlagAttr(n, "feature:nothread");
234   }
235 
initialize_threads(String * f_init)236   int initialize_threads(String *f_init) {
237     if (!threads) {
238       return SWIG_OK;
239     }
240     Printf(f_init, "\n");
241     Printf(f_init, "/* Initialize threading */\n");
242     Printf(f_init, "SWIG_PYTHON_INITIALIZE_THREADS;\n");
243 
244     return SWIG_OK;
245   }
246 
thread_begin_block(Node * n,String * f)247   virtual void thread_begin_block(Node *n, String *f) {
248     if (!GetFlag(n, "feature:nothreadblock")) {
249       String *bb = Getattr(n, "feature:threadbeginblock");
250       if (bb) {
251 	Append(f, bb);
252       } else {
253 	Append(f, "SWIG_PYTHON_THREAD_BEGIN_BLOCK;\n");
254       }
255     }
256   }
257 
thread_end_block(Node * n,String * f)258   virtual void thread_end_block(Node *n, String *f) {
259     if (!GetFlag(n, "feature:nothreadblock")) {
260       String *eb = Getattr(n, "feature:threadendblock");
261       if (eb) {
262 	Append(f, eb);
263       } else {
264 	Append(f, "SWIG_PYTHON_THREAD_END_BLOCK;\n");
265       }
266     }
267   }
268 
thread_begin_allow(Node * n,String * f)269   virtual void thread_begin_allow(Node *n, String *f) {
270     if (!GetFlag(n, "feature:nothreadallow")) {
271       String *bb = Getattr(n, "feature:threadbeginallow");
272       Append(f, "{\n");
273       if (bb) {
274 	Append(f, bb);
275       } else {
276 	Append(f, "SWIG_PYTHON_THREAD_BEGIN_ALLOW;\n");
277       }
278     }
279   }
280 
thread_end_allow(Node * n,String * f)281   virtual void thread_end_allow(Node *n, String *f) {
282     if (!GetFlag(n, "feature:nothreadallow")) {
283       String *eb = Getattr(n, "feature:threadendallow");
284       Append(f, "\n");
285       if (eb) {
286 	Append(f, eb);
287       } else {
288 	Append(f, "SWIG_PYTHON_THREAD_END_ALLOW;");
289       }
290       Append(f, "\n}");
291     }
292   }
293 
294 
295   /* ------------------------------------------------------------
296    * main()
297    * ------------------------------------------------------------ */
298 
main(int argc,char * argv[])299   virtual void main(int argc, char *argv[]) {
300 
301     SWIG_library_directory("python");
302 
303     int doxygen_translator_flags = 0;
304 
305     for (int i = 1; i < argc; i++) {
306       if (argv[i]) {
307 	if (strcmp(argv[i], "-interface") == 0) {
308 	  if (argv[i + 1]) {
309 	    interface = NewString(argv[i + 1]);
310 	    Swig_mark_arg(i);
311 	    Swig_mark_arg(i + 1);
312 	    i++;
313 	  } else {
314 	    Swig_arg_error();
315 	  }
316 	  /* end added */
317 	} else if (strcmp(argv[i], "-globals") == 0) {
318 	  if (argv[i + 1]) {
319 	    global_name = NewString(argv[i + 1]);
320 	    Swig_mark_arg(i);
321 	    Swig_mark_arg(i + 1);
322 	    i++;
323 	  } else {
324 	    Swig_arg_error();
325 	  }
326 	} else if ((strcmp(argv[i], "-shadow") == 0) || ((strcmp(argv[i], "-proxy") == 0))) {
327 	  shadow = 1;
328 	  Swig_mark_arg(i);
329 	} else if ((strcmp(argv[i], "-noproxy") == 0)) {
330 	  shadow = 0;
331 	  Swig_mark_arg(i);
332 	} else if (strcmp(argv[i], "-keyword") == 0) {
333 	  use_kw = 1;
334 	  SWIG_cparse_set_compact_default_args(1);
335 	  Swig_mark_arg(i);
336 	} else if (strcmp(argv[i], "-nortti") == 0) {
337 	  nortti = 1;
338 	  Swig_mark_arg(i);
339 	} else if (strcmp(argv[i], "-threads") == 0) {
340 	  threads = 1;
341 	  Swig_mark_arg(i);
342 	} else if (strcmp(argv[i], "-nothreads") == 0) {
343 	  /* Turn off thread support mode */
344 	  nothreads = 1;
345 	  Swig_mark_arg(i);
346 	} else if (strcmp(argv[i], "-dirvtable") == 0) {
347 	  dirvtable = 1;
348 	  Swig_mark_arg(i);
349 	} else if (strcmp(argv[i], "-doxygen") == 0) {
350 	  doxygen = 1;
351 	  scan_doxygen_comments = 1;
352 	  Swig_mark_arg(i);
353 	} else if (strcmp(argv[i], "-debug-doxygen-translator") == 0) {
354 	  doxygen_translator_flags |= DoxygenTranslator::debug_translator;
355 	  Swig_mark_arg(i);
356 	} else if (strcmp(argv[i], "-debug-doxygen-parser") == 0) {
357 	  doxygen_translator_flags |= DoxygenTranslator::debug_parser;
358 	  Swig_mark_arg(i);
359 	} else if (strcmp(argv[i], "-nofastunpack") == 0) {
360 	  fastunpack = 0;
361 	  Swig_mark_arg(i);
362 	} else if (strcmp(argv[i], "-fastproxy") == 0) {
363 	  fastproxy = 1;
364 	  Swig_mark_arg(i);
365 	} else if (strcmp(argv[i], "-olddefs") == 0) {
366 	  olddefs = 1;
367 	  Swig_mark_arg(i);
368 	} else if (strcmp(argv[i], "-castmode") == 0) {
369 	  castmode = 1;
370 	  Swig_mark_arg(i);
371 	} else if (strcmp(argv[i], "-extranative") == 0) {
372 	  extranative = 1;
373 	  Swig_mark_arg(i);
374 	} else if (strcmp(argv[i], "-noh") == 0) {
375 	  no_header_file = 1;
376 	  Swig_mark_arg(i);
377 	} else if (strcmp(argv[i], "-newvwm") == 0) {
378 	  /* Turn on new value wrapper mode */
379 	  /* Undocumented option, did have -help text: New value wrapper mode, use only when everything else fails */
380 	  Swig_value_wrapper_mode(1);
381 	  no_header_file = 1;
382 	  Swig_mark_arg(i);
383 	} else if (strcmp(argv[i], "-O") == 0) {
384 	  fastproxy = 1;
385 	  Wrapper_fast_dispatch_mode_set(1);
386 	  Wrapper_virtual_elimination_mode_set(1);
387 	  Swig_mark_arg(i);
388 	} else if (strcmp(argv[i], "-help") == 0) {
389 	  fputs(usage1, stdout);
390 	  fputs(usage2, stdout);
391 	  fputs(usage3, stdout);
392 	} else if (strcmp(argv[i], "-py3") == 0) {
393 	  py3 = 1;
394 	  Preprocessor_define("SWIGPYTHON_PY3", 0);
395 	  Swig_mark_arg(i);
396 	} else if (strcmp(argv[i], "-builtin") == 0) {
397 	  builtin = 1;
398 	  Preprocessor_define("SWIGPYTHON_BUILTIN", 0);
399 	  Swig_mark_arg(i);
400 	} else if (strcmp(argv[i], "-relativeimport") == 0) {
401 	  relativeimport = 1;
402 	  Swig_mark_arg(i);
403 	} else if (strcmp(argv[i], "-cppcast") == 0 ||
404 		   strcmp(argv[i], "-fastinit") == 0 ||
405 		   strcmp(argv[i], "-fastquery") == 0 ||
406 		   strcmp(argv[i], "-fastunpack") == 0 ||
407 		   strcmp(argv[i], "-modern") == 0 ||
408 		   strcmp(argv[i], "-modernargs") == 0 ||
409 		   strcmp(argv[i], "-noproxydel") == 0 ||
410 		   strcmp(argv[i], "-safecstrings") == 0) {
411 	  Printf(stderr, "Deprecated command line option: %s. This option is now always on.\n", argv[i]);
412 	  Swig_mark_arg(i);
413 	} else if (strcmp(argv[i], "-aliasobj0") == 0 ||
414 		   strcmp(argv[i], "-buildnone") == 0 ||
415 		   strcmp(argv[i], "-classic") == 0 ||
416 		   strcmp(argv[i], "-classptr") == 0 ||
417 		   strcmp(argv[i], "-new_repr") == 0 ||
418 		   strcmp(argv[i], "-new_vwm") == 0 ||
419 		   strcmp(argv[i], "-newrepr") == 0 ||
420 		   strcmp(argv[i], "-noaliasobj0") == 0 ||
421 		   strcmp(argv[i], "-nobuildnone") == 0 ||
422 		   strcmp(argv[i], "-nocastmode") == 0 ||
423 		   strcmp(argv[i], "-nocppcast") == 0 ||
424 		   strcmp(argv[i], "-nodirvtable") == 0 ||
425 		   strcmp(argv[i], "-noextranative") == 0 ||
426 		   strcmp(argv[i], "-nofastinit") == 0 ||
427 		   strcmp(argv[i], "-nofastproxy") == 0 ||
428 		   strcmp(argv[i], "-nofastquery") == 0 ||
429 		   strcmp(argv[i], "-nomodern") == 0 ||
430 		   strcmp(argv[i], "-nomodernargs") == 0 ||
431 		   strcmp(argv[i], "-noolddefs") == 0 ||
432 		   strcmp(argv[i], "-nooutputtuple") == 0 ||
433 		   strcmp(argv[i], "-noproxyimport") == 0 ||
434 		   strcmp(argv[i], "-nosafecstrings") == 0 ||
435 		   strcmp(argv[i], "-old_repr") == 0 ||
436 		   strcmp(argv[i], "-oldrepr") == 0 ||
437 		   strcmp(argv[i], "-outputtuple") == 0 ||
438 		   strcmp(argv[i], "-proxydel") == 0) {
439 	  Printf(stderr, "Deprecated command line option: %s. This option is no longer supported.\n", argv[i]);
440 	  Swig_mark_arg(i);
441 	  SWIG_exit(EXIT_FAILURE);
442 	}
443 
444       }
445     }
446 
447     if (doxygen)
448       doxygenTranslator = new PyDocConverter(doxygen_translator_flags);
449 
450     if (!global_name)
451       global_name = NewString("cvar");
452     Preprocessor_define("SWIGPYTHON 1", 0);
453     SWIG_typemap_lang("python");
454     SWIG_config_file("python.swg");
455     allow_overloading();
456   }
457 
458 
459   /* ------------------------------------------------------------
460    * top()
461    * ------------------------------------------------------------ */
462 
top(Node * n)463   virtual int top(Node *n) {
464     /* check if directors are enabled for this module.  note: this
465      * is a "master" switch, without which no director code will be
466      * emitted.  %feature("director") statements are also required
467      * to enable directors for individual classes or methods.
468      *
469      * use %module(directors="1") modulename at the start of the
470      * interface file to enable director generation.
471      */
472     String *mod_docstring = NULL;
473     String *moduleimport = NULL;
474     {
475       Node *mod = Getattr(n, "module");
476       if (mod) {
477 	Node *options = Getattr(mod, "options");
478 	if (options) {
479 	  int dirprot = 0;
480 	  if (Getattr(options, "dirprot")) {
481 	    dirprot = 1;
482 	  }
483 	  if (Getattr(options, "nodirprot")) {
484 	    dirprot = 0;
485 	  }
486 	  if (Getattr(options, "directors")) {
487 	    allow_directors();
488 	    if (dirprot)
489 	      allow_dirprot();
490 	  }
491 	  if (Getattr(options, "threads")) {
492 	    threads = 1;
493 	  }
494 	  if (Getattr(options, "castmode")) {
495 	    castmode = 1;
496 	  }
497 	  if (Getattr(options, "nocastmode")) {
498 	    Printf(stderr, "Deprecated module option: %s. This option is no longer supported.\n", "nocastmode");
499 	    SWIG_exit(EXIT_FAILURE);
500 	  }
501 	  if (Getattr(options, "extranative")) {
502 	    extranative = 1;
503 	  }
504 	  if (Getattr(options, "noextranative")) {
505 	    Printf(stderr, "Deprecated module option: %s. This option is no longer supported.\n", "noextranative");
506 	    SWIG_exit(EXIT_FAILURE);
507 	  }
508 	  if (Getattr(options, "outputtuple")) {
509 	    Printf(stderr, "Deprecated module option: %s. This option is no longer supported.\n", "outputtuple");
510 	    SWIG_exit(EXIT_FAILURE);
511 	  }
512 	  if (Getattr(options, "nooutputtuple")) {
513 	    Printf(stderr, "Deprecated module option: %s. This option is no longer supported.\n", "nooutputtuple");
514 	    SWIG_exit(EXIT_FAILURE);
515 	  }
516 	  mod_docstring = Getattr(options, "docstring");
517 	  package = Getattr(options, "package");
518 	  moduleimport = Getattr(options, "moduleimport");
519 	}
520       }
521     }
522 
523     /* Set comparison with none for ConstructorToFunction */
524     setSubclassInstanceCheck(NewString("$arg != Py_None"));
525 
526     /* Initialize all of the output files */
527     String *outfile = Getattr(n, "outfile");
528     String *outfile_h = !no_header_file ? Getattr(n, "outfile_h") : 0;
529 
530     f_begin = NewFile(outfile, "w", SWIG_output_files());
531     if (!f_begin) {
532       FileErrorDisplay(outfile);
533       SWIG_exit(EXIT_FAILURE);
534     }
535     f_runtime = NewString("");
536     f_init = NewString("");
537     f_header = NewString("");
538     f_wrappers = NewString("");
539     f_directors_h = NewString("");
540     f_directors = NewString("");
541     builtin_getset = NewHash();
542     builtin_closures = NewHash();
543     builtin_closures_code = NewString("");
544     class_members = NewHash();
545     builtin_methods = NewString("");
546     builtin_default_unref = NewString("delete $self;");
547 
548     if (builtin) {
549       f_builtins = NewString("");
550     }
551 
552     if (directorsEnabled()) {
553       if (!no_header_file) {
554 	f_runtime_h = NewFile(outfile_h, "w", SWIG_output_files());
555 	if (!f_runtime_h) {
556 	  FileErrorDisplay(outfile_h);
557 	  SWIG_exit(EXIT_FAILURE);
558 	}
559       } else {
560 	f_runtime_h = f_runtime;
561       }
562     }
563 
564     /* Register file targets with the SWIG file handler */
565     Swig_register_filebyname("header", f_header);
566     Swig_register_filebyname("wrapper", f_wrappers);
567     Swig_register_filebyname("begin", f_begin);
568     Swig_register_filebyname("runtime", f_runtime);
569     Swig_register_filebyname("init", f_init);
570     Swig_register_filebyname("director", f_directors);
571     Swig_register_filebyname("director_h", f_directors_h);
572 
573     const_code = NewString("");
574     methods = NewString("");
575     methods_proxydocs = NewString("");
576 
577     Swig_banner(f_begin);
578 
579     Printf(f_runtime, "\n\n#ifndef SWIGPYTHON\n#define SWIGPYTHON\n#endif\n\n");
580 
581     if (directorsEnabled()) {
582       Printf(f_runtime, "#define SWIG_DIRECTORS\n");
583     }
584 
585     if (nothreads) {
586       Printf(f_runtime, "#define SWIG_PYTHON_NO_THREADS\n");
587     } else if (threads) {
588       Printf(f_runtime, "#define SWIG_PYTHON_THREADS\n");
589     }
590 
591     if (!dirvtable) {
592       Printf(f_runtime, "#define SWIG_PYTHON_DIRECTOR_NO_VTABLE\n");
593     }
594 
595     if (nortti) {
596       Printf(f_runtime, "#ifndef SWIG_DIRECTOR_NORTTI\n");
597       Printf(f_runtime, "#define SWIG_DIRECTOR_NORTTI\n");
598       Printf(f_runtime, "#endif\n");
599     }
600 
601     if (castmode) {
602       Printf(f_runtime, "#define SWIG_CASTRANK_MODE\n");
603       Printf(f_runtime, "#define SWIG_PYTHON_CAST_MODE\n");
604     }
605 
606     if (extranative) {
607       Printf(f_runtime, "#define SWIG_PYTHON_EXTRA_NATIVE_CONTAINERS\n");
608     }
609 
610     if (builtin) {
611       Printf(f_runtime, "#define SWIGPYTHON_BUILTIN\n");
612     }
613 
614     Printf(f_runtime, "\n");
615 
616     Printf(f_header, "#ifdef SWIG_TypeQuery\n");
617     Printf(f_header, "# undef SWIG_TypeQuery\n");
618     Printf(f_header, "#endif\n");
619     Printf(f_header, "#define SWIG_TypeQuery SWIG_Python_TypeQuery\n");
620 
621 
622     /* Set module name */
623     module = Copy(Getattr(n, "name"));
624     mainmodule = Getattr(n, "name");
625 
626     if (directorsEnabled()) {
627       Swig_banner(f_directors_h);
628       Printf(f_directors_h, "\n");
629       Printf(f_directors_h, "#ifndef SWIG_%s_WRAP_H_\n", module);
630       Printf(f_directors_h, "#define SWIG_%s_WRAP_H_\n\n", module);
631       if (dirprot_mode()) {
632 	Printf(f_directors_h, "#include <map>\n");
633 	Printf(f_directors_h, "#include <string>\n\n");
634       }
635 
636       Printf(f_directors, "\n\n");
637       Printf(f_directors, "/* ---------------------------------------------------\n");
638       Printf(f_directors, " * C++ director class methods\n");
639       Printf(f_directors, " * --------------------------------------------------- */\n\n");
640       if (outfile_h) {
641 	String *filename = Swig_file_filename(outfile_h);
642 	Printf(f_directors, "#include \"%s\"\n\n", filename);
643 	Delete(filename);
644       }
645     }
646 
647     /* If shadow classing is enabled, we're going to change the module name to "_module" */
648     String *default_import_code = NewString("");
649     if (shadow) {
650       String *filen = NewStringf("%s%s.py", SWIG_output_directory(), Char(module));
651       // If we don't have an interface then change the module name X to _X
652       if (interface)
653 	module = interface;
654       else
655 	Insert(module, 0, "_");
656       if ((f_shadow_py = NewFile(filen, "w", SWIG_output_files())) == 0) {
657 	FileErrorDisplay(filen);
658 	SWIG_exit(EXIT_FAILURE);
659       }
660       Delete(filen);
661       filen = NULL;
662 
663       f_shadow = NewString("");
664       f_shadow_begin = NewString("");
665       f_shadow_imports = NewHash();
666       f_shadow_after_begin = NewString("");
667       f_shadow_stubs = NewString("");
668 
669       Swig_register_filebyname("shadow", f_shadow);
670       Swig_register_filebyname("python", f_shadow);
671 
672       if (!builtin) {
673 	/* Import the low-level C/C++ module.  This should be a relative import,
674 	 * since the shadow module may also have been imported by a relative
675 	 * import, and there is thus no guarantee that the low-level C/C++ module is on
676 	 * sys.path.  Relative imports must be explicitly specified from 2.6.0
677 	 * onwards (implicit relative imports raised a DeprecationWarning in 2.6,
678 	 * and fail in 2.7 onwards).
679 	 *
680 	 * First check for __package__ which is available from 2.6 onwards, see PEP366.
681 	 * Next try determine the shadow wrapper's package based on the __name__ it
682 	 * was given by the importer that loaded it.
683 	 * If the module is in a package, load the low-level C/C++ module from the
684 	 * same package, otherwise load it as a global module.
685 	 */
686         Printv(default_import_code, "# Import the low-level C/C++ module\n", NULL);
687         Printv(default_import_code, "if __package__ or \".\" in __name__:\n", NULL);
688         Printv(default_import_code, tab4, "from . import ", module, "\n", NULL);
689         Printv(default_import_code, "else:\n", NULL);
690         Printv(default_import_code, tab4, "import ", module, "\n", NULL);
691       } else {
692         Printv(default_import_code, "# Pull in all the attributes from the low-level C/C++ module\n", NULL);
693         Printv(default_import_code, "if __package__ or \".\" in __name__:\n", NULL);
694         Printv(default_import_code, tab4, "from .", module, " import *\n", NULL);
695         Printv(default_import_code, "else:\n", NULL);
696         Printv(default_import_code, tab4, "from ", module, " import *\n", NULL);
697       }
698 
699       /* Need builtins to qualify names like Exception that might also be
700          defined in this module (try both Python 3 and Python 2 names) */
701       Printv(f_shadow, "try:\n", tab4, "import builtins as __builtin__\n", "except ImportError:\n", tab4, "import __builtin__\n", NULL);
702 
703       if (!builtin && fastproxy) {
704 	Printf(f_shadow, "\n");
705 	Printf(f_shadow, "_swig_new_instance_method = %s.SWIG_PyInstanceMethod_New\n", module);
706 	Printf(f_shadow, "_swig_new_static_method = %s.SWIG_PyStaticMethod_New\n", module);
707       }
708 
709       Printv(f_shadow, "\n",
710 	     "def _swig_repr(self):\n",
711 	     tab4, "try:\n",
712 	     tab4, tab4, "strthis = \"proxy of \" + self.this.__repr__()\n",
713 	     tab4, "except __builtin__.Exception:\n",
714 	     tab4, tab4, "strthis = \"\"\n",
715 	     tab4, "return \"<%s.%s; %s >\" % (self.__class__.__module__, self.__class__.__name__, strthis,)\n\n", NIL);
716 
717       Printv(f_shadow,  "\n",
718 	     "def _swig_setattr_nondynamic_instance_variable(set):\n",
719 	     tab4, "def set_instance_attr(self, name, value):\n",
720 #ifdef USE_THISOWN
721 	     tab4, tab4, "if name in (\"this\", \"thisown\"):\n",
722 	     tab4, tab4, tab4, "set(self, name, value)\n",
723 #else
724 	     tab4, tab4, "if name == \"thisown\":\n",
725 	     tab4, tab4, tab4, "self.this.own(value)\n",
726 	     tab4, tab4, "elif name == \"this\":\n",
727 	     tab4, tab4, tab4, "set(self, name, value)\n",
728 #endif
729 	     tab4, tab4, "elif hasattr(self, name) and isinstance(getattr(type(self), name), property):\n",
730 	     tab4, tab4, tab4, "set(self, name, value)\n",
731 	     tab4, tab4, "else:\n",
732 	     tab4, tab4, tab4, "raise AttributeError(\"You cannot add instance attributes to %s\" % self)\n",
733 	     tab4, "return set_instance_attr\n\n", NIL);
734 
735       Printv(f_shadow,  "\n",
736 	     "def _swig_setattr_nondynamic_class_variable(set):\n",
737 	     tab4, "def set_class_attr(cls, name, value):\n",
738 	     tab4, tab4, "if hasattr(cls, name) and not isinstance(getattr(cls, name), property):\n",
739 	     tab4, tab4, tab4, "set(cls, name, value)\n",
740 	     tab4, tab4, "else:\n",
741 	     tab4, tab4, tab4, "raise AttributeError(\"You cannot add class attributes to %s\" % cls)\n",
742 	     tab4, "return set_class_attr\n\n", NIL);
743 
744       Printv(f_shadow,  "\n",
745 	     "def _swig_add_metaclass(metaclass):\n",
746 	     tab4, "\"\"\"Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass\"\"\"\n",
747 	     tab4, "def wrapper(cls):\n",
748 	     tab4, tab4, "return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy())\n",
749 	     tab4, "return wrapper\n\n", NIL);
750 
751       Printv(f_shadow,  "\n",
752 	     "class _SwigNonDynamicMeta(type):\n",
753 	     tab4, "\"\"\"Meta class to enforce nondynamic attributes (no new attributes) for a class\"\"\"\n",
754 	     tab4, "__setattr__ = _swig_setattr_nondynamic_class_variable(type.__setattr__)\n",
755 	     "\n", NIL);
756 
757       Printv(f_shadow, "\n", NIL);
758 
759       if (directorsEnabled()) {
760 	Printv(f_shadow, "import weakref\n\n", NIL);
761       }
762     }
763     // Include some information in the code
764     Printf(f_header, "\n/*-----------------------------------------------\n              @(target):= %s.so\n\
765   ------------------------------------------------*/\n", module);
766 
767     Printf(f_header, "#if PY_VERSION_HEX >= 0x03000000\n");
768     Printf(f_header, "#  define SWIG_init    PyInit_%s\n\n", module);
769     Printf(f_header, "#else\n");
770     Printf(f_header, "#  define SWIG_init    init%s\n\n", module);
771     Printf(f_header, "#endif\n");
772     Printf(f_header, "#define SWIG_name    \"%s\"\n", module);
773 
774     Printf(f_wrappers, "#ifdef __cplusplus\n");
775     Printf(f_wrappers, "extern \"C\" {\n");
776     Printf(f_wrappers, "#endif\n");
777     Append(const_code, "static swig_const_info swig_const_table[] = {\n");
778     Append(methods, "static PyMethodDef SwigMethods[] = {\n");
779     Append(methods_proxydocs, "static PyMethodDef SwigMethods_proxydocs[] = {\n");
780 
781     /* the method exported for replacement of new.instancemethod in Python 3 */
782     add_pyinstancemethod_new();
783     add_pystaticmethod_new();
784 
785     if (builtin) {
786       SwigType *s = NewString("SwigPyObject");
787       SwigType_add_pointer(s);
788       SwigType_remember(s);
789       Delete(s);
790     }
791 
792     /* emit code */
793     Language::top(n);
794 
795     if (directorsEnabled()) {
796       // Insert director runtime into the f_runtime file (make it occur before %header section)
797       Swig_insert_file("director_common.swg", f_runtime);
798       Swig_insert_file("director.swg", f_runtime);
799     }
800 
801     /* Close language module */
802     Append(methods, "\t { NULL, NULL, 0, NULL }\n");
803     Append(methods, "};\n");
804     Printf(f_wrappers, "%s\n", methods);
805     Append(methods_proxydocs, "\t { NULL, NULL, 0, NULL }\n");
806     Append(methods_proxydocs, "};\n");
807     Printf(f_wrappers, "%s\n", methods_proxydocs);
808 
809     if (builtin) {
810       Dump(f_builtins, f_wrappers);
811     }
812 
813     SwigType_emit_type_table(f_runtime, f_wrappers);
814 
815     Append(const_code, "{0, 0, 0, 0.0, 0, 0}};\n");
816     Printf(f_wrappers, "%s\n", const_code);
817     initialize_threads(f_init);
818 
819     Printf(f_init, "#if PY_VERSION_HEX >= 0x03000000\n");
820     Printf(f_init, "  return m;\n");
821     Printf(f_init, "#else\n");
822     Printf(f_init, "  return;\n");
823     Printf(f_init, "#endif\n");
824     Printf(f_init, "}\n");
825 
826     Printf(f_wrappers, "#ifdef __cplusplus\n");
827     Printf(f_wrappers, "}\n");
828     Printf(f_wrappers, "#endif\n");
829 
830     if (shadow) {
831       Swig_banner_target_lang(f_shadow_py, "#");
832 
833       if (mod_docstring) {
834 	if (Len(mod_docstring)) {
835 	  const char *triple_double = "\"\"\"";
836 	  // follow PEP257 rules: https://www.python.org/dev/peps/pep-0257/
837 	  // reported by pep257: https://github.com/GreenSteam/pep257
838 	  bool multi_line_ds = Strchr(mod_docstring, '\n') != 0;
839 	  Printv(f_shadow_py, "\n", triple_double, multi_line_ds ? "\n":"", mod_docstring, multi_line_ds ? "\n":"", triple_double, "\n", NIL);
840 	}
841 	Delete(mod_docstring);
842 	mod_docstring = NULL;
843       }
844 
845       if (Len(f_shadow_begin) > 0)
846 	Printv(f_shadow_py, "\n", f_shadow_begin, "\n", NIL);
847 
848       Printv(f_shadow_py, "\nfrom sys import version_info as _swig_python_version_info\n", NULL);
849       Printv(f_shadow_py, "if _swig_python_version_info < (2, 7, 0):\n", NULL);
850       Printv(f_shadow_py, tab4, "raise RuntimeError(\"Python 2.7 or later required\")\n\n", NULL);
851 
852       if (Len(f_shadow_after_begin) > 0)
853 	Printv(f_shadow_py, f_shadow_after_begin, "\n", NIL);
854 
855       if (moduleimport) {
856 	Replaceall(moduleimport, "$module", module);
857 	Printv(f_shadow_py, moduleimport, "\n", NIL);
858       } else {
859 	Printv(f_shadow_py, default_import_code, NIL);
860       }
861 
862       Printv(f_shadow_py, "\n", f_shadow, "\n", NIL);
863       Printv(f_shadow_py, f_shadow_stubs, "\n", NIL);
864       Delete(f_shadow_py);
865     }
866 
867     /* Close all of the files */
868     Dump(f_runtime, f_begin);
869     Dump(f_header, f_begin);
870 
871     if (directorsEnabled()) {
872       Dump(f_directors_h, f_runtime_h);
873       Printf(f_runtime_h, "\n");
874       Printf(f_runtime_h, "#endif\n");
875       if (f_runtime_h != f_begin)
876 	Delete(f_runtime_h);
877       Dump(f_directors, f_begin);
878     }
879 
880     Dump(f_wrappers, f_begin);
881     if (builtin && builtin_bases_needed)
882       Printf(f_begin, "static PyTypeObject *builtin_bases[%d];\n\n", max_bases + 2);
883     Wrapper_pretty_print(f_init, f_begin);
884 
885     Delete(default_import_code);
886     Delete(f_shadow_after_begin);
887     Delete(f_shadow_imports);
888     Delete(f_shadow_begin);
889     Delete(f_shadow);
890     Delete(f_header);
891     Delete(f_wrappers);
892     Delete(f_builtins);
893     Delete(f_init);
894     Delete(f_directors);
895     Delete(f_directors_h);
896     Delete(f_runtime);
897     Delete(f_begin);
898 
899     return SWIG_OK;
900   }
901 
902   /* ------------------------------------------------------------
903    * Emit the wrapper for PyInstanceMethod_New to MethodDef array.
904    * This wrapper is used to implement -fastproxy,
905    * as a replacement of new.instancemethod in Python 3.
906    * ------------------------------------------------------------ */
add_pyinstancemethod_new()907   int add_pyinstancemethod_new() {
908     String *name = NewString("SWIG_PyInstanceMethod_New");
909     String *line = NewString("");
910     Printf(line, "\t { \"%s\", %s, METH_O, NULL},\n", name, name);
911     Append(methods, line);
912     if (fastproxy) {
913       Append(methods_proxydocs, line);
914     }
915     Delete(line);
916     Delete(name);
917     return 0;
918   }
919 
920   /* ------------------------------------------------------------
921    * Emit the wrapper for PyStaticMethod_New to MethodDef array.
922    * This wrapper is used to ensure the correct documentation is
923    * generated for static methods when using -fastproxy
924    * ------------------------------------------------------------ */
add_pystaticmethod_new()925   int add_pystaticmethod_new() {
926     if (fastproxy) {
927       String *name = NewString("SWIG_PyStaticMethod_New");
928       String *line = NewString("");
929       Printf(line, "\t { \"%s\", %s, METH_O, NULL},\n", name, name);
930       Append(methods, line);
931       Append(methods_proxydocs, line);
932       Delete(line);
933       Delete(name);
934     }
935     return 0;
936   }
937 
938   /* ------------------------------------------------------------
939    * subpkg_tail()
940    *
941    * Return the name of 'other' package relative to 'base'.
942    *
943    * 1. If 'other' is a sub-package of 'base', returns the 'other' relative to
944    *    'base'.
945    * 2. If 'other' and 'base' are equal, returns empty string "".
946    * 3. In any other case, NULL pointer is returned.
947    *
948    * The 'base' and 'other' are expected to be fully qualified names.
949    *
950    * NOTE: none of 'base' nor 'other' can be null.
951    *
952    * Examples:
953    *
954    *  #  base       other         tail
955    * --  ----       -----         ----
956    *  1  "Foo"      "Foo.Bar" ->  "Bar"
957    *  2	 "Foo"      "Foo."    ->  ""
958    *  3	 "Foo"      "FooB.ar" ->  NULL
959    *  4	 "Foo.Bar"  "Foo.Bar" ->  ""
960    *  5  "Foo.Bar"  "Foo"     ->  NULL
961    *  6  "Foo.Bar"  "Foo.Gez" ->  NULL
962    *
963    *  NOTE: the example #2 is actually a syntax error (at input). I believe
964    *        swig parser prevents us from this case happening here.
965    * ------------------------------------------------------------ */
966 
subpkg_tail(const String * base,const String * other)967   static String *subpkg_tail(const String *base, const String *other) {
968     int baselen = Len(base);
969     int otherlen = Len(other);
970 
971     if (Strncmp(other, base, baselen) == 0) {
972       if ((baselen < otherlen) && (Char(other))[baselen] == '.') {
973         return NewString((Char(other)) + baselen + 1);
974       } else if (baselen == otherlen) {
975         return NewString("");
976       } else {
977         return 0;
978       }
979     } else {
980       return 0;
981     }
982   }
983 
984   /* ------------------------------------------------------------
985    * abs_import_directive_string()
986    *
987    * Return a string containing python code to import module.
988    *
989    * 	pkg     package name or the module being imported
990    * 	mod     module name of the module being imported
991    * 	pfx     optional prefix to module name
992    *
993    * NOTE: keep this function consistent with abs_import_name_string().
994    * ------------------------------------------------------------ */
995 
abs_import_directive_string(const String * pkg,const String * mod,const char * pfx="")996   static String *abs_import_directive_string(const String *pkg, const String *mod, const char *pfx = "") {
997     String *out = NewString("");
998 
999     if (pkg && *Char(pkg)) {
1000       Printf(out, "import %s.%s%s\n", pkg, pfx, mod);
1001     } else {
1002       Printf(out, "import %s%s\n", pfx, mod);
1003     }
1004     return out;
1005   }
1006 
1007   /* ------------------------------------------------------------
1008    * rel_import_directive_string()
1009    *
1010    * Return a string containing python code to import module that
1011    * is potentially within a package.
1012    *
1013    * 	mainpkg	package name of the module which imports the other module
1014    * 	pkg     package name or the module being imported
1015    * 	mod     module name of the module being imported
1016    * 	pfx     optional prefix to module name
1017    *
1018    * NOTE: keep this function consistent with rel_import_name_string().
1019    * ------------------------------------------------------------ */
1020 
rel_import_directive_string(const String * mainpkg,const String * pkg,const String * mod,const char * pfx="")1021   static String *rel_import_directive_string(const String *mainpkg, const String *pkg, const String *mod, const char *pfx = "") {
1022 
1023     /* NOTE: things are not so trivial. This is what we do here (by examples):
1024      *
1025      * 0. To import module 'foo', which is not in any package, we do absolute
1026      *    import:
1027      *
1028      *       import foo
1029      *
1030      * 1. To import 'pkg1.pkg2.foo', when mainpkg != "pkg1" and
1031      *    mainpkg != "pkg1.pkg2" or when mainpkg is not given we do absolute
1032      *    import:
1033      *
1034      *          import pkg1.pkg2.foo
1035      *
1036      * 2. To import module pkg1.foo, when mainpkg == "pkg1", we do:
1037      *
1038      *    - for py3 = 0:
1039      *
1040      *          import foo
1041      *
1042      *    - for py3 = 1:
1043      *
1044      *          from . import foo
1045      *
1046      * 3. To import "pkg1.pkg2.pkg3.foo", when mainpkg = "pkg1", we do:
1047      *
1048      *    - for py3 == 0:
1049      *
1050      *          import pkg2.pkg3.foo
1051      *
1052      *    - for py3 == 1:
1053      *
1054      *          from . import pkg2  # [1]
1055      *          import pkg1.pkg2.pkg3.foo
1056      *
1057      * NOTE: [1] is necessary for pkg2.foo to be present in the importing module
1058      */
1059 
1060     String *apkg = 0; // absolute (FQDN) package name of pkg
1061     String *rpkg = 0; // relative package name
1062     int py3_rlen1 = 0; // length of 1st level sub-package name, used by py3
1063     String *out = NewString("");
1064 
1065     if (pkg && *Char(pkg)) {
1066       if (mainpkg) {
1067 	String *tail = subpkg_tail(mainpkg, pkg);
1068 	if (tail) {
1069 	  if (*Char(tail)) {
1070 	    rpkg = NewString(tail);
1071 	    const char *py3_end1 = Strchr(rpkg, '.');
1072 	    if (!py3_end1)
1073 	      py3_end1 = (Char(rpkg)) + Len(rpkg);
1074 	    py3_rlen1 = (int)(py3_end1 - Char(rpkg));
1075 	  } else {
1076 	    rpkg = NewString("");
1077 	  }
1078 	  Delete(tail);
1079 	} else {
1080 	  apkg = NewString(pkg);
1081 	}
1082       } else {
1083 	apkg = NewString(pkg);
1084       }
1085     } else {
1086       apkg = NewString("");
1087     }
1088 
1089     if (apkg) {
1090       Printf(out, "import %s%s%s%s\n", apkg, *Char(apkg) ? "." : "", pfx, mod);
1091       Delete(apkg);
1092     } else {
1093       if (py3_rlen1)
1094 	Printf(out, "from . import %.*s\n", py3_rlen1, rpkg);
1095       Printf(out, "from .%s import %s%s\n", rpkg, pfx, mod);
1096       Delete(rpkg);
1097     }
1098     return out;
1099   }
1100 
1101   /* ------------------------------------------------------------
1102    * import_directive_string()
1103    * ------------------------------------------------------------ */
1104 
import_directive_string(const String * mainpkg,const String * pkg,const String * mod,const char * pfx="")1105   static String *import_directive_string(const String *mainpkg, const String *pkg, const String *mod, const char *pfx = "") {
1106     if (!relativeimport) {
1107       return abs_import_directive_string(pkg, mod, pfx);
1108     } else {
1109       return rel_import_directive_string(mainpkg, pkg, mod, pfx);
1110     }
1111   }
1112 
1113   /* ------------------------------------------------------------
1114    * abs_import_name_string()
1115    *
1116    * Return a string with the name of a symbol (perhaps imported
1117    * from external module by absolute import directive).
1118    *
1119    * mainpkg  package name of current module
1120    * mainmod  module name of current module
1121    * pkg      package name of (perhaps other) module
1122    * mod      module name of (perhaps other) module
1123    * sym      symbol name
1124    *
1125    * NOTE: mainmod, mod, and sym can't be NULL.
1126    * NOTE: keep this function consistent with abs_import_directive_string()
1127    * ------------------------------------------------------------ */
1128 
abs_import_name_string(const String * mainpkg,const String * mainmod,const String * pkg,const String * mod,const String * sym)1129   static String *abs_import_name_string(const String *mainpkg, const String *mainmod, const String *pkg, const String *mod, const String *sym) {
1130     String *out = NewString("");
1131     if (pkg && *Char(pkg)) {
1132       if (mainpkg && *Char(mainpkg)) {
1133         if (Strcmp(mainpkg,pkg) != 0 || Strcmp(mainmod, mod) != 0) {
1134           Printf(out, "%s.%s.", pkg, mod);
1135         }
1136       } else {
1137         Printf(out, "%s.%s.", pkg, mod);
1138       }
1139     } else if ((mainpkg && *Char(mainpkg)) || Strcmp(mainmod, mod) != 0) {
1140       Printf(out, "%s.", mod);
1141     }
1142     Append(out, sym);
1143     return out;
1144   }
1145 
1146   /* ------------------------------------------------------------
1147    * rel_import_name_string()
1148    *
1149    * Return a string with the name of a symbol (perhaps imported
1150    * from external module by relative import directive).
1151    *
1152    * mainpkg  package name of current module
1153    * mainmod  module name of current module
1154    * pkg      package name of (perhaps other) module
1155    * mod      module name of (perhaps other) module
1156    * sym      symbol name
1157    *
1158    * NOTE: mainmod, mod, and sym can't be NULL.
1159    * NOTE: keep this function consistent with rel_import_directive_string()
1160    * ------------------------------------------------------------ */
1161 
rel_import_name_string(const String * mainpkg,const String * mainmod,const String * pkg,const String * mod,const String * sym)1162   static String *rel_import_name_string(const String *mainpkg, const String *mainmod, const String *pkg, const String *mod, const String *sym) {
1163     String *out = NewString("");
1164     if (pkg && *Char(pkg)) {
1165       String *tail = 0;
1166       if (mainpkg)
1167         tail = subpkg_tail(mainpkg, pkg);
1168       if (!tail)
1169         tail = NewString(pkg);
1170       if (*Char(tail)) {
1171         Printf(out, "%s.%s.", tail, mod);
1172       } else if (Strcmp(mainmod, mod) != 0) {
1173         Printf(out, "%s.", mod);
1174       }
1175       Delete(tail);
1176     } else if ((mainpkg && *Char(mainpkg)) || Strcmp(mainmod, mod) != 0) {
1177       Printf(out, "%s.", mod);
1178     }
1179     Append(out, sym);
1180     return out;
1181   }
1182 
1183   /* ------------------------------------------------------------
1184    * import_name_string()
1185    * ------------------------------------------------------------ */
1186 
import_name_string(const String * mainpkg,const String * mainmod,const String * pkg,const String * mod,const String * sym)1187   static String *import_name_string(const String *mainpkg, const String *mainmod, const String *pkg, const String *mod, const String *sym) {
1188     if (!relativeimport) {
1189       return abs_import_name_string(mainpkg,mainmod,pkg,mod,sym);
1190     } else {
1191       return rel_import_name_string(mainpkg,mainmod,pkg,mod,sym);
1192     }
1193   }
1194 
1195   /* ------------------------------------------------------------
1196    * importDirective()
1197    * ------------------------------------------------------------ */
1198 
importDirective(Node * n)1199   virtual int importDirective(Node *n) {
1200     if (shadow) {
1201       String *modname = Getattr(n, "module");
1202 
1203       if (modname) {
1204 	// Find the module node for this imported module.  It should be the
1205 	// first child but search just in case.
1206 	Node *mod = firstChild(n);
1207 	while (mod && Strcmp(nodeType(mod), "module") != 0)
1208 	  mod = nextSibling(mod);
1209 
1210 	Node *options = Getattr(mod, "options");
1211 	String *pkg = options ? Getattr(options, "package") : 0;
1212 
1213 	if (!options || (!Getattr(options, "noshadow") && !Getattr(options, "noproxy"))) {
1214 	  String *_import = import_directive_string(package, pkg, modname, "_");
1215 	  if (!GetFlagAttr(f_shadow_imports, _import)) {
1216 	    String *import = import_directive_string(package, pkg, modname);
1217 	    Printf(builtin ? f_shadow_after_begin : f_shadow, "%s", import);
1218 	    Delete(import);
1219 	    SetFlag(f_shadow_imports, _import);
1220 	  }
1221 	  Delete(_import);
1222 	}
1223 
1224       }
1225     }
1226     return Language::importDirective(n);
1227   }
1228 
1229   /* ------------------------------------------------------------
1230    * funcCall()
1231    *
1232    * Emit shadow code to call a function in the extension
1233    * module. Using proper argument and calling style for
1234    * given node n.
1235    * ------------------------------------------------------------ */
funcCall(String * name,String * parms)1236   String *funcCall(String *name, String *parms) {
1237     String *str = NewString("");
1238 
1239     Printv(str, module, ".", name, "(", parms, ")", NIL);
1240     return str;
1241   }
1242 
1243   /* ------------------------------------------------------------
1244    * indent_pythoncode()
1245    *
1246    * Format (indent) Python code.
1247    * Remove leading whitespace from 'code' and re-indent using
1248    * the indentation string in 'indent'.
1249    * ------------------------------------------------------------ */
1250 
indent_pythoncode(const String * code,const_String_or_char_ptr indent,String * file,int line,const char * directive_name)1251   String *indent_pythoncode(const String *code, const_String_or_char_ptr indent, String *file, int line, const char *directive_name) {
1252     String *out = NewString("");
1253     String *temp;
1254     char *t;
1255     if (!indent)
1256       indent = "";
1257 
1258     temp = NewString(code);
1259 
1260     t = Char(temp);
1261     if (*t == '{') {
1262       Delitem(temp, 0);
1263       Delitem(temp, DOH_END);
1264     }
1265 
1266     /* Split the input text into lines */
1267     List *clist = SplitLines(temp);
1268     Delete(temp);
1269 
1270     // Line number within the pythoncode.
1271     int py_line = 0;
1272 
1273     String *initial = 0;
1274     Iterator si;
1275 
1276     /* Get the initial indentation.  Skip lines which only contain whitespace
1277      * and/or a comment, as the indentation of those doesn't matter:
1278      *
1279      *     A logical line that contains only spaces, tabs, formfeeds and
1280      *     possibly a comment, is ignored (i.e., no NEWLINE token is
1281      *     generated).
1282      *
1283      * see:
1284      * https://docs.python.org/2/reference/lexical_analysis.html#blank-lines
1285      * https://docs.python.org/3/reference/lexical_analysis.html#blank-lines
1286      */
1287     for (si = First(clist); si.item; si = Next(si), ++py_line) {
1288       const char *c = Char(si.item);
1289       int i;
1290       for (i = 0; isspace((unsigned char)c[i]); i++) {
1291 	// Scan forward until we find a non-space (which may be a null byte).
1292       }
1293       char ch = c[i];
1294       if (ch && ch != '#') {
1295 	// Found a line with actual content.
1296 	initial = NewStringWithSize(c, i);
1297 	break;
1298       }
1299       if (ch) {
1300 	Printv(out, indent, c, NIL);
1301       }
1302       Putc('\n', out);
1303     }
1304 
1305     // Process remaining lines.
1306     for ( ; si.item; si = Next(si), ++py_line) {
1307       const char *c = Char(si.item);
1308       // If no prefixed line was found, the above loop should have completed.
1309       assert(initial);
1310 
1311       int i;
1312       for (i = 0; isspace((unsigned char)c[i]); i++) {
1313 	// Scan forward until we find a non-space (which may be a null byte).
1314       }
1315       char ch = c[i];
1316       if (!ch) {
1317 	// Line is just whitespace - emit an empty line.
1318 	Putc('\n', out);
1319 	continue;
1320       }
1321 
1322       if (ch == '#') {
1323 	// Comment - the indentation doesn't matter to python, but try to
1324 	// adjust the whitespace for the benefit of human readers (though SWIG
1325 	// currently seems to always remove any whitespace before a '#' before
1326 	// we get here, in which case we'll just leave the comment at the start
1327 	// of the line).
1328 	if (i >= Len(initial)) {
1329 	  Printv(out, indent, NIL);
1330 	}
1331 
1332 	Printv(out, c + i, "\n", NIL);
1333 	continue;
1334       }
1335 
1336       if (i < Len(initial)) {
1337 	// There's non-whitespace in the initial prefix of this line.
1338 	Swig_error(file, line, "Line indented less than expected (line %d of %s) as no line should be indented less than the indentation in line 1\n", py_line, directive_name);
1339 	Printv(out, indent, c, "\n", NIL);
1340       } else {
1341 	if (memcmp(c, Char(initial), Len(initial)) == 0) {
1342 	  // Prefix matches initial, so just remove it.
1343 	  Printv(out, indent, c + Len(initial), "\n", NIL);
1344 	  continue;
1345 	}
1346 	Swig_warning(WARN_PYTHON_INDENT_MISMATCH,
1347 		     file, line, "Whitespace indentation is inconsistent compared to earlier lines (line %d of %s)\n", py_line, directive_name);
1348 	// To avoid gratuitously breaking interface files which worked with
1349 	// SWIG <= 3.0.5, we remove a prefix of the same number of bytes for
1350 	// lines which start with different whitespace to the line we got
1351 	// 'initial' from.
1352 	Printv(out, indent, c + Len(initial), "\n", NIL);
1353       }
1354     }
1355     Delete(clist);
1356     return out;
1357   }
1358 
1359   /* ------------------------------------------------------------
1360    * indent_docstring()
1361    *
1362    * Format (indent) a Python docstring.
1363    * Remove leading whitespace from 'code' and re-indent using
1364    * the indentation string in 'indent'.
1365    * ------------------------------------------------------------ */
1366 
indent_docstring(const String * code,const_String_or_char_ptr indent)1367   String *indent_docstring(const String *code, const_String_or_char_ptr indent) {
1368     String *out = NewString("");
1369     String *temp;
1370     char *t;
1371     if (!indent)
1372       indent = "";
1373 
1374     temp = NewString(code);
1375 
1376     t = Char(temp);
1377     if (*t == '{') {
1378       Delitem(temp, 0);
1379       Delitem(temp, DOH_END);
1380     }
1381 
1382     /* Split the input text into lines */
1383     List *clist = SplitLines(temp);
1384     Delete(temp);
1385 
1386     Iterator si;
1387 
1388     int truncate_characters_count = INT_MAX;
1389     for (si = First(clist); si.item; si = Next(si)) {
1390       const char *c = Char(si.item);
1391       int i;
1392       for (i = 0; isspace((unsigned char)c[i]); i++) {
1393 	// Scan forward until we find a non-space (which may be a null byte).
1394       }
1395       char ch = c[i];
1396       if (ch) {
1397 	// Found a line which isn't just whitespace
1398 	if (i < truncate_characters_count)
1399 	  truncate_characters_count = i;
1400       }
1401     }
1402 
1403     if (truncate_characters_count == INT_MAX)
1404       truncate_characters_count = 0;
1405 
1406     for (si = First(clist); si.item; si = Next(si)) {
1407       const char *c = Char(si.item);
1408 
1409       int i;
1410       for (i = 0; isspace((unsigned char)c[i]); i++) {
1411 	// Scan forward until we find a non-space (which may be a null byte).
1412       }
1413       char ch = c[i];
1414       if (!ch) {
1415 	// Line is just whitespace - emit an empty line.
1416 	Putc('\n', out);
1417 	continue;
1418       }
1419 
1420       Printv(out, indent, c + truncate_characters_count, "\n", NIL);
1421     }
1422     Delete(clist);
1423     return out;
1424   }
1425 
1426   /* ------------------------------------------------------------
1427    * autodoc level declarations
1428    * ------------------------------------------------------------ */
1429 
1430   enum autodoc_l {
1431     NO_AUTODOC = -2,		// no autodoc
1432     STRING_AUTODOC = -1,	// use provided string
1433     NAMES_AUTODOC = 0,		// only parameter names
1434     TYPES_AUTODOC = 1,		// parameter names and types
1435     EXTEND_AUTODOC = 2,		// extended documentation and parameter names
1436     EXTEND_TYPES_AUTODOC = 3	// extended documentation and parameter types + names
1437   };
1438 
1439 
autodoc_level(String * autodoc)1440   autodoc_l autodoc_level(String *autodoc) {
1441     autodoc_l dlevel = NO_AUTODOC;
1442     char *c = Char(autodoc);
1443     if (c) {
1444       if (isdigit(c[0])) {
1445 	dlevel = (autodoc_l) atoi(c);
1446       } else {
1447 	if (strcmp(c, "extended") == 0) {
1448 	  dlevel = EXTEND_AUTODOC;
1449 	} else {
1450 	  dlevel = STRING_AUTODOC;
1451 	}
1452       }
1453     }
1454     return dlevel;
1455   }
1456 
1457 
1458   /* ------------------------------------------------------------
1459    * have_docstring()
1460    *
1461    * Check if there is a docstring directive and it has text,
1462    * or there is an autodoc flag set
1463    * ------------------------------------------------------------ */
1464 
have_docstring(Node * n)1465   bool have_docstring(Node *n) {
1466     String *str = Getattr(n, "feature:docstring");
1467     return ((str && Len(str) > 0)
1468 	|| (Getattr(n, "feature:autodoc") && !GetFlag(n, "feature:noautodoc"))
1469 	|| (doxygen && doxygenTranslator->hasDocumentation(n))
1470       );
1471   }
1472 
1473   /* ------------------------------------------------------------
1474    * build_combined_docstring()
1475    *
1476    * Build the full docstring which may be a combination of the
1477    * explicit docstring and autodoc string or, if none of them
1478    * is specified, obtained by translating Doxygen comment to
1479    * Python.
1480    *
1481    * Return new string to be deleted by caller (never NIL but
1482    * may be empty if there is no docstring).
1483    * ------------------------------------------------------------ */
1484 
build_combined_docstring(Node * n,autodoc_t ad_type,const String * indent="",bool low_level=false)1485   String *build_combined_docstring(Node *n, autodoc_t ad_type, const String *indent = "", bool low_level = false) {
1486     String *docstr = Getattr(n, "feature:docstring");
1487     if (docstr) {
1488       // Simplify the code below by just ignoring empty docstrings.
1489       if (!Len(docstr))
1490 	docstr = NULL;
1491       else
1492 	docstr = Copy(docstr);
1493     }
1494 
1495     if (docstr) {
1496       char *t = Char(docstr);
1497       if (*t == '{') {
1498 	Delitem(docstr, 0);
1499 	Delitem(docstr, DOH_END);
1500       }
1501     }
1502 
1503     if (Getattr(n, "feature:autodoc") && !GetFlag(n, "feature:noautodoc")) {
1504       String *autodoc = make_autodoc(n, ad_type, low_level);
1505       if (autodoc && Len(autodoc) > 0) {
1506 	if (docstr) {
1507 	  Append(autodoc, "\n");
1508 	  Append(autodoc, docstr);
1509 	}
1510 
1511 	String *tmp = autodoc;
1512 	autodoc = docstr;
1513 	docstr = tmp;
1514       }
1515 
1516       Delete(autodoc);
1517     }
1518 
1519     if (!docstr) {
1520       if (doxygen) {
1521 	docstr = Getattr(n, "python:docstring");
1522 	if (!docstr && doxygenTranslator->hasDocumentation(n)) {
1523 	  docstr = doxygenTranslator->getDocumentation(n, 0);
1524 
1525 	  // Avoid rebuilding it again the next time: notice that we can't do
1526 	  // this for the combined doc string as autodoc part of it depends on
1527 	  // the sym:name of the node and it is changed while handling it, so
1528 	  // the cached results become incorrect. But Doxygen docstring only
1529 	  // depends on the comment which is not going to change, so we can
1530 	  // safely cache it.
1531 	  Setattr(n, "python:docstring", Copy(docstr));
1532 	} else {
1533 	  // Must copy here since if the docstring is multi-line, the String*
1534 	  // here will get Deleted below, which is bad if it is a pointer to
1535 	  // the cached object!
1536 	  docstr = Copy(docstr);
1537 	}
1538       }
1539     }
1540 
1541     if (!docstr)
1542       docstr = NewString("");
1543 
1544     // If there is more than one line then make docstrings like this:
1545     //
1546     //      """
1547     //      This is line1
1548     //      And here is line2 followed by the rest of them
1549     //      """
1550     //
1551     // otherwise, put it all on a single line
1552     if (Strchr(docstr, '\n')) {
1553       String *tmp = NewString("");
1554       Append(tmp, "\n");
1555       Append(tmp, indent_docstring(docstr, indent));
1556       Append(tmp, indent);
1557       Delete(docstr);
1558       docstr = tmp;
1559     }
1560 
1561     return docstr;
1562   }
1563 
1564   /* ------------------------------------------------------------
1565    * docstring()
1566    *
1567    * Get the docstring text, stripping off {} if necessary,
1568    * and enclose in triple double quotes.  If autodoc is also
1569    * set then it will build a combined docstring.
1570    * ------------------------------------------------------------ */
1571 
docstring(Node * n,autodoc_t ad_type,const String * indent,bool low_level=false)1572   String *docstring(Node *n, autodoc_t ad_type, const String *indent, bool low_level = false) {
1573     String *docstr = build_combined_docstring(n, ad_type, indent, low_level);
1574     const int len = Len(docstr);
1575     if (!len)
1576       return docstr;
1577 
1578     // Notice that all comments are created as raw strings (prefix "r"),
1579     // because '\' is used often in comments, but may break Python module from
1580     // loading. For example, in doxy comment one may write path in quotes:
1581     //
1582     //     This is path to file "C:\x\file.txt"
1583     //
1584     // Python will not load the module with such comment because of illegal
1585     // escape '\x'. '\' may additionally appear in verbatim or htmlonly sections
1586     // of doxygen doc, Latex expressions, ...
1587     String *doc = NewString("");
1588 
1589     // Determine which kind of quotes to use as delimiters: for single line
1590     // strings we can avoid problems with having a quote as the last character
1591     // of the docstring by using different kind of quotes as delimiters. For
1592     // multi-line strings this problem doesn't arise, as we always have a new
1593     // line or spaces at the end of it, but it still does no harm to do it for
1594     // them too.
1595     //
1596     // Note: we use double quotes by default, i.e. if there is no reason to
1597     // prefer using single ones, for consistency with the older SWIG versions.
1598     const bool useSingleQuotes = (Char(docstr))[len - 1] == '"';
1599 
1600     Append(doc, useSingleQuotes ? "r'''" : "r\"\"\"");
1601 
1602     // We also need to avoid having triple quotes of whichever type we use, as
1603     // this would break Python doc string syntax too. Unfortunately there is no
1604     // way to have triple quotes inside of raw-triple-quoted string, so we have
1605     // to break the string in parts and rely on concatenation of the adjacent
1606     // string literals.
1607     if (useSingleQuotes)
1608       Replaceall(docstr, "'''", "''' \"'''\" '''");
1609     else
1610       Replaceall(docstr, "\"\"\"", "\"\"\" '\"\"\"' \"\"\"");
1611 
1612     Append(doc, docstr);
1613     Append(doc, useSingleQuotes ? "'''" : "\"\"\"");
1614     Delete(docstr);
1615 
1616     return doc;
1617   }
1618 
1619   /* ------------------------------------------------------------
1620    * cdocstring()
1621    *
1622    * Get the docstring text as it would appear in C-language
1623    * source code (but without quotes around it).
1624    * ------------------------------------------------------------ */
1625 
cdocstring(Node * n,autodoc_t ad_type,bool low_level=false)1626   String *cdocstring(Node *n, autodoc_t ad_type, bool low_level = false) {
1627     String *ds = build_combined_docstring(n, ad_type, "", low_level);
1628     Replaceall(ds, "\\", "\\\\");
1629     Replaceall(ds, "\"", "\\\"");
1630     Replaceall(ds, "\n", "\\n\"\n\t\t\"");
1631     return ds;
1632   }
1633 
1634   /* -----------------------------------------------------------------------------
1635    * addMissingParameterNames()
1636    *
1637    * For functions that have not had nameless parameters set in the Language class.
1638    *
1639    * Inputs:
1640    *   plist - entire parameter list
1641    *   arg_num - the number to start from when naming arguments
1642    * Side effects:
1643    *   The "lname" attribute in each parameter in plist will be contain a parameter name
1644    * ----------------------------------------------------------------------------- */
1645 
addMissingParameterNames(Node * n,ParmList * plist,int arg_num)1646   void addMissingParameterNames(Node *n, ParmList *plist, int arg_num) {
1647     Parm *p = plist;
1648     int i = arg_num;
1649     while (p) {
1650       if (!Getattr(p, "lname")) {
1651 	String *name = makeParameterName(n, p, i);
1652 	Setattr(p, "lname", name);
1653 	Delete(name);
1654       }
1655       i++;
1656       p = nextSibling(p);
1657     }
1658   }
1659 
1660   /* ------------------------------------------------------------
1661    * make_autodocParmList()
1662    *
1663    * Generate the documentation for the function parameters
1664    * Parameters:
1665    *    arg_num:         The number to start assigning unnamed arguments from
1666    *    func_annotation: Function annotation support
1667    * ------------------------------------------------------------ */
1668 
make_autodocParmList(Node * n,bool showTypes,int arg_num=1,bool calling=false,bool func_annotation=false)1669   String *make_autodocParmList(Node *n, bool showTypes, int arg_num = 1, bool calling = false, bool func_annotation = false) {
1670 
1671     String *doc = NewString("");
1672     String *pdocs = 0;
1673     ParmList *plist = CopyParmList(Getattr(n, "parms"));
1674     Parm *p;
1675     Parm *pnext;
1676 
1677     if (calling)
1678       func_annotation = false;
1679 
1680     addMissingParameterNames(n, plist, arg_num); // for $1_name substitutions done in Swig_typemap_attach_parms
1681     Swig_typemap_attach_parms("in", plist, 0);
1682     Swig_typemap_attach_parms("doc", plist, 0);
1683 
1684     if (Strcmp(ParmList_protostr(plist), "void") == 0) {
1685       //No parameters actually
1686       return doc;
1687     }
1688 
1689     for (p = plist; p; p = pnext) {
1690       String *tm = Getattr(p, "tmap:in");
1691       if (tm) {
1692 	pnext = Getattr(p, "tmap:in:next");
1693 	if (checkAttribute(p, "tmap:in:numinputs", "0")) {
1694 	  continue;
1695 	}
1696       } else {
1697 	pnext = nextSibling(p);
1698       }
1699 
1700       String *name = 0;
1701       String *type = 0;
1702       String *value = 0;
1703       String *pdoc = Getattr(p, "tmap:doc");
1704       if (pdoc) {
1705 	name = Getattr(p, "tmap:doc:name");
1706 	type = Getattr(p, "tmap:doc:type");
1707 	value = Getattr(p, "tmap:doc:value");
1708       }
1709 
1710       // Skip the "self" argument - it is added to the parameter list automatically
1711       // and shouldn't be included in the Parameters block
1712       if (Getattr(p, "self")) {
1713 	continue;
1714       }
1715 
1716       // Note: the generated name should be consistent with that in kwnames[]
1717       String *made_name = 0;
1718       if (!name) {
1719 	name = made_name = makeParameterName(n, p, arg_num);
1720       }
1721 
1722       // Increment the argument number once we are sure this is a real argument to count
1723       arg_num++;
1724 
1725       type = type ? type : Getattr(p, "type");
1726       value = value ? value : Getattr(p, "value");
1727 
1728       if (SwigType_isvarargs(type)) {
1729 	Delete(made_name);
1730 	break;
1731       }
1732 
1733       if (Len(doc)) {
1734 	// add a comma to the previous one if any
1735 	Append(doc, ", ");
1736       }
1737 
1738       // Do the param type too?
1739       Node *nn = classLookup(Getattr(p, "type"));
1740       String *type_str = nn ? Copy(Getattr(nn, "sym:name")) : SwigType_str(type, 0);
1741       if (showTypes)
1742 	Printf(doc, "%s ", type_str);
1743 
1744       Append(doc, name);
1745       if (pdoc) {
1746 	if (!pdocs)
1747 	  // numpydoc style: https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
1748 	  pdocs = NewString("\nParameters\n----------\n");
1749 	Printf(pdocs, "%s\n", pdoc);
1750       }
1751       // Write the function annotation
1752       if (func_annotation)
1753 	Printf(doc, ": \"%s\"", type_str);
1754 
1755       // Write default value
1756       if (value && !calling) {
1757 	String *new_value = convertValue(value, Getattr(p, "type"));
1758 	if (new_value) {
1759 	  value = new_value;
1760 	} else {
1761 	  // Even if the value is not representable in the target language, still use it in the documentation, for compatibility with the previous SWIG versions
1762 	  // and because it can still be useful to see the C++ expression there.
1763 	  Node *lookup = Swig_symbol_clookup(value, 0);
1764 	  if (lookup)
1765 	    value = Getattr(lookup, "sym:name");
1766 	}
1767 	Printf(doc, "=%s", value);
1768 
1769 	if (new_value)
1770 	  Delete(new_value);
1771       }
1772       Delete(type_str);
1773       Delete(made_name);
1774     }
1775     if (pdocs)
1776       Setattr(n, "feature:pdocs", pdocs);
1777     Delete(plist);
1778     return doc;
1779   }
1780 
1781   /* ------------------------------------------------------------
1782    * make_autodoc()
1783    *
1784    * Build a docstring for the node, using parameter and other
1785    * info in the parse tree.  If the value of the autodoc
1786    * attribute is "0" then do not include parameter types, if
1787    * it is "1" (the default) then do.  If it has some other
1788    * value then assume it is supplied by the extension writer
1789    * and use it directly.
1790    * ------------------------------------------------------------ */
1791 
make_autodoc(Node * n,autodoc_t ad_type,bool low_level=false)1792   String *make_autodoc(Node *n, autodoc_t ad_type, bool low_level = false) {
1793     int extended = 0;
1794     bool first_func = true;
1795     // If the function is overloaded then this function is called
1796     // for the last one.  Rewind to the first so the docstrings are
1797     // in order.
1798     while (Getattr(n, "sym:previousSibling"))
1799       n = Getattr(n, "sym:previousSibling");
1800 
1801     String *doc = NewString("");
1802     while (n) {
1803       bool showTypes = false;
1804       bool skipAuto = false;
1805       String *autodoc = Getattr(n, "feature:autodoc");
1806       autodoc_l dlevel = autodoc_level(autodoc);
1807       switch (dlevel) {
1808       case NO_AUTODOC:
1809 	break;
1810       case NAMES_AUTODOC:
1811 	showTypes = false;
1812 	break;
1813       case TYPES_AUTODOC:
1814 	showTypes = true;
1815 	break;
1816       case EXTEND_AUTODOC:
1817 	extended = 1;
1818 	showTypes = false;
1819 	break;
1820       case EXTEND_TYPES_AUTODOC:
1821 	extended = 1;
1822 	showTypes = true;
1823 	break;
1824       case STRING_AUTODOC:
1825 	Append(doc, autodoc);
1826 	skipAuto = true;
1827 	break;
1828       }
1829 
1830       if (!skipAuto) {
1831 	/* Check if a documentation name was given for either the low-level C API or high-level Python shadow API */
1832 	String *symname = Getattr(n, low_level ? "doc:low:name" : "doc:high:name");
1833 	if (!symname) {
1834 	  symname = Getattr(n, "sym:name");
1835 	}
1836 
1837 	SwigType *type = Getattr(n, "type");
1838 	String *type_str = NULL;
1839 
1840 	// If the function has default arguments, then that documentation covers this version too
1841 	if (Getattr(n, "defaultargs") != NULL) {
1842 	  n = Getattr(n, "sym:nextSibling");
1843 	  continue;
1844 	}
1845 
1846 	if (!first_func)
1847 	  Append(doc, "\n");
1848 
1849 	if (type) {
1850 	  if (Strcmp(type, "void") == 0) {
1851 	    type_str = NULL;
1852 	  } else {
1853 	    Node *nn = classLookup(type);
1854 	    type_str = nn ? Copy(Getattr(nn, "sym:name")) : SwigType_str(type, 0);
1855 	  }
1856 	}
1857 
1858 	/* Treat the low-level C API functions for getting/setting variables as methods for documentation purposes */
1859 	String *kind = Getattr(n, "kind");
1860 	if (kind && Strcmp(kind, "variable") == 0) {
1861 	  if (ad_type == AUTODOC_FUNC) {
1862 	    ad_type = AUTODOC_METHOD;
1863 	  }
1864 	}
1865 	/* Treat destructors as methods for documentation purposes */
1866 	String *nodeType = Getattr(n, "nodeType");
1867 	if (nodeType && Strcmp(nodeType, "destructor") == 0) {
1868 	  if (ad_type == AUTODOC_FUNC) {
1869 	    ad_type = AUTODOC_METHOD;
1870 	  }
1871 	}
1872 
1873 	switch (ad_type) {
1874 	case AUTODOC_CLASS:
1875 	  {
1876 	    // Only do the autodoc if there isn't a docstring for the class
1877 	    String *str = Getattr(n, "feature:docstring");
1878 	    if (!str || Len(str) == 0) {
1879 	      if (builtin) {
1880 		String *name = Getattr(n, "name");
1881 		String *rname = add_explicit_scope(SwigType_namestr(name));
1882 		Printf(doc, "%s", rname);
1883 		Delete(rname);
1884 	      } else {
1885 		if (CPlusPlus) {
1886 		  Printf(doc, "Proxy of C++ %s class.", SwigType_namestr(real_classname));
1887 		} else {
1888 		  Printf(doc, "Proxy of C %s struct.", SwigType_namestr(real_classname));
1889 		}
1890 	      }
1891 	    }
1892 	  }
1893 	  break;
1894 	case AUTODOC_CTOR:
1895 	  if (Strcmp(class_name, symname) == 0) {
1896 	    String *paramList = make_autodocParmList(n, showTypes, 2);
1897 	    Printf(doc, "__init__(");
1898 	    if (showTypes)
1899 	      Printf(doc, "%s ", class_name);
1900 	    if (Len(paramList))
1901 	      Printf(doc, "self, %s) -> %s", paramList, class_name);
1902 	    else
1903 	      Printf(doc, "self) -> %s", class_name);
1904 	  } else
1905 	    Printf(doc, "%s(%s) -> %s", symname, make_autodocParmList(n, showTypes), class_name);
1906 	  break;
1907 
1908 	case AUTODOC_DTOR:
1909 	  if (showTypes)
1910 	    Printf(doc, "__del__(%s self)", class_name);
1911 	  else
1912 	    Printf(doc, "__del__(self)");
1913 	  break;
1914 
1915 	case AUTODOC_STATICFUNC:
1916 	  Printf(doc, "%s(%s)", symname, make_autodocParmList(n, showTypes));
1917 	  if (type_str)
1918 	    Printf(doc, " -> %s", type_str);
1919 	  break;
1920 
1921 	case AUTODOC_FUNC:
1922 	  Printf(doc, "%s(%s)", symname, make_autodocParmList(n, showTypes));
1923 	  if (type_str)
1924 	    Printf(doc, " -> %s", type_str);
1925 	  break;
1926 
1927 	case AUTODOC_METHOD:
1928 	  {
1929 	    String *paramList = make_autodocParmList(n, showTypes, 2);
1930 	    Printf(doc, "%s(", symname);
1931 	    if (showTypes)
1932 	      Printf(doc, "%s ", class_name);
1933 	    if (Len(paramList))
1934 	      Printf(doc, "self, %s)", paramList);
1935 	    else
1936 	      Printf(doc, "self)");
1937 	    if (type_str)
1938 	      Printf(doc, " -> %s", type_str);
1939 	  }
1940 	  break;
1941 
1942 	case AUTODOC_CONST:
1943 	  // There is no autodoc support for constants currently, this enum
1944 	  // element only exists to allow calling docstring() with it.
1945 	  return NULL;
1946 	case AUTODOC_VAR:
1947 	  // Variables can also be documented (e.g. through the property() function in python)
1948 	  Printf(doc, "%s", symname);
1949 	  if (showTypes) {
1950 	    String *type = Getattr(n, "tmap:doc:type");
1951 	    if (!type)
1952 	      type = Getattr(n, "membervariableHandler:type");
1953 	    if (!type)
1954 	      type = Getattr(n, "type");
1955 	    Printf(doc, " : %s", type);
1956 	  }
1957 	  break;
1958 	}
1959 	Delete(type_str);
1960 
1961 	// Special case: wrapper functions to get a variable should have no parameters.
1962 	// Because the node is re-used for the setter and getter, the feature:pdocs field will
1963 	// exist for the getter function, so explicitly avoid printing parameters in this case.
1964 	bool variable_getter = kind && Strcmp(kind, "variable") == 0 && Getattr(n, "memberget");
1965 	if (extended && ad_type != AUTODOC_VAR && !variable_getter) {
1966 	  String *pdocs = Getattr(n, "feature:pdocs");
1967 	  if (pdocs) {
1968 	    Printv(doc, "\n", pdocs, NULL);
1969 	  }
1970 	}
1971       }
1972       // if it's overloaded then get the next decl and loop around again
1973       n = Getattr(n, "sym:nextSibling");
1974       if (n)
1975 	first_func = false;
1976     }
1977 
1978     return doc;
1979   }
1980 
1981   /* ------------------------------------------------------------
1982    * convertIntegerValue()
1983    *
1984    * Check if string v is an integer and can be represented in
1985    * Python. If so, return an appropriate Python representation,
1986    * otherwise (or if we are unsure), return NIL.
1987    * ------------------------------------------------------------ */
convertIntegerValue(String * v,SwigType * resolved_type)1988   String *convertIntegerValue(String *v, SwigType *resolved_type) {
1989     const char *const s = Char(v);
1990     char *end;
1991     String *result = NIL;
1992 
1993     // Check if this is an integer number in any base.
1994     errno = 0;
1995     long value = strtol(s, &end, 0);
1996     if (errno == ERANGE || end == s)
1997       return NIL;
1998 
1999     if (*end != '\0') {
2000       // If there is a suffix after the number, we can safely ignore "l"
2001       // and (provided the number is unsigned) "u", and also combinations of
2002       // these, but not anything else.
2003       for (char *p = end; *p != '\0'; ++p) {
2004         switch (*p) {
2005           case 'l':
2006           case 'L':
2007 	    break;
2008           case 'u':
2009           case 'U':
2010 	    if (value < 0)
2011 	      return NIL;
2012             break;
2013           default:
2014             return NIL;
2015         }
2016       }
2017     }
2018     // So now we are certain that we are indeed dealing with an integer
2019     // that has a representation as long given by value.
2020 
2021     // Restrict to guaranteed supported range in Python, see maxint docs: https://docs.python.org/2/library/sys.html#sys.maxint
2022     // Don't do this pointless check when long is 32 bits or smaller as strtol will have already failed with ERANGE
2023 #if LONG_MAX > PYTHON_INT_MAX || LONG_MIN < PYTHON_INT_MIN
2024     if (value > PYTHON_INT_MAX || value < PYTHON_INT_MIN) {
2025       return NIL;
2026     }
2027 #endif
2028 
2029     if (Cmp(resolved_type, "bool") == 0)
2030       // Allow integers as the default value for a bool parameter.
2031       return NewString(value ? "True" : "False");
2032 
2033     if (value == 0)
2034       return NewString(SwigType_ispointer(resolved_type) ? "None" : "0");
2035 
2036     // v may still be octal or hexadecimal:
2037     const char *p = s;
2038     if (*p == '+' || *p == '-')
2039       ++p;
2040     if (*p == '0' && *(p+1) != 'x' && *(p+1) != 'X') {
2041       // This must have been an octal number. This is the only case we
2042       // cannot use in Python directly, since Python 2 and 3 use non-
2043       // compatible representations.
2044       result = NewString(*s == '-' ? "int(\"-" : "int(\"");
2045       String *octal_string = NewStringWithSize(p, (int) (end - p));
2046       Append(result, octal_string);
2047       Append(result, "\", 8)");
2048       Delete(octal_string);
2049       return result;
2050     }
2051     result = *end == '\0' ? Copy(v) : NewStringWithSize(s, (int) (end - s));
2052     return result;
2053   }
2054 
2055   /* ------------------------------------------------------------
2056    * convertDoubleValue()
2057    *
2058    * Check if the given string looks like a decimal floating point constant
2059    * and return it if it does, otherwise return NIL.
2060    * ------------------------------------------------------------ */
convertDoubleValue(String * v)2061   String *convertDoubleValue(String *v) {
2062     const char *const s = Char(v);
2063     char *end;
2064 
2065     errno = 0;
2066     double value = strtod(s, &end);
2067     (void) value;
2068     if (errno != ERANGE && end != s) {
2069       // An added complication: at least some versions of strtod() recognize
2070       // hexadecimal floating point numbers which don't exist in Python, so
2071       // detect them ourselves and refuse to convert them (this can't be done
2072       // without loss of precision in general).
2073       //
2074       // Also don't accept neither "NAN" nor "INFINITY" (both of which
2075       // conveniently contain "n").
2076       if (strpbrk(s, "xXnN"))
2077 	return NIL;
2078 
2079       // Disregard optional "f" suffix, it can be just dropped in Python as it
2080       // uses doubles for everything anyhow.
2081       for (char * p = end; *p != '\0'; ++p) {
2082 	switch (*p) {
2083 	  case 'f':
2084 	  case 'F':
2085 	    break;
2086 
2087 	  default:
2088 	    return NIL;
2089 	}
2090       }
2091 
2092       // Avoid unnecessary string allocation in the common case when we don't
2093       // need to remove any suffix.
2094       return *end == '\0' ? Copy(v) : NewStringWithSize(s, (int)(end - s));
2095     }
2096 
2097     return NIL;
2098   }
2099 
2100   /* ------------------------------------------------------------
2101    * convertValue()
2102    *
2103    * Check if string v can be a Python value literal or a
2104    * constant. Return an equivalent Python representation,
2105    * or NIL if it isn't, or we are unsure.
2106    * ------------------------------------------------------------ */
convertValue(String * v,SwigType * type)2107   String *convertValue(String *v, SwigType *type) {
2108     const char *const s = Char(v);
2109     String *result = NIL;
2110     SwigType *resolved_type = SwigType_typedef_resolve_all(type);
2111 
2112     result = convertIntegerValue(v, resolved_type);
2113     if (!result) {
2114       result = convertDoubleValue(v);
2115       if (!result) {
2116 	if (Strcmp(v, "true") == 0)
2117 	  result = NewString("True");
2118 	else if (Strcmp(v, "false") == 0)
2119 	  result = NewString("False");
2120 	else if (Strcmp(v, "NULL") == 0 || Strcmp(v, "nullptr") == 0)
2121 	  result = SwigType_ispointer(resolved_type) ? NewString("None") : NewString("0");
2122 	// This could also be an enum type, default value of which could be
2123 	// representable in Python if it doesn't include any scope (which could,
2124 	// but currently is not, translated).
2125 	else if (!Strchr(s, ':')) {
2126 	  Node *lookup = Swig_symbol_clookup(v, 0);
2127 	  if (lookup) {
2128 	    if (Cmp(Getattr(lookup, "nodeType"), "enumitem") == 0)
2129 	      result = Copy(Getattr(lookup, "sym:name"));
2130 	  }
2131 	}
2132       }
2133     }
2134 
2135     Delete(resolved_type);
2136     return result;
2137   }
2138 
2139   /* ------------------------------------------------------------
2140    * is_representable_as_pyargs()
2141    *
2142    * Check if the function parameters default argument values
2143    * can be represented in Python.
2144    *
2145    * If this method returns false, the parameters will be translated
2146    * to a generic "*args" which allows us to deal with default values
2147    * at C++ code level where they can always be handled.
2148    * ------------------------------------------------------------ */
is_representable_as_pyargs(Node * n)2149   bool is_representable_as_pyargs(Node *n) {
2150     ParmList *plist = CopyParmList(Getattr(n, "parms"));
2151     Swig_typemap_attach_parms("default", plist, NULL);
2152 
2153     Parm *p;
2154     Parm *pnext;
2155 
2156     for (p = plist; p; p = pnext) {
2157       pnext = nextSibling(p);
2158       String *tm = Getattr(p, "tmap:in");
2159       if (tm) {
2160 	Parm *in_next = Getattr(p, "tmap:in:next");
2161 	if (in_next)
2162 	  pnext = in_next;
2163 	if (checkAttribute(p, "tmap:in:numinputs", "0")) {
2164 	  continue;
2165 	}
2166       }
2167 
2168       // "default" typemap can contain arbitrary C++ code, so while it could, in
2169       // principle, be possible to examine it and check if it's just something
2170       // simple of the form "$1 = expression" and then use convertValue() to
2171       // check if expression can be used in Python, but for now we just
2172       // pessimistically give up and prefer to handle this at C++ level only.
2173       if (Getattr(p, "tmap:default"))
2174 	return false;
2175 
2176       String *value = Getattr(p, "value");
2177       if (value) {
2178 	String *convertedValue = convertValue(value, Getattr(p, "type"));
2179 	if (!convertedValue)
2180 	  return false;
2181 	Delete(convertedValue);
2182       }
2183     }
2184 
2185     return true;
2186   }
2187 
2188 
2189   /* ------------------------------------------------------------
2190    * is_real_overloaded()
2191    *
2192    * Check if the function is overloaded, but not just have some
2193    * siblings generated due to the original function having
2194    * default arguments.
2195    * ------------------------------------------------------------ */
is_real_overloaded(Node * n)2196   bool is_real_overloaded(Node *n) {
2197     Node *h = Getattr(n, "sym:overloaded");
2198     Node *i;
2199     if (!h)
2200       return false;
2201 
2202     i = Getattr(h, "sym:nextSibling");
2203     while (i) {
2204       Node *nn = Getattr(i, "defaultargs");
2205       if (nn != h) {
2206 	/* Check if overloaded function has defaultargs and
2207 	 * pointed to the first overloaded. */
2208 	return true;
2209       }
2210       i = Getattr(i, "sym:nextSibling");
2211     }
2212 
2213     return false;
2214   }
2215 
2216   /* ------------------------------------------------------------
2217    * make_pyParmList()
2218    *
2219    * Generate parameter list for Python functions or methods,
2220    * reuse make_autodocParmList() to do so.
2221    * ------------------------------------------------------------ */
make_pyParmList(Node * n,bool in_class,bool is_calling,int kw,bool has_self_for_count=false)2222   String *make_pyParmList(Node *n, bool in_class, bool is_calling, int kw, bool has_self_for_count = false) {
2223     /* Get the original function for a defaultargs copy,
2224      * see default_arguments() in parser.y. */
2225     Node *nn = Getattr(n, "defaultargs");
2226     if (nn)
2227       n = nn;
2228 
2229     Parm *parms = Getattr(n, "parms");
2230     int varargs = parms ? emit_isvarargs(parms) : 0;
2231 
2232     /* We prefer to explicitly list all parameters of the C function in the
2233        generated Python code as this makes the function more convenient to use,
2234        however in some cases we must replace the real parameters list with just
2235        the catch all "*args". This happens when:
2236 
2237 	1. The function is overloaded as Python doesn't support this.
2238 	2. We were explicitly asked to use the "compact" arguments form.
2239 	3. We were explicitly asked to use default args from C via the "python:cdefaultargs" feature.
2240 	4. One of the default argument values can't be represented in Python.
2241 	5. Varargs that haven't been forced to use a fixed number of arguments with %varargs.
2242      */
2243     if (is_real_overloaded(n) || GetFlag(n, "feature:compactdefaultargs") || GetFlag(n, "feature:python:cdefaultargs") || !is_representable_as_pyargs(n) || varargs) {
2244       String *parms = NewString("");
2245       if (in_class)
2246 	Printf(parms, "self, ");
2247       Printf(parms, "*args");
2248       if (kw)
2249 	Printf(parms, ", **kwargs");
2250       return parms;
2251     }
2252 
2253     bool funcanno = py3 ? true : false;
2254     String *params = NewString("");
2255     String *_params = make_autodocParmList(n, false, ((in_class || has_self_for_count)? 2 : 1), is_calling, funcanno);
2256 
2257     if (in_class) {
2258       Printf(params, "self");
2259       if (Len(_params) > 0)
2260 	Printf(params, ", ");
2261     }
2262 
2263     Printv(params, _params, NULL);
2264 
2265     return params;
2266   }
2267 
2268   /* ------------------------------------------------------------
2269    * have_pythonprepend()
2270    *
2271    * Check if there is a %pythonprepend directive and it has text
2272    * ------------------------------------------------------------ */
2273 
have_pythonprepend(Node * n)2274   bool have_pythonprepend(Node *n) {
2275     String *str = Getattr(n, "feature:pythonprepend");
2276     return (str && Len(str) > 0);
2277   }
2278 
2279   /* ------------------------------------------------------------
2280    * pythonprepend()
2281    *
2282    * Get the %pythonprepend code, stripping off {} if necessary
2283    * ------------------------------------------------------------ */
2284 
pythonprepend(Node * n)2285   String *pythonprepend(Node *n) {
2286     String *str = Getattr(n, "feature:pythonprepend");
2287     char *t = Char(str);
2288     if (*t == '{') {
2289       Delitem(str, 0);
2290       Delitem(str, DOH_END);
2291     }
2292     return str;
2293   }
2294 
2295   /* ------------------------------------------------------------
2296    * have_pythonappend()
2297    *
2298    * Check if there is a %pythonappend directive and it has text
2299    * ------------------------------------------------------------ */
2300 
have_pythonappend(Node * n)2301   bool have_pythonappend(Node *n) {
2302     String *str = Getattr(n, "feature:pythonappend");
2303     if (!str)
2304       str = Getattr(n, "feature:addtofunc");
2305     return (str && Len(str) > 0);
2306   }
2307 
2308   /* ------------------------------------------------------------
2309    * pythonappend()
2310    *
2311    * Get the %pythonappend code, stripping off {} if necessary
2312    * ------------------------------------------------------------ */
2313 
pythonappend(Node * n)2314   String *pythonappend(Node *n) {
2315     String *str = Getattr(n, "feature:pythonappend");
2316     if (!str)
2317       str = Getattr(n, "feature:addtofunc");
2318 
2319     char *t = Char(str);
2320     if (*t == '{') {
2321       Delitem(str, 0);
2322       Delitem(str, DOH_END);
2323     }
2324     return str;
2325   }
2326 
2327   /* ------------------------------------------------------------
2328    * have_addtofunc()
2329    *
2330    * Check if there is a %addtofunc directive and it has text
2331    * ------------------------------------------------------------ */
2332 
have_addtofunc(Node * n)2333   bool have_addtofunc(Node *n) {
2334     return have_pythonappend(n) || have_pythonprepend(n);
2335   }
2336 
2337 
2338   /* ------------------------------------------------------------
2339    * returnTypeAnnotation()
2340    *
2341    * Helper function for constructing the function annotation
2342    * of the returning type, return a empty string for Python 2.x
2343    * ------------------------------------------------------------ */
returnTypeAnnotation(Node * n)2344   String *returnTypeAnnotation(Node *n) {
2345     String *ret = 0;
2346     Parm *p = Getattr(n, "parms");
2347     String *tm;
2348     /* Try to guess the returning type by argout typemap,
2349      * however the result may not accurate. */
2350     while (p) {
2351       if ((tm = Getattr(p, "tmap:argout:match_type"))) {
2352 	tm = SwigType_str(tm, 0);
2353 	if (ret)
2354 	  Printv(ret, ", ", tm, NULL);
2355 	else
2356 	  ret = tm;
2357 	p = Getattr(p, "tmap:argout:next");
2358       } else {
2359 	p = nextSibling(p);
2360       }
2361     }
2362     /* If no argout typemap, then get the returning type from
2363      * the function prototype. */
2364     if (!ret) {
2365       ret = Getattr(n, "type");
2366       if (ret)
2367 	ret = SwigType_str(ret, 0);
2368     }
2369     return (ret && py3) ? NewStringf(" -> \"%s\"", ret)
2370 	: NewString("");
2371   }
2372 
2373   /* ------------------------------------------------------------
2374    * emitFunctionShadowHelper()
2375    *
2376    * Refactoring some common code out of functionWrapper and
2377    * dispatchFunction that writes the proxy code for non-member
2378    * functions.
2379    * ------------------------------------------------------------ */
2380 
emitFunctionShadowHelper(Node * n,File * f_dest,String * name,int kw)2381   void emitFunctionShadowHelper(Node *n, File *f_dest, String *name, int kw) {
2382     String *parms = make_pyParmList(n, false, false, kw);
2383     String *callParms = make_pyParmList(n, false, true, kw);
2384 
2385     // Callbacks need the C function in order to extract the pointer from the swig_ptr: string
2386     bool fast = (fastproxy && !have_addtofunc(n)) || Getattr(n, "feature:callback");
2387 
2388     if (!fast || olddefs) {
2389       /* Make a wrapper function to insert the code into */
2390       Printv(f_dest, "\n", "def ", name, "(", parms, ")", returnTypeAnnotation(n), ":\n", NIL);
2391       if (have_docstring(n))
2392 	Printv(f_dest, tab4, docstring(n, AUTODOC_FUNC, tab4, true), "\n", NIL);
2393       if (have_pythonprepend(n))
2394 	Printv(f_dest, indent_pythoncode(pythonprepend(n), tab4, Getfile(n), Getline(n), "%pythonprepend or %feature(\"pythonprepend\")"), "\n", NIL);
2395       if (have_pythonappend(n)) {
2396 	Printv(f_dest, tab4 "val = ", funcCall(name, callParms), "\n", NIL);
2397 	Printv(f_dest, indent_pythoncode(pythonappend(n), tab4, Getfile(n), Getline(n), "%pythonappend or %feature(\"pythonappend\")"), "\n", NIL);
2398 	Printv(f_dest, tab4 "return val\n", NIL);
2399       } else {
2400 	Printv(f_dest, tab4 "return ", funcCall(name, callParms), "\n", NIL);
2401       }
2402     }
2403 
2404     // Below may result in a 2nd definition of the method when -olddefs is used. The Python interpreter will use the second definition as it overwrites the first.
2405     if (fast) {
2406       /* If there is no addtofunc directive then just assign from the extension module (for speed up) */
2407       Printv(f_dest, name, " = ", module, ".", name, "\n", NIL);
2408     }
2409   }
2410 
2411 
2412   /* ------------------------------------------------------------
2413    * check_kwargs()
2414    *
2415    * check if using kwargs is allowed for this Node
2416    * ------------------------------------------------------------ */
2417 
check_kwargs(Node * n) const2418   int check_kwargs(Node *n) const {
2419     return (use_kw || GetFlag(n, "feature:kwargs"))
2420 	&& !GetFlag(n, "memberset") && !GetFlag(n, "memberget");
2421   }
2422 
2423 
2424 
2425   /* ------------------------------------------------------------
2426    * add_method()
2427    * ------------------------------------------------------------ */
2428 
add_method(String * name,String * function,int kw,Node * n=0,int funpack=0,int num_required=-1,int num_arguments=-1)2429   void add_method(String *name, String *function, int kw, Node *n = 0, int funpack = 0, int num_required = -1, int num_arguments = -1) {
2430     String * meth_str = NewString("");
2431     if (!kw) {
2432       if (funpack) {
2433 	if (num_required == 0 && num_arguments == 0) {
2434 	  Printf(meth_str, "\t { \"%s\", %s, METH_NOARGS, ", name, function);
2435 	} else if (num_required == 1 && num_arguments == 1) {
2436 	  Printf(meth_str, "\t { \"%s\", %s, METH_O, ", name, function);
2437 	} else {
2438 	  Printf(meth_str, "\t { \"%s\", %s, METH_VARARGS, ", name, function);
2439 	}
2440       } else {
2441 	Printf(meth_str, "\t { \"%s\", %s, METH_VARARGS, ", name, function);
2442       }
2443     } else {
2444       // Cast via void(*)(void) to suppress GCC -Wcast-function-type warning.
2445       // Python should always call the function correctly, but the Python C API
2446       // requires us to store it in function pointer of a different type.
2447       Printf(meth_str, "\t { \"%s\", (PyCFunction)(void(*)(void))%s, METH_VARARGS|METH_KEYWORDS, ", name, function);
2448     }
2449     Append(methods, meth_str);
2450     if (fastproxy) {
2451       Append(methods_proxydocs, meth_str);
2452     }
2453     Delete(meth_str);
2454 
2455     if (!n) {
2456       Append(methods, "NULL");
2457       if (fastproxy) {
2458 	Append(methods_proxydocs, "NULL");
2459       }
2460     } else if (have_docstring(n)) {
2461       /* Use the low-level docstring here since this is the docstring that will be used for the C API */
2462       String *ds = cdocstring(n, Getattr(n, "memberfunction") ? AUTODOC_METHOD : AUTODOC_FUNC, true);
2463       Printf(methods, "\"%s\"", ds);
2464       if (fastproxy) {
2465 	/* In the fastproxy case, we must also record the high-level docstring for use in the Python shadow API */
2466 	Delete(ds);
2467         ds = cdocstring(n, Getattr(n, "memberfunction") ? AUTODOC_METHOD : AUTODOC_FUNC);
2468 	Printf(methods_proxydocs, "\"%s\"", ds);
2469       }
2470       Delete(ds);
2471     } else if (Getattr(n, "feature:callback")) {
2472       Printf(methods, "\"swig_ptr: %s\"", Getattr(n, "feature:callback:name"));
2473       if (fastproxy) {
2474 	Printf(methods_proxydocs, "\"swig_ptr: %s\"", Getattr(n, "feature:callback:name"));
2475       }
2476     } else {
2477       Append(methods, "NULL");
2478       if (fastproxy) {
2479 	Append(methods_proxydocs, "NULL");
2480       }
2481     }
2482 
2483     Append(methods, "},\n");
2484     if (fastproxy) {
2485       Append(methods_proxydocs, "},\n");
2486     }
2487   }
2488 
2489   /* ------------------------------------------------------------
2490    * dispatchFunction()
2491    * ------------------------------------------------------------ */
dispatchFunction(Node * n,String * linkage,int funpack=0,bool builtin_self=false,bool builtin_ctor=false,bool director_class=false)2492   void dispatchFunction(Node *n, String *linkage, int funpack = 0, bool builtin_self = false, bool builtin_ctor = false, bool director_class = false) {
2493     /* Last node in overloaded chain */
2494 
2495     bool add_self = builtin_self && (!builtin_ctor || director_class);
2496 
2497     int maxargs;
2498 
2499     String *tmp = NewString("");
2500     String *dispatch;
2501 
2502     const char *dispatch_call = funpack ? "%s(self, argc, argv);" : (builtin_ctor ? "%s(self, args, NULL);" : "%s(self, args);");
2503     String *dispatch_code = NewStringf("return %s", dispatch_call);
2504 
2505     if (castmode) {
2506       dispatch = Swig_overload_dispatch_cast(n, dispatch_code, &maxargs);
2507     } else {
2508       String *fastdispatch_code;
2509       if (builtin_ctor)
2510 	fastdispatch_code = NewStringf("int retval = %s\nif (retval == 0 || !SWIG_Python_TypeErrorOccurred(NULL)) return retval;\nSWIG_fail;", dispatch_call);
2511       else
2512 	fastdispatch_code = NewStringf("PyObject *retobj = %s\nif (!SWIG_Python_TypeErrorOccurred(retobj)) return retobj;\nSWIG_fail;", dispatch_call);
2513       if (!CPlusPlus) {
2514 	Insert(fastdispatch_code, 0, "{\n");
2515 	Append(fastdispatch_code, "\n}");
2516       }
2517       dispatch = Swig_overload_dispatch(n, dispatch_code, &maxargs, fastdispatch_code);
2518       Delete(fastdispatch_code);
2519     }
2520 
2521     /* Generate a dispatch wrapper for all overloaded functions */
2522 
2523     Wrapper *f = NewWrapper();
2524     String *symname = Getattr(n, "sym:name");
2525     String *wname = Swig_name_wrapper(symname);
2526 
2527     const char *builtin_kwargs = builtin_ctor ? ", PyObject *kwargs" : "";
2528     Printv(f->def, linkage, builtin_ctor ? "int " : "PyObject *", wname, "(PyObject *self, PyObject *args", builtin_kwargs, ") {", NIL);
2529 
2530     Wrapper_add_local(f, "argc", "Py_ssize_t argc");
2531     Printf(tmp, "PyObject *argv[%d] = {0}", maxargs + 1);
2532     Wrapper_add_local(f, "argv", tmp);
2533 
2534     if (!fastunpack) {
2535       Wrapper_add_local(f, "ii", "Py_ssize_t ii");
2536 
2537       if (builtin_ctor)
2538 	Printf(f->code, "if (!SWIG_Python_CheckNoKeywords(kwargs, \"%s\")) SWIG_fail;\n", symname);
2539 
2540       if (maxargs - (add_self ? 1 : 0) > 0) {
2541         Append(f->code, "if (!PyTuple_Check(args)) SWIG_fail;\n");
2542         Append(f->code, "argc = PyObject_Length(args);\n");
2543       } else {
2544         Append(f->code, "argc = args ? PyObject_Length(args) : 0;\n");
2545       }
2546 
2547       if (add_self)
2548 	Append(f->code, "argv[0] = self;\n");
2549       Printf(f->code, "for (ii = 0; (ii < %d) && (ii < argc); ii++) {\n", add_self ? maxargs - 1 : maxargs);
2550       Printf(f->code, "argv[ii%s] = PyTuple_GET_ITEM(args,ii);\n", add_self ? " + 1" : "");
2551       Append(f->code, "}\n");
2552       if (add_self)
2553 	Append(f->code, "argc++;\n");
2554     } else {
2555       if (builtin_ctor)
2556 	Printf(f->code, "if (!SWIG_Python_CheckNoKeywords(kwargs, \"%s\")) SWIG_fail;\n", symname);
2557       Printf(f->code, "if (!(argc = SWIG_Python_UnpackTuple(args, \"%s\", 0, %d, argv%s))) SWIG_fail;\n", symname, maxargs, add_self ? "+1" : "");
2558       if (add_self)
2559 	Append(f->code, "argv[0] = self;\n");
2560       else
2561 	Append(f->code, "--argc;\n");
2562     }
2563 
2564     Replaceall(dispatch, "$args", "self, args");
2565 
2566     Printv(f->code, dispatch, "\n", NIL);
2567 
2568     if (GetFlag(n, "feature:python:maybecall")) {
2569       Append(f->code, "fail:\n");
2570       Append(f->code, "  Py_INCREF(Py_NotImplemented);\n");
2571       Append(f->code, "  return Py_NotImplemented;\n");
2572     } else {
2573       Node *sibl = n;
2574       while (Getattr(sibl, "sym:previousSibling"))
2575 	sibl = Getattr(sibl, "sym:previousSibling");	// go all the way up
2576       String *protoTypes = NewString("");
2577       do {
2578 	String *fulldecl = Swig_name_decl(sibl);
2579 	Printf(protoTypes, "\n\"    %s\\n\"", fulldecl);
2580 	Delete(fulldecl);
2581       } while ((sibl = Getattr(sibl, "sym:nextSibling")));
2582       Append(f->code, "fail:\n");
2583       Printf(f->code, "  SWIG_Python_RaiseOrModifyTypeError("
2584 	     "\"Wrong number or type of arguments for overloaded function '%s'.\\n\"" "\n\"  Possible C/C++ prototypes are:\\n\"%s);\n", symname, protoTypes);
2585       Printf(f->code, "return %s;\n", builtin_ctor ? "-1" : "0");
2586       Delete(protoTypes);
2587     }
2588     Printv(f->code, "}\n", NIL);
2589     Wrapper_print(f, f_wrappers);
2590     Node *p = Getattr(n, "sym:previousSibling");
2591     if (!builtin_self)
2592       add_method(symname, wname, 0, p);
2593 
2594     /* Create a shadow for this function (if enabled and not in a member function) */
2595     if (!builtin && (shadow) && (!(shadow & PYSHADOW_MEMBER))) {
2596       emitFunctionShadowHelper(n, in_class ? f_shadow_stubs : f_shadow, symname, 0);
2597     }
2598     DelWrapper(f);
2599     Delete(dispatch);
2600     Delete(dispatch_code);
2601     Delete(tmp);
2602     Delete(wname);
2603   }
2604 
2605   /* ------------------------------------------------------------
2606    * functionWrapper()
2607    * ------------------------------------------------------------ */
2608 
2609   /*
2610     A note about argument marshalling with built-in types.
2611     There are three distinct cases for member (non-static) methods:
2612 
2613     1) An ordinary member function.  In this case, the first param in
2614     the param list is 'this'.  For builtin types, 'this' is taken from
2615     the first argument to the wrapper (usually called 'self); it's not
2616     extracted from the second argument (which is usually a tuple).
2617 
2618     2) A constructor for a non-director class.  In this case, the
2619     param list doesn't contain an entry for 'this', but the first ('self')
2620     argument to the wrapper *does* contain the newly-allocated,
2621     uninitialized object.
2622 
2623     3) A constructor for a director class.  In this case, the param
2624     list contains a 'self' param, which comes from the first argument
2625     to the wrapper function.
2626   */
2627 
get_implicitconv_flag(Node * klass)2628   const char *get_implicitconv_flag(Node *klass) {
2629     int conv = 0;
2630     if (klass && GetFlag(klass, "feature:implicitconv")) {
2631       conv = 1;
2632     }
2633     return conv ? "SWIG_POINTER_IMPLICIT_CONV" : "0";
2634   }
2635 
2636 
functionWrapper(Node * n)2637   virtual int functionWrapper(Node *n) {
2638 
2639     String *name = Getattr(n, "name");
2640     String *iname = Getattr(n, "sym:name");
2641     SwigType *d = Getattr(n, "type");
2642     ParmList *l = Getattr(n, "parms");
2643     Node *parent = Swig_methodclass(n);
2644 
2645     int director_method = 0;
2646 
2647     Parm *p;
2648     int i;
2649     char source[64];
2650     Wrapper *f;
2651     String *self_parse;
2652     String *parse_args;
2653     String *arglist;
2654     String *get_pointers;
2655     String *cleanup;
2656     String *outarg;
2657     String *kwargs;
2658     String *tm;
2659     String *overname = 0;
2660 
2661     int num_required;
2662     int num_arguments;
2663     int num_fixed_arguments;
2664     int tuple_required;
2665     int tuple_arguments;
2666     int varargs = 0;
2667     int allow_kwargs = check_kwargs(n);
2668 
2669     String *nodeType = Getattr(n, "nodeType");
2670     int constructor = (!Cmp(nodeType, "constructor"));
2671     int destructor = (!Cmp(nodeType, "destructor"));
2672     String *storage = Getattr(n, "storage");
2673     /* Only the first constructor is handled as init method. Others
2674        constructor can be emitted via %rename */
2675     int handled_as_init = 0;
2676     if (!have_constructor && (constructor || Getattr(n, "handled_as_constructor"))
2677 	&& ((shadow & PYSHADOW_MEMBER))) {
2678       String *nname = Getattr(n, "sym:name");
2679       String *sname = Getattr(getCurrentClass(), "sym:name");
2680       String *cname = Swig_name_construct(NSPACE_TODO, sname);
2681       handled_as_init = (Strcmp(nname, sname) == 0) || (Strcmp(nname, cname) == 0);
2682       Delete(cname);
2683     }
2684     bool builtin_self = builtin && in_class && (constructor || (l && Getattr(l, "self")));
2685     bool builtin_ctor = false;
2686     if (builtin_self && constructor) {
2687       String *class_mname = Getattr(getCurrentClass(), "sym:name");
2688       String *mrename = Swig_name_construct(getNSpace(), class_mname);
2689       if (Cmp(iname, mrename))
2690 	builtin_self = false;
2691       else
2692 	builtin_ctor = true;
2693       Delete(mrename);
2694     }
2695     bool director_class = (getCurrentClass() && Swig_directorclass(getCurrentClass()));
2696     bool add_self = builtin_self && (!builtin_ctor || director_class);
2697     bool builtin_getter = (builtin && GetFlag(n, "memberget"));
2698     bool builtin_setter = (builtin && GetFlag(n, "memberset") && !builtin_getter);
2699     char const *self_param = builtin ? "self" : "SWIGUNUSEDPARM(self)";
2700     char const *wrap_return = builtin_ctor ? "int " : "PyObject *";
2701     String *linkage = NewString("SWIGINTERN ");
2702     String *wrapper_name = Swig_name_wrapper(iname);
2703 
2704     if (Getattr(n, "sym:overloaded")) {
2705       overname = Getattr(n, "sym:overname");
2706     } else {
2707       if (!addSymbol(iname, n))
2708 	return SWIG_ERROR;
2709     }
2710 
2711     f = NewWrapper();
2712     self_parse = NewString("");
2713     parse_args = NewString("");
2714     arglist = NewString("");
2715     get_pointers = NewString("");
2716     cleanup = NewString("");
2717     outarg = NewString("");
2718     kwargs = NewString("");
2719 
2720     int allow_thread = threads_enable(n);
2721 
2722     Wrapper_add_local(f, "resultobj", "PyObject *resultobj = 0");
2723 
2724     // Emit all of the local variables for holding arguments.
2725     emit_parameter_variables(l, f);
2726 
2727     /* Attach the standard typemaps */
2728     emit_attach_parmmaps(l, f);
2729     Setattr(n, "wrap:parms", l);
2730     /* Get number of required and total arguments */
2731     tuple_arguments = num_arguments = emit_num_arguments(l);
2732     tuple_required = num_required = emit_num_required(l);
2733     if (add_self) {
2734       --tuple_arguments;
2735       --tuple_required;
2736     }
2737     num_fixed_arguments = tuple_required;
2738 
2739     // builtin handles/checks kwargs by default except in constructor wrappers so we need to explicitly handle them in the C constructor wrapper
2740     // The check below is for zero arguments. Sometimes (eg directors) self is the first argument for a method with zero arguments.
2741     if (((num_arguments == 0) && (num_required == 0)) || ((num_arguments == 1) && (num_required == 1) && Getattr(l, "self")))
2742       if (!builtin_ctor)
2743 	allow_kwargs = 0;
2744     varargs = emit_isvarargs(l);
2745 
2746     String *wname = Copy(wrapper_name);
2747     if (overname) {
2748       Append(wname, overname);
2749     }
2750 
2751     const char *builtin_kwargs = builtin_ctor ? ", PyObject *kwargs" : "";
2752     if (!allow_kwargs || overname) {
2753       if (!varargs) {
2754 	Printv(f->def, linkage, wrap_return, wname, "(PyObject *", self_param, ", PyObject *args", builtin_kwargs, ") {", NIL);
2755       } else {
2756 	Printv(f->def, linkage, wrap_return, wname, "__varargs__", "(PyObject *", self_param, ", PyObject *args, PyObject *varargs) {", NIL);
2757       }
2758       if (allow_kwargs) {
2759 	Swig_warning(WARN_LANG_OVERLOAD_KEYWORD, input_file, line_number, "Can't use keyword arguments with overloaded functions (%s).\n", Swig_name_decl(n));
2760 	allow_kwargs = 0;
2761       }
2762     } else {
2763       if (varargs) {
2764 	Swig_warning(WARN_LANG_VARARGS_KEYWORD, input_file, line_number, "Can't wrap varargs with keyword arguments enabled\n");
2765 	varargs = 0;
2766       }
2767       Printv(f->def, linkage, wrap_return, wname, "(PyObject *", self_param, ", PyObject *args, PyObject *kwargs) {", NIL);
2768     }
2769     if (!builtin || !in_class || tuple_arguments > 0 || builtin_ctor) {
2770       if (!allow_kwargs) {
2771 	Append(parse_args, "    if (!PyArg_ParseTuple(args, \"");
2772       } else {
2773 	Append(parse_args, "    if (!PyArg_ParseTupleAndKeywords(args, kwargs, \"");
2774 	Append(arglist, ", kwnames");
2775       }
2776     }
2777 
2778     bool over_varargs = emit_isvarargs_function(n);
2779 
2780     int funpack = fastunpack && !varargs && !over_varargs && !allow_kwargs;
2781     int noargs = funpack && (tuple_required == 0 && tuple_arguments == 0);
2782     int onearg = funpack && (tuple_required == 1 && tuple_arguments == 1);
2783 
2784     if (builtin && funpack && !overname && !builtin_ctor) {
2785       int compactdefargs = ParmList_is_compactdefargs(l);
2786       if (!(compactdefargs && (tuple_arguments > tuple_required || varargs))) {
2787 	String *argattr = NewStringf("%d", tuple_arguments);
2788 	Setattr(n, "python:argcount", argattr);
2789 	Delete(argattr);
2790       }
2791     }
2792 
2793     /* Generate code for argument marshalling */
2794     if (funpack) {
2795       if (num_arguments > 0 && !overname) {
2796 	sprintf(source, "PyObject *swig_obj[%d]", num_arguments);
2797 	Wrapper_add_localv(f, "swig_obj", source, NIL);
2798       }
2799     }
2800 
2801 
2802     if (constructor && num_arguments == 1 && num_required == 1) {
2803       if (Cmp(storage, "explicit") == 0) {
2804 	if (GetFlag(parent, "feature:implicitconv")) {
2805 	  String *desc = NewStringf("SWIGTYPE%s", SwigType_manglestr(Getattr(n, "type")));
2806 	  Printf(f->code, "if (SWIG_CheckImplicit(%s)) SWIG_fail;\n", desc);
2807 	  Delete(desc);
2808 	}
2809       }
2810     }
2811 
2812     if (builtin_ctor && checkAttribute(n, "access", "protected")) {
2813       String *tmp_none_comparison = Copy(none_comparison);
2814       Replaceall(tmp_none_comparison, "$arg", "self");
2815       Printf(self_parse, "if (!(%s)) {\n", tmp_none_comparison);
2816       Printv(self_parse, "  SWIG_SetErrorMsg(PyExc_RuntimeError, \"accessing abstract class or protected constructor\");\n  SWIG_fail;\n}\n", NIL);
2817       Delete(tmp_none_comparison);
2818     }
2819 
2820     int use_parse = 0;
2821     Append(kwargs, "{");
2822     for (i = 0, p = l; i < num_arguments; i++) {
2823       while (checkAttribute(p, "tmap:in:numinputs", "0")) {
2824 	p = Getattr(p, "tmap:in:next");
2825       }
2826 
2827       SwigType *pt = Getattr(p, "type");
2828       String *ln = Getattr(p, "lname");
2829       bool parse_from_tuple = (i > 0 || !add_self);
2830       if (SwigType_type(pt) == T_VARARGS) {
2831 	parse_from_tuple = false;
2832 	num_fixed_arguments -= atoi(Char(Getattr(p, "tmap:in:numinputs")));
2833       }
2834       if (!parse_from_tuple)
2835 	sprintf(source, "self");
2836       else if (funpack)
2837 	sprintf(source, "swig_obj[%d]", add_self && !overname ? i - 1 : i);
2838       else
2839 	sprintf(source, "obj%d", builtin_ctor ? i + 1 : i);
2840 
2841       if (parse_from_tuple) {
2842 	Printf(arglist, ", ");
2843 	if (i == num_required)
2844 	  Putc('|', parse_args);	/* Optional argument separator */
2845       }
2846 
2847       /* Keyword argument handling */
2848       if (allow_kwargs && parse_from_tuple) {
2849 	String *name = makeParameterName(n, p, i + 1);
2850 	Printf(kwargs, " (char *)\"%s\", ", name);
2851 	Delete(name);
2852       }
2853 
2854       /* Look for an input typemap */
2855       if ((tm = Getattr(p, "tmap:in"))) {
2856 	String *parse = Getattr(p, "tmap:in:parse");
2857 	if (!parse) {
2858 	  if (builtin_self) {
2859 	    Replaceall(tm, "$self", "self");
2860 	  } else if (funpack) {
2861 	    Replaceall(tm, "$self", "swig_obj[0]");
2862 	  } else {
2863 	    Replaceall(tm, "$self", "obj0");
2864 	  }
2865 	  Replaceall(tm, "$source", source);
2866 	  Replaceall(tm, "$target", ln);
2867 	  Replaceall(tm, "$input", source);
2868 	  Setattr(p, "emit:input", source);	/* Save the location of the object */
2869 
2870 	  if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) {
2871 	    Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN");
2872 	  } else {
2873 	    Replaceall(tm, "$disown", "0");
2874 	  }
2875 
2876 	  if (Getattr(p, "tmap:in:implicitconv")) {
2877 	    const char *convflag = "0";
2878 	    if (!Getattr(p, "hidden")) {
2879 	      SwigType *ptype = Getattr(p, "type");
2880 	      convflag = get_implicitconv_flag(classLookup(ptype));
2881 	    }
2882 	    Replaceall(tm, "$implicitconv", convflag);
2883 	    Setattr(p, "implicitconv", convflag);
2884 	  }
2885 
2886 	  if (parse_from_tuple)
2887 	    Putc('O', parse_args);
2888 	  if (!funpack && parse_from_tuple) {
2889 	    Wrapper_add_localv(f, source, "PyObject *", source, "= 0", NIL);
2890 	    Printf(arglist, "&%s", source);
2891 	  }
2892 	  if (i >= num_required)
2893 	    Printv(get_pointers, "if (", source, ") {\n", NIL);
2894 	  Printv(get_pointers, tm, "\n", NIL);
2895 	  if (i >= num_required)
2896 	    Printv(get_pointers, "}\n", NIL);
2897 
2898 	} else {
2899 	  use_parse = 1;
2900 	  Append(parse_args, parse);
2901 	  if (parse_from_tuple)
2902 	    Printf(arglist, "&%s", ln);
2903 	}
2904 	p = Getattr(p, "tmap:in:next");
2905 	continue;
2906       } else {
2907 	Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0));
2908 	break;
2909       }
2910     }
2911 
2912     /* finish argument marshalling */
2913     Append(kwargs, " NULL }");
2914     if (allow_kwargs) {
2915       Printv(f->locals, "  char * kwnames[] = ", kwargs, ";\n", NIL);
2916     }
2917 
2918     if (use_parse || allow_kwargs) {
2919       Printf(parse_args, ":%s\"", iname);
2920       Printv(parse_args, arglist, ")) SWIG_fail;\n", NIL);
2921       funpack = 0;
2922     } else {
2923       Clear(parse_args);
2924 
2925       if (funpack) {
2926 	Clear(f->def);
2927 	if (overname) {
2928 	  if (noargs) {
2929 	    Printv(f->def, linkage, wrap_return, wname, "(PyObject *", self_param, ", Py_ssize_t nobjs, PyObject **SWIGUNUSEDPARM(swig_obj)) {", NIL);
2930 	  } else {
2931 	    Printv(f->def, linkage, wrap_return, wname, "(PyObject *", self_param, ", Py_ssize_t nobjs, PyObject **swig_obj) {", NIL);
2932 	  }
2933 	  Printf(parse_args, "if ((nobjs < %d) || (nobjs > %d)) SWIG_fail;\n", num_required, num_arguments);
2934 	} else {
2935 	  int is_tp_call = Equal(Getattr(n, "feature:python:slot"), "tp_call");
2936 	  Printv(f->def, linkage, wrap_return, wname, "(PyObject *", self_param, ", PyObject *args", builtin_kwargs, ") {", NIL);
2937 	  if (builtin_ctor)
2938 	    Printf(parse_args, "if (!SWIG_Python_CheckNoKeywords(kwargs, \"%s\")) SWIG_fail;\n", iname);
2939 	  if (onearg && !builtin_ctor && !is_tp_call) {
2940 	    Printf(parse_args, "if (!args) SWIG_fail;\n");
2941 	    Append(parse_args, "swig_obj[0] = args;\n");
2942 	  } else if (!noargs) {
2943 	    Printf(parse_args, "if (!SWIG_Python_UnpackTuple(args, \"%s\", %d, %d, swig_obj)) SWIG_fail;\n", iname, num_fixed_arguments, tuple_arguments);
2944 	  } else if (noargs) {
2945 	    Printf(parse_args, "if (!SWIG_Python_UnpackTuple(args, \"%s\", %d, %d, 0)) SWIG_fail;\n", iname, num_fixed_arguments, tuple_arguments);
2946 	  }
2947 	}
2948       } else {
2949 	if (builtin_ctor)
2950 	  Printf(parse_args, "if (!SWIG_Python_CheckNoKeywords(kwargs, \"%s\")) SWIG_fail;\n", iname);
2951 	if (builtin && in_class && tuple_arguments == 0) {
2952 	  Printf(parse_args, "    if (args && PyTuple_Check(args) && PyTuple_GET_SIZE(args) > 0) SWIG_exception_fail(SWIG_TypeError, \"%s takes no arguments\");\n", iname);
2953 	} else {
2954 	  Printf(parse_args, "if (!PyArg_UnpackTuple(args, \"%s\", %d, %d", iname, num_fixed_arguments, tuple_arguments);
2955 	  Printv(parse_args, arglist, ")) SWIG_fail;\n", NIL);
2956 	}
2957       }
2958     }
2959 
2960     /* Now piece together the first part of the wrapper function */
2961     Printv(f->code, self_parse, parse_args, get_pointers, NIL);
2962 
2963     /* Check for trailing varargs */
2964     if (varargs) {
2965       if (p && (tm = Getattr(p, "tmap:in"))) {
2966 	Replaceall(tm, "$input", "varargs");
2967 	Printv(f->code, tm, "\n", NIL);
2968       }
2969     }
2970 
2971     /* Insert constraint checking code */
2972     for (p = l; p;) {
2973       if ((tm = Getattr(p, "tmap:check"))) {
2974 	Replaceall(tm, "$target", Getattr(p, "lname"));
2975 	Printv(f->code, tm, "\n", NIL);
2976 	p = Getattr(p, "tmap:check:next");
2977       } else {
2978 	p = nextSibling(p);
2979       }
2980     }
2981 
2982     /* Insert cleanup code */
2983     for (p = l; p;) {
2984       if (!Getattr(p, "tmap:in:parse") && (tm = Getattr(p, "tmap:freearg"))) {
2985 	if (Getattr(p, "tmap:freearg:implicitconv")) {
2986 	  const char *convflag = "0";
2987 	  if (!Getattr(p, "hidden")) {
2988 	    SwigType *ptype = Getattr(p, "type");
2989 	    convflag = get_implicitconv_flag(classLookup(ptype));
2990 	  }
2991 	  if (strcmp(convflag, "0") == 0) {
2992 	    tm = 0;
2993 	  }
2994 	}
2995 	if (tm && (Len(tm) != 0)) {
2996 	  Replaceall(tm, "$source", Getattr(p, "lname"));
2997 	  Printv(cleanup, tm, "\n", NIL);
2998 	}
2999 	p = Getattr(p, "tmap:freearg:next");
3000       } else {
3001 	p = nextSibling(p);
3002       }
3003     }
3004 
3005     /* Insert argument output code */
3006     for (p = l; p;) {
3007       if ((tm = Getattr(p, "tmap:argout"))) {
3008 	Replaceall(tm, "$source", Getattr(p, "lname"));
3009 	Replaceall(tm, "$target", "resultobj");
3010 	Replaceall(tm, "$arg", Getattr(p, "emit:input"));
3011 	Replaceall(tm, "$input", Getattr(p, "emit:input"));
3012 	Printv(outarg, tm, "\n", NIL);
3013 	p = Getattr(p, "tmap:argout:next");
3014       } else {
3015 	p = nextSibling(p);
3016       }
3017     }
3018 
3019     /* if the object is a director, and the method call originated from its
3020      * underlying python object, resolve the call by going up the c++
3021      * inheritance chain.  otherwise try to resolve the method in python.
3022      * without this check an infinite loop is set up between the director and
3023      * shadow class method calls.
3024      */
3025 
3026     // NOTE: this code should only be inserted if this class is the
3027     // base class of a director class.  however, in general we haven't
3028     // yet analyzed all classes derived from this one to see if they are
3029     // directors.  furthermore, this class may be used as the base of
3030     // a director class defined in a completely different module at a
3031     // later time, so this test must be included whether or not directorbase
3032     // is true.  we do skip this code if directors have not been enabled
3033     // at the command line to preserve source-level compatibility with
3034     // non-polymorphic swig.  also, if this wrapper is for a smart-pointer
3035     // method, there is no need to perform the test since the calling object
3036     // (the smart-pointer) and the director object (the "pointee") are
3037     // distinct.
3038 
3039     director_method = is_member_director(n) && !is_smart_pointer() && !destructor;
3040     if (director_method) {
3041       Wrapper_add_local(f, "director", "Swig::Director *director = 0");
3042       Append(f->code, "director = SWIG_DIRECTOR_CAST(arg1);\n");
3043       if (dirprot_mode() && !is_public(n)) {
3044 	Printf(f->code, "if (!director || !(director->swig_get_inner(\"%s\"))) {\n", name);
3045 	Printf(f->code, "SWIG_SetErrorMsg(PyExc_RuntimeError,\"accessing protected member %s\");\n", name);
3046 	Append(f->code, "SWIG_fail;\n");
3047 	Append(f->code, "}\n");
3048       }
3049       Wrapper_add_local(f, "upcall", "bool upcall = false");
3050       if (funpack) {
3051 	const char *self_parm = builtin_self ? "self" : "swig_obj[0]";
3052 	Printf(f->code, "upcall = (director && (director->swig_get_self()==%s));\n", self_parm);
3053       } else {
3054 	const char *self_parm = builtin_self ? "self" : "obj0";
3055 	Printf(f->code, "upcall = (director && (director->swig_get_self()==%s));\n", self_parm);
3056       }
3057     }
3058 
3059     /* Emit the function call */
3060     if (director_method) {
3061       Append(f->code, "try {\n");
3062     } else {
3063       if (allow_thread) {
3064 	String *preaction = NewString("");
3065 	thread_begin_allow(n, preaction);
3066 	Setattr(n, "wrap:preaction", preaction);
3067 
3068 	String *postaction = NewString("");
3069 	thread_end_allow(n, postaction);
3070 	Setattr(n, "wrap:postaction", postaction);
3071       }
3072     }
3073 
3074     Setattr(n, "wrap:name", wname);
3075 
3076     Swig_director_emit_dynamic_cast(n, f);
3077     String *actioncode = emit_action(n);
3078 
3079     if (director_method) {
3080       Append(actioncode, "} catch (Swig::DirectorException&) {\n");
3081       Append(actioncode, "  SWIG_fail;\n");
3082       Append(actioncode, "}\n");
3083     }
3084 
3085     /* This part below still needs cleanup */
3086 
3087     /* Return the function value */
3088     tm = Swig_typemap_lookup_out("out", n, Swig_cresult_name(), f, actioncode);
3089 
3090     if (tm) {
3091       if (builtin_self) {
3092 	Replaceall(tm, "$self", "self");
3093       } else if (funpack) {
3094 	Replaceall(tm, "$self", "swig_obj[0]");
3095       } else {
3096 	Replaceall(tm, "$self", "obj0");
3097       }
3098       Replaceall(tm, "$source", Swig_cresult_name());
3099       Replaceall(tm, "$target", "resultobj");
3100       Replaceall(tm, "$result", "resultobj");
3101       if (builtin_ctor) {
3102 	Replaceall(tm, "$owner", "SWIG_BUILTIN_INIT");
3103       } else if (handled_as_init) {
3104 	Replaceall(tm, "$owner", "SWIG_POINTER_NEW");
3105       } else {
3106 	if (GetFlag(n, "feature:new")) {
3107 	  Replaceall(tm, "$owner", "SWIG_POINTER_OWN");
3108 	} else {
3109 	  Replaceall(tm, "$owner", "0");
3110 	}
3111       }
3112       // FIXME: this will not try to unwrap directors returned as non-director
3113       //        base class pointers!
3114 
3115       /* New addition to unwrap director return values so that the original
3116        * python object is returned instead.
3117        */
3118 #if 1
3119       int unwrap = 0;
3120       String *decl = Getattr(n, "decl");
3121       int is_pointer = SwigType_ispointer_return(decl);
3122       int is_reference = SwigType_isreference_return(decl);
3123       if (is_pointer || is_reference) {
3124 	String *type = Getattr(n, "type");
3125 	//Node *classNode = Swig_methodclass(n);
3126 	//Node *module = Getattr(classNode, "module");
3127 	Node *module = Getattr(parent, "module");
3128 	Node *target = Swig_directormap(module, type);
3129 	if (target)
3130 	  unwrap = 1;
3131       }
3132       if (unwrap) {
3133 	Wrapper_add_local(f, "director", "Swig::Director *director = 0");
3134 	Printf(f->code, "director = SWIG_DIRECTOR_CAST(%s);\n", Swig_cresult_name());
3135 	Append(f->code, "if (director) {\n");
3136 	Append(f->code, "  resultobj = director->swig_get_self();\n");
3137 	Append(f->code, "  Py_INCREF(resultobj);\n");
3138 	Append(f->code, "} else {\n");
3139 	Printf(f->code, "%s\n", tm);
3140 	Append(f->code, "}\n");
3141       } else {
3142 	Printf(f->code, "%s\n", tm);
3143       }
3144 #else
3145       Printf(f->code, "%s\n", tm);
3146 #endif
3147       Delete(tm);
3148     } else {
3149       Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s in function %s.\n", SwigType_str(d, 0), name);
3150     }
3151     emit_return_variable(n, d, f);
3152 
3153     /* Output argument output code */
3154     Printv(f->code, outarg, NIL);
3155 
3156     /* Output cleanup code */
3157     int need_cleanup = Len(cleanup) != 0;
3158     if (need_cleanup) {
3159       Printv(f->code, cleanup, NIL);
3160     }
3161 
3162     /* Look to see if there is any newfree cleanup code */
3163     if (GetFlag(n, "feature:new")) {
3164       if ((tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0))) {
3165 	Replaceall(tm, "$source", Swig_cresult_name());
3166 	Printf(f->code, "%s\n", tm);
3167 	Delete(tm);
3168       }
3169     }
3170 
3171     /* See if there is any return cleanup code */
3172     if ((tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0))) {
3173       Replaceall(tm, "$source", Swig_cresult_name());
3174       Printf(f->code, "%s\n", tm);
3175       Delete(tm);
3176     }
3177 
3178     if (director_method) {
3179       if ((tm = Swig_typemap_lookup("directorfree", n, Swig_cresult_name(), 0))) {
3180 	Replaceall(tm, "$input", Swig_cresult_name());
3181 	Replaceall(tm, "$result", "resultobj");
3182 	Printf(f->code, "%s\n", tm);
3183 	Delete(tm);
3184       }
3185     }
3186 
3187     if (builtin_ctor)
3188       Append(f->code, "    return resultobj == Py_None ? -1 : 0;\n");
3189     else
3190       Append(f->code, "    return resultobj;\n");
3191 
3192     /* Error handling code */
3193 
3194     Append(f->code, "fail:\n");
3195     if (need_cleanup) {
3196       Printv(f->code, cleanup, NIL);
3197     }
3198     if (builtin_ctor) {
3199       Printv(f->code, "  return -1;\n", NIL);
3200     } else {
3201       if (GetFlag(n, "feature:python:maybecall")) {
3202 	Append(f->code, "  PyErr_Clear();\n");
3203 	Append(f->code, "  Py_INCREF(Py_NotImplemented);\n");
3204 	Append(f->code, "  return Py_NotImplemented;\n");
3205       } else {
3206         Printv(f->code, "  return NULL;\n", NIL);
3207       }
3208     }
3209 
3210     Append(f->code, "}\n");
3211 
3212     /* Substitute the cleanup code */
3213     Replaceall(f->code, "$cleanup", cleanup);
3214 
3215     /* Substitute the function name */
3216     Replaceall(f->code, "$symname", iname);
3217     Replaceall(f->code, "$result", "resultobj");
3218 
3219     if (builtin_self) {
3220       Replaceall(f->code, "$self", "self");
3221     } else if (funpack) {
3222       Replaceall(f->code, "$self", "swig_obj[0]");
3223     } else {
3224       Replaceall(f->code, "$self", "obj0");
3225     }
3226 
3227     /* Dump the function out */
3228     Wrapper_print(f, f_wrappers);
3229 
3230     /* If varargs.  Need to emit a varargs stub */
3231     if (varargs) {
3232       DelWrapper(f);
3233       f = NewWrapper();
3234       if (funpack) {
3235 	// Note: funpack is currently always false for varargs
3236 	Printv(f->def, linkage, wrap_return, wname, "(PyObject *", self_param, ", Py_ssize_t nobjs, PyObject **swig_obj) {", NIL);
3237       } else {
3238 	Printv(f->def, linkage, wrap_return, wname, "(PyObject *", self_param, ", PyObject *args", builtin_kwargs, ") {", NIL);
3239       }
3240       Wrapper_add_local(f, "resultobj", builtin_ctor ? "int resultobj" : "PyObject *resultobj");
3241       Wrapper_add_local(f, "varargs", "PyObject *varargs");
3242       Wrapper_add_local(f, "newargs", "PyObject *newargs");
3243       if (funpack) {
3244 	Wrapper_add_local(f, "i", "int i");
3245 	Printf(f->code, "newargs = PyTuple_New(%d);\n", num_fixed_arguments);
3246 	Printf(f->code, "for (i = 0; i < %d; ++i) {\n", num_fixed_arguments);
3247 	Printf(f->code, "  PyTuple_SET_ITEM(newargs, i, swig_obj[i]);\n");
3248 	Printf(f->code, "  Py_XINCREF(swig_obj[i]);\n");
3249 	Printf(f->code, "}\n");
3250 	Printf(f->code, "varargs = PyTuple_New(nobjs > %d ? nobjs - %d : 0);\n", num_fixed_arguments, num_fixed_arguments);
3251 	Printf(f->code, "for (i = 0; i < nobjs - %d; ++i) {\n", num_fixed_arguments);
3252 	Printf(f->code, "  PyTuple_SET_ITEM(newargs, i, swig_obj[i + %d]);\n", num_fixed_arguments);
3253 	Printf(f->code, "  Py_XINCREF(swig_obj[i + %d]);\n", num_fixed_arguments);
3254 	Printf(f->code, "}\n");
3255       } else {
3256 	Printf(f->code, "newargs = PyTuple_GetSlice(args,0,%d);\n", num_fixed_arguments);
3257 	Printf(f->code, "varargs = PyTuple_GetSlice(args,%d,PyTuple_Size(args));\n", num_fixed_arguments);
3258       }
3259       Printf(f->code, "resultobj = %s__varargs__(%s,newargs,varargs);\n", wname, builtin ? "self" : "NULL");
3260       Append(f->code, "Py_XDECREF(newargs);\n");
3261       Append(f->code, "Py_XDECREF(varargs);\n");
3262       Append(f->code, "return resultobj;\n");
3263       Append(f->code, "}\n");
3264       Wrapper_print(f, f_wrappers);
3265     }
3266 
3267     /* Now register the function with the interpreter.   */
3268     if (!Getattr(n, "sym:overloaded")) {
3269       if (!builtin_self)
3270 	add_method(iname, wname, allow_kwargs, n, funpack, num_required, num_arguments);
3271 
3272       /* Create a shadow for this function (if enabled and not in a member function) */
3273       if (!builtin && (shadow) && (!(shadow & PYSHADOW_MEMBER))) {
3274 	emitFunctionShadowHelper(n, in_class ? f_shadow_stubs : f_shadow, iname, allow_kwargs);
3275       }
3276     } else {
3277       if (!Getattr(n, "sym:nextSibling")) {
3278 	dispatchFunction(n, linkage, funpack, builtin_self, builtin_ctor, director_class);
3279       }
3280     }
3281 
3282     // Put this in tp_init of the PyTypeObject
3283     if (builtin_ctor) {
3284       if ((director_method || !is_private(n)) && !Getattr(class_members, iname)) {
3285 	Setattr(class_members, iname, n);
3286 	if (!builtin_tp_init)
3287 	  builtin_tp_init = Swig_name_wrapper(iname);
3288       }
3289     }
3290 
3291     /* If this is a builtin type, create a PyGetSetDef entry for this member variable. */
3292     if (builtin) {
3293       const char *memname = "__dict__";
3294       Hash *h = Getattr(builtin_getset, memname);
3295       if (!h) {
3296         h = NewHash();
3297         Setattr(builtin_getset, memname, h);
3298         Delete(h);
3299       }
3300       Setattr(h, "getter", "SwigPyObject_get___dict__");
3301       if (!Getattr(h, "doc")) {
3302 	Setattr(n, "doc:high:name", Getattr(n, "name"));
3303 	Setattr(h, "doc", cdocstring(n, AUTODOC_VAR));
3304       }
3305     }
3306 
3307     if (builtin_getter) {
3308       String *memname = Getattr(n, "membervariableHandler:sym:name");
3309       if (!memname)
3310 	memname = iname;
3311       Hash *h = Getattr(builtin_getset, memname);
3312       if (!h) {
3313 	h = NewHash();
3314 	Setattr(builtin_getset, memname, h);
3315 	Delete(h);
3316       }
3317       Setattr(h, "getter", wrapper_name);
3318       Delattr(n, "memberget");
3319       if (!Getattr(h, "doc")) {
3320 	Setattr(n, "doc:high:name", Getattr(n, "name"));
3321 	String *ds = cdocstring(n, AUTODOC_VAR);
3322 	Setattr(h, "doc", ds);
3323 	Delete(ds);
3324       }
3325     }
3326     if (builtin_setter) {
3327       String *memname = Getattr(n, "membervariableHandler:sym:name");
3328       if (!memname)
3329 	memname = iname;
3330       Hash *h = Getattr(builtin_getset, memname);
3331       if (!h) {
3332 	h = NewHash();
3333 	Setattr(builtin_getset, memname, h);
3334 	Delete(h);
3335       }
3336       Setattr(h, "setter", wrapper_name);
3337       Delattr(n, "memberset");
3338       if (!Getattr(h, "doc")) {
3339 	Setattr(n, "doc:high:name", Getattr(n, "name"));
3340 	String *ds = cdocstring(n, AUTODOC_VAR);
3341 	Setattr(h, "doc", ds);
3342 	Delete(ds);
3343       }
3344     }
3345 
3346     if (in_class && builtin) {
3347       /* Handle operator overloads for builtin types */
3348       String *slot = Getattr(n, "feature:python:slot");
3349       if (slot) {
3350 	String *func_type = Getattr(n, "feature:python:slot:functype");
3351 	String *closure_decl = getClosure(func_type, wrapper_name, overname ? 0 : funpack);
3352 	String *feature_name = NewStringf("feature:python:%s", slot);
3353 	String *closure_name = 0;
3354 	if (closure_decl) {
3355 	  closure_name = NewStringf("%s_%s_closure", wrapper_name, func_type);
3356 	  if (!GetFlag(builtin_closures, closure_name))
3357 	    Printf(builtin_closures_code, "%s /* defines %s */\n\n", closure_decl, closure_name);
3358 	  SetFlag(builtin_closures, closure_name);
3359 	  Delete(closure_decl);
3360 	} else {
3361 	  closure_name = Copy(wrapper_name);
3362 	}
3363 	if (func_type) {
3364 	  String *s = NewStringf("%s", closure_name);
3365 	  Delete(closure_name);
3366 	  closure_name = s;
3367 	}
3368 	Setattr(parent, feature_name, closure_name);
3369 	Delete(feature_name);
3370 	Delete(closure_name);
3371       }
3372 
3373       /* Handle comparison operators for builtin types */
3374       String *compare = Getattr(n, "feature:python:compare");
3375       if (compare) {
3376 	Hash *richcompare = Getattr(parent, "python:richcompare");
3377 	assert(richcompare);
3378 	Setattr(richcompare, compare, wrapper_name);
3379       }
3380     }
3381 
3382     Delete(self_parse);
3383     Delete(parse_args);
3384     Delete(linkage);
3385     Delete(arglist);
3386     Delete(get_pointers);
3387     Delete(cleanup);
3388     Delete(outarg);
3389     Delete(kwargs);
3390     Delete(wname);
3391     DelWrapper(f);
3392     Delete(wrapper_name);
3393     return SWIG_OK;
3394   }
3395 
3396 
3397 
3398   /* ------------------------------------------------------------
3399    * variableWrapper()
3400    * ------------------------------------------------------------ */
3401 
variableWrapper(Node * n)3402   virtual int variableWrapper(Node *n) {
3403     String *name = Getattr(n, "name");
3404     String *iname = Getattr(n, "sym:name");
3405     SwigType *t = Getattr(n, "type");
3406 
3407     static int have_globals = 0;
3408     String *tm;
3409     Wrapper *getf, *setf;
3410 
3411     if (!addSymbol(iname, n))
3412       return SWIG_ERROR;
3413 
3414     getf = NewWrapper();
3415     setf = NewWrapper();
3416 
3417     /* If this is our first call, add the globals variable to the
3418        Python dictionary. */
3419 
3420     if (!have_globals) {
3421       Printf(f_init, "\t globals = SWIG_globals();\n");
3422       Printf(f_init, "\t if (!globals) {\n");
3423       Printf(f_init, "     PyErr_SetString(PyExc_TypeError, \"Failure to create SWIG globals.\");\n");
3424       Printf(f_init, "#if PY_VERSION_HEX >= 0x03000000\n");
3425       Printf(f_init, "\t   return NULL;\n");
3426       Printf(f_init, "#else\n");
3427       Printf(f_init, "\t   return;\n");
3428       Printf(f_init, "#endif\n");
3429       Printf(f_init, "\t }\n");
3430       Printf(f_init, "\t PyDict_SetItemString(md, \"%s\", globals);\n", global_name);
3431       Printf(f_init, "\t Py_DECREF(globals);\n");
3432       if (builtin)
3433 	Printf(f_init, "\t SwigPyBuiltin_AddPublicSymbol(public_interface, \"%s\");\n", global_name);
3434       have_globals = 1;
3435       if (!builtin && (shadow) && (!(shadow & PYSHADOW_MEMBER))) {
3436 	Printf(f_shadow_stubs, "%s = %s.%s\n", global_name, module, global_name);
3437       }
3438     }
3439     int assignable = is_assignable(n);
3440 
3441     if (!builtin && shadow && !assignable && !in_class)
3442       Printf(f_shadow_stubs, "%s = %s.%s\n", iname, global_name, iname);
3443 
3444     String *getname = Swig_name_get(NSPACE_TODO, iname);
3445     String *setname = Swig_name_set(NSPACE_TODO, iname);
3446     String *vargetname = NewStringf("Swig_var_%s", getname);
3447     String *varsetname = NewStringf("Swig_var_%s", setname);
3448 
3449     /* Create a function for setting the value of the variable */
3450     if (assignable) {
3451       Setattr(n, "wrap:name", varsetname);
3452       if (builtin && in_class) {
3453 	String *set_wrapper = Swig_name_wrapper(setname);
3454 	Setattr(n, "pybuiltin:setter", set_wrapper);
3455 	Delete(set_wrapper);
3456       }
3457       Printf(setf->def, "SWIGINTERN int %s(PyObject *_val) {", varsetname);
3458       if ((tm = Swig_typemap_lookup("varin", n, name, 0))) {
3459 	Replaceall(tm, "$source", "_val");
3460 	Replaceall(tm, "$target", name);
3461 	Replaceall(tm, "$input", "_val");
3462 	if (Getattr(n, "tmap:varin:implicitconv")) {
3463 	  Replaceall(tm, "$implicitconv", get_implicitconv_flag(n));
3464 	}
3465 	emit_action_code(n, setf->code, tm);
3466 	Delete(tm);
3467       } else {
3468 	Swig_warning(WARN_TYPEMAP_VARIN_UNDEF, input_file, line_number, "Unable to set variable of type %s.\n", SwigType_str(t, 0));
3469       }
3470       Printv(setf->code, "  return 0;\n", NULL);
3471       Append(setf->code, "fail:\n");
3472       Printv(setf->code, "  return 1;\n", NULL);
3473     } else {
3474       /* Is a readonly variable.  Issue an error */
3475       if (CPlusPlus) {
3476 	Printf(setf->def, "SWIGINTERN int %s(PyObject *) {", varsetname);
3477       } else {
3478 	Printf(setf->def, "SWIGINTERN int %s(PyObject *_val SWIGUNUSED) {", varsetname);
3479       }
3480       Printv(setf->code, "  SWIG_Error(SWIG_AttributeError,\"Variable ", iname, " is read-only.\");\n", "  return 1;\n", NIL);
3481     }
3482 
3483     Append(setf->code, "}\n");
3484     Wrapper_print(setf, f_wrappers);
3485 
3486     /* Create a function for getting the value of a variable */
3487     Setattr(n, "wrap:name", vargetname);
3488     if (builtin && in_class) {
3489       String *get_wrapper = Swig_name_wrapper(getname);
3490       Setattr(n, "pybuiltin:getter", get_wrapper);
3491       Delete(get_wrapper);
3492     }
3493     int addfail = 0;
3494     Printf(getf->def, "SWIGINTERN PyObject *%s(void) {", vargetname);
3495     Wrapper_add_local(getf, "pyobj", "PyObject *pyobj = 0");
3496     if (builtin) {
3497       Wrapper_add_local(getf, "self", "PyObject *self = 0");
3498       Append(getf->code, "  (void)self;\n");
3499     }
3500     if ((tm = Swig_typemap_lookup("varout", n, name, 0))) {
3501       Replaceall(tm, "$source", name);
3502       Replaceall(tm, "$target", "pyobj");
3503       Replaceall(tm, "$result", "pyobj");
3504       addfail = emit_action_code(n, getf->code, tm);
3505       Delete(tm);
3506     } else {
3507       Swig_warning(WARN_TYPEMAP_VAROUT_UNDEF, input_file, line_number, "Unable to read variable of type %s\n", SwigType_str(t, 0));
3508     }
3509     Append(getf->code, "  return pyobj;\n");
3510     if (addfail) {
3511       Append(getf->code, "fail:\n");
3512       Append(getf->code, "  return NULL;\n");
3513     }
3514     Append(getf->code, "}\n");
3515 
3516     Wrapper_print(getf, f_wrappers);
3517 
3518     /* Now add this to the variable linking mechanism */
3519     Printf(f_init, "\t SWIG_addvarlink(globals, \"%s\", %s, %s);\n", iname, vargetname, varsetname);
3520     if (builtin && shadow && !assignable && !in_class) {
3521       Printf(f_init, "\t PyDict_SetItemString(md, \"%s\", PyObject_GetAttrString(globals, \"%s\"));\n", iname, iname);
3522       Printf(f_init, "\t SwigPyBuiltin_AddPublicSymbol(public_interface, \"%s\");\n", iname);
3523     }
3524     Delete(vargetname);
3525     Delete(varsetname);
3526     Delete(getname);
3527     Delete(setname);
3528     DelWrapper(setf);
3529     DelWrapper(getf);
3530     return SWIG_OK;
3531   }
3532 
3533   /* ------------------------------------------------------------
3534    * constantWrapper()
3535    * ------------------------------------------------------------ */
3536 
3537   /* Determine if the node requires the _swigconstant code to be generated */
needs_swigconstant(Node * n)3538   bool needs_swigconstant(Node *n) {
3539     SwigType *type = Getattr(n, "type");
3540     SwigType *qtype = SwigType_typedef_resolve_all(type);
3541     SwigType *uqtype = SwigType_strip_qualifiers(qtype);
3542     bool result = false;
3543 
3544     /* Note, that we need special handling for function pointers, as
3545      * SwigType_base(fptr) does not return the underlying pointer-to-function
3546      * type but the return-type of function. */
3547     if (!SwigType_isfunction(uqtype) && !SwigType_isfunctionpointer(uqtype)) {
3548       SwigType *basetype = SwigType_base(uqtype);
3549       result = SwigType_isclass(basetype) != 0;
3550       Delete(basetype);
3551     }
3552 
3553     Delete(qtype);
3554     Delete(uqtype);
3555 
3556     return result;
3557   }
3558 
constantWrapper(Node * n)3559   virtual int constantWrapper(Node *n) {
3560     String *name = Getattr(n, "name");
3561     String *iname = Getattr(n, "sym:name");
3562     SwigType *type = Getattr(n, "type");
3563     String *rawval = Getattr(n, "rawval");
3564     String *value = rawval ? rawval : Getattr(n, "value");
3565     String *tm;
3566     int have_tm = 0;
3567     int have_builtin_symname = 0;
3568 
3569     if (!addSymbol(iname, n))
3570       return SWIG_ERROR;
3571 
3572     /* Special hook for member pointer */
3573     if (SwigType_type(type) == T_MPOINTER) {
3574       String *wname = Swig_name_wrapper(iname);
3575       String *str = SwigType_str(type, wname);
3576       Printf(f_header, "static %s = %s;\n", str, value);
3577       Delete(str);
3578       value = wname;
3579     }
3580 
3581     if ((tm = Swig_typemap_lookup("consttab", n, name, 0))) {
3582       Replaceall(tm, "$source", value);
3583       Replaceall(tm, "$target", name);
3584       Replaceall(tm, "$value", value);
3585       Printf(const_code, "%s,\n", tm);
3586       Delete(tm);
3587       have_tm = 1;
3588     }
3589 
3590 
3591     if (builtin && in_class && Getattr(n, "pybuiltin:symname")) {
3592       have_builtin_symname = 1;
3593       Swig_require("builtin_constantWrapper", n, "*sym:name", "pybuiltin:symname", NIL);
3594       Setattr(n, "sym:name", Getattr(n, "pybuiltin:symname"));
3595     }
3596 
3597     if ((tm = Swig_typemap_lookup("constcode", n, name, 0))) {
3598       Replaceall(tm, "$source", value);
3599       Replaceall(tm, "$target", name);
3600       Replaceall(tm, "$value", value);
3601       if (needs_swigconstant(n) && !builtin && (shadow) && (!(shadow & PYSHADOW_MEMBER)) && (!in_class || !Getattr(n, "feature:python:callback"))) {
3602 	// Generate `*_swigconstant()` method which registers the new constant.
3603 	//
3604 	// *_swigconstant methods are required for constants of class type.
3605 	// Class types are registered in shadow file (see *_swigregister). The
3606 	// instances of class must be created (registered) after the type is
3607 	// registered, so we can't let SWIG_init() to register constants of
3608 	// class type (the SWIG_init() is called before shadow classes are
3609 	// defined and registered).
3610         Printf(f_wrappers, "SWIGINTERN PyObject *%s_swigconstant(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {\n", iname);
3611         Printf(f_wrappers, tab2 "PyObject *module;\n", tm);
3612         Printf(f_wrappers, tab2 "PyObject *d;\n");
3613 	Printf(f_wrappers, tab2 "if (!SWIG_Python_UnpackTuple(args, \"swigconstant\", 1, 1, &module)) return NULL;\n");
3614         Printf(f_wrappers, tab2 "d = PyModule_GetDict(module);\n");
3615         Printf(f_wrappers, tab2 "if (!d) return NULL;\n");
3616         Printf(f_wrappers, tab2 "%s\n", tm);
3617         Printf(f_wrappers, tab2 "return SWIG_Py_Void();\n");
3618         Printf(f_wrappers, "}\n\n\n");
3619 
3620         // Register the method in SwigMethods array
3621 	String *cname = NewStringf("%s_swigconstant", iname);
3622 	add_method(cname, cname, 0, 0, 1, 1, 1);
3623 	Delete(cname);
3624       } else {
3625         Printf(f_init, "%s\n", tm);
3626       }
3627       Delete(tm);
3628       have_tm = 1;
3629     }
3630 
3631     if (have_builtin_symname)
3632       Swig_restore(n);
3633 
3634     if (!have_tm) {
3635       Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value.\n");
3636       return SWIG_NOWRAP;
3637     }
3638 
3639     if (!builtin && (shadow) && (!(shadow & PYSHADOW_MEMBER))) {
3640       String *f_s;
3641       if (!in_class) {
3642 	f_s = f_shadow;
3643       } else {
3644 	f_s = Getattr(n, "feature:python:callback") ? NIL : f_shadow_stubs;
3645       }
3646 
3647       if (f_s) {
3648 	if (needs_swigconstant(n)) {
3649 	  Printv(f_s, "\n",NIL);
3650 	  Printv(f_s, module, ".", iname, "_swigconstant(",module,")\n", NIL);
3651 	}
3652 	Printv(f_s, iname, " = ", module, ".", iname, "\n", NIL);
3653 	if (have_docstring(n))
3654 	  Printv(f_s, docstring(n, AUTODOC_CONST, tab4), "\n", NIL);
3655       }
3656     }
3657     return SWIG_OK;
3658   }
3659 
3660 
3661   /* ------------------------------------------------------------
3662    * nativeWrapper()
3663    * ------------------------------------------------------------ */
3664 
nativeWrapper(Node * n)3665   virtual int nativeWrapper(Node *n) {
3666     String *name = Getattr(n, "sym:name");
3667     String *wrapname = Getattr(n, "wrap:name");
3668 
3669     if (!addSymbol(wrapname, n))
3670       return SWIG_ERROR;
3671 
3672     add_method(name, wrapname, 0);
3673     if (!builtin && shadow) {
3674       Printv(f_shadow_stubs, name, " = ", module, ".", name, "\n", NIL);
3675     }
3676     return SWIG_OK;
3677   }
3678 
3679 
3680 
3681   /* ----------------------------------------------------------------------------
3682    * BEGIN C++ Director Class modifications
3683    * ------------------------------------------------------------------------- */
3684 
3685   /* C++/Python polymorphism demo code
3686    *
3687    * TODO
3688    *
3689    * Move some boilerplate code generation to Swig_...() functions.
3690    *
3691    */
3692 
3693   /* ---------------------------------------------------------------
3694    * classDirectorMethod()
3695    *
3696    * Emit a virtual director method to pass a method call on to the
3697    * underlying Python object.
3698    * ** Moved down due to gcc-2.96 internal error **
3699    * --------------------------------------------------------------- */
3700 
3701   int classDirectorMethods(Node *n);
3702 
3703   int classDirectorMethod(Node *n, Node *parent, String *super);
3704 
3705   /* ------------------------------------------------------------
3706    * classDirectorConstructor()
3707    * ------------------------------------------------------------ */
3708 
classDirectorConstructor(Node * n)3709   int classDirectorConstructor(Node *n) {
3710     Node *parent = Getattr(n, "parentNode");
3711     String *sub = NewString("");
3712     String *decl = Getattr(n, "decl");
3713     String *supername = Swig_class_name(parent);
3714     String *classname = NewString("");
3715     Printf(classname, "SwigDirector_%s", supername);
3716 
3717     /* insert self parameter */
3718     Parm *p;
3719     ParmList *superparms = Getattr(n, "parms");
3720     ParmList *parms = CopyParmList(superparms);
3721     String *type = NewString("PyObject");
3722     SwigType_add_pointer(type);
3723     p = NewParm(type, NewString("self"), n);
3724     set_nextSibling(p, parms);
3725     parms = p;
3726 
3727     if (!Getattr(n, "defaultargs")) {
3728       /* constructor */
3729       {
3730 	Wrapper *w = NewWrapper();
3731 	String *call;
3732 	String *basetype = Getattr(parent, "classtype");
3733 	String *target = Swig_method_decl(0, decl, classname, parms, 0);
3734 	call = Swig_csuperclass_call(0, basetype, superparms);
3735 	Printf(w->def, "%s::%s: %s, Swig::Director(self) { \n", classname, target, call);
3736 	Printf(w->def, "   SWIG_DIRECTOR_RGTR((%s *)this, this); \n", basetype);
3737 	Append(w->def, "}\n");
3738 	Delete(target);
3739 	Wrapper_print(w, f_directors);
3740 	Delete(call);
3741 	DelWrapper(w);
3742       }
3743 
3744       /* constructor header */
3745       {
3746 	String *target = Swig_method_decl(0, decl, classname, parms, 1);
3747 	Printf(f_directors_h, "    %s;\n", target);
3748 	Delete(target);
3749       }
3750     }
3751 
3752     Delete(sub);
3753     Delete(classname);
3754     Delete(supername);
3755     Delete(parms);
3756     return Language::classDirectorConstructor(n);
3757   }
3758 
3759   /* ------------------------------------------------------------
3760    * classDirectorDefaultConstructor()
3761    * ------------------------------------------------------------ */
3762 
classDirectorDefaultConstructor(Node * n)3763   int classDirectorDefaultConstructor(Node *n) {
3764     String *classname = Swig_class_name(n);
3765     {
3766       Node *parent = Swig_methodclass(n);
3767       String *basetype = Getattr(parent, "classtype");
3768       Wrapper *w = NewWrapper();
3769       Printf(w->def, "SwigDirector_%s::SwigDirector_%s(PyObject *self) : Swig::Director(self) { \n", classname, classname);
3770       Printf(w->def, "   SWIG_DIRECTOR_RGTR((%s *)this, this); \n", basetype);
3771       Append(w->def, "}\n");
3772       Wrapper_print(w, f_directors);
3773       DelWrapper(w);
3774     }
3775     Printf(f_directors_h, "    SwigDirector_%s(PyObject *self);\n", classname);
3776     Delete(classname);
3777     return Language::classDirectorDefaultConstructor(n);
3778   }
3779 
3780 
3781   /* ------------------------------------------------------------
3782    * classDirectorInit()
3783    * ------------------------------------------------------------ */
3784 
classDirectorInit(Node * n)3785   int classDirectorInit(Node *n) {
3786     String *declaration = Swig_director_declaration(n);
3787     Printf(f_directors_h, "\n");
3788     Printf(f_directors_h, "%s\n", declaration);
3789     Printf(f_directors_h, "public:\n");
3790     Delete(declaration);
3791     return Language::classDirectorInit(n);
3792   }
3793 
3794   /* ------------------------------------------------------------
3795    * classDirectorEnd()
3796    * ------------------------------------------------------------ */
3797 
classDirectorEnd(Node * n)3798   int classDirectorEnd(Node *n) {
3799     String *classname = Swig_class_name(n);
3800 
3801     if (dirprot_mode()) {
3802       /*
3803          This implementation uses a std::map<std::string,int>.
3804 
3805          It should be possible to rewrite it using a more elegant way,
3806          like copying the Java approach for the 'override' array.
3807 
3808          But for now, this seems to be the least intrusive way.
3809        */
3810       Printf(f_directors_h, "\n");
3811       Printf(f_directors_h, "/* Internal director utilities */\n");
3812       Printf(f_directors_h, "public:\n");
3813       Printf(f_directors_h, "    bool swig_get_inner(const char *swig_protected_method_name) const {\n");
3814       Printf(f_directors_h, "      std::map<std::string, bool>::const_iterator iv = swig_inner.find(swig_protected_method_name);\n");
3815       Printf(f_directors_h, "      return (iv != swig_inner.end() ? iv->second : false);\n");
3816       Printf(f_directors_h, "    }\n");
3817 
3818       Printf(f_directors_h, "    void swig_set_inner(const char *swig_protected_method_name, bool swig_val) const {\n");
3819       Printf(f_directors_h, "      swig_inner[swig_protected_method_name] = swig_val;\n");
3820       Printf(f_directors_h, "    }\n");
3821       Printf(f_directors_h, "private:\n");
3822       Printf(f_directors_h, "    mutable std::map<std::string, bool> swig_inner;\n");
3823 
3824     }
3825     if (director_method_index) {
3826       Printf(f_directors_h, "\n");
3827       Printf(f_directors_h, "#if defined(SWIG_PYTHON_DIRECTOR_VTABLE)\n");
3828       Printf(f_directors_h, "/* VTable implementation */\n");
3829       Printf(f_directors_h, "    PyObject *swig_get_method(size_t method_index, const char *method_name) const {\n");
3830       Printf(f_directors_h, "      PyObject *method = vtable[method_index];\n");
3831       Printf(f_directors_h, "      if (!method) {\n");
3832       Printf(f_directors_h, "        swig::SwigVar_PyObject name = SWIG_Python_str_FromChar(method_name);\n");
3833       Printf(f_directors_h, "        method = PyObject_GetAttr(swig_get_self(), name);\n");
3834       Printf(f_directors_h, "        if (!method) {\n");
3835       Printf(f_directors_h, "          std::string msg = \"Method in class %s doesn't exist, undefined \";\n", classname);
3836       Printf(f_directors_h, "          msg += method_name;\n");
3837       Printf(f_directors_h, "          Swig::DirectorMethodException::raise(msg.c_str());\n");
3838       Printf(f_directors_h, "        }\n");
3839       Printf(f_directors_h, "        vtable[method_index] = method;\n");
3840       Printf(f_directors_h, "      }\n");
3841       Printf(f_directors_h, "      return method;\n");
3842       Printf(f_directors_h, "    }\n");
3843       Printf(f_directors_h, "private:\n");
3844       Printf(f_directors_h, "    mutable swig::SwigVar_PyObject vtable[%d];\n", director_method_index);
3845       Printf(f_directors_h, "#endif\n\n");
3846     }
3847 
3848     Printf(f_directors_h, "};\n\n");
3849     return Language::classDirectorEnd(n);
3850   }
3851 
3852 
3853   /* ------------------------------------------------------------
3854    * classDirectorDisown()
3855    * ------------------------------------------------------------ */
3856 
classDirectorDisown(Node * n)3857   int classDirectorDisown(Node *n) {
3858     int result;
3859     int oldshadow = shadow;
3860     /* disable shadowing */
3861     if (shadow)
3862       shadow = shadow | PYSHADOW_MEMBER;
3863     result = Language::classDirectorDisown(n);
3864     shadow = oldshadow;
3865     if (shadow) {
3866       if (builtin) {
3867 	String *rname = SwigType_namestr(real_classname);
3868 	Printf(builtin_methods, "  { \"__disown__\", Swig::Director::swig_pyobj_disown< %s >, METH_NOARGS, \"\" },\n", rname);
3869 	Delete(rname);
3870       } else {
3871 	String *symname = Getattr(n, "sym:name");
3872 	String *mrename = Swig_name_disown(NSPACE_TODO, symname);	//Getattr(n, "name"));
3873 	Printv(f_shadow, tab4, "def __disown__(self):\n", NIL);
3874 #ifdef USE_THISOWN
3875 	Printv(f_shadow, tab8, "self.thisown = 0\n", NIL);
3876 #else
3877 	Printv(f_shadow, tab8, "self.this.disown()\n", NIL);
3878 #endif
3879 	Printv(f_shadow, tab8, module, ".", mrename, "(self)\n", NIL);
3880 	Printv(f_shadow, tab8, "return weakref.proxy(self)\n", NIL);
3881 	Delete(mrename);
3882       }
3883     }
3884     return result;
3885   }
3886 
3887   /* ----------------------------------------------------------------------------
3888    * END of C++ Director Class modifications
3889    * ------------------------------------------------------------------------- */
3890 
3891 
3892   /* ------------------------------------------------------------
3893    * classDeclaration()
3894    * ------------------------------------------------------------ */
3895 
classDeclaration(Node * n)3896   virtual int classDeclaration(Node *n) {
3897     if (shadow && !Getattr(n, "feature:onlychildren")) {
3898       Node *mod = Getattr(n, "module");
3899       if (mod) {
3900 	String *modname = Getattr(mod, "name");
3901 	Node *options = Getattr(mod, "options");
3902 	String *pkg = options ? Getattr(options, "package") : 0;
3903 	String *sym = Getattr(n, "sym:name");
3904 	String *importname = import_name_string(package, mainmodule, pkg, modname, sym);
3905 	Setattr(n, "python:proxy", importname);
3906 	Delete(importname);
3907       }
3908     }
3909     int result = Language::classDeclaration(n);
3910     return result;
3911   }
3912 
3913   /* ------------------------------------------------------------
3914    * classHandler()
3915    * ------------------------------------------------------------ */
3916 
add_explicit_scope(String * s)3917   String *add_explicit_scope(String *s) {
3918     if (!Strstr(s, "::")) {
3919       String *ss = NewStringf("::%s", s);
3920       Delete(s);
3921       s = ss;
3922     }
3923     return s;
3924   }
3925 
builtin_pre_decl(Node * n)3926   void builtin_pre_decl(Node *n) {
3927     String *name = Getattr(n, "name");
3928     String *rname = add_explicit_scope(SwigType_namestr(name));
3929     String *mname = SwigType_manglestr(rname);
3930 
3931     Printf(f_init, "\n/* type '%s' */\n", rname);
3932     Printf(f_init, "    builtin_pytype = (PyTypeObject *)&SwigPyBuiltin_%s_type;\n", mname);
3933     Printf(f_init, "    builtin_pytype->tp_dict = d = PyDict_New();\n");
3934 
3935     Delete(rname);
3936     Delete(mname);
3937   }
3938 
builtin_post_decl(File * f,Node * n)3939   void builtin_post_decl(File *f, Node *n) {
3940     String *name = Getattr(n, "name");
3941     String *pname = Copy(name);
3942     SwigType_add_pointer(pname);
3943     String *symname = Getattr(n, "sym:name");
3944     String *rname = add_explicit_scope(SwigType_namestr(name));
3945     String *mname = SwigType_manglestr(rname);
3946     String *pmname = SwigType_manglestr(pname);
3947     String *templ = NewStringf("SwigPyBuiltin_%s", mname);
3948     int funpack = fastunpack;
3949     static String *tp_new = NewString("PyType_GenericNew");
3950 
3951     Printv(f_init, "  SwigPyBuiltin_SetMetaType(builtin_pytype, metatype);\n", NIL);
3952 
3953     // We can’t statically initialize a structure member with a function defined in another C module
3954     // So this is done in the initialization function instead, see https://docs.python.org/2/extending/newtypes.html
3955     Printf(f_init, "  builtin_pytype->tp_new = %s;\n", getSlot(n, "feature:python:tp_new", tp_new));
3956 
3957     Printv(f_init, "  builtin_base_count = 0;\n", NIL);
3958     List *baselist = Getattr(n, "bases");
3959     if (baselist) {
3960       int base_count = 0;
3961       for (Iterator b = First(baselist); b.item; b = Next(b)) {
3962 	String *bname = Getattr(b.item, "name");
3963 	if (!bname || GetFlag(b.item, "feature:ignore"))
3964 	  continue;
3965 	base_count++;
3966 	String *base_name = Copy(bname);
3967 	SwigType_add_pointer(base_name);
3968 	String *base_mname = SwigType_manglestr(base_name);
3969 	Printf(f_init, "  builtin_basetype = SWIG_MangledTypeQuery(\"%s\");\n", base_mname);
3970 	Printv(f_init, "  if (builtin_basetype && builtin_basetype->clientdata && ((SwigPyClientData *) builtin_basetype->clientdata)->pytype) {\n", NIL);
3971 	Printv(f_init, "    builtin_bases[builtin_base_count++] = ((SwigPyClientData *) builtin_basetype->clientdata)->pytype;\n", NIL);
3972 	Printv(f_init, "  } else {\n", NIL);
3973 	Printf(f_init, "    PyErr_SetString(PyExc_TypeError, \"Could not create type '%s' as base '%s' has not been initialized.\\n\");\n", symname, bname);
3974 	Printv(f_init, "#if PY_VERSION_HEX >= 0x03000000\n", NIL);
3975 	Printv(f_init, "      return NULL;\n", NIL);
3976 	Printv(f_init, "#else\n", NIL);
3977 	Printv(f_init, "      return;\n", NIL);
3978 	Printv(f_init, "#endif\n", NIL);
3979 	Printv(f_init, "  }\n", NIL);
3980 	Delete(base_name);
3981 	Delete(base_mname);
3982       }
3983       if (base_count > max_bases)
3984 	max_bases = base_count;
3985     }
3986     Printv(f_init, "  builtin_bases[builtin_base_count] = NULL;\n", NIL);
3987     Printv(f_init, "  SwigPyBuiltin_InitBases(builtin_pytype, builtin_bases);\n", NIL);
3988     builtin_bases_needed = 1;
3989 
3990     // Check for non-public destructor, in which case tp_dealloc will issue
3991     // a warning and allow the memory to leak.  Any class that doesn't explicitly
3992     // have a private/protected destructor has an implicit public destructor.
3993     static String *tp_dealloc_bad = NewString("SwigPyBuiltin_BadDealloc");
3994 
3995     String *getset_name = NewStringf("%s_getset", templ);
3996     String *methods_name = NewStringf("%s_methods", templ);
3997     String *getset_def = NewString("");
3998     Printf(getset_def, "SWIGINTERN PyGetSetDef %s[] = {\n", getset_name);
3999 
4000     // All objects have 'this' and 'thisown' attributes
4001     Printv(f_init, "PyDict_SetItemString(d, \"this\", this_descr);\n", NIL);
4002     Printv(f_init, "PyDict_SetItemString(d, \"thisown\", thisown_descr);\n", NIL);
4003 
4004     // Now, the rest of the attributes
4005     for (Iterator member_iter = First(builtin_getset); member_iter.item; member_iter = Next(member_iter)) {
4006       String *memname = member_iter.key;
4007       Hash *mgetset = member_iter.item;
4008       String *getter = Getattr(mgetset, "getter");
4009       String *setter = Getattr(mgetset, "setter");
4010       const char *getter_closure = getter ? funpack ? "SwigPyBuiltin_FunpackGetterClosure" : "SwigPyBuiltin_GetterClosure" : "0";
4011       const char *setter_closure = setter ? funpack ? "SwigPyBuiltin_FunpackSetterClosure" : "SwigPyBuiltin_SetterClosure" : "0";
4012       String *gspair = NewStringf("%s_%s_getset", symname, memname);
4013       Printf(f, "static SwigPyGetSet %s = { %s, %s };\n", gspair, getter ? getter : "0", setter ? setter : "0");
4014       String *doc = Getattr(mgetset, "doc");
4015       if (!doc)
4016 	doc = NewStringf("%s.%s", name, memname);
4017       String *entry = NewStringf("{ (char *)\"%s\", %s, %s, (char *)\"%s\", &%s }", memname, getter_closure, setter_closure, doc, gspair);
4018       if (GetFlag(mgetset, "static")) {
4019 	Printf(f, "static PyGetSetDef %s_def = %s;\n", gspair, entry);
4020 	Printf(f_init, "static_getset = SwigPyStaticVar_new_getset(metatype, &%s_def);\n", gspair);
4021 	Printf(f_init, "PyDict_SetItemString(d, static_getset->d_getset->name, (PyObject *) static_getset);\n", memname);
4022 	Printf(f_init, "Py_DECREF(static_getset);\n");
4023       } else {
4024 	Printf(getset_def, "    %s,\n", entry);
4025       }
4026       Delete(gspair);
4027       Delete(entry);
4028     }
4029     Printv(f, getset_def, "    { NULL, NULL, NULL, NULL, NULL } /* Sentinel */\n", "};\n\n", NIL);
4030 
4031     // Rich compare function
4032     Hash *richcompare = Getattr(n, "python:richcompare");
4033     String *richcompare_func = NewStringf("%s_richcompare", templ);
4034     assert(richcompare);
4035     Printf(f, "SWIGINTERN PyObject *\n");
4036     Printf(f, "%s(PyObject *self, PyObject *other, int op) {\n", richcompare_func);
4037     Printf(f, "  PyObject *result = NULL;\n");
4038     if (!funpack) {
4039       Printf(f, "  PyObject *tuple = PyTuple_New(1);\n");
4040       Printf(f, "  assert(tuple);\n");
4041       Printf(f, "  PyTuple_SET_ITEM(tuple, 0, other);\n");
4042       Printf(f, "  Py_XINCREF(other);\n");
4043     }
4044     Iterator rich_iter = First(richcompare);
4045     if (rich_iter.item) {
4046       Printf(f, "  switch (op) {\n");
4047       for (; rich_iter.item; rich_iter = Next(rich_iter))
4048 	Printf(f, "    case %s : result = %s(self, %s); break;\n", rich_iter.key, rich_iter.item, funpack ? "other" : "tuple");
4049       Printv(f, "    default : break;\n", NIL);
4050       Printf(f, "  }\n");
4051     }
4052     Printv(f, "  if (!result) {\n", NIL);
4053     Printv(f, "    if (SwigPyObject_Check(self) && SwigPyObject_Check(other)) {\n", NIL);
4054     Printv(f, "      result = SwigPyObject_richcompare((SwigPyObject *)self, (SwigPyObject *)other, op);\n", NIL);
4055     Printv(f, "    } else {\n", NIL);
4056     Printv(f, "      result = Py_NotImplemented;\n", NIL);
4057     Printv(f, "      Py_INCREF(result);\n", NIL);
4058     Printv(f, "    }\n", NIL);
4059     Printv(f, "  }\n", NIL);
4060     if (!funpack)
4061       Printf(f, "  Py_DECREF(tuple);\n");
4062     Printf(f, "  return result;\n");
4063     Printf(f, "}\n\n");
4064 
4065     // Methods
4066     Printf(f, "SWIGINTERN PyMethodDef %s_methods[] = {\n", templ);
4067     Dump(builtin_methods, f);
4068     Printf(f, "  { NULL, NULL, 0, NULL } /* Sentinel */\n};\n\n");
4069 
4070     // No instance dict for nondynamic objects
4071     if (GetFlag(n, "feature:python:nondynamic"))
4072       Setattr(n, "feature:python:tp_setattro", "SWIG_Python_NonDynamicSetAttr");
4073 
4074     Node *mod = Getattr(n, "module");
4075     String *modname = mod ? Getattr(mod, "name") : 0;
4076     String *quoted_symname;
4077     if (package) {
4078       if (modname)
4079 	quoted_symname = NewStringf("\"%s.%s.%s\"", package, modname, symname);
4080       else
4081 	quoted_symname = NewStringf("\"%s.%s\"", package, symname);
4082     } else {
4083       if (modname)
4084 	quoted_symname = NewStringf("\"%s.%s\"", modname, symname);
4085       else
4086 	quoted_symname = NewStringf("\"%s\"", symname);
4087     }
4088     String *quoted_tp_doc_str = NewStringf("\"%s\"", getSlot(n, "feature:python:tp_doc"));
4089     String *tp_init = NewString(builtin_tp_init ? Char(builtin_tp_init) : Swig_directorclass(n) ? "0" : "SwigPyBuiltin_BadInit");
4090     String *tp_flags = NewString("Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_CHECKTYPES");
4091     String *tp_flags_py3 = NewString("Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE");
4092 
4093     static String *tp_basicsize = NewStringf("sizeof(SwigPyObject)");
4094     static String *tp_dictoffset_default = NewString("offsetof(SwigPyObject, dict)");
4095     static String *tp_hash = NewString("SwigPyObject_hash");
4096     String *tp_as_number = NewStringf("&%s_type.as_number", templ);
4097     String *tp_as_sequence = NewStringf("&%s_type.as_sequence", templ);
4098     String *tp_as_mapping = NewStringf("&%s_type.as_mapping", templ);
4099     String *tp_as_buffer = NewStringf("&%s_type.as_buffer", templ);
4100 
4101     Printf(f, "static PyHeapTypeObject %s_type = {\n", templ);
4102 
4103     // PyTypeObject ht_type
4104     Printf(f, "  {\n");
4105     Printv(f, "#if PY_VERSION_HEX >= 0x03000000\n", NIL);
4106     Printv(f, "    PyVarObject_HEAD_INIT(NULL, 0)\n", NIL);
4107     Printv(f, "#else\n", NIL);
4108     Printf(f, "    PyObject_HEAD_INIT(NULL)\n");
4109     printSlot(f, getSlot(), "ob_size");
4110     Printv(f, "#endif\n", NIL);
4111     printSlot(f, quoted_symname, "tp_name");
4112     printSlot(f, getSlot(n, "feature:python:tp_basicsize", tp_basicsize), "tp_basicsize");
4113     printSlot(f, getSlot(n, "feature:python:tp_itemsize"), "tp_itemsize");
4114     printSlot(f, getSlot(n, "feature:python:tp_dealloc", tp_dealloc_bad), "tp_dealloc", "destructor");
4115     printSlot(f, getSlot(n, "feature:python:tp_print"), "tp_print", "printfunc");
4116     printSlot(f, getSlot(n, "feature:python:tp_getattr"), "tp_getattr", "getattrfunc");
4117     printSlot(f, getSlot(n, "feature:python:tp_setattr"), "tp_setattr", "setattrfunc");
4118     Printv(f, "#if PY_VERSION_HEX >= 0x03000000\n", NIL);
4119     printSlot(f, getSlot(n, "feature:python:tp_compare"), "tp_compare");
4120     Printv(f, "#else\n", NIL);
4121     printSlot(f, getSlot(n, "feature:python:tp_compare"), "tp_compare", "cmpfunc");
4122     Printv(f, "#endif\n", NIL);
4123     printSlot(f, getSlot(n, "feature:python:tp_repr"), "tp_repr", "reprfunc");
4124     printSlot(f, getSlot(n, "feature:python:tp_as_number", tp_as_number), "tp_as_number");
4125     printSlot(f, getSlot(n, "feature:python:tp_as_sequence", tp_as_sequence), "tp_as_sequence");
4126     printSlot(f, getSlot(n, "feature:python:tp_as_mapping", tp_as_mapping), "tp_as_mapping");
4127     printSlot(f, getSlot(n, "feature:python:tp_hash", tp_hash), "tp_hash", "hashfunc");
4128     printSlot(f, getSlot(n, "feature:python:tp_call"), "tp_call", "ternaryfunc");
4129     printSlot(f, getSlot(n, "feature:python:tp_str"), "tp_str", "reprfunc");
4130     printSlot(f, getSlot(n, "feature:python:tp_getattro"), "tp_getattro", "getattrofunc");
4131     printSlot(f, getSlot(n, "feature:python:tp_setattro"), "tp_setattro", "setattrofunc");
4132     printSlot(f, getSlot(n, "feature:python:tp_as_buffer", tp_as_buffer), "tp_as_buffer");
4133     Printv(f, "#if PY_VERSION_HEX >= 0x03000000\n", NIL);
4134     printSlot(f, getSlot(n, "feature:python:tp_flags", tp_flags_py3), "tp_flags");
4135     Printv(f, "#else\n", NIL);
4136     printSlot(f, getSlot(n, "feature:python:tp_flags", tp_flags), "tp_flags");
4137     Printv(f, "#endif\n", NIL);
4138     if (have_docstring(n)) {
4139       String *ds = cdocstring(n, AUTODOC_CLASS);
4140       String *tp_doc = NewString("");
4141       Printf(tp_doc, "\"%s\"", ds);
4142       Delete(ds);
4143       printSlot(f, tp_doc, "tp_doc");
4144       Delete(tp_doc);
4145     } else {
4146       printSlot(f, quoted_tp_doc_str, "tp_doc");
4147     }
4148     printSlot(f, getSlot(n, "feature:python:tp_traverse"), "tp_traverse", "traverseproc");
4149     printSlot(f, getSlot(n, "feature:python:tp_clear"), "tp_clear", "inquiry");
4150     printSlot(f, getSlot(n, "feature:python:tp_richcompare", richcompare_func), "tp_richcompare", "richcmpfunc");
4151     printSlot(f, getSlot(n, "feature:python:tp_weaklistoffset"), "tp_weaklistoffset");
4152     printSlot(f, getSlot(n, "feature:python:tp_iter"), "tp_iter", "getiterfunc");
4153     printSlot(f, getSlot(n, "feature:python:tp_iternext"), "tp_iternext", "iternextfunc");
4154     printSlot(f, getSlot(n, "feature:python:tp_methods", methods_name), "tp_methods");
4155     printSlot(f, getSlot(n, "feature:python:tp_members"), "tp_members");
4156     printSlot(f, getSlot(n, "feature:python:tp_getset", getset_name), "tp_getset");
4157     printSlot(f, getSlot(n, "feature:python:tp_base"), "tp_base");
4158     printSlot(f, getSlot(n, "feature:python:tp_dict"), "tp_dict");
4159     printSlot(f, getSlot(n, "feature:python:tp_descr_get"), "tp_descr_get", "descrgetfunc");
4160     printSlot(f, getSlot(n, "feature:python:tp_descr_set"), "tp_descr_set", "descrsetfunc");
4161     printSlot(f, getSlot(n, "feature:python:tp_dictoffset", tp_dictoffset_default), "tp_dictoffset", "Py_ssize_t");
4162     printSlot(f, getSlot(n, "feature:python:tp_init", tp_init), "tp_init", "initproc");
4163     printSlot(f, getSlot(n, "feature:python:tp_alloc"), "tp_alloc", "allocfunc");
4164     printSlot(f, getSlot(), "tp_new", "newfunc");
4165     printSlot(f, getSlot(n, "feature:python:tp_free"), "tp_free", "freefunc");
4166     printSlot(f, getSlot(n, "feature:python:tp_is_gc"), "tp_is_gc", "inquiry");
4167     printSlot(f, getSlot(n, "feature:python:tp_bases"), "tp_bases", "PyObject *");
4168     printSlot(f, getSlot(n, "feature:python:tp_mro"), "tp_mro", "PyObject *");
4169     printSlot(f, getSlot(n, "feature:python:tp_cache"), "tp_cache", "PyObject *");
4170     printSlot(f, getSlot(n, "feature:python:tp_subclasses"), "tp_subclasses", "PyObject *");
4171     printSlot(f, getSlot(n, "feature:python:tp_weaklist"), "tp_weaklist", "PyObject *");
4172     printSlot(f, getSlot(n, "feature:python:tp_del"), "tp_del", "destructor");
4173     printSlot(f, getSlot(n, "feature:python:tp_version_tag"), "tp_version_tag", "int");
4174     Printv(f, "#if PY_VERSION_HEX >= 0x03040000\n", NIL);
4175     printSlot(f, getSlot(n, "feature:python:tp_finalize"), "tp_finalize", "destructor");
4176     Printv(f, "#endif\n", NIL);
4177     Printv(f, "#if PY_VERSION_HEX >= 0x03080000\n", NIL);
4178     printSlot(f, getSlot(n, "feature:python:tp_vectorcall"), "tp_vectorcall", "vectorcallfunc");
4179     Printv(f, "#endif\n", NIL);
4180     Printv(f, "#if (PY_VERSION_HEX >= 0x03080000) && (PY_VERSION_HEX < 0x03090000)\n", NIL);
4181     printSlot(f, getSlot(), "tp_print");
4182     Printv(f, "#endif\n", NIL);
4183 
4184     Printv(f, "#ifdef COUNT_ALLOCS\n", NIL);
4185     printSlot(f, getSlot(n, "feature:python:tp_allocs"), "tp_allocs", "Py_ssize_t");
4186     printSlot(f, getSlot(n, "feature:python:tp_frees"), "tp_frees", "Py_ssize_t");
4187     printSlot(f, getSlot(n, "feature:python:tp_maxalloc"), "tp_maxalloc", "Py_ssize_t");
4188     printSlot(f, getSlot(n, "feature:python:tp_prev"), "tp_prev");
4189     printSlot(f, getSlot(n, "feature:python:tp_next"), "tp_next");
4190     Printv(f, "#endif\n", NIL);
4191     Printf(f, "  },\n");
4192 
4193     // PyAsyncMethods as_async
4194     Printv(f, "#if PY_VERSION_HEX >= 0x03050000\n", NIL);
4195     Printf(f, "  {\n");
4196     printSlot(f, getSlot(n, "feature:python:am_await"), "am_await", "unaryfunc");
4197     printSlot(f, getSlot(n, "feature:python:am_aiter"), "am_aiter", "unaryfunc");
4198     printSlot(f, getSlot(n, "feature:python:am_anext"), "am_anext", "unaryfunc");
4199     Printf(f, "  },\n");
4200     Printv(f, "#endif\n", NIL);
4201 
4202     // PyNumberMethods as_number
4203     Printf(f, "  {\n");
4204     printSlot(f, getSlot(n, "feature:python:nb_add"), "nb_add", "binaryfunc");
4205     printSlot(f, getSlot(n, "feature:python:nb_subtract"), "nb_subtract", "binaryfunc");
4206     printSlot(f, getSlot(n, "feature:python:nb_multiply"), "nb_multiply", "binaryfunc");
4207     Printv(f, "#if PY_VERSION_HEX < 0x03000000\n", NIL);
4208     printSlot(f, getSlot(n, "feature:python:nb_divide"), "nb_divide", "binaryfunc");
4209     Printv(f, "#endif\n", NIL);
4210     printSlot(f, getSlot(n, "feature:python:nb_remainder"), "nb_remainder", "binaryfunc");
4211     printSlot(f, getSlot(n, "feature:python:nb_divmod"), "nb_divmod", "binaryfunc");
4212     printSlot(f, getSlot(n, "feature:python:nb_power"), "nb_power", "ternaryfunc");
4213     printSlot(f, getSlot(n, "feature:python:nb_negative"), "nb_negative", "unaryfunc");
4214     printSlot(f, getSlot(n, "feature:python:nb_positive"), "nb_positive", "unaryfunc");
4215     printSlot(f, getSlot(n, "feature:python:nb_absolute"), "nb_absolute", "unaryfunc");
4216     printSlot(f, getSlot(n, "feature:python:nb_nonzero"), "nb_nonzero", "inquiry");
4217     printSlot(f, getSlot(n, "feature:python:nb_invert"), "nb_invert", "unaryfunc");
4218     printSlot(f, getSlot(n, "feature:python:nb_lshift"), "nb_lshift", "binaryfunc");
4219     printSlot(f, getSlot(n, "feature:python:nb_rshift"), "nb_rshift", "binaryfunc");
4220     printSlot(f, getSlot(n, "feature:python:nb_and"), "nb_and", "binaryfunc");
4221     printSlot(f, getSlot(n, "feature:python:nb_xor"), "nb_xor", "binaryfunc");
4222     printSlot(f, getSlot(n, "feature:python:nb_or"), "nb_or", "binaryfunc");
4223     Printv(f, "#if PY_VERSION_HEX < 0x03000000\n", NIL);
4224     printSlot(f, getSlot(n, "feature:python:nb_coerce"), "nb_coerce", "coercion");
4225     Printv(f, "#endif\n", NIL);
4226     printSlot(f, getSlot(n, "feature:python:nb_int"), "nb_int", "unaryfunc");
4227     Printv(f, "#if PY_VERSION_HEX >= 0x03000000\n", NIL);
4228     printSlot(f, getSlot(n, "feature:python:nb_reserved"), "nb_reserved", "void *");
4229     Printv(f, "#else\n", NIL);
4230     printSlot(f, getSlot(n, "feature:python:nb_long"), "nb_long", "unaryfunc");
4231     Printv(f, "#endif\n", NIL);
4232     printSlot(f, getSlot(n, "feature:python:nb_float"), "nb_float", "unaryfunc");
4233     Printv(f, "#if PY_VERSION_HEX < 0x03000000\n", NIL);
4234     printSlot(f, getSlot(n, "feature:python:nb_oct"), "nb_oct", "unaryfunc");
4235     printSlot(f, getSlot(n, "feature:python:nb_hex"), "nb_hex", "unaryfunc");
4236     Printv(f, "#endif\n", NIL);
4237     printSlot(f, getSlot(n, "feature:python:nb_inplace_add"), "nb_inplace_add", "binaryfunc");
4238     printSlot(f, getSlot(n, "feature:python:nb_inplace_subtract"), "nb_inplace_subtract", "binaryfunc");
4239     printSlot(f, getSlot(n, "feature:python:nb_inplace_multiply"), "nb_inplace_multiply", "binaryfunc");
4240     Printv(f, "#if PY_VERSION_HEX < 0x03000000\n", NIL);
4241     printSlot(f, getSlot(n, "feature:python:nb_inplace_divide"), "nb_inplace_divide", "binaryfunc");
4242     Printv(f, "#endif\n", NIL);
4243     printSlot(f, getSlot(n, "feature:python:nb_inplace_remainder"), "nb_inplace_remainder", "binaryfunc");
4244     printSlot(f, getSlot(n, "feature:python:nb_inplace_power"), "nb_inplace_power", "ternaryfunc");
4245     printSlot(f, getSlot(n, "feature:python:nb_inplace_lshift"), "nb_inplace_lshift", "binaryfunc");
4246     printSlot(f, getSlot(n, "feature:python:nb_inplace_rshift"), "nb_inplace_rshift", "binaryfunc");
4247     printSlot(f, getSlot(n, "feature:python:nb_inplace_and"), "nb_inplace_and", "binaryfunc");
4248     printSlot(f, getSlot(n, "feature:python:nb_inplace_xor"), "nb_inplace_xor", "binaryfunc");
4249     printSlot(f, getSlot(n, "feature:python:nb_inplace_or"), "nb_inplace_or", "binaryfunc");
4250     printSlot(f, getSlot(n, "feature:python:nb_floor_divide"), "nb_floor_divide", "binaryfunc");
4251     printSlot(f, getSlot(n, "feature:python:nb_divide"), "nb_true_divide", "binaryfunc");
4252     printSlot(f, getSlot(n, "feature:python:nb_inplace_floor_divide"), "nb_inplace_floor_divide", "binaryfunc");
4253     printSlot(f, getSlot(n, "feature:python:nb_inplace_divide"), "nb_inplace_true_divide", "binaryfunc");
4254     printSlot(f, getSlot(n, "feature:python:nb_index"), "nb_index", "unaryfunc");
4255     Printv(f, "#if PY_VERSION_HEX >= 0x03050000\n", NIL);
4256     printSlot(f, getSlot(n, "feature:python:nb_matrix_multiply"), "nb_matrix_multiply", "binaryfunc");
4257     printSlot(f, getSlot(n, "feature:python:nb_inplace_matrix_multiply"), "nb_inplace_matrix_multiply", "binaryfunc");
4258     Printv(f, "#endif\n", NIL);
4259     Printf(f, "  },\n");
4260 
4261     // PyMappingMethods as_mapping;
4262     Printf(f, "  {\n");
4263     printSlot(f, getSlot(n, "feature:python:mp_length"), "mp_length", "lenfunc");
4264     printSlot(f, getSlot(n, "feature:python:mp_subscript"), "mp_subscript", "binaryfunc");
4265     printSlot(f, getSlot(n, "feature:python:mp_ass_subscript"), "mp_ass_subscript", "objobjargproc");
4266     Printf(f, "  },\n");
4267 
4268     // PySequenceMethods as_sequence;
4269     Printf(f, "  {\n");
4270     printSlot(f, getSlot(n, "feature:python:sq_length"), "sq_length", "lenfunc");
4271     printSlot(f, getSlot(n, "feature:python:sq_concat"), "sq_concat", "binaryfunc");
4272     printSlot(f, getSlot(n, "feature:python:sq_repeat"), "sq_repeat", "ssizeargfunc");
4273     printSlot(f, getSlot(n, "feature:python:sq_item"), "sq_item", "ssizeargfunc");
4274     Printv(f, "#if PY_VERSION_HEX >= 0x03000000\n", NIL);
4275     printSlot(f, getSlot(n, "feature:python:was_sq_slice"), "was_sq_slice", "void *");
4276     Printv(f, "#else\n", NIL);
4277     printSlot(f, getSlot(n, "feature:python:sq_slice"), "sq_slice", "ssizessizeargfunc");
4278     Printv(f, "#endif\n", NIL);
4279     printSlot(f, getSlot(n, "feature:python:sq_ass_item"), "sq_ass_item", "ssizeobjargproc");
4280     Printv(f, "#if PY_VERSION_HEX >= 0x03000000\n", NIL);
4281     printSlot(f, getSlot(n, "feature:python:was_sq_ass_slice"), "was_sq_ass_slice", "void *");
4282     Printv(f, "#else\n", NIL);
4283     printSlot(f, getSlot(n, "feature:python:sq_ass_slice"), "sq_ass_slice", "ssizessizeobjargproc");
4284     Printv(f, "#endif\n", NIL);
4285     printSlot(f, getSlot(n, "feature:python:sq_contains"), "sq_contains", "objobjproc");
4286     printSlot(f, getSlot(n, "feature:python:sq_inplace_concat"), "sq_inplace_concat", "binaryfunc");
4287     printSlot(f, getSlot(n, "feature:python:sq_inplace_repeat"), "sq_inplace_repeat", "ssizeargfunc");
4288     Printf(f, "  },\n");
4289 
4290     // PyBufferProcs as_buffer;
4291     Printf(f, "  {\n");
4292     Printv(f, "#if PY_VERSION_HEX < 0x03000000\n", NIL);
4293     printSlot(f, getSlot(n, "feature:python:bf_getreadbuffer"), "bf_getreadbuffer", "readbufferproc");
4294     printSlot(f, getSlot(n, "feature:python:bf_getwritebuffer"), "bf_getwritebuffer", "writebufferproc");
4295     printSlot(f, getSlot(n, "feature:python:bf_getsegcount"), "bf_getsegcount", "segcountproc");
4296     printSlot(f, getSlot(n, "feature:python:bf_getcharbuffer"), "bf_getcharbuffer", "charbufferproc");
4297     Printv(f, "#endif\n", NIL);
4298     printSlot(f, getSlot(n, "feature:python:bf_getbuffer"), "bf_getbuffer", "getbufferproc");
4299     printSlot(f, getSlot(n, "feature:python:bf_releasebuffer"), "bf_releasebuffer", "releasebufferproc");
4300     Printf(f, "  },\n");
4301 
4302     // PyObject *ht_name, *ht_slots, *ht_qualname;
4303     printSlot(f, getSlot(n, "feature:python:ht_name"), "ht_name", "PyObject *");
4304     printSlot(f, getSlot(n, "feature:python:ht_slots"), "ht_slots", "PyObject *");
4305     Printv(f, "#if PY_VERSION_HEX >= 0x03030000\n", NIL);
4306     printSlot(f, getSlot(n, "feature:python:ht_qualname"), "ht_qualname", "PyObject *");
4307 
4308     // struct _dictkeysobject *ht_cached_keys;
4309     printSlot(f, getSlot(n, "feature:python:ht_cached_keys"), "ht_cached_keys");
4310     Printv(f, "#endif\n", NIL);
4311     Printf(f, "};\n\n");
4312 
4313     String *clientdata = NewString("");
4314     Printf(clientdata, "&%s_clientdata", templ);
4315     SwigType_remember_mangleddata(pmname, clientdata);
4316 
4317     SwigType *smart = Swig_cparse_smartptr(n);
4318     if (smart) {
4319       SwigType_add_pointer(smart);
4320       String *smart_pmname = SwigType_manglestr(smart);
4321       SwigType_remember_mangleddata(smart_pmname, clientdata);
4322       Delete(smart_pmname);
4323     }
4324 
4325     String *clientdata_klass = NewString("0");
4326     if (GetFlag(n, "feature:implicitconv")) {
4327       Clear(clientdata_klass);
4328       Printf(clientdata_klass, "(PyObject *) &%s_type", templ);
4329     }
4330 
4331     Printf(f, "SWIGINTERN SwigPyClientData %s_clientdata = {%s, 0, 0, 0, 0, 0, (PyTypeObject *)&%s_type};\n\n", templ, clientdata_klass, templ);
4332 
4333     Printv(f_init, "    if (PyType_Ready(builtin_pytype) < 0) {\n", NIL);
4334     Printf(f_init, "      PyErr_SetString(PyExc_TypeError, \"Could not create type '%s'.\");\n", symname);
4335     Printv(f_init, "#if PY_VERSION_HEX >= 0x03000000\n", NIL);
4336     Printv(f_init, "      return NULL;\n", NIL);
4337     Printv(f_init, "#else\n", NIL);
4338     Printv(f_init, "      return;\n", NIL);
4339     Printv(f_init, "#endif\n", NIL);
4340     Printv(f_init, "    }\n", NIL);
4341     Printv(f_init, "    Py_INCREF(builtin_pytype);\n", NIL);
4342     Printf(f_init, "    PyModule_AddObject(m, \"%s\", (PyObject *)builtin_pytype);\n", symname);
4343     Printf(f_init, "    SwigPyBuiltin_AddPublicSymbol(public_interface, \"%s\");\n", symname);
4344     Printv(f_init, "    d = md;\n", NIL);
4345 
4346     Delete(clientdata);
4347     Delete(smart);
4348     Delete(rname);
4349     Delete(pname);
4350     Delete(mname);
4351     Delete(pmname);
4352     Delete(templ);
4353     Delete(tp_flags);
4354     Delete(tp_flags_py3);
4355     Delete(tp_as_buffer);
4356     Delete(tp_as_mapping);
4357     Delete(tp_as_sequence);
4358     Delete(tp_as_number);
4359     Delete(quoted_symname);
4360     Delete(quoted_tp_doc_str);
4361     Delete(tp_init);
4362     Delete(clientdata_klass);
4363     Delete(richcompare_func);
4364     Delete(getset_name);
4365     Delete(methods_name);
4366   }
4367 
classHandler(Node * n)4368   virtual int classHandler(Node *n) {
4369     File *f_shadow_file = f_shadow;
4370     Node *base_node = NULL;
4371 
4372     if (shadow) {
4373 
4374       /* Create new strings for building up a wrapper function */
4375       have_constructor = 0;
4376       have_repr = 0;
4377 
4378       class_name = Getattr(n, "sym:name");
4379       real_classname = Getattr(n, "name");
4380 
4381       if (!addSymbol(class_name, n))
4382 	return SWIG_ERROR;
4383 
4384       if (builtin) {
4385 	List *baselist = Getattr(n, "bases");
4386 	if (baselist && Len(baselist) > 0) {
4387 	  Iterator b = First(baselist);
4388 	  base_node = b.item;
4389 	}
4390       }
4391 
4392       shadow_indent = (String *) tab4;
4393 
4394       /* Handle inheritance */
4395       String *base_class = NewString("");
4396       List *baselist = Getattr(n, "bases");
4397       if (baselist && Len(baselist)) {
4398 	Iterator b;
4399 	b = First(baselist);
4400 	while (b.item) {
4401 	  String *bname = Getattr(b.item, "python:proxy");
4402 	  bool ignore = GetFlag(b.item, "feature:ignore") ? true : false;
4403 	  if (!bname || ignore) {
4404 	    if (!bname && !ignore) {
4405 	      Swig_warning(WARN_TYPE_UNDEFINED_CLASS, Getfile(n), Getline(n),
4406 			   "Base class '%s' ignored - unknown module name for base. Either import the appropriate module interface file or specify the name of the module in the %%import directive.\n",
4407 			   SwigType_namestr(Getattr(b.item, "name")));
4408 	    }
4409 	    b = Next(b);
4410 	    continue;
4411 	  }
4412 	  Printv(base_class, bname, NIL);
4413 	  b = Next(b);
4414 	  if (b.item) {
4415             Printv(base_class, ", ", NIL);
4416 	  }
4417 	}
4418       }
4419 
4420       if (builtin) {
4421 	Hash *base_richcompare = NULL;
4422 	Hash *richcompare = NULL;
4423 	if (base_node)
4424 	  base_richcompare = Getattr(base_node, "python:richcompare");
4425 	if (base_richcompare)
4426 	  richcompare = Copy(base_richcompare);
4427 	else
4428 	  richcompare = NewHash();
4429 	Setattr(n, "python:richcompare", richcompare);
4430       }
4431 
4432       /* dealing with abstract base class */
4433       String *abcs = Getattr(n, "feature:python:abc");
4434       if (py3 && abcs) {
4435 	if (Len(base_class)) {
4436 	  Printv(base_class, ", ", NIL);
4437 	}
4438 	Printv(base_class, abcs, NIL);
4439       }
4440 
4441       if (builtin) {
4442 	if (have_docstring(n)) {
4443 	  String *ds = cdocstring(n, AUTODOC_CLASS);
4444 	  Setattr(n, "feature:python:tp_doc", ds);
4445 	  Delete(ds);
4446 	} else {
4447 	  String *name = Getattr(n, "name");
4448 	  String *rname = add_explicit_scope(SwigType_namestr(name));
4449 	  Setattr(n, "feature:python:tp_doc", rname);
4450 	  Delete(rname);
4451 	}
4452       } else {
4453 	if (!py3) {
4454 	  if (GetFlag(n, "feature:python:nondynamic"))
4455 	    Printv(f_shadow, "@_swig_add_metaclass(_SwigNonDynamicMeta)\n", NIL);
4456 	}
4457 	Printv(f_shadow, "class ", class_name, NIL);
4458 
4459 	if (Len(base_class)) {
4460 	  Printf(f_shadow, "(%s)", base_class);
4461 	} else {
4462 	  if (GetFlag(n, "feature:exceptionclass")) {
4463 	    Printf(f_shadow, "(Exception)");
4464 	  } else {
4465 	    Printf(f_shadow, "(object");
4466 	    Printf(f_shadow, py3 && GetFlag(n, "feature:python:nondynamic") ? ", metaclass=_SwigNonDynamicMeta" : "", ")");
4467 	    Printf(f_shadow, ")");
4468 	  }
4469 	}
4470 
4471 	Printf(f_shadow, ":\n");
4472 
4473 	// write docstrings if requested
4474 	if (have_docstring(n)) {
4475 	  String *str = docstring(n, AUTODOC_CLASS, tab4);
4476 	  if (str && Len(str))
4477 	    Printv(f_shadow, tab4, str, "\n\n", NIL);
4478 	}
4479 
4480 	Printv(f_shadow, tab4, "thisown = property(lambda x: x.this.own(), ", "lambda x, v: x.this.own(v), doc=\"The membership flag\")\n", NIL);
4481 	/* Add static attribute */
4482 	if (GetFlag(n, "feature:python:nondynamic")) {
4483 	  Printv(f_shadow_file, tab4, "__setattr__ = _swig_setattr_nondynamic_instance_variable(object.__setattr__)\n", NIL);
4484 	}
4485       }
4486     }
4487 
4488     /* Emit all of the members */
4489 
4490     in_class = 1;
4491     if (builtin)
4492       builtin_pre_decl(n);
4493 
4494     /* Override the shadow file so we can capture its methods */
4495     f_shadow = NewString("");
4496 
4497     // Set up type check for director class constructor
4498     Clear(none_comparison);
4499     if (builtin && Swig_directorclass(n)) {
4500       String *p_real_classname = Copy(real_classname);
4501       SwigType_add_pointer(p_real_classname);
4502       String *mangle = SwigType_manglestr(p_real_classname);
4503       String *descriptor = NewStringf("SWIGTYPE%s", mangle);
4504       Printv(none_comparison, "self->ob_type != ((SwigPyClientData *)(", descriptor, ")->clientdata)->pytype", NIL);
4505       Delete(descriptor);
4506       Delete(mangle);
4507       Delete(p_real_classname);
4508     } else {
4509       Printv(none_comparison, "$arg != Py_None", NIL);
4510     }
4511 
4512     Language::classHandler(n);
4513 
4514     in_class = 0;
4515 
4516     /* Complete the class */
4517     if (shadow) {
4518       /* Generate a class registration function */
4519       // Replace storing a pointer to underlying class with a smart pointer (intended for use with non-intrusive smart pointers)
4520       SwigType *smart = Swig_cparse_smartptr(n);
4521       SwigType *ct = Copy(smart ? smart : real_classname);
4522       SwigType_add_pointer(ct);
4523       SwigType *realct = Copy(real_classname);
4524       SwigType_add_pointer(realct);
4525       SwigType_remember(realct);
4526       if (builtin) {
4527 	Printv(f_wrappers, builtin_closures_code, NIL);
4528 	Delete(builtin_closures_code);
4529 	builtin_closures_code = NewString("");
4530 	Clear(builtin_closures);
4531       } else {
4532 	Printv(f_wrappers, "SWIGINTERN PyObject *", class_name, "_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {\n", NIL);
4533 	Printv(f_wrappers, "  PyObject *obj;\n", NIL);
4534 	Printv(f_wrappers, "  if (!SWIG_Python_UnpackTuple(args, \"swigregister\", 1, 1, &obj)) return NULL;\n", NIL);
4535 
4536 	Printv(f_wrappers,
4537 	       "  SWIG_TypeNewClientData(SWIGTYPE", SwigType_manglestr(ct), ", SWIG_NewClientData(obj));\n", "  return SWIG_Py_Void();\n", "}\n\n", NIL);
4538 	String *cname = NewStringf("%s_swigregister", class_name);
4539 	add_method(cname, cname, 0, 0, 1, 1, 1);
4540 	Delete(cname);
4541       }
4542       Delete(smart);
4543       Delete(ct);
4544       Delete(realct);
4545       if (!have_constructor) {
4546 	if (!builtin)
4547 	  Printv(f_shadow_file, "\n", tab4, "def __init__(self, *args, **kwargs):\n", tab8, "raise AttributeError(\"", "No constructor defined",
4548 		 (Getattr(n, "abstracts") ? " - class is abstract" : ""), "\")\n", NIL);
4549       } else if (!builtin) {
4550 
4551 	Printv(f_wrappers, "SWIGINTERN PyObject *", class_name, "_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {\n", NIL);
4552 	Printv(f_wrappers, "  return SWIG_Python_InitShadowInstance(args);\n", "}\n\n", NIL);
4553 	String *cname = NewStringf("%s_swiginit", class_name);
4554 	add_method(cname, cname, 0);
4555 	Delete(cname);
4556       }
4557       if (!have_repr && !builtin) {
4558 	/* Supply a repr method for this class  */
4559 	String *rname = SwigType_namestr(real_classname);
4560 	Printv(f_shadow_file, tab4, "__repr__ = _swig_repr\n", NIL);
4561 	Delete(rname);
4562       }
4563 
4564       if (builtin)
4565 	builtin_post_decl(f_builtins, n);
4566 
4567       if (builtin_tp_init) {
4568 	Delete(builtin_tp_init);
4569 	builtin_tp_init = 0;
4570       }
4571 
4572       if (!builtin) {
4573 	/* Now emit methods */
4574 	Printv(f_shadow_file, f_shadow, NIL);
4575 	Printf(f_shadow_file, "\n");
4576 	Printf(f_shadow_file, "# Register %s in %s:\n", class_name, module);
4577 	Printf(f_shadow_file, "%s.%s_swigregister(%s)\n", module, class_name, class_name);
4578       }
4579 
4580       shadow_indent = 0;
4581       Printf(f_shadow_file, "%s\n", f_shadow_stubs);
4582       Clear(f_shadow_stubs);
4583     }
4584 
4585     if (builtin) {
4586       Clear(class_members);
4587       Clear(builtin_getset);
4588       Clear(builtin_methods);
4589     }
4590 
4591     /* Restore shadow file back to original version */
4592     Delete(f_shadow);
4593     f_shadow = f_shadow_file;
4594 
4595     return SWIG_OK;
4596   }
4597 
4598   /* ------------------------------------------------------------
4599    * functionHandler()  -  Mainly overloaded for callback handling
4600    * ------------------------------------------------------------ */
4601 
functionHandler(Node * n)4602   virtual int functionHandler(Node *n) {
4603     String *pcb = GetFlagAttr(n, "feature:python:callback");
4604     if (pcb) {
4605       if (Strcmp(pcb, "1") == 0) {
4606 	SetFlagAttr(n, "feature:callback", "%s_cb_ptr");
4607       } else {
4608 	SetFlagAttr(n, "feature:callback", pcb);
4609       }
4610       autodoc_l dlevel = autodoc_level(Getattr(n, "feature:autodoc"));
4611       if (dlevel != NO_AUTODOC && dlevel > TYPES_AUTODOC) {
4612 	Setattr(n, "feature:autodoc", "1");
4613       }
4614     }
4615     return Language::functionHandler(n);
4616   }
4617 
4618   /* ------------------------------------------------------------
4619    * memberfunctionHandler()
4620    * ------------------------------------------------------------ */
4621 
memberfunctionHandler(Node * n)4622   virtual int memberfunctionHandler(Node *n) {
4623     String *symname = Getattr(n, "sym:name");
4624     int oldshadow;
4625 
4626     if (builtin)
4627       Swig_save("builtin_memberfunc", n, "python:argcount", NIL);
4628 
4629     /* Create the default member function */
4630     oldshadow = shadow;		/* Disable shadowing when wrapping member functions */
4631     if (shadow)
4632       shadow = shadow | PYSHADOW_MEMBER;
4633     Language::memberfunctionHandler(n);
4634     shadow = oldshadow;
4635 
4636     if (builtin && in_class) {
4637       // Can't use checkAttribute(n, "access", "public") because
4638       // "access" attr isn't set on %extend methods
4639       if (!checkAttribute(n, "access", "private") && strncmp(Char(symname), "operator ", 9) && !Getattr(class_members, symname)) {
4640 	String *fullname = Swig_name_member(NSPACE_TODO, class_name, symname);
4641 	String *wname = Swig_name_wrapper(fullname);
4642 	Setattr(class_members, symname, n);
4643 	int argcount = Getattr(n, "python:argcount") ? atoi(Char(Getattr(n, "python:argcount"))) : 2;
4644 	String *ds = have_docstring(n) ? cdocstring(n, AUTODOC_METHOD) : NewString("");
4645 	if (check_kwargs(n)) {
4646 	  // Cast via void(*)(void) to suppress GCC -Wcast-function-type
4647 	  // warning.  Python should always call the function correctly, but
4648 	  // the Python C API requires us to store it in function pointer of a
4649 	  // different type.
4650 	  Printf(builtin_methods, "  { \"%s\", (PyCFunction)(void(*)(void))%s, METH_VARARGS|METH_KEYWORDS, \"%s\" },\n", symname, wname, ds);
4651 	} else if (argcount == 0) {
4652 	  Printf(builtin_methods, "  { \"%s\", %s, METH_NOARGS, \"%s\" },\n", symname, wname, ds);
4653 	} else if (argcount == 1) {
4654 	  Printf(builtin_methods, "  { \"%s\", %s, METH_O, \"%s\" },\n", symname, wname, ds);
4655 	} else {
4656 	  Printf(builtin_methods, "  { \"%s\", %s, METH_VARARGS, \"%s\" },\n", symname, wname, ds);
4657 	}
4658 	Delete(fullname);
4659 	Delete(wname);
4660 	Delete(ds);
4661       }
4662     }
4663 
4664     if (builtin)
4665       Swig_restore(n);
4666 
4667     if (!Getattr(n, "sym:nextSibling")) {
4668       if (shadow && !builtin) {
4669 	int fproxy = fastproxy;
4670 	String *fullname = Swig_name_member(NSPACE_TODO, class_name, symname);
4671 	if (Strcmp(symname, "__repr__") == 0) {
4672 	  have_repr = 1;
4673 	}
4674 	if (Getattr(n, "feature:shadow")) {
4675 	  String *pycode = indent_pythoncode(Getattr(n, "feature:shadow"), tab4, Getfile(n), Getline(n), "%feature(\"shadow\")");
4676 	  String *pyaction = NewStringf("%s.%s", module, fullname);
4677 	  Replaceall(pycode, "$action", pyaction);
4678 	  Delete(pyaction);
4679 	  Printv(f_shadow, pycode, "\n", NIL);
4680 	  Delete(pycode);
4681 	  fproxy = 0;
4682 	} else {
4683 	  int allow_kwargs = (check_kwargs(n) && !Getattr(n, "sym:overloaded")) ? 1 : 0;
4684 	  String *parms = make_pyParmList(n, true, false, allow_kwargs);
4685 	  String *callParms = make_pyParmList(n, true, true, allow_kwargs);
4686 	  if (!have_addtofunc(n)) {
4687 	    if (!fastproxy || olddefs) {
4688 	      Printv(f_shadow, "\n", tab4, "def ", symname, "(", parms, ")", returnTypeAnnotation(n), ":\n", NIL);
4689 	      if (have_docstring(n))
4690 		Printv(f_shadow, tab8, docstring(n, AUTODOC_METHOD, tab8), "\n", NIL);
4691 	      Printv(f_shadow, tab8, "return ", funcCall(fullname, callParms), "\n", NIL);
4692 	    }
4693 	  } else {
4694 	    Printv(f_shadow, "\n", tab4, "def ", symname, "(", parms, ")", returnTypeAnnotation(n), ":\n", NIL);
4695 	    if (have_docstring(n))
4696 	      Printv(f_shadow, tab8, docstring(n, AUTODOC_METHOD, tab8), "\n", NIL);
4697 	    if (have_pythonprepend(n)) {
4698 	      fproxy = 0;
4699 	      Printv(f_shadow, indent_pythoncode(pythonprepend(n), tab8, Getfile(n), Getline(n), "%pythonprepend or %feature(\"pythonprepend\")"), "\n", NIL);
4700 	    }
4701 	    if (have_pythonappend(n)) {
4702 	      fproxy = 0;
4703 	      Printv(f_shadow, tab8, "val = ", funcCall(fullname, callParms), "\n", NIL);
4704 	      Printv(f_shadow, indent_pythoncode(pythonappend(n), tab8, Getfile(n), Getline(n), "%pythonappend or %feature(\"pythonappend\")"), "\n", NIL);
4705 	      Printv(f_shadow, tab8, "return val\n\n", NIL);
4706 	    } else {
4707 	      Printv(f_shadow, tab8, "return ", funcCall(fullname, callParms), "\n\n", NIL);
4708 	    }
4709 	  }
4710 	}
4711 	if (fproxy) {
4712 	  Printf(f_shadow, tab4);
4713 	  Printf(f_shadow, "%s = _swig_new_instance_method(%s.%s)\n", symname, module, Swig_name_member(NSPACE_TODO, class_name, symname));
4714 	}
4715 	Delete(fullname);
4716       }
4717     }
4718     return SWIG_OK;
4719   }
4720 
4721 
4722   /* ------------------------------------------------------------
4723    * staticmemberfunctionHandler()
4724    * ------------------------------------------------------------ */
4725 
staticmemberfunctionHandler(Node * n)4726   virtual int staticmemberfunctionHandler(Node *n) {
4727     String *symname = Getattr(n, "sym:name");
4728     if (builtin && in_class) {
4729       Swig_save("builtin_memberconstantHandler", n, "pybuiltin:symname", NIL);
4730       Setattr(n, "pybuiltin:symname", symname);
4731     }
4732     Language::staticmemberfunctionHandler(n);
4733     if (builtin && in_class) {
4734       Swig_restore(n);
4735     }
4736 
4737     if (builtin && in_class) {
4738       if ((GetFlagAttr(n, "feature:extend") || checkAttribute(n, "access", "public"))
4739 	  && !Getattr(class_members, symname)) {
4740 	String *fullname = Swig_name_member(NSPACE_TODO, class_name, symname);
4741 	String *wname = Swig_name_wrapper(fullname);
4742 	Setattr(class_members, symname, n);
4743 	int funpack = fastunpack && !Getattr(n, "sym:overloaded");
4744 	String *pyflags = NewString("METH_STATIC|");
4745 	int argcount = Getattr(n, "python:argcount") ? atoi(Char(Getattr(n, "python:argcount"))) : 2;
4746 	if (funpack && argcount == 0)
4747 	  Append(pyflags, "METH_NOARGS");
4748 	else if (funpack && argcount == 1)
4749 	  Append(pyflags, "METH_O");
4750 	else
4751 	  Append(pyflags, "METH_VARARGS");
4752 	// Cast via void(*)(void) to suppress GCC -Wcast-function-type warning.
4753 	// Python should always call the function correctly, but the Python C
4754 	// API requires us to store it in function pointer of a different type.
4755 	if (have_docstring(n)) {
4756 	  String *ds = cdocstring(n, AUTODOC_STATICFUNC);
4757 	  Printf(builtin_methods, "  { \"%s\", (PyCFunction)(void(*)(void))%s, %s, \"%s\" },\n", symname, wname, pyflags, ds);
4758 	  Delete(ds);
4759 	} else {
4760 	  Printf(builtin_methods, "  { \"%s\", (PyCFunction)(void(*)(void))%s, %s, \"\" },\n", symname, wname, pyflags);
4761 	}
4762 	Delete(fullname);
4763 	Delete(wname);
4764 	Delete(pyflags);
4765       }
4766       return SWIG_OK;
4767     }
4768 
4769     if (Getattr(n, "sym:nextSibling")) {
4770       return SWIG_OK;
4771     }
4772 
4773     if (shadow) {
4774       String *staticfunc_name = NewString(fastproxy ? "_swig_new_static_method" : "staticmethod");
4775       bool fast = (fastproxy && !have_addtofunc(n)) || Getattr(n, "feature:callback");
4776       if (!fast || olddefs) {
4777 	int kw = (check_kwargs(n) && !Getattr(n, "sym:overloaded")) ? 1 : 0;
4778 	String *parms = make_pyParmList(n, false, false, kw);
4779 	String *callParms = make_pyParmList(n, false, true, kw);
4780 	Printv(f_shadow, "\n", tab4, "@staticmethod", NIL);
4781 	Printv(f_shadow, "\n", tab4, "def ", symname, "(", parms, ")", returnTypeAnnotation(n), ":\n", NIL);
4782 	if (have_docstring(n))
4783 	  Printv(f_shadow, tab8, docstring(n, AUTODOC_STATICFUNC, tab8), "\n", NIL);
4784 	if (have_pythonprepend(n))
4785 	  Printv(f_shadow, indent_pythoncode(pythonprepend(n), tab8, Getfile(n), Getline(n), "%pythonprepend or %feature(\"pythonprepend\")"), "\n", NIL);
4786 	if (have_pythonappend(n)) {
4787 	  Printv(f_shadow, tab8, "val = ", funcCall(Swig_name_member(NSPACE_TODO, class_name, symname), callParms), "\n", NIL);
4788 	  Printv(f_shadow, indent_pythoncode(pythonappend(n), tab8, Getfile(n), Getline(n), "%pythonappend or %feature(\"pythonappend\")"), "\n", NIL);
4789 	  Printv(f_shadow, tab8, "return val\n", NIL);
4790 	} else {
4791 	  Printv(f_shadow, tab8, "return ", funcCall(Swig_name_member(NSPACE_TODO, class_name, symname), callParms), "\n", NIL);
4792 	}
4793       }
4794 
4795       // Below may result in a 2nd definition of the method when -olddefs is used. The Python interpreter will use the second definition as it overwrites the first.
4796       if (fast) {
4797 	Printv(f_shadow, tab4, symname, " = ", staticfunc_name, "(", module, ".", Swig_name_member(NSPACE_TODO, class_name, symname),
4798 	       ")\n", NIL);
4799       }
4800       Delete(staticfunc_name);
4801     }
4802     return SWIG_OK;
4803   }
4804 
4805   /* ------------------------------------------------------------
4806    * constructorDeclaration()
4807    * ------------------------------------------------------------ */
4808 
constructorHandler(Node * n)4809   virtual int constructorHandler(Node *n) {
4810     String *symname = Getattr(n, "sym:name");
4811     int oldshadow = shadow;
4812     int use_director = Swig_directorclass(n);
4813 
4814     /*
4815      * If we're wrapping the constructor of a C++ director class, prepend a new parameter
4816      * to receive the scripting language object (e.g. 'self')
4817      *
4818      */
4819     Swig_save("python:constructorHandler", n, "parms", NIL);
4820     if (use_director) {
4821       Parm *parms = Getattr(n, "parms");
4822       Parm *self;
4823       String *name = NewString("self");
4824       String *type = NewString("PyObject");
4825       SwigType_add_pointer(type);
4826       self = NewParm(type, name, n);
4827       Delete(type);
4828       Delete(name);
4829       Setattr(self, "lname", "O");
4830       if (parms)
4831 	set_nextSibling(self, parms);
4832       Setattr(n, "parms", self);
4833       Setattr(n, "wrap:self", "1");
4834       Setattr(n, "hidden", "1");
4835       Delete(self);
4836     }
4837 
4838     if (shadow)
4839       shadow = shadow | PYSHADOW_MEMBER;
4840     Language::constructorHandler(n);
4841     shadow = oldshadow;
4842 
4843     Delattr(n, "wrap:self");
4844     Swig_restore(n);
4845 
4846     if (!Getattr(n, "sym:nextSibling")) {
4847       if (shadow) {
4848 	int allow_kwargs = (check_kwargs(n) && (!Getattr(n, "sym:overloaded"))) ? 1 : 0;
4849 	int handled_as_init = 0;
4850 	if (!have_constructor) {
4851 	  String *nname = Getattr(n, "sym:name");
4852 	  String *sname = Getattr(getCurrentClass(), "sym:name");
4853 	  String *cname = Swig_name_construct(NSPACE_TODO, sname);
4854 	  handled_as_init = (Strcmp(nname, sname) == 0) || (Strcmp(nname, cname) == 0);
4855 	  Delete(cname);
4856 	}
4857 
4858 	String *subfunc = Swig_name_construct(NSPACE_TODO, symname);
4859 	if (!have_constructor && handled_as_init) {
4860 	  if (!builtin) {
4861 	    if (Getattr(n, "feature:shadow")) {
4862 	      String *pycode = indent_pythoncode(Getattr(n, "feature:shadow"), tab4, Getfile(n), Getline(n), "%feature(\"shadow\")");
4863 	      String *pyaction = NewStringf("%s.%s", module, subfunc);
4864 	      Replaceall(pycode, "$action", pyaction);
4865 	      Delete(pyaction);
4866 	      Printv(f_shadow, pycode, "\n", NIL);
4867 	      Delete(pycode);
4868 	    } else {
4869 	      String *pass_self = NewString("");
4870 	      Node *parent = Swig_methodclass(n);
4871 	      String *classname = Swig_class_name(parent);
4872 	      String *rclassname = Swig_class_name(getCurrentClass());
4873 	      assert(rclassname);
4874 
4875 	      String *parms = make_pyParmList(n, true, false, allow_kwargs);
4876 	      /* Pass 'self' only if using director */
4877 	      String *callParms = make_pyParmList(n, false, true, allow_kwargs, true);
4878 
4879 	      if (use_director) {
4880 		Insert(callParms, 0, "_self, ");
4881 		Printv(pass_self, tab8, NIL);
4882 		Printf(pass_self, "if self.__class__ == %s:\n", classname);
4883 		//Printv(pass_self, tab8, tab4, "args = (None,) + args\n", tab8, "else:\n", tab8, tab4, "args = (self,) + args\n", NIL);
4884 		Printv(pass_self, tab8, tab4, "_self = None\n", tab8, "else:\n", tab8, tab4, "_self = self\n", NIL);
4885 	      }
4886 
4887 	      Printv(f_shadow, "\n", tab4, "def __init__(", parms, ")", returnTypeAnnotation(n), ":\n", NIL);
4888 	      if (have_docstring(n))
4889 		Printv(f_shadow, tab8, docstring(n, AUTODOC_CTOR, tab8), "\n", NIL);
4890 	      if (have_pythonprepend(n))
4891 		Printv(f_shadow, indent_pythoncode(pythonprepend(n), tab8, Getfile(n), Getline(n), "%pythonprepend or %feature(\"pythonprepend\")"), "\n", NIL);
4892 	      Printv(f_shadow, pass_self, NIL);
4893 	      Printv(f_shadow, tab8, module, ".", class_name, "_swiginit(self, ", funcCall(subfunc, callParms), ")\n", NIL);
4894 	      if (have_pythonappend(n))
4895 		Printv(f_shadow, indent_pythoncode(pythonappend(n), tab8, Getfile(n), Getline(n), "%pythonappend or %feature(\"pythonappend\")"), "\n\n", NIL);
4896 	      Delete(pass_self);
4897 	    }
4898 	    have_constructor = 1;
4899 	  }
4900 	} else {
4901 	  /* Hmmm. We seem to be creating a different constructor.  We're just going to create a
4902 	     function for it. */
4903 	  if (!builtin) {
4904 	    if (Getattr(n, "feature:shadow")) {
4905 	      String *pycode = indent_pythoncode(Getattr(n, "feature:shadow"), "", Getfile(n), Getline(n), "%feature(\"shadow\")");
4906 	      String *pyaction = NewStringf("%s.%s", module, subfunc);
4907 	      Replaceall(pycode, "$action", pyaction);
4908 	      Delete(pyaction);
4909 	      Printv(f_shadow_stubs, pycode, "\n", NIL);
4910 	      Delete(pycode);
4911 	    } else {
4912 	      String *parms = make_pyParmList(n, false, false, allow_kwargs);
4913 	      String *callParms = make_pyParmList(n, false, true, allow_kwargs);
4914 
4915 	      Printv(f_shadow_stubs, "\ndef ", symname, "(", parms, ")", returnTypeAnnotation(n), ":\n", NIL);
4916 	      if (have_docstring(n))
4917 		Printv(f_shadow_stubs, tab4, docstring(n, AUTODOC_CTOR, tab4), "\n", NIL);
4918 	      if (have_pythonprepend(n))
4919 		Printv(f_shadow_stubs, indent_pythoncode(pythonprepend(n), tab4, Getfile(n), Getline(n), "%pythonprepend or %feature(\"pythonprepend\")"), "\n", NIL);
4920 	      Printv(f_shadow_stubs, tab4, "val = ", funcCall(subfunc, callParms), "\n", NIL);
4921 #ifdef USE_THISOWN
4922 	      Printv(f_shadow_stubs, tab4, "val.thisown = 1\n", NIL);
4923 #endif
4924 	      if (have_pythonappend(n))
4925 		Printv(f_shadow_stubs, indent_pythoncode(pythonappend(n), tab4, Getfile(n), Getline(n), "%pythonappend or %feature(\"pythonappend\")"), "\n", NIL);
4926 	      Printv(f_shadow_stubs, tab4, "return val\n", NIL);
4927 	    }
4928 	  } else {
4929 	    Printf(f_shadow_stubs, "%s = %s\n", symname, subfunc);
4930 	  }
4931 	}
4932 	Delete(subfunc);
4933       }
4934     }
4935     return SWIG_OK;
4936   }
4937 
4938   /* ------------------------------------------------------------
4939    * destructorHandler()
4940    * ------------------------------------------------------------ */
4941 
destructorHandler(Node * n)4942   virtual int destructorHandler(Node *n) {
4943     String *symname = Getattr(n, "sym:name");
4944     int oldshadow = shadow;
4945 
4946     if (builtin && in_class) {
4947       Node *cls = Swig_methodclass(n);
4948       // Use the destructor for the tp_dealloc slot unless a user overrides it with another method
4949       if (!Getattr(cls, "feature:python:tp_dealloc")) {
4950 	Setattr(n, "feature:python:slot", "tp_dealloc");
4951 	Setattr(n, "feature:python:slot:functype", "destructor");
4952       }
4953     }
4954 
4955     if (shadow)
4956       shadow = shadow | PYSHADOW_MEMBER;
4957     //Setattr(n,"emit:dealloc","1");
4958     Language::destructorHandler(n);
4959     shadow = oldshadow;
4960 
4961     if (shadow) {
4962       if (Getattr(n, "feature:shadow")) {
4963 	String *pycode = indent_pythoncode(Getattr(n, "feature:shadow"), tab4, Getfile(n), Getline(n), "%feature(\"shadow\")");
4964 	String *pyaction = NewStringf("%s.%s", module, Swig_name_destroy(NSPACE_TODO, symname));
4965 	Replaceall(pycode, "$action", pyaction);
4966 	Delete(pyaction);
4967 	Printv(f_shadow, pycode, "\n", NIL);
4968 	Delete(pycode);
4969       } else {
4970 	Printv(f_shadow, tab4, "__swig_destroy__ = ", module, ".", Swig_name_destroy(NSPACE_TODO, symname), "\n", NIL);
4971 	if (!have_pythonprepend(n) && !have_pythonappend(n)) {
4972 	  return SWIG_OK;
4973 	}
4974 	Printv(f_shadow, tab4, "def __del__(self):\n", NIL);
4975 	if (have_docstring(n))
4976 	  Printv(f_shadow, tab8, docstring(n, AUTODOC_DTOR, tab8), "\n", NIL);
4977 	if (have_pythonprepend(n))
4978 	  Printv(f_shadow, indent_pythoncode(pythonprepend(n), tab8, Getfile(n), Getline(n), "%pythonprepend or %feature(\"pythonprepend\")"), "\n", NIL);
4979 #ifdef USE_THISOWN
4980 	Printv(f_shadow, tab8, "try:\n", NIL);
4981 	Printv(f_shadow, tab8, tab4, "if self.thisown:", module, ".", Swig_name_destroy(NSPACE_TODO, symname), "(self)\n", NIL);
4982 	Printv(f_shadow, tab8, "except __builtin__.Exception: pass\n", NIL);
4983 #else
4984 #endif
4985 	if (have_pythonappend(n))
4986 	  Printv(f_shadow, indent_pythoncode(pythonappend(n), tab8, Getfile(n), Getline(n), "%pythonappend or %feature(\"pythonappend\")"), "\n", NIL);
4987 	Printv(f_shadow, tab8, "pass\n", NIL);
4988 	Printv(f_shadow, "\n", NIL);
4989       }
4990     }
4991     return SWIG_OK;
4992   }
4993 
4994   /* ------------------------------------------------------------
4995    * membervariableHandler()
4996    * ------------------------------------------------------------ */
4997 
membervariableHandler(Node * n)4998   virtual int membervariableHandler(Node *n) {
4999     String *symname = Getattr(n, "sym:name");
5000 
5001     int oldshadow = shadow;
5002     if (shadow)
5003       shadow = shadow | PYSHADOW_MEMBER;
5004     Language::membervariableHandler(n);
5005     shadow = oldshadow;
5006 
5007     if (shadow && !builtin) {
5008       String *mname = Swig_name_member(NSPACE_TODO, class_name, symname);
5009       String *setname = Swig_name_set(NSPACE_TODO, mname);
5010       String *getname = Swig_name_get(NSPACE_TODO, mname);
5011       int assignable = is_assignable(n);
5012       Printv(f_shadow, tab4, symname, " = property(", module, ".", getname, NIL);
5013       if (assignable)
5014 	Printv(f_shadow, ", ", module, ".", setname, NIL);
5015       if (have_docstring(n))
5016 	Printv(f_shadow, ", doc=", docstring(n, AUTODOC_VAR, tab4), NIL);
5017       Printv(f_shadow, ")\n", NIL);
5018       Delete(mname);
5019       Delete(setname);
5020       Delete(getname);
5021     }
5022 
5023     return SWIG_OK;
5024   }
5025 
5026   /* ------------------------------------------------------------
5027    * staticmembervariableHandler()
5028    * ------------------------------------------------------------ */
5029 
staticmembervariableHandler(Node * n)5030   virtual int staticmembervariableHandler(Node *n) {
5031     Swig_save("builtin_staticmembervariableHandler", n, "builtin_symname", NIL);
5032     Language::staticmembervariableHandler(n);
5033     Swig_restore(n);
5034 
5035     if (GetFlag(n, "wrappedasconstant"))
5036       return SWIG_OK;
5037 
5038     String *symname = Getattr(n, "sym:name");
5039 
5040     if (shadow) {
5041       if (!builtin && GetFlag(n, "hasconsttype")) {
5042 	String *mname = Swig_name_member(NSPACE_TODO, class_name, symname);
5043 	Printf(f_shadow_stubs, "%s.%s = %s.%s.%s\n", class_name, symname, module, global_name, mname);
5044 	Delete(mname);
5045       } else {
5046 	String *mname = Swig_name_member(NSPACE_TODO, class_name, symname);
5047 	String *getname = Swig_name_get(NSPACE_TODO, mname);
5048 	String *wrapgetname = Swig_name_wrapper(getname);
5049 	String *vargetname = NewStringf("Swig_var_%s", getname);
5050 	String *setname = Swig_name_set(NSPACE_TODO, mname);
5051 	String *wrapsetname = Swig_name_wrapper(setname);
5052 	String *varsetname = NewStringf("Swig_var_%s", setname);
5053 
5054 	Wrapper *f = NewWrapper();
5055 	Printv(f->def, "SWIGINTERN PyObject *", wrapgetname, "(PyObject *SWIGUNUSEDPARM(self), PyObject *SWIGUNUSEDPARM(args)) {", NIL);
5056 	Printv(f->code, "  return ", vargetname, "();\n", NIL);
5057 	Append(f->code, "}\n");
5058 	add_method(getname, wrapgetname, 0);
5059 	Wrapper_print(f, f_wrappers);
5060 	DelWrapper(f);
5061 	int assignable = is_assignable(n);
5062 	if (assignable) {
5063 	  int funpack = fastunpack;
5064 	  Wrapper *f = NewWrapper();
5065 	  Printv(f->def, "SWIGINTERN PyObject *", wrapsetname, "(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {", NIL);
5066 	  Wrapper_add_local(f, "res", "int res");
5067 	  if (!funpack) {
5068 	    Wrapper_add_local(f, "value", "PyObject *value");
5069 	    Append(f->code, "if (!PyArg_ParseTuple(args, \"O:set\", &value)) return NULL;\n");
5070 	  }
5071 	  Printf(f->code, "res = %s(%s);\n", varsetname, funpack ? "args" : "value");
5072 	  Append(f->code, "return !res ? SWIG_Py_Void() : NULL;\n");
5073 	  Append(f->code, "}\n");
5074 	  Wrapper_print(f, f_wrappers);
5075 	  add_method(setname, wrapsetname, 0, 0, funpack, 1, 1);
5076 	  DelWrapper(f);
5077 	}
5078 	if (!builtin) {
5079 	  Printv(f_shadow, tab4, symname, " = property(", module, ".", getname, NIL);
5080 	  if (assignable)
5081 	    Printv(f_shadow, ", ", module, ".", setname, NIL);
5082 	  if (have_docstring(n))
5083 	    Printv(f_shadow, ", doc=", docstring(n, AUTODOC_VAR, tab4), NIL);
5084 	  Printv(f_shadow, ")\n", NIL);
5085 	}
5086 	String *getter = Getattr(n, "pybuiltin:getter");
5087 	String *setter = Getattr(n, "pybuiltin:setter");
5088 	Hash *h = NULL;
5089 	if (getter || setter) {
5090 	  h = Getattr(builtin_getset, symname);
5091 	  if (!h) {
5092 	    h = NewHash();
5093 	    Setattr(h, "static", "1");
5094 	    Setattr(builtin_getset, symname, h);
5095 	  }
5096 	}
5097 	if (getter)
5098 	  Setattr(h, "getter", getter);
5099 	if (setter)
5100 	  Setattr(h, "setter", setter);
5101 	if (h)
5102 	  Delete(h);
5103 	Delete(mname);
5104 	Delete(getname);
5105 	Delete(wrapgetname);
5106 	Delete(vargetname);
5107 	Delete(setname);
5108 	Delete(wrapsetname);
5109 	Delete(varsetname);
5110       }
5111     }
5112     return SWIG_OK;
5113   }
5114 
5115   /* ------------------------------------------------------------
5116    * memberconstantHandler()
5117    * ------------------------------------------------------------ */
5118 
memberconstantHandler(Node * n)5119   virtual int memberconstantHandler(Node *n) {
5120     String *symname = Getattr(n, "sym:name");
5121     if (builtin && in_class) {
5122       Swig_save("builtin_memberconstantHandler", n, "pybuiltin:symname", NIL);
5123       Setattr(n, "pybuiltin:symname", symname);
5124     }
5125     int oldshadow = shadow;
5126     if (shadow)
5127       shadow = shadow | PYSHADOW_MEMBER;
5128     Language::memberconstantHandler(n);
5129     shadow = oldshadow;
5130 
5131     if (builtin && in_class) {
5132       Swig_restore(n);
5133     } else if (shadow) {
5134       Printv(f_shadow, tab4, symname, " = ", module, ".", Swig_name_member(NSPACE_TODO, class_name, symname), "\n", NIL);
5135       if (have_docstring(n))
5136 	Printv(f_shadow, tab4, docstring(n, AUTODOC_CONST, tab4), "\n", NIL);
5137     }
5138     return SWIG_OK;
5139   }
5140 
5141   /* ------------------------------------------------------------
5142    * insertDirective()
5143    *
5144    * Hook for %insert directive.   We're going to look for special %shadow inserts
5145    * as a special case so we can do indenting correctly
5146    * ------------------------------------------------------------ */
5147 
insertDirective(Node * n)5148   virtual int insertDirective(Node *n) {
5149     String *code = Getattr(n, "code");
5150     String *section = Getattr(n, "section");
5151 
5152     if (!ImportMode && (Cmp(section, "python") == 0 || Cmp(section, "shadow") == 0)) {
5153       if (shadow) {
5154 	String *pycode = indent_pythoncode(code, shadow_indent, Getfile(n), Getline(n), "%pythoncode or %insert(\"python\") block");
5155 	Printv(f_shadow, pycode, NIL);
5156 	Delete(pycode);
5157       }
5158     } else if (!ImportMode && (Cmp(section, "pythonbegin") == 0)) {
5159       if (shadow) {
5160 	String *pycode = indent_pythoncode(code, "", Getfile(n), Getline(n), "%pythonbegin or %insert(\"pythonbegin\") block");
5161 	Printv(f_shadow_begin, pycode, NIL);
5162 	Delete(pycode);
5163       }
5164     } else {
5165       Language::insertDirective(n);
5166     }
5167     return SWIG_OK;
5168   }
5169 
runtimeCode()5170   virtual String *runtimeCode() {
5171     String *s = NewString("");
5172     String *shead = Swig_include_sys("pyhead.swg");
5173     if (!shead) {
5174       Printf(stderr, "*** Unable to open 'pyhead.swg'\n");
5175     } else {
5176       Append(s, shead);
5177       Delete(shead);
5178     }
5179     String *serrors = Swig_include_sys("pyerrors.swg");
5180     if (!serrors) {
5181       Printf(stderr, "*** Unable to open 'pyerrors.swg'\n");
5182     } else {
5183       Append(s, serrors);
5184       Delete(serrors);
5185     }
5186     String *sthread = Swig_include_sys("pythreads.swg");
5187     if (!sthread) {
5188       Printf(stderr, "*** Unable to open 'pythreads.swg'\n");
5189     } else {
5190       Append(s, sthread);
5191       Delete(sthread);
5192     }
5193     String *sapi = Swig_include_sys("pyapi.swg");
5194     if (!sapi) {
5195       Printf(stderr, "*** Unable to open 'pyapi.swg'\n");
5196     } else {
5197       Append(s, sapi);
5198       Delete(sapi);
5199     }
5200     String *srun = Swig_include_sys("pyrun.swg");
5201     if (!srun) {
5202       Printf(stderr, "*** Unable to open 'pyrun.swg'\n");
5203     } else {
5204       Append(s, srun);
5205       Delete(srun);
5206     }
5207     return s;
5208   }
5209 
defaultExternalRuntimeFilename()5210   virtual String *defaultExternalRuntimeFilename() {
5211     return NewString("swigpyrun.h");
5212   }
5213 
5214   /*----------------------------------------------------------------------
5215    * kwargsSupport()
5216    *--------------------------------------------------------------------*/
5217 
kwargsSupport() const5218   bool kwargsSupport() const {
5219     return true;
5220   }
5221 };
5222 
5223 /* ---------------------------------------------------------------
5224  * classDirectorMethod()
5225  *
5226  * Emit a virtual director method to pass a method call on to the
5227  * underlying Python object.
5228  *
5229  * ** Moved it here due to internal error on gcc-2.96 **
5230  * --------------------------------------------------------------- */
classDirectorMethods(Node * n)5231 int PYTHON::classDirectorMethods(Node *n) {
5232   director_method_index = 0;
5233   return Language::classDirectorMethods(n);
5234 }
5235 
5236 
classDirectorMethod(Node * n,Node * parent,String * super)5237 int PYTHON::classDirectorMethod(Node *n, Node *parent, String *super) {
5238   int is_void = 0;
5239   int is_pointer = 0;
5240   String *decl = Getattr(n, "decl");
5241   String *name = Getattr(n, "name");
5242   String *classname = Getattr(parent, "sym:name");
5243   String *c_classname = Getattr(parent, "name");
5244   String *symname = Getattr(n, "sym:name");
5245   String *declaration = NewString("");
5246   ParmList *l = Getattr(n, "parms");
5247   Wrapper *w = NewWrapper();
5248   String *tm;
5249   String *wrap_args = NewString("");
5250   String *returntype = Getattr(n, "type");
5251   String *value = Getattr(n, "value");
5252   String *storage = Getattr(n, "storage");
5253   bool pure_virtual = false;
5254   int status = SWIG_OK;
5255   int idx;
5256   bool ignored_method = GetFlag(n, "feature:ignore") ? true : false;
5257 
5258   if (builtin) {
5259     // Rename any wrapped parameters called 'self' as the generated code contains a variable with same name
5260     Parm *p;
5261     for (p = l; p; p = nextSibling(p)) {
5262       String *arg = Getattr(p, "name");
5263       if (arg && Cmp(arg, "self") == 0)
5264 	Delattr(p, "name");
5265     }
5266   }
5267 
5268   if (Cmp(storage, "virtual") == 0) {
5269     if (Cmp(value, "0") == 0) {
5270       pure_virtual = true;
5271     }
5272   }
5273 
5274   /* determine if the method returns a pointer */
5275   is_pointer = SwigType_ispointer_return(decl);
5276   is_void = (!Cmp(returntype, "void") && !is_pointer);
5277 
5278   /* virtual method definition */
5279   String *target;
5280   String *pclassname = NewStringf("SwigDirector_%s", classname);
5281   String *qualified_name = NewStringf("%s::%s", pclassname, name);
5282   SwigType *rtype = Getattr(n, "conversion_operator") ? 0 : Getattr(n, "classDirectorMethods:type");
5283   target = Swig_method_decl(rtype, decl, qualified_name, l, 0);
5284   Printf(w->def, "%s", target);
5285   Delete(qualified_name);
5286   Delete(target);
5287   /* header declaration */
5288   target = Swig_method_decl(rtype, decl, name, l, 1);
5289   Printf(declaration, "    virtual %s", target);
5290   Delete(target);
5291 
5292   // Get any exception classes in the throws typemap
5293   if (Getattr(n, "noexcept")) {
5294     Append(w->def, " noexcept");
5295     Append(declaration, " noexcept");
5296   }
5297   ParmList *throw_parm_list = 0;
5298   if ((throw_parm_list = Getattr(n, "throws")) || Getattr(n, "throw")) {
5299     Parm *p;
5300     int gencomma = 0;
5301 
5302     Append(w->def, " throw(");
5303     Append(declaration, " throw(");
5304 
5305     if (throw_parm_list)
5306       Swig_typemap_attach_parms("throws", throw_parm_list, 0);
5307     for (p = throw_parm_list; p; p = nextSibling(p)) {
5308       if (Getattr(p, "tmap:throws")) {
5309 	if (gencomma++) {
5310 	  Append(w->def, ", ");
5311 	  Append(declaration, ", ");
5312 	}
5313 	String *str = SwigType_str(Getattr(p, "type"), 0);
5314 	Append(w->def, str);
5315 	Append(declaration, str);
5316 	Delete(str);
5317       }
5318     }
5319 
5320     Append(w->def, ")");
5321     Append(declaration, ")");
5322   }
5323 
5324   Append(w->def, " {");
5325   Append(declaration, ";\n");
5326 
5327   /* declare method return value
5328    * if the return value is a reference or const reference, a specialized typemap must
5329    * handle it, including declaration of c_result ($result).
5330    */
5331   if (!is_void && (!ignored_method || pure_virtual)) {
5332     if (!SwigType_isclass(returntype)) {
5333       if (!(SwigType_ispointer(returntype) || SwigType_isreference(returntype))) {
5334 	String *construct_result = NewStringf("= SwigValueInit< %s >()", SwigType_lstr(returntype, 0));
5335 	Wrapper_add_localv(w, "c_result", SwigType_lstr(returntype, "c_result"), construct_result, NIL);
5336 	Delete(construct_result);
5337       } else {
5338 	Wrapper_add_localv(w, "c_result", SwigType_lstr(returntype, "c_result"), "= 0", NIL);
5339       }
5340     } else {
5341       String *cres = SwigType_lstr(returntype, "c_result");
5342       Printf(w->code, "%s;\n", cres);
5343       Delete(cres);
5344     }
5345   }
5346 
5347   if (builtin) {
5348     Printv(w->code, "PyObject *self = NULL;\n", NIL);
5349     Printv(w->code, "(void)self;\n", NIL);
5350   }
5351 
5352   if (ignored_method) {
5353     if (!pure_virtual) {
5354       if (!is_void)
5355 	Printf(w->code, "return ");
5356       String *super_call = Swig_method_call(super, l);
5357       Printf(w->code, "%s;\n", super_call);
5358       Delete(super_call);
5359     } else {
5360       Printf(w->code, "Swig::DirectorPureVirtualException::raise(\"Attempted to invoke pure virtual method %s::%s\");\n", SwigType_namestr(c_classname),
5361 	     SwigType_namestr(name));
5362     }
5363   } else {
5364     /* attach typemaps to arguments (C/C++ -> Python) */
5365     String *arglist = NewString("");
5366     String *parse_args = NewString("");
5367 
5368     Swig_director_parms_fixup(l);
5369 
5370     /* remove the wrapper 'w' since it was producing spurious temps */
5371     Swig_typemap_attach_parms("in", l, 0);
5372     Swig_typemap_attach_parms("directorin", l, w);
5373     Swig_typemap_attach_parms("directorargout", l, w);
5374 
5375     Parm *p;
5376     char source[256];
5377 
5378     int outputs = 0;
5379     if (!is_void)
5380       outputs++;
5381 
5382     /* build argument list and type conversion string */
5383     idx = 0;
5384     p = l;
5385     int use_parse = 0;
5386     while (p) {
5387       if (checkAttribute(p, "tmap:in:numinputs", "0")) {
5388 	p = Getattr(p, "tmap:in:next");
5389 	continue;
5390       }
5391 
5392       /* old style?  caused segfaults without the p!=0 check
5393          in the for() condition, and seems dangerous in the
5394          while loop as well.
5395          while (Getattr(p, "tmap:ignore")) {
5396          p = Getattr(p, "tmap:ignore:next");
5397          }
5398        */
5399 
5400       if (Getattr(p, "tmap:directorargout") != 0)
5401 	outputs++;
5402 
5403       String *pname = Getattr(p, "name");
5404       String *ptype = Getattr(p, "type");
5405 
5406       Putc(',', arglist);
5407       if ((tm = Getattr(p, "tmap:directorin")) != 0) {
5408 	String *parse = Getattr(p, "tmap:directorin:parse");
5409 	if (!parse) {
5410 	  sprintf(source, "obj%d", idx++);
5411 	  String *input = NewString(source);
5412 	  Setattr(p, "emit:directorinput", input);
5413 	  Replaceall(tm, "$input", input);
5414 	  Delete(input);
5415 	  Replaceall(tm, "$owner", "0");
5416 	  /* Wrapper_add_localv(w, source, "swig::SwigVar_PyObject", source, "= 0", NIL); */
5417 	  Printv(wrap_args, "swig::SwigVar_PyObject ", source, ";\n", NIL);
5418 
5419 	  Printv(wrap_args, tm, "\n", NIL);
5420 	  Printv(arglist, "(PyObject *)", source, NIL);
5421 	  Putc('O', parse_args);
5422 	} else {
5423 	  use_parse = 1;
5424 	  Append(parse_args, parse);
5425 	  Setattr(p, "emit:directorinput", pname);
5426 	  Replaceall(tm, "$input", pname);
5427 	  Replaceall(tm, "$owner", "0");
5428 	  if (Len(tm) == 0)
5429 	    Append(tm, pname);
5430 	  Append(arglist, tm);
5431 	}
5432 	p = Getattr(p, "tmap:directorin:next");
5433 	continue;
5434       } else if (Cmp(ptype, "void")) {
5435 	/* special handling for pointers to other C++ director classes.
5436 	 * ideally this would be left to a typemap, but there is currently no
5437 	 * way to selectively apply the dynamic_cast<> to classes that have
5438 	 * directors.  in other words, the type "SwigDirector_$1_lname" only exists
5439 	 * for classes with directors.  we avoid the problem here by checking
5440 	 * module.wrap::directormap, but it's not clear how to get a typemap to
5441 	 * do something similar.  perhaps a new default typemap (in addition
5442 	 * to SWIGTYPE) called DIRECTORTYPE?
5443 	 */
5444 	if (SwigType_ispointer(ptype) || SwigType_isreference(ptype)) {
5445 	  Node *module = Getattr(parent, "module");
5446 	  Node *target = Swig_directormap(module, ptype);
5447 	  sprintf(source, "obj%d", idx++);
5448 	  String *nonconst = 0;
5449 	  /* strip pointer/reference --- should move to Swig/stype.c */
5450 	  String *nptype = NewString(Char(ptype) + 2);
5451 	  /* name as pointer */
5452 	  String *ppname = Copy(pname);
5453 	  if (SwigType_isreference(ptype)) {
5454 	    Insert(ppname, 0, "&");
5455 	  }
5456 	  /* if necessary, cast away const since Python doesn't support it! */
5457 	  if (SwigType_isconst(nptype)) {
5458 	    nonconst = NewStringf("nc_tmp_%s", pname);
5459 	    String *nonconst_i = NewStringf("= const_cast< %s >(%s)", SwigType_lstr(ptype, 0), ppname);
5460 	    Wrapper_add_localv(w, nonconst, SwigType_lstr(ptype, 0), nonconst, nonconst_i, NIL);
5461 	    Delete(nonconst_i);
5462 	    Swig_warning(WARN_LANG_DISCARD_CONST, input_file, line_number,
5463 			 "Target language argument '%s' discards const in director method %s::%s.\n",
5464 			 SwigType_str(ptype, pname), SwigType_namestr(c_classname), SwigType_namestr(name));
5465 	  } else {
5466 	    nonconst = Copy(ppname);
5467 	  }
5468 	  Delete(nptype);
5469 	  Delete(ppname);
5470 	  String *mangle = SwigType_manglestr(ptype);
5471 	  if (target) {
5472 	    String *director = NewStringf("director_%s", mangle);
5473 	    Wrapper_add_localv(w, director, "Swig::Director *", director, "= 0", NIL);
5474 	    Wrapper_add_localv(w, source, "swig::SwigVar_PyObject", source, "= 0", NIL);
5475 	    Printf(wrap_args, "%s = SWIG_DIRECTOR_CAST(%s);\n", director, nonconst);
5476 	    Printf(wrap_args, "if (!%s) {\n", director);
5477 	    Printf(wrap_args, "%s = SWIG_InternalNewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle);
5478 	    Append(wrap_args, "} else {\n");
5479 	    Printf(wrap_args, "%s = %s->swig_get_self();\n", source, director);
5480 	    Printf(wrap_args, "Py_INCREF((PyObject *)%s);\n", source);
5481 	    Append(wrap_args, "}\n");
5482 	    Delete(director);
5483 	    Printv(arglist, source, NIL);
5484 	  } else {
5485 	    Wrapper_add_localv(w, source, "swig::SwigVar_PyObject", source, "= 0", NIL);
5486 	    Printf(wrap_args, "%s = SWIG_InternalNewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle);
5487 	    //Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE_p_%s, 0);\n",
5488 	    //       source, nonconst, base);
5489 	    Printv(arglist, source, NIL);
5490 	  }
5491 	  Putc('O', parse_args);
5492 	  Delete(mangle);
5493 	  Delete(nonconst);
5494 	} else {
5495 	  Swig_warning(WARN_TYPEMAP_DIRECTORIN_UNDEF, input_file, line_number,
5496 		       "Unable to use type %s as a function argument in director method %s::%s (skipping method).\n", SwigType_str(ptype, 0),
5497 		       SwigType_namestr(c_classname), SwigType_namestr(name));
5498 	  status = SWIG_NOWRAP;
5499 	  break;
5500 	}
5501       }
5502       p = nextSibling(p);
5503     }
5504 
5505     /* add the method name as a PyString */
5506     String *pyname = Getattr(n, "sym:name");
5507 
5508     int allow_thread = threads_enable(n);
5509 
5510     if (allow_thread) {
5511       thread_begin_block(n, w->code);
5512       Append(w->code, "{\n");
5513     }
5514 
5515     /* wrap complex arguments to PyObjects */
5516     Printv(w->code, wrap_args, NIL);
5517 
5518     /* pass the method call on to the Python object */
5519     if (dirprot_mode() && !is_public(n)) {
5520       Printf(w->code, "swig_set_inner(\"%s\", true);\n", name);
5521     }
5522 
5523 
5524     Append(w->code, "if (!swig_get_self()) {\n");
5525     Printf(w->code, "  Swig::DirectorException::raise(\"'self' uninitialized, maybe you forgot to call %s.__init__.\");\n", classname);
5526     Append(w->code, "}\n");
5527     Append(w->code, "#if defined(SWIG_PYTHON_DIRECTOR_VTABLE)\n");
5528     Printf(w->code, "const size_t swig_method_index = %d;\n", director_method_index++);
5529     Printf(w->code, "const char *const swig_method_name = \"%s\";\n", pyname);
5530 
5531     Append(w->code, "PyObject *method = swig_get_method(swig_method_index, swig_method_name);\n");
5532     if (Len(parse_args) > 0) {
5533       if (use_parse) {
5534 	Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_CallFunction(method, (char *)\"(%s)\" %s);\n", Swig_cresult_name(), parse_args, arglist);
5535       } else {
5536 	Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_CallFunctionObjArgs(method %s, NULL);\n", Swig_cresult_name(), arglist);
5537       }
5538     } else {
5539       Append(w->code, "swig::SwigVar_PyObject args = PyTuple_New(0);\n");
5540       Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_Call(method, (PyObject *) args, NULL);\n", Swig_cresult_name());
5541     }
5542     Append(w->code, "#else\n");
5543     if (Len(parse_args) > 0) {
5544       if (use_parse) {
5545 	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);
5546       } else {
5547 	Printf(w->code, "swig::SwigVar_PyObject swig_method_name = SWIG_Python_str_FromChar(\"%s\");\n", pyname);
5548 	Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_CallMethodObjArgs(swig_get_self(), (PyObject *) swig_method_name %s, NULL);\n", Swig_cresult_name(), arglist);
5549       }
5550     } else {
5551       Printf(w->code, "swig::SwigVar_PyObject swig_method_name = SWIG_Python_str_FromChar(\"%s\");\n", pyname);
5552       Printf(w->code, "swig::SwigVar_PyObject %s = PyObject_CallMethodObjArgs(swig_get_self(), (PyObject *) swig_method_name, NULL);\n", Swig_cresult_name());
5553     }
5554     Append(w->code, "#endif\n");
5555 
5556     if (dirprot_mode() && !is_public(n))
5557       Printf(w->code, "swig_set_inner(\"%s\", false);\n", name);
5558 
5559     /* exception handling */
5560     tm = Swig_typemap_lookup("director:except", n, Swig_cresult_name(), 0);
5561     if (!tm) {
5562       tm = Getattr(n, "feature:director:except");
5563       if (tm)
5564 	tm = Copy(tm);
5565     }
5566     Printf(w->code, "if (!%s) {\n", Swig_cresult_name());
5567     Append(w->code, "  PyObject *error = PyErr_Occurred();\n");
5568     if ((tm) && Len(tm) && (Strcmp(tm, "1") != 0)) {
5569       Replaceall(tm, "$error", "error");
5570       Printv(w->code, Str(tm), "\n", NIL);
5571     } else {
5572       Append(w->code, "  if (error) {\n");
5573       Printf(w->code, "    Swig::DirectorMethodException::raise(\"Error detected when calling '%s.%s'\");\n", classname, pyname);
5574       Append(w->code, "  }\n");
5575     }
5576     Append(w->code, "}\n");
5577     Delete(tm);
5578 
5579     /*
5580      * Python method may return a simple object, or a tuple.
5581      * for in/out arguments, we have to extract the appropriate PyObjects from the tuple,
5582      * then marshal everything back to C/C++ (return value and output arguments).
5583      *
5584      */
5585 
5586     /* marshal return value and other outputs (if any) from PyObject to C/C++ type */
5587 
5588     String *cleanup = NewString("");
5589     String *outarg = NewString("");
5590 
5591     if (outputs > 1) {
5592       Wrapper_add_local(w, "output", "PyObject *output");
5593       Printf(w->code, "if (!PyTuple_Check(%s)) {\n", Swig_cresult_name());
5594       Printf(w->code, "  Swig::DirectorTypeMismatchException::raise(\"Python method %s.%sfailed to return a tuple.\");\n", classname, pyname);
5595       Append(w->code, "}\n");
5596     }
5597 
5598     idx = 0;
5599 
5600     /* marshal return value */
5601     if (!is_void) {
5602       tm = Swig_typemap_lookup("directorout", n, Swig_cresult_name(), w);
5603       if (tm != 0) {
5604 	if (outputs > 1) {
5605 	  Printf(w->code, "output = PyTuple_GetItem(%s, %d);\n", Swig_cresult_name(), idx++);
5606 	  Replaceall(tm, "$input", "output");
5607 	} else {
5608 	  Replaceall(tm, "$input", Swig_cresult_name());
5609 	}
5610 	char temp[24];
5611 	sprintf(temp, "%d", idx);
5612 	Replaceall(tm, "$argnum", temp);
5613 
5614 	/* TODO check this */
5615 	if (Getattr(n, "wrap:disown")) {
5616 	  Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN");
5617 	} else {
5618 	  Replaceall(tm, "$disown", "0");
5619 	}
5620 	if (Getattr(n, "tmap:directorout:implicitconv")) {
5621 	  Replaceall(tm, "$implicitconv", get_implicitconv_flag(n));
5622 	}
5623 	Replaceall(tm, "$result", "c_result");
5624 	Printv(w->code, tm, "\n", NIL);
5625 	Delete(tm);
5626       } else {
5627 	Swig_warning(WARN_TYPEMAP_DIRECTOROUT_UNDEF, input_file, line_number,
5628 		     "Unable to use return type %s in director method %s::%s (skipping method).\n", SwigType_str(returntype, 0), SwigType_namestr(c_classname),
5629 		     SwigType_namestr(name));
5630 	status = SWIG_ERROR;
5631       }
5632     }
5633 
5634     /* marshal outputs */
5635     for (p = l; p;) {
5636       if ((tm = Getattr(p, "tmap:directorargout")) != 0) {
5637 	if (outputs > 1) {
5638 	  Printf(w->code, "output = PyTuple_GetItem(%s, %d);\n", Swig_cresult_name(), idx++);
5639 	  Replaceall(tm, "$result", "output");
5640 	} else {
5641 	  Replaceall(tm, "$result", Swig_cresult_name());
5642 	}
5643 	Replaceall(tm, "$input", Getattr(p, "emit:directorinput"));
5644 	Printv(w->code, tm, "\n", NIL);
5645 	p = Getattr(p, "tmap:directorargout:next");
5646       } else {
5647 	p = nextSibling(p);
5648       }
5649     }
5650 
5651     /* any existing helper functions to handle this? */
5652     if (allow_thread) {
5653       Append(w->code, "}\n");
5654       thread_end_block(n, w->code);
5655     }
5656 
5657     Delete(parse_args);
5658     Delete(arglist);
5659     Delete(cleanup);
5660     Delete(outarg);
5661   }
5662 
5663   if (!is_void) {
5664     if (!(ignored_method && !pure_virtual)) {
5665       String *rettype = SwigType_str(returntype, 0);
5666       if (!SwigType_isreference(returntype)) {
5667 	Printf(w->code, "return (%s) c_result;\n", rettype);
5668       } else {
5669 	Printf(w->code, "return (%s) *c_result;\n", rettype);
5670       }
5671       Delete(rettype);
5672     }
5673   }
5674 
5675   Append(w->code, "}\n");
5676 
5677   // We expose protected methods via an extra public inline method which makes a straight call to the wrapped class' method
5678   String *inline_extra_method = NewString("");
5679   if (dirprot_mode() && !is_public(n) && !pure_virtual) {
5680     Printv(inline_extra_method, declaration, NIL);
5681     String *extra_method_name = NewStringf("%sSwigPublic", name);
5682     Replaceall(inline_extra_method, name, extra_method_name);
5683     Replaceall(inline_extra_method, ";\n", " {\n      ");
5684     if (!is_void)
5685       Printf(inline_extra_method, "return ");
5686     String *methodcall = Swig_method_call(super, l);
5687     Printv(inline_extra_method, methodcall, ";\n    }\n", NIL);
5688     Delete(methodcall);
5689     Delete(extra_method_name);
5690   }
5691 
5692   /* emit the director method */
5693   if (status == SWIG_OK) {
5694     if (!Getattr(n, "defaultargs")) {
5695       Replaceall(w->code, "$symname", symname);
5696       Wrapper_print(w, f_directors);
5697       Printv(f_directors_h, declaration, NIL);
5698       Printv(f_directors_h, inline_extra_method, NIL);
5699     }
5700   }
5701 
5702   /* clean up */
5703   Delete(wrap_args);
5704   Delete(pclassname);
5705   DelWrapper(w);
5706   return status;
5707 }
5708 
5709 /* -----------------------------------------------------------------------------
5710  * swig_python()    - Instantiate module
5711  * ----------------------------------------------------------------------------- */
5712 
new_swig_python()5713 static Language *new_swig_python() {
5714   return new PYTHON();
5715 }
swig_python(void)5716 extern "C" Language *swig_python(void) {
5717   return new_swig_python();
5718 }
5719