PageRenderTime 139ms CodeModel.GetById 33ms app.highlight 92ms RepoModel.GetById 2ms app.codeStats 0ms

/trunk/Source/Modules/python.cxx

#
C++ | 1956 lines | 1621 code | 166 blank | 169 comment | 380 complexity | 115ecb1a1c01caaf3a190e19b5fad57d MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   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
  14char cvsroot_python_cxx[] = "$Id: python.cxx 12877 2011-12-20 20:50:36Z wsfulton $";
  15
  16#include "swigmod.h"
  17#include "cparse.h"
  18
  19static int treduce = SWIG_cparse_template_reduce(0);
  20
  21#include <ctype.h>
  22
  23#define PYSHADOW_MEMBER  0x2
  24#define WARN_PYTHON_MULTIPLE_INH 405
  25
  26static String *const_code = 0;
  27static String *module = 0;
  28static String *package = 0;
  29static String *mainmodule = 0;
  30static String *interface = 0;
  31static String *global_name = 0;
  32static int shadow = 1;
  33static int use_kw = 0;
  34static int director_method_index = 0;
  35static int builtin = 0;
  36
  37static File *f_begin = 0;
  38static File *f_runtime = 0;
  39static File *f_runtime_h = 0;
  40static File *f_header = 0;
  41static File *f_wrappers = 0;
  42static File *f_directors = 0;
  43static File *f_directors_h = 0;
  44static File *f_init = 0;
  45static File *f_shadow_py = 0;
  46static String *f_shadow = 0;
  47static Hash *f_shadow_imports = 0;
  48static String *f_shadow_builtin_imports = 0;
  49static String *f_shadow_stubs = 0;
  50static Hash *builtin_getset = 0;
  51static Hash *class_members = 0;
  52static File *f_builtins = 0;
  53static String *builtin_tp_init = 0;
  54static String *builtin_methods = 0;
  55static String *builtin_default_unref = 0;
  56
  57static String *methods;
  58static String *class_name;
  59static String *shadow_indent = 0;
  60static int in_class = 0;
  61static int classic = 0;
  62static int modern = 0;
  63static int new_repr = 1;
  64static int no_header_file = 0;
  65static int max_bases = 0;
  66static int builtin_bases_needed = 0;
  67
  68static int py3 = 0;
  69
  70/* C++ Support + Shadow Classes */
  71
  72static int have_constructor;
  73static int have_repr;
  74static String *real_classname;
  75
  76/* Thread Support */
  77static int threads = 0;
  78static int nothreads = 0;
  79static int classptr = 0;
  80/* Other options */
  81static int shadowimport = 1;
  82static int buildnone = 0;
  83static int nobuildnone = 0;
  84static int safecstrings = 0;
  85static int dirvtable = 0;
  86static int proxydel = 1;
  87static int fastunpack = 0;
  88static int fastproxy = 0;
  89static int fastquery = 0;
  90static int fastinit = 0;
  91static int olddefs = 0;
  92static int modernargs = 0;
  93static int aliasobj0 = 0;
  94static int castmode = 0;
  95static int extranative = 0;
  96static int outputtuple = 0;
  97static int nortti = 0;
  98
  99/* flags for the make_autodoc function */
 100enum autodoc_t {
 101  AUTODOC_CLASS,
 102  AUTODOC_CTOR,
 103  AUTODOC_DTOR,
 104  AUTODOC_STATICFUNC,
 105  AUTODOC_FUNC,
 106  AUTODOC_METHOD
 107};
 108
 109
 110static const char *usage1 = (char *) "\
 111Python Options (available with -python)\n\
 112     -aliasobj0      - Alias obj0 when using fastunpack, needed for some old typemaps \n\
 113     -buildnone      - Use Py_BuildValue(" ") to obtain Py_None (default in Windows)\n\
 114     -builtin        - Create new python built-in types, rather than proxy classes, for better performance\n\
 115     -castmode       - Enable the casting mode, which allows implicit cast between types in python\n\
 116     -classic        - Use classic classes only\n\
 117     -classptr       - Generate shadow 'ClassPtr' as in older swig versions\n\
 118     -cppcast        - Enable C++ casting operators (default) \n\
 119     -dirvtable      - Generate a pseudo virtual table for directors for faster dispatch \n\
 120     -extranative    - Return extra native C++ wraps for std containers when possible \n\
 121     -fastinit       - Use fast init mechanism for classes (default)\n\
 122     -fastunpack     - Use fast unpack mechanism to parse the argument functions \n\
 123     -fastproxy      - Use fast proxy mechanism for member methods \n\
 124     -fastquery      - Use fast query mechanism for types \n\
 125     -globals <name> - Set <name> used to access C global variable [default: 'cvar']\n\
 126     -interface <lib>- Set the lib name to <lib>\n\
 127     -keyword        - Use keyword arguments\n\
 128     -modern         - Use modern python features only, without compatibility code\n\
 129     -modernargs     - Use \"modern\" args mechanism to pack/unpack the function arguments\n";
 130static const char *usage2 = (char *) "\
 131     -newrepr        - Use more informative version of __repr__ in proxy classes (default) \n\
 132     -newvwm         - New value wrapper mode, use only when everything else fails \n\
 133     -noaliasobj0    - Don't generate an obj0 alias when using fastunpack (default) \n\
 134     -nobuildnone    - Access Py_None directly (default in non-Windows systems)\n\
 135     -nocastmode     - Disable the casting mode (default)\n\
 136     -nocppcast      - Disable C++ casting operators, useful for generating bugs\n\
 137     -nodirvtable    - Don't use the virtual table feature, resolve the python method each time (default)\n\
 138     -noexcept       - No automatic exception handling\n\
 139     -noextranative  - Don't use extra native C++ wraps for std containers when possible (default) \n\
 140     -nofastinit     - Use traditional init mechanism for classes \n\
 141     -nofastunpack   - Use traditional UnpackTuple method to parse the argument functions (default) \n\
 142     -nofastproxy    - Use traditional proxy mechanism for member methods (default) \n\
 143     -nofastquery    - Use traditional query mechanism for types (default) \n\
 144     -noh            - Don't generate the output header file\n\
 145     -nomodern       - Don't use modern python features which are not backwards compatible \n\
 146     -nomodernargs   - Use classic ParseTuple/CallFunction methods to pack/unpack the function arguments (default) \n";
 147static const char *usage3 = (char *) "\
 148     -noolddefs      - Don't emit the old method definitions even when using fastproxy (default) \n\
 149     -nooutputtuple  - Use a PyList for appending output values (default) \n\
 150     -noproxy        - Don't generate proxy classes \n\
 151     -noproxydel     - Don't generate the redundant __del__ method \n\
 152     -noproxyimport  - Don't insert proxy import statements derived from the %import directive \n\
 153     -nortti         - Disable the use of the native C++ RTTI with directors\n\
 154     -nosafecstrings - Avoid extra strings copies when possible (default)\n\
 155     -nothreads      - Disable thread support for the entire interface\n\
 156     -olddefs        - Keep the old method definitions even when using fastproxy\n\
 157     -oldrepr        - Use shorter and old version of __repr__ in proxy classes\n\
 158     -outputtuple    - Use a PyTuple for outputs instead of a PyList (use carefully with legacy interfaces) \n\
 159     -proxydel       - Generate a __del__ method even though it is now redundant (default) \n\
 160     -safecstrings   - Use safer (but slower) C string mapping, generating copies from Python -> C/C++\n\
 161     -threads        - Add thread support for all the interface\n\
 162     -O              - Enable the following optimization options: \n\
 163                         -modern -fastdispatch -nosafecstrings -fvirtual -noproxydel \n\
 164                         -fastproxy -fastinit -fastunpack -fastquery -modernargs -nobuildnone \n\
 165     -py3            - Generate code with Python 3 specific features:\n\
 166                         Function annotation \n\
 167\n";
 168
 169static String *getSlot(Node *n = NULL, const char *key = NULL) {
 170  static String *slot_default = NewString("0");
 171  String *val = key && *key ? Getattr(n, key) : NULL;
 172  return val ? val : slot_default;
 173}
 174
 175static void printSlot(File *f, const String *slotval, const char *slotname, const char *functype = NULL) {
 176  String *slotval_override = functype ? NewStringf("(%s) %s", functype, slotval) : 0;
 177  if (slotval_override)
 178    slotval = slotval_override;
 179  int len = Len(slotval);
 180  int fieldwidth = len > 40 ? 0 : 40 - len;
 181  Printf(f, "    %s, %*s/* %s */\n", slotval, fieldwidth, "", slotname);
 182  Delete(slotval_override);
 183}
 184
 185static String *getClosure(String *functype, String *wrapper, int funpack = 0) {
 186  static const char *functypes[] = {
 187    "unaryfunc", "SWIGPY_UNARYFUNC_CLOSURE",
 188    "destructor", "SWIGPY_DESTRUCTOR_CLOSURE",
 189    "inquiry", "SWIGPY_INQUIRY_CLOSURE",
 190    "getiterfunc", "SWIGPY_UNARYFUNC_CLOSURE",
 191    "binaryfunc", "SWIGPY_BINARYFUNC_CLOSURE",
 192    "ternaryfunc", "SWIGPY_TERNARYFUNC_CLOSURE",
 193    "ternarycallfunc", "SWIGPY_TERNARYCALLFUNC_CLOSURE",
 194    "lenfunc", "SWIGPY_LENFUNC_CLOSURE",
 195    "ssizeargfunc", "SWIGPY_SSIZEARGFUNC_CLOSURE",
 196    "ssizessizeargfunc", "SWIGPY_SSIZESSIZEARGFUNC_CLOSURE",
 197    "ssizeobjargproc", "SWIGPY_SSIZEOBJARGPROC_CLOSURE",
 198    "ssizessizeobjargproc", "SWIGPY_SSIZESSIZEOBJARGPROC_CLOSURE",
 199    "objobjargproc", "SWIGPY_OBJOBJARGPROC_CLOSURE",
 200    "reprfunc", "SWIGPY_REPRFUNC_CLOSURE",
 201    "hashfunc", "SWIGPY_HASHFUNC_CLOSURE",
 202    "iternextfunc", "SWIGPY_ITERNEXT_CLOSURE",
 203    NULL
 204  };
 205
 206  static const char *funpack_functypes[] = {
 207    "unaryfunc", "SWIGPY_UNARYFUNC_CLOSURE",
 208    "destructor", "SWIGPY_DESTRUCTOR_CLOSURE",
 209    "inquiry", "SWIGPY_INQUIRY_CLOSURE",
 210    "getiterfunc", "SWIGPY_UNARYFUNC_CLOSURE",
 211    "ternaryfunc", "SWIGPY_TERNARYFUNC_CLOSURE",
 212    "ternarycallfunc", "SWIGPY_TERNARYCALLFUNC_CLOSURE",
 213    "lenfunc", "SWIGPY_LENFUNC_CLOSURE",
 214    "ssizeargfunc", "SWIGPY_FUNPACK_SSIZEARGFUNC_CLOSURE",
 215    "ssizessizeargfunc", "SWIGPY_SSIZESSIZEARGFUNC_CLOSURE",
 216    "ssizeobjargproc", "SWIGPY_SSIZEOBJARGPROC_CLOSURE",
 217    "ssizessizeobjargproc", "SWIGPY_SSIZESSIZEOBJARGPROC_CLOSURE",
 218    "objobjargproc", "SWIGPY_OBJOBJARGPROC_CLOSURE",
 219    "reprfunc", "SWIGPY_REPRFUNC_CLOSURE",
 220    "hashfunc", "SWIGPY_HASHFUNC_CLOSURE",
 221    "iternextfunc", "SWIGPY_ITERNEXT_CLOSURE",
 222    NULL
 223  };
 224
 225  if (!functype)
 226    return NULL;
 227  char *c = Char(functype);
 228  int i;
 229  if (funpack) {
 230    for (i = 0; funpack_functypes[i] != NULL; i += 2) {
 231      if (!strcmp(c, funpack_functypes[i]))
 232	return NewStringf("%s(%s)", funpack_functypes[i + 1], wrapper);
 233    }
 234  } else {
 235    for (i = 0; functypes[i] != NULL; i += 2) {
 236      if (!strcmp(c, functypes[i]))
 237	return NewStringf("%s(%s)", functypes[i + 1], wrapper);
 238    }
 239  }
 240  return NULL;
 241}
 242
 243class PYTHON:public Language {
 244public:
 245  PYTHON() {
 246    /* Add code to manage protected constructors and directors */
 247    director_prot_ctor_code = NewString("");
 248    Printv(director_prot_ctor_code,
 249	   "if ( $comparison ) { /* subclassed */\n",
 250	   "  $director_new \n",
 251	   "} else {\n", "  SWIG_SetErrorMsg(PyExc_RuntimeError,\"accessing abstract class or protected constructor\"); \n", "  SWIG_fail;\n", "}\n", NIL);
 252    director_multiple_inheritance = 1;
 253    director_language = 1;
 254  }
 255  /* ------------------------------------------------------------
 256   * Thread Implementation
 257   * ------------------------------------------------------------ */
 258  int threads_enable(Node *n) const {
 259    return threads && !GetFlagAttr(n, "feature:nothread");
 260  }
 261
 262  int initialize_threads(String *f_init) {
 263    if (!threads) {
 264      return SWIG_OK;
 265    }
 266    Printf(f_init, "\n");
 267    Printf(f_init, "/* Initialize threading */\n");
 268    Printf(f_init, "SWIG_PYTHON_INITIALIZE_THREADS;\n");
 269
 270    return SWIG_OK;
 271  }
 272
 273  virtual void thread_begin_block(Node *n, String *f) {
 274    if (!GetFlag(n, "feature:nothreadblock")) {
 275      String *bb = Getattr(n, "feature:threadbeginblock");
 276      if (bb) {
 277	Append(f, bb);
 278      } else {
 279	Append(f, "SWIG_PYTHON_THREAD_BEGIN_BLOCK;\n");
 280      }
 281    }
 282  }
 283
 284  virtual void thread_end_block(Node *n, String *f) {
 285    if (!GetFlag(n, "feature:nothreadblock")) {
 286      String *eb = Getattr(n, "feature:threadendblock");
 287      if (eb) {
 288	Append(f, eb);
 289      } else {
 290	Append(f, "SWIG_PYTHON_THREAD_END_BLOCK;\n");
 291      }
 292    }
 293  }
 294
 295  virtual void thread_begin_allow(Node *n, String *f) {
 296    if (!GetFlag(n, "feature:nothreadallow")) {
 297      String *bb = Getattr(n, "feature:threadbeginallow");
 298      Append(f, "{\n");
 299      if (bb) {
 300	Append(f, bb);
 301      } else {
 302	Append(f, "SWIG_PYTHON_THREAD_BEGIN_ALLOW;\n");
 303      }
 304    }
 305  }
 306
 307  virtual void thread_end_allow(Node *n, String *f) {
 308    if (!GetFlag(n, "feature:nothreadallow")) {
 309      String *eb = Getattr(n, "feature:threadendallow");
 310      Append(f, "\n");
 311      if (eb) {
 312	Append(f, eb);
 313      } else {
 314	Append(f, "SWIG_PYTHON_THREAD_END_ALLOW;");
 315      }
 316      Append(f, "\n}");
 317    }
 318  }
 319
 320
 321  /* ------------------------------------------------------------
 322   * main()
 323   * ------------------------------------------------------------ */
 324
 325  virtual void main(int argc, char *argv[]) {
 326    int cppcast = 1;
 327
 328    SWIG_library_directory("python");
 329
 330    for (int i = 1; i < argc; i++) {
 331      if (argv[i]) {
 332	if (strcmp(argv[i], "-interface") == 0) {
 333	  if (argv[i + 1]) {
 334	    interface = NewString(argv[i + 1]);
 335	    Swig_mark_arg(i);
 336	    Swig_mark_arg(i + 1);
 337	    i++;
 338	  } else {
 339	    Swig_arg_error();
 340	  }
 341	  /* end added */
 342	} else if (strcmp(argv[i], "-globals") == 0) {
 343	  if (argv[i + 1]) {
 344	    global_name = NewString(argv[i + 1]);
 345	    Swig_mark_arg(i);
 346	    Swig_mark_arg(i + 1);
 347	    i++;
 348	  } else {
 349	    Swig_arg_error();
 350	  }
 351	} else if ((strcmp(argv[i], "-shadow") == 0) || ((strcmp(argv[i], "-proxy") == 0))) {
 352	  shadow = 1;
 353	  Swig_mark_arg(i);
 354	} else if ((strcmp(argv[i], "-new_repr") == 0) || (strcmp(argv[i], "-newrepr") == 0)) {
 355	  new_repr = 1;
 356	  Swig_mark_arg(i);
 357	} else if ((strcmp(argv[i], "-old_repr") == 0) || (strcmp(argv[i], "-oldrepr") == 0)) {
 358	  new_repr = 0;
 359	  Swig_mark_arg(i);
 360	} else if (strcmp(argv[i], "-classptr") == 0) {
 361	  classptr = 1;
 362	  Swig_mark_arg(i);
 363	} else if ((strcmp(argv[i], "-noproxy") == 0)) {
 364	  shadow = 0;
 365	  Swig_mark_arg(i);
 366	} else if ((strcmp(argv[i], "-noproxyimport") == 0)) {
 367	  shadowimport = 0;
 368	  Swig_mark_arg(i);
 369	} else if (strcmp(argv[i], "-keyword") == 0) {
 370	  use_kw = 1;
 371	  SWIG_cparse_set_compact_default_args(1);
 372	  Swig_mark_arg(i);
 373	} else if (strcmp(argv[i], "-classic") == 0) {
 374	  classic = 1;
 375	  modernargs = 0;
 376	  modern = 0;
 377	  Swig_mark_arg(i);
 378	} else if (strcmp(argv[i], "-cppcast") == 0) {
 379	  cppcast = 1;
 380	  Swig_mark_arg(i);
 381	} else if (strcmp(argv[i], "-nocppcast") == 0) {
 382	  cppcast = 0;
 383	  Swig_mark_arg(i);
 384	} else if (strcmp(argv[i], "-outputtuple") == 0) {
 385	  outputtuple = 1;
 386	  Swig_mark_arg(i);
 387	} else if (strcmp(argv[i], "-nooutputtuple") == 0) {
 388	  outputtuple = 0;
 389	  Swig_mark_arg(i);
 390	} else if (strcmp(argv[i], "-nortti") == 0) {
 391	  nortti = 1;
 392	  Swig_mark_arg(i);
 393	} else if (strcmp(argv[i], "-threads") == 0) {
 394	  threads = 1;
 395	  Swig_mark_arg(i);
 396	} else if (strcmp(argv[i], "-nothreads") == 0) {
 397	  /* Turn off thread suppor mode */
 398	  nothreads = 1;
 399	  Swig_mark_arg(i);
 400	} else if (strcmp(argv[i], "-safecstrings") == 0) {
 401	  safecstrings = 1;
 402	  Swig_mark_arg(i);
 403	} else if (strcmp(argv[i], "-nosafecstrings") == 0) {
 404	  safecstrings = 0;
 405	  Swig_mark_arg(i);
 406	} else if (strcmp(argv[i], "-buildnone") == 0) {
 407	  buildnone = 1;
 408	  nobuildnone = 0;
 409	  Swig_mark_arg(i);
 410	} else if (strcmp(argv[i], "-nobuildnone") == 0) {
 411	  buildnone = 0;
 412	  nobuildnone = 1;
 413	  Swig_mark_arg(i);
 414	} else if (strcmp(argv[i], "-dirvtable") == 0) {
 415	  dirvtable = 1;
 416	  Swig_mark_arg(i);
 417	} else if (strcmp(argv[i], "-nodirvtable") == 0) {
 418	  dirvtable = 0;
 419	  Swig_mark_arg(i);
 420	} else if (strcmp(argv[i], "-fastunpack") == 0) {
 421	  fastunpack = 1;
 422	  Swig_mark_arg(i);
 423	} else if (strcmp(argv[i], "-nofastunpack") == 0) {
 424	  fastunpack = 0;
 425	  Swig_mark_arg(i);
 426	} else if (strcmp(argv[i], "-fastproxy") == 0) {
 427	  fastproxy = 1;
 428	  Swig_mark_arg(i);
 429	} else if (strcmp(argv[i], "-nofastproxy") == 0) {
 430	  fastproxy = 0;
 431	  Swig_mark_arg(i);
 432	} else if (strcmp(argv[i], "-fastquery") == 0) {
 433	  fastquery = 1;
 434	  Swig_mark_arg(i);
 435	} else if (strcmp(argv[i], "-nofastquery") == 0) {
 436	  fastquery = 0;
 437	  Swig_mark_arg(i);
 438	} else if (strcmp(argv[i], "-fastinit") == 0) {
 439	  fastinit = 1;
 440	  Swig_mark_arg(i);
 441	} else if (strcmp(argv[i], "-nofastinit") == 0) {
 442	  fastinit = 0;
 443	  Swig_mark_arg(i);
 444	} else if (strcmp(argv[i], "-olddefs") == 0) {
 445	  olddefs = 1;
 446	  Swig_mark_arg(i);
 447	} else if (strcmp(argv[i], "-noolddefs") == 0) {
 448	  olddefs = 0;
 449	  Swig_mark_arg(i);
 450	} else if (strcmp(argv[i], "-castmode") == 0) {
 451	  castmode = 1;
 452	  Swig_mark_arg(i);
 453	} else if (strcmp(argv[i], "-nocastmode") == 0) {
 454	  castmode = 0;
 455	  Swig_mark_arg(i);
 456	} else if (strcmp(argv[i], "-extranative") == 0) {
 457	  extranative = 1;
 458	  Swig_mark_arg(i);
 459	} else if (strcmp(argv[i], "-noextranative") == 0) {
 460	  extranative = 0;
 461	  Swig_mark_arg(i);
 462	} else if (strcmp(argv[i], "-modernargs") == 0) {
 463	  modernargs = 1;
 464	  Swig_mark_arg(i);
 465	} else if (strcmp(argv[i], "-nomodernargs") == 0) {
 466	  modernargs = 0;
 467	  Swig_mark_arg(i);
 468	} else if (strcmp(argv[i], "-aliasobj0") == 0) {
 469	  aliasobj0 = 1;
 470	  Swig_mark_arg(i);
 471	} else if (strcmp(argv[i], "-noaliasobj0") == 0) {
 472	  aliasobj0 = 0;
 473	  Swig_mark_arg(i);
 474	} else if (strcmp(argv[i], "-proxydel") == 0) {
 475	  proxydel = 1;
 476	  Swig_mark_arg(i);
 477	} else if (strcmp(argv[i], "-noproxydel") == 0) {
 478	  proxydel = 0;
 479	  Swig_mark_arg(i);
 480	} else if (strcmp(argv[i], "-modern") == 0) {
 481	  classic = 0;
 482	  modern = 1;
 483	  modernargs = 1;
 484	  Swig_mark_arg(i);
 485	} else if (strcmp(argv[i], "-nomodern") == 0) {
 486	  modern = 0;
 487	  modernargs = 0;
 488	  Swig_mark_arg(i);
 489	} else if (strcmp(argv[i], "-noh") == 0) {
 490	  no_header_file = 1;
 491	  Swig_mark_arg(i);
 492	} else if ((strcmp(argv[i], "-new_vwm") == 0) || (strcmp(argv[i], "-newvwm") == 0)) {
 493	  /* Turn on new value wrapper mpde */
 494	  Swig_value_wrapper_mode(1);
 495	  no_header_file = 1;
 496	  Swig_mark_arg(i);
 497	} else if (strcmp(argv[i], "-O") == 0) {
 498	  classic = 0;
 499	  modern = 1;
 500	  safecstrings = 0;
 501	  buildnone = 0;
 502	  nobuildnone = 1;
 503	  classptr = 0;
 504	  proxydel = 0;
 505	  fastunpack = 1;
 506	  fastproxy = 1;
 507	  fastinit = 1;
 508	  fastquery = 1;
 509	  modernargs = 1;
 510	  Wrapper_fast_dispatch_mode_set(1);
 511	  Wrapper_virtual_elimination_mode_set(1);
 512	  Swig_mark_arg(i);
 513	} else if (strcmp(argv[i], "-help") == 0) {
 514	  fputs(usage1, stdout);
 515	  fputs(usage2, stdout);
 516	  fputs(usage3, stdout);
 517	} else if (strcmp(argv[i], "-py3") == 0) {
 518	  py3 = 1;
 519	  Swig_mark_arg(i);
 520	} else if (strcmp(argv[i], "-builtin") == 0) {
 521	  builtin = 1;
 522	  Preprocessor_define("SWIGPYTHON_BUILTIN", 0);
 523	  Swig_mark_arg(i);
 524	}
 525
 526      }
 527    }
 528
 529    if (py3) {
 530      /* force disable features that not compatible with Python 3.x */
 531      classic = 0;
 532    }
 533
 534    if (cppcast) {
 535      Preprocessor_define((DOH *) "SWIG_CPLUSPLUS_CAST", 0);
 536    }
 537
 538    if (!global_name)
 539      global_name = NewString("cvar");
 540    Preprocessor_define("SWIGPYTHON 1", 0);
 541    SWIG_typemap_lang("python");
 542    SWIG_config_file("python.swg");
 543    allow_overloading();
 544  }
 545
 546
 547  /* ------------------------------------------------------------
 548   * top()
 549   * ------------------------------------------------------------ */
 550
 551  virtual int top(Node *n) {
 552    /* check if directors are enabled for this module.  note: this 
 553     * is a "master" switch, without which no director code will be
 554     * emitted.  %feature("director") statements are also required
 555     * to enable directors for individual classes or methods.
 556     *
 557     * use %module(directors="1") modulename at the start of the 
 558     * interface file to enable director generation.
 559     */
 560    String *mod_docstring = NULL;
 561    {
 562      Node *mod = Getattr(n, "module");
 563      if (mod) {
 564	Node *options = Getattr(mod, "options");
 565	if (options) {
 566	  int dirprot = 0;
 567	  if (Getattr(options, "dirprot")) {
 568	    dirprot = 1;
 569	  }
 570	  if (Getattr(options, "nodirprot")) {
 571	    dirprot = 0;
 572	  }
 573	  if (Getattr(options, "directors")) {
 574	    allow_directors();
 575	    if (dirprot)
 576	      allow_dirprot();
 577	  }
 578	  if (Getattr(options, "threads")) {
 579	    threads = 1;
 580	  }
 581	  if (Getattr(options, "castmode")) {
 582	    castmode = 1;
 583	  }
 584	  if (Getattr(options, "nocastmode")) {
 585	    castmode = 0;
 586	  }
 587	  if (Getattr(options, "extranative")) {
 588	    extranative = 1;
 589	  }
 590	  if (Getattr(options, "noextranative")) {
 591	    extranative = 0;
 592	  }
 593	  if (Getattr(options, "outputtuple")) {
 594	    outputtuple = 1;
 595	  }
 596	  if (Getattr(options, "nooutputtuple")) {
 597	    outputtuple = 0;
 598	  }
 599	  mod_docstring = Getattr(options, "docstring");
 600	  package = Getattr(options, "package");
 601	}
 602      }
 603    }
 604
 605    /* Set comparison with none for ConstructorToFunction */
 606    setSubclassInstanceCheck(NewString("$arg != Py_None"));
 607
 608    /* Initialize all of the output files */
 609    String *outfile = Getattr(n, "outfile");
 610    String *outfile_h = !no_header_file ? Getattr(n, "outfile_h") : 0;
 611
 612    f_begin = NewFile(outfile, "w", SWIG_output_files());
 613    if (!f_begin) {
 614      FileErrorDisplay(outfile);
 615      SWIG_exit(EXIT_FAILURE);
 616    }
 617    f_runtime = NewString("");
 618    f_init = NewString("");
 619    f_header = NewString("");
 620    f_wrappers = NewString("");
 621    f_directors_h = NewString("");
 622    f_directors = NewString("");
 623    builtin_getset = NewHash();
 624    class_members = NewHash();
 625    builtin_methods = NewString("");
 626    builtin_default_unref = NewString("delete $self;");
 627
 628    if (builtin) {
 629      f_builtins = NewString("");
 630    }
 631
 632    if (directorsEnabled()) {
 633      if (!no_header_file) {
 634	f_runtime_h = NewFile(outfile_h, "w", SWIG_output_files());
 635	if (!f_runtime_h) {
 636	  FileErrorDisplay(outfile_h);
 637	  SWIG_exit(EXIT_FAILURE);
 638	}
 639      } else {
 640	f_runtime_h = f_runtime;
 641      }
 642    }
 643
 644    /* Register file targets with the SWIG file handler */
 645    Swig_register_filebyname("header", f_header);
 646    Swig_register_filebyname("wrapper", f_wrappers);
 647    Swig_register_filebyname("begin", f_begin);
 648    Swig_register_filebyname("runtime", f_runtime);
 649    Swig_register_filebyname("init", f_init);
 650    Swig_register_filebyname("director", f_directors);
 651    Swig_register_filebyname("director_h", f_directors_h);
 652
 653    const_code = NewString("");
 654    methods = NewString("");
 655
 656    Swig_banner(f_begin);
 657
 658    Printf(f_runtime, "\n");
 659    Printf(f_runtime, "#define SWIGPYTHON\n");
 660
 661    if (directorsEnabled()) {
 662      Printf(f_runtime, "#define SWIG_DIRECTORS\n");
 663    }
 664
 665    if (nothreads) {
 666      Printf(f_runtime, "#define SWIG_PYTHON_NO_THREADS\n");
 667    } else if (threads) {
 668      Printf(f_runtime, "#define SWIG_PYTHON_THREADS\n");
 669    }
 670
 671    if (safecstrings) {
 672      Printf(f_runtime, "#define SWIG_PYTHON_SAFE_CSTRINGS\n");
 673    }
 674
 675    if (buildnone) {
 676      Printf(f_runtime, "#define SWIG_PYTHON_BUILD_NONE\n");
 677    }
 678
 679    if (nobuildnone) {
 680      Printf(f_runtime, "#define SWIG_PYTHON_NO_BUILD_NONE\n");
 681    }
 682
 683    if (!dirvtable) {
 684      Printf(f_runtime, "#define SWIG_PYTHON_DIRECTOR_NO_VTABLE\n");
 685    }
 686
 687    if (outputtuple) {
 688      Printf(f_runtime, "#define SWIG_PYTHON_OUTPUT_TUPLE\n");
 689    }
 690
 691    if (nortti) {
 692      Printf(f_runtime, "#ifndef SWIG_DIRECTOR_NORTTI\n");
 693      Printf(f_runtime, "#define SWIG_DIRECTOR_NORTTI\n");
 694      Printf(f_runtime, "#endif\n");
 695    }
 696
 697    if (castmode) {
 698      Printf(f_runtime, "#define SWIG_CASTRANK_MODE\n");
 699      Printf(f_runtime, "#define SWIG_PYTHON_CAST_MODE\n");
 700    }
 701
 702    if (extranative) {
 703      Printf(f_runtime, "#define SWIG_PYTHON_EXTRA_NATIVE_CONTAINERS\n");
 704    }
 705
 706    if (classic) {
 707      Printf(f_runtime, "#define SWIG_PYTHON_CLASSIC\n");
 708    }
 709
 710    if (builtin) {
 711      Printf(f_runtime, "#define SWIGPYTHON_BUILTIN\n");
 712    }
 713
 714    Printf(f_runtime, "\n");
 715
 716    Printf(f_header, "#if (PY_VERSION_HEX <= 0x02000000)\n");
 717    Printf(f_header, "# if !defined(SWIG_PYTHON_CLASSIC)\n");
 718    Printf(f_header, "#  error \"This python version requires swig to be run with the '-classic' option\"\n");
 719    Printf(f_header, "# endif\n");
 720    Printf(f_header, "#endif\n");
 721
 722    if (modern) {
 723      Printf(f_header, "#if (PY_VERSION_HEX <= 0x02020000)\n");
 724      Printf(f_header, "# error \"This python version requires swig to be run with the '-nomodern' option\"\n");
 725      Printf(f_header, "#endif\n");
 726    }
 727
 728    if (modernargs) {
 729      Printf(f_header, "#if (PY_VERSION_HEX <= 0x02020000)\n");
 730      Printf(f_header, "# error \"This python version requires swig to be run with the '-nomodernargs' option\"\n");
 731      Printf(f_header, "#endif\n");
 732    }
 733
 734    if (fastunpack) {
 735      Printf(f_header, "#ifndef METH_O\n");
 736      Printf(f_header, "# error \"This python version requires swig to be run with the '-nofastunpack' option\"\n");
 737      Printf(f_header, "#endif\n");
 738    }
 739
 740    if (fastquery) {
 741      Printf(f_header, "#ifdef SWIG_TypeQuery\n");
 742      Printf(f_header, "# undef SWIG_TypeQuery\n");
 743      Printf(f_header, "#endif\n");
 744      Printf(f_header, "#define SWIG_TypeQuery SWIG_Python_TypeQuery\n");
 745    }
 746
 747
 748    /* Set module name */
 749    module = Copy(Getattr(n, "name"));
 750    mainmodule = Getattr(n, "name");
 751
 752    if (directorsEnabled()) {
 753      Swig_banner(f_directors_h);
 754      Printf(f_directors_h, "\n");
 755      Printf(f_directors_h, "#ifndef SWIG_%s_WRAP_H_\n", module);
 756      Printf(f_directors_h, "#define SWIG_%s_WRAP_H_\n\n", module);
 757      if (dirprot_mode()) {
 758	Printf(f_directors_h, "#include <map>\n");
 759	Printf(f_directors_h, "#include <string>\n\n");
 760      }
 761
 762      Printf(f_directors, "\n\n");
 763      Printf(f_directors, "/* ---------------------------------------------------\n");
 764      Printf(f_directors, " * C++ director class methods\n");
 765      Printf(f_directors, " * --------------------------------------------------- */\n\n");
 766      if (outfile_h)
 767	Printf(f_directors, "#include \"%s\"\n\n", Swig_file_filename(outfile_h));
 768    }
 769
 770    /* If shadow classing is enabled, we're going to change the module name to "_module" */
 771    if (shadow) {
 772      String *filen = NewStringf("%s%s.py", SWIG_output_directory(), Char(module));
 773      // If we don't have an interface then change the module name X to _X
 774      if (interface)
 775	module = interface;
 776      else
 777	Insert(module, 0, "_");
 778      if ((f_shadow_py = NewFile(filen, "w", SWIG_output_files())) == 0) {
 779	FileErrorDisplay(filen);
 780	SWIG_exit(EXIT_FAILURE);
 781      }
 782      Delete(filen);
 783      filen = NULL;
 784
 785      f_shadow = NewString("");
 786      f_shadow_imports = NewHash();
 787      f_shadow_builtin_imports = NewString("");
 788      f_shadow_stubs = NewString("");
 789
 790      Swig_register_filebyname("shadow", f_shadow);
 791      Swig_register_filebyname("python", f_shadow);
 792
 793      if (mod_docstring && Len(mod_docstring)) {
 794	Printv(f_shadow, "\"\"\"\n", mod_docstring, "\n\"\"\"\n\n", NIL);
 795	Delete(mod_docstring);
 796	mod_docstring = NULL;
 797      }
 798
 799      Printv(f_shadow, "\nfrom sys import version_info\n", NULL);
 800
 801      if (!builtin && fastproxy) {
 802	Printv(f_shadow, "if version_info >= (3,0,0):\n", NULL);
 803	Printf(f_shadow, tab4 "new_instancemethod = lambda func, inst, cls: %s.SWIG_PyInstanceMethod_New(func)\n", module);
 804	Printv(f_shadow, "else:\n", NULL);
 805	Printv(f_shadow, tab4, "from new import instancemethod as new_instancemethod\n", NULL);
 806      }
 807
 808      /* Import the C-extension module.  This should be a relative import,
 809       * since the shadow module may also have been imported by a relative
 810       * import, and there is thus no guarantee that the C-extension is on
 811       * sys.path.  Relative imports must be explicitly specified from 2.6.0
 812       * onwards (implicit relative imports will raise a DeprecationWarning
 813       * in 2.6, and fail in 2.7 onwards), but the relative import syntax
 814       * isn't available in python 2.4 or earlier, so we have to write some
 815       * code conditional on the python version.
 816       */
 817      Printv(f_shadow, "if version_info >= (2,6,0):\n", NULL);
 818      Printv(f_shadow, tab4, "def swig_import_helper():\n", NULL);
 819      Printv(f_shadow, tab8, "from os.path import dirname\n", NULL);
 820      Printv(f_shadow, tab8, "import imp\n", NULL);
 821      Printv(f_shadow, tab8, "fp = None\n", NULL);
 822      Printv(f_shadow, tab8, "try:\n", NULL);
 823      Printf(f_shadow, tab4 tab8 "fp, pathname, description = imp.find_module('%s', [dirname(__file__)])\n", module);
 824      Printf(f_shadow, tab8 "except ImportError:\n");
 825      /* At here, the module may already loaded, so simply import it. */
 826      Printf(f_shadow, tab4 tab8 "import %s\n", module);
 827      Printf(f_shadow, tab4 tab8 "return %s\n", module);
 828      Printv(f_shadow, tab8 "if fp is not None:\n", NULL);
 829      Printv(f_shadow, tab4 tab8 "try:\n", NULL);
 830      Printf(f_shadow, tab8 tab8 "_mod = imp.load_module('%s', fp, pathname, description)\n", module);
 831      Printv(f_shadow, tab4 tab8, "finally:\n", NULL);
 832      Printv(f_shadow, tab8 tab8, "fp.close()\n", NULL);
 833      Printv(f_shadow, tab4 tab8, "return _mod\n", NULL);
 834      Printf(f_shadow, tab4 "%s = swig_import_helper()\n", module);
 835      Printv(f_shadow, tab4, "del swig_import_helper\n", NULL);
 836      Printv(f_shadow, "else:\n", NULL);
 837      Printf(f_shadow, tab4 "import %s\n", module);
 838
 839      /* Delete the version_info symbol since we don't use it elsewhere in the
 840       * module. */
 841      Printv(f_shadow, "del version_info\n", NULL);
 842
 843      if (builtin) {
 844	Printf(f_shadow, "from %s import *\n", module);
 845      }
 846      if (modern || !classic) {
 847	Printv(f_shadow, "try:\n", tab4, "_swig_property = property\n", "except NameError:\n", tab4, "pass # Python < 2.2 doesn't have 'property'.\n", NULL);
 848      }
 849      /* if (!modern) */
 850      /* always needed, a class can be forced to be no-modern, such as an exception */
 851      {
 852	// Python-2.2 object hack
 853	Printv(f_shadow,
 854	       "def _swig_setattr_nondynamic(self,class_type,name,value,static=1):\n",
 855	       tab4, "if (name == \"thisown\"): return self.this.own(value)\n",
 856	       tab4, "if (name == \"this\"):\n", tab4, tab4, "if type(value).__name__ == 'SwigPyObject':\n", tab4, tab8, "self.__dict__[name] = value\n",
 857#ifdef USE_THISOWN
 858	       tab4, tab8, "if hasattr(value,\"thisown\"): self.__dict__[\"thisown\"] = value.thisown\n", tab4, tab8, "del value.thisown\n",
 859#endif
 860	       tab4, tab8, "return\n", tab4, "method = class_type.__swig_setmethods__.get(name,None)\n", tab4, "if method: return method(self,value)\n",
 861#ifdef USE_THISOWN
 862	       tab4, "if (not static) or (name == \"thisown\"):\n",
 863#else
 864	       tab4, "if (not static):\n",
 865#endif
 866	       tab4, tab4, "self.__dict__[name] = value\n",
 867	       tab4, "else:\n",
 868	       tab4, tab4, "raise AttributeError(\"You cannot add attributes to %s\" % self)\n\n",
 869	       "def _swig_setattr(self,class_type,name,value):\n", tab4, "return _swig_setattr_nondynamic(self,class_type,name,value,0)\n\n", NIL);
 870
 871	Printv(f_shadow,
 872	       "def _swig_getattr(self,class_type,name):\n",
 873	       tab4, "if (name == \"thisown\"): return self.this.own()\n",
 874	       tab4, "method = class_type.__swig_getmethods__.get(name,None)\n",
 875	       tab4, "if method: return method(self)\n", tab4, "raise AttributeError(name)\n\n", NIL);
 876
 877	Printv(f_shadow,
 878	       "def _swig_repr(self):\n",
 879	       tab4, "try: strthis = \"proxy of \" + self.this.__repr__()\n",
 880	       tab4, "except: strthis = \"\"\n", tab4, "return \"<%s.%s; %s >\" % (self.__class__.__module__, self.__class__.__name__, strthis,)\n\n", NIL);
 881
 882	if (!classic) {
 883	  /* Usage of types.ObjectType is deprecated.
 884	   * But don't sure wether this would broken old Python?
 885	   */
 886	  Printv(f_shadow,
 887//               "import types\n",
 888		 "try:\n",
 889//               "    _object = types.ObjectType\n",
 890		 "    _object = object\n", "    _newclass = 1\n", "except AttributeError:\n", "    class _object : pass\n", "    _newclass = 0\n",
 891//                 "del types\n", 
 892		 "\n\n", NIL);
 893	}
 894      }
 895      if (modern) {
 896	Printv(f_shadow, "def _swig_setattr_nondynamic_method(set):\n", tab4, "def set_attr(self,name,value):\n",
 897#ifdef USE_THISOWN
 898	       tab4, tab4, "if hasattr(self,name) or (name in (\"this\", \"thisown\")):\n",
 899#else
 900	       tab4, tab4, "if (name == \"thisown\"): return self.this.own(value)\n", tab4, tab4, "if hasattr(self,name) or (name == \"this\"):\n",
 901#endif
 902	       tab4, tab4, tab4, "set(self,name,value)\n",
 903	       tab4, tab4, "else:\n",
 904	       tab4, tab4, tab4, "raise AttributeError(\"You cannot add attributes to %s\" % self)\n", tab4, "return set_attr\n\n\n", NIL);
 905      }
 906
 907      if (directorsEnabled()) {
 908	// Try loading weakref.proxy, which is only available in Python 2.1 and higher
 909	Printv(f_shadow,
 910	       "try:\n", tab4, "import weakref\n", tab4, "weakref_proxy = weakref.proxy\n", "except:\n", tab4, "weakref_proxy = lambda x: x\n", "\n\n", NIL);
 911      }
 912    }
 913    // Include some information in the code
 914    Printf(f_header, "\n/*-----------------------------------------------\n              @(target):= %s.so\n\
 915  ------------------------------------------------*/\n", module);
 916
 917    Printf(f_header, "#if PY_VERSION_HEX >= 0x03000000\n");
 918    Printf(f_header, "#  define SWIG_init    PyInit_%s\n\n", module);
 919    Printf(f_header, "#else\n");
 920    Printf(f_header, "#  define SWIG_init    init%s\n\n", module);
 921    Printf(f_header, "#endif\n");
 922    Printf(f_header, "#define SWIG_name    \"%s\"\n", module);
 923
 924    Printf(f_wrappers, "#ifdef __cplusplus\n");
 925    Printf(f_wrappers, "extern \"C\" {\n");
 926    Printf(f_wrappers, "#endif\n");
 927    Append(const_code, "static swig_const_info swig_const_table[] = {\n");
 928    Append(methods, "static PyMethodDef SwigMethods[] = {\n");
 929
 930    /* the method exported for replacement of new.instancemethod in Python 3 */
 931    add_pyinstancemethod_new();
 932
 933    if (builtin) {
 934      SwigType *s = NewString("SwigPyObject");
 935      SwigType_add_pointer(s);
 936      SwigType_remember(s);
 937      Delete(s);
 938    }
 939
 940    /* emit code */
 941    Language::top(n);
 942
 943    if (directorsEnabled()) {
 944      // Insert director runtime into the f_runtime file (make it occur before %header section)
 945      Swig_insert_file("director.swg", f_runtime);
 946    }
 947
 948    /* Close language module */
 949    Append(methods, "\t { NULL, NULL, 0, NULL }\n");
 950    Append(methods, "};\n");
 951    Printf(f_wrappers, "%s\n", methods);
 952
 953    if (builtin) {
 954      Dump(f_builtins, f_wrappers);
 955    }
 956
 957    SwigType_emit_type_table(f_runtime, f_wrappers);
 958
 959    Append(const_code, "{0, 0, 0, 0.0, 0, 0}};\n");
 960    Printf(f_wrappers, "%s\n", const_code);
 961    initialize_threads(f_init);
 962
 963    Printf(f_init, "#if PY_VERSION_HEX >= 0x03000000\n");
 964    Printf(f_init, "  return m;\n");
 965    Printf(f_init, "#else\n");
 966    Printf(f_init, "  return;\n");
 967    Printf(f_init, "#endif\n");
 968    Printf(f_init, "}\n");
 969
 970    Printf(f_wrappers, "#ifdef __cplusplus\n");
 971    Printf(f_wrappers, "}\n");
 972    Printf(f_wrappers, "#endif\n");
 973
 974    if (shadow) {
 975      Swig_banner_target_lang(f_shadow_py, "#");
 976      if (!modern) {
 977	Printv(f_shadow, "# This file is compatible with both classic and new-style classes.\n", NIL);
 978      }
 979      Printv(f_shadow_py, "\n", f_shadow_builtin_imports, "\n", NIL);
 980      Printv(f_shadow_py, f_shadow, "\n", NIL);
 981      Printv(f_shadow_py, f_shadow_stubs, "\n", NIL);
 982      Close(f_shadow_py);
 983      Delete(f_shadow_py);
 984    }
 985
 986    /* Close all of the files */
 987    Dump(f_runtime, f_begin);
 988    Dump(f_header, f_begin);
 989
 990    if (directorsEnabled()) {
 991      Dump(f_directors_h, f_runtime_h);
 992      Printf(f_runtime_h, "\n");
 993      Printf(f_runtime_h, "#endif\n");
 994      if (f_runtime_h != f_begin)
 995	Close(f_runtime_h);
 996      Dump(f_directors, f_begin);
 997    }
 998
 999    Dump(f_wrappers, f_begin);
1000    if (builtin && builtin_bases_needed)
1001      Printf(f_begin, "static PyTypeObject *builtin_bases[%d];\n\n", max_bases + 2);
1002    Wrapper_pretty_print(f_init, f_begin);
1003
1004    Delete(f_header);
1005    Delete(f_wrappers);
1006    Delete(f_builtins);
1007    Delete(f_init);
1008    Delete(f_directors);
1009    Delete(f_directors_h);
1010
1011    Close(f_begin);
1012    Delete(f_runtime);
1013    Delete(f_begin);
1014
1015    return SWIG_OK;
1016  }
1017
1018  /* ------------------------------------------------------------
1019   * Emit the wrapper for PyInstanceMethod_New to MethodDef array.
1020   * This wrapper is used to implement -fastproxy,
1021   * as a replacement of new.instancemethod in Python 3.
1022   * ------------------------------------------------------------ */
1023  int add_pyinstancemethod_new() {
1024    String *name = NewString("SWIG_PyInstanceMethod_New");
1025    Printf(methods, "\t { (char *)\"%s\", (PyCFunction)%s, METH_O, NULL},\n", name, name);
1026    Delete(name);
1027    return 0;
1028  }
1029
1030  /* ------------------------------------------------------------
1031   * importDirective()
1032   * ------------------------------------------------------------ */
1033
1034  virtual int importDirective(Node *n) {
1035    if (shadow) {
1036      String *modname = Getattr(n, "module");
1037
1038      if (modname) {
1039	String *import = NewString("import ");
1040
1041	// Find the module node for this imported module.  It should be the
1042	// first child but search just in case.
1043	Node *mod = firstChild(n);
1044	while (mod && Strcmp(nodeType(mod), "module") != 0)
1045	  mod = nextSibling(mod);
1046
1047	// Is the imported module in another package?  (IOW, does it use the
1048	// %module(package="name") option and it's different than the package
1049	// of this module.)
1050	Node *options = Getattr(mod, "options");
1051	String *pkg = options ? Getattr(options, "package") : 0;
1052	if (pkg && (!package || Strcmp(pkg, package) != 0)) {
1053	  Printf(import, "%s.", pkg);
1054	}
1055	// finally, output the name of the imported module
1056	if (shadowimport) {
1057	  if (!options || (!Getattr(options, "noshadow") && !Getattr(options, "noproxy"))) {
1058	    Printf(import, "_%s\n", modname);
1059	    if (!GetFlagAttr(f_shadow_imports, import)) {
1060	      if (pkg && (!package || Strcmp(pkg, package) != 0)) {
1061		Printf(builtin ? f_shadow_builtin_imports : f_shadow, "import %s.%s\n", pkg, modname);
1062	      } else {
1063		Printf(builtin ? f_shadow_builtin_imports : f_shadow, "import %s\n", modname);
1064	      }
1065	      SetFlag(f_shadow_imports, import);
1066	    }
1067	  }
1068	}
1069
1070	Delete(import);
1071      }
1072    }
1073    return Language::importDirective(n);
1074  }
1075
1076  /* ------------------------------------------------------------
1077   * funcCall()
1078   *    Emit shadow code to call a function in the extension
1079   *    module. Using proper argument and calling style for
1080   *    given node n.
1081   * ------------------------------------------------------------ */
1082  String *funcCall(String *name, String *parms) {
1083    String *str = NewString("");
1084
1085    Printv(str, module, ".", name, "(", parms, ")", NIL);
1086    return str;
1087  }
1088
1089
1090  /* ------------------------------------------------------------
1091   * pythoncode()     - Output python code into the shadow file
1092   * ------------------------------------------------------------ */
1093
1094  String *pythoncode(String *code, const_String_or_char_ptr indent) {
1095    String *out = NewString("");
1096    String *temp;
1097    char *t;
1098    if (!indent)
1099      indent = "";
1100
1101    temp = NewString(code);
1102
1103    t = Char(temp);
1104    if (*t == '{') {
1105      Delitem(temp, 0);
1106      Delitem(temp, DOH_END);
1107    }
1108
1109    /* Split the input text into lines */
1110    List *clist = DohSplitLines(temp);
1111    Delete(temp);
1112    int initial = 0;
1113    String *s = 0;
1114    Iterator si;
1115    /* Get the initial indentation */
1116
1117    for (si = First(clist); si.item; si = Next(si)) {
1118      s = si.item;
1119      if (Len(s)) {
1120	char *c = Char(s);
1121	while (*c) {
1122	  if (!isspace(*c))
1123	    break;
1124	  initial++;
1125	  c++;
1126	}
1127	if (*c && !isspace(*c)) {
1128	  break;
1129	} else {
1130	  initial = 0;
1131	}
1132      }
1133    }
1134    while (si.item) {
1135      s = si.item;
1136      if (Len(s) > initial) {
1137	char *c = Char(s);
1138	c += initial;
1139	Printv(out, indent, c, "\n", NIL);
1140      } else {
1141	Printv(out, "\n", NIL);
1142      }
1143      si = Next(si);
1144    }
1145    Delete(clist);
1146    return out;
1147  }
1148
1149
1150  /* ------------------------------------------------------------
1151   * autodoc level declarations
1152   * ------------------------------------------------------------ */
1153
1154  enum autodoc_l {
1155    NO_AUTODOC = -2,		// no autodoc
1156    STRING_AUTODOC = -1,	// use provided string
1157    NAMES_AUTODOC = 0,		// only parameter names
1158    TYPES_AUTODOC = 1,		// parameter names and types
1159    EXTEND_AUTODOC = 2,		// extended documentation and parameter names
1160    EXTEND_TYPES_AUTODOC = 3	// extended documentation and parameter types + names
1161  };
1162
1163
1164  autodoc_l autodoc_level(String *autodoc) {
1165    autodoc_l dlevel = NO_AUTODOC;
1166    if (autodoc) {
1167      char *c = Char(autodoc);
1168      if (c && isdigit(c[0])) {
1169	dlevel = (autodoc_l) atoi(c);
1170      } else {
1171	if (strcmp(c, "extended") == 0) {
1172	  dlevel = EXTEND_AUTODOC;
1173	} else {
1174	  dlevel = STRING_AUTODOC;
1175	}
1176      }
1177    }
1178    return dlevel;
1179  }
1180
1181
1182  /* ------------------------------------------------------------
1183   * have_docstring()
1184   *    Check if there is a docstring directive and it has text,
1185   *    or there is an autodoc flag set
1186   * ------------------------------------------------------------ */
1187
1188  bool have_docstring(Node *n) {
1189    String *str = Getattr(n, "feature:docstring");
1190    return (str && Len(str) > 0) || (Getattr(n, "feature:autodoc") && !GetFlag(n, "feature:noautodoc"));
1191  }
1192
1193  /* ------------------------------------------------------------
1194   * docstring()
1195   *    Get the docstring text, stripping off {} if neccessary,
1196   *    and enclose in triple double quotes.  If autodoc is also
1197   *    set then it will build a combined docstring.
1198   * ------------------------------------------------------------ */
1199
1200  String *docstring(Node *n, autodoc_t ad_type, const String *indent, bool use_triple = true) {
1201    String *str = Getattr(n, "feature:docstring");
1202    bool have_ds = (str && Len(str) > 0);
1203    bool have_auto = (Getattr(n, "feature:autodoc") && !GetFlag(n, "feature:noautodoc"));
1204    const char *triple_double = use_triple ? "\"\"\"" : "";
1205    String *autodoc = NULL;
1206    String *doc = NULL;
1207
1208    if (have_ds) {
1209      char *t = Char(str);
1210      if (*t == '{') {
1211	Delitem(str, 0);
1212	Delitem(str, DOH_END);
1213      }
1214    }
1215
1216    if (have_auto) {
1217      autodoc = make_autodoc(n, ad_type);
1218      have_auto = (autodoc && Len(autodoc) > 0);
1219    }
1220    // If there is more than one line then make docstrings like this:
1221    //
1222    //      """
1223    //      This is line1
1224    //      And here is line2 followed by the rest of them
1225    //      """
1226    //
1227    // otherwise, put it all on a single line
1228    //
1229    if (have_auto && have_ds) {	// Both autodoc and docstring are present
1230      doc = NewString("");
1231      Printv(doc, triple_double, "\n", pythoncode(autodoc, indent), "\n", pythoncode(str, indent), indent, triple_double, NIL);
1232    } else if (!have_auto && have_ds) {	// only docstring
1233      if (Strchr(str, '\n') == 0) {
1234	doc = NewStringf("%s%s%s", triple_double, str, triple_double);
1235      } else {
1236	doc = NewString("");
1237	Printv(doc, triple_double, "\n", pythoncode(str, indent), indent, triple_double, NIL);
1238      }
1239    } else if (have_auto && !have_ds) {	// only autodoc
1240      if (Strchr(autodoc, '\n') == 0) {
1241	doc = NewStringf("%s%s%s", triple_double, autodoc, triple_double);
1242      } else {
1243	doc = NewString("");
1244	Printv(doc, triple_double, "\n", pythoncode(autodoc, indent), indent, triple_double, NIL);
1245      }
1246    } else
1247      doc = NewString("");
1248
1249    // Save the generated strings in the parse tree in case they are used later
1250    // by post processing tools
1251    Setattr(n, "python:docstring", doc);
1252    Setattr(n, "python:autodoc", autodoc);
1253    return doc;
1254  }   
1255
1256  /* ------------------------------------------------------------
1257   * cdocstring()
1258   *    Get the docstring text as it would appear in C-language
1259   *	source code.
1260   * ------------------------------------------------------------ */
1261
1262  String *cdocstring(Node *n, autodoc_t ad_type)
1263  {
1264    String *ds = docstring(n, ad_type, "", false);
1265    Replaceall(ds, "\\", "\\\\");
1266    Replaceall(ds, "\"", "\\\"");
1267    Replaceall(ds, "\n", "\\n\"\n\t\t\"");
1268    return ds;
1269  }
1270
1271  /* -----------------------------------------------------------------------------
1272   * addMissingParameterNames()
1273   *  For functions that have not had nameless parameters set in the Language class.
1274   *
1275   * Inputs: 
1276   *   plist - entire parameter list
1277   *   arg_offset - argument number for first parameter
1278   * Side effects:
1279   *   The "lname" attribute in each parameter in plist will be contain a parameter name
1280   * ----------------------------------------------------------------------------- */
1281
1282  void addMissingParameterNames(ParmList *plist, int arg_offset) {
1283    Parm *p = plist;
1284    int i = arg_offset;
1285    while (p) {
1286      if (!Getattr(p, "lname")) {
1287	String *pname = Swig_cparm_name(p, i);
1288	Delete(pname);
1289      }
1290      i++;
1291      p = nextSibling(p);
1292    }
1293  }
1294
1295  /* ------------------------------------------------------------
1296   * make_autodocParmList()
1297   *   Generate the documentation for the function parameters
1298   *   Parameters:
1299   *    func_annotation: Function annotation support
1300   * ------------------------------------------------------------ */
1301
1302  String *make_autodocParmList(Node *n, bool showTypes, bool calling = false, bool func_annotation = false) {
1303
1304    String *doc = NewString("");
1305    String *pdocs = 0;
1306    ParmList *plist = CopyParmList(Getattr(n, "parms"));
1307    Parm *p;
1308    Parm *pnext;
1309
1310
1311    int lines = 0;
1312    int start_arg_num = is_wrapping_class() ? 1 : 0;
1313    const int maxwidth = 80;
1314
1315    if (calling)
1316      func_annotation = false;
1317
1318    addMissingParameterNames(plist, start_arg_num); // for $1_name substitutions done in Swig_typemap_attach_parms
1319    Swig_typemap_attach_parms("in", plist, 0);
1320    Swig_typemap_attach_parms("doc", plist, 0);
1321
1322    if (Strcmp(ParmList_protostr(plist), "void") == 0) {
1323      //No parameters actually
1324      return doc;
1325    }
1326
1327    for (p = plist; p; p = pnext) {
1328
1329      String *tm = Getattr(p, "tmap:in");
1330      if (tm) {
1331	pnext = Getattr(p, "tmap:in:next");
1332	if (checkAttribute(p, "tmap:in:numinputs", "0")) {
1333	  continue;
1334	}
1335      } else {
1336	pnext = nextSibling(p);
1337      }
1338
1339      String *name = 0;
1340      String *type = 0;
1341      String *value = 0;
1342      String *pdoc = Getattr(p, "tmap:doc");
1343      if (pdoc) {
1344	name = Getattr(p, "tmap:doc:name");
1345	type = Getattr(p, "tmap:doc:type");
1346	value = Getattr(p, "tmap:doc:value");
1347      }
1348
1349      // Note: the generated name should be consistent with that in kwnames[]
1350      name = name ? name : Getattr(p, "name");
1351      name = name ? name : Getattr(p, "lname");
1352      name = Swig_name_make(p, 0, name, 0, 0); // rename parameter if a keyword
1353
1354      type = type ? type : Getattr(p, "type");
1355      value = value ? value : Getattr(p, "value");
1356
1357      if (SwigType_isvarargs(type))
1358	break;
1359
1360      if (Len(doc)) {
1361	// add a comma to the previous one if any
1362	Append(doc, ", ");
1363
1364	// Do we need to wrap a long line?
1365	if ((Len(doc) - lines * maxwidth) > maxwidth) {
1366	  Printf(doc, "\n%s", tab4);
1367	  lines += 1;
1368	}
1369      }
1370
1371      // Do the param type too?
1372      Node *nn = classLookup(Getattr(p, "type"));
1373      String *type_str = nn ? Copy(Getattr(nn, "sym:name")) : SwigType_str(type, 0);
1374      if (showTypes)
1375	Printf(doc, "%s ", type_str);
1376
1377      Append(doc, name);
1378      if (pdoc) {
1379	if (!pdocs)
1380	  pdocs = NewString("\nParameters:\n");
1381	Printf(pdocs, "    %s\n", pdoc);
1382      }
1383      // Write the function annotation
1384      if (func_annotation)
1385	Printf(doc, " : '%s'", type_str);
1386
1387      // Write default value
1388      if (value && !calling) {
1389	String *new_value = convertValue(value, Getattr(p, "type"));
1390	if (new_value) {
1391	  value = new_value;
1392	} else {
1393	  Node *lookup = Swig_symbol_clookup(value, 0);
1394	  if (lookup)
1395	    value = Getattr(lookup, "sym:name");
1396	}
1397	Printf(doc, "=%s", value);
1398      }
1399      Delete(type_str);
1400      Delete(name);
1401    }
1402    if (pdocs)
1403      Setattr(n, "feature:pdocs", pdocs);
1404    Delete(plist);
1405    return doc;
1406  }
1407
1408  /* ------------------------------------------------------------
1409   * make_autodoc()
1410   *    Build a docstring for the node, using parameter and other
1411   *    info in the parse tree.  If the value of the autodoc
1412   *    attribute is "0" then do not include parameter types, if
1413   *    it is "1" (the default) then do.  If it has some other
1414   *    value then assume it is supplied by the extension writer
1415   *    and use it directly.
1416   * ------------------------------------------------------------ */
1417
1418  String *make_autodoc(Node *n, autodoc_t ad_type) {
1419    int extended = 0;
1420    // If the function is overloaded then this function is called
1421    // for the last one.  Rewind to the first so the docstrings are
1422    // in order.
1423    while (Getattr(n, "sym:previousSibling"))
1424      n = Getattr(n, "sym:previousSibling");
1425
1426    String *doc = NewString("");
1427    while (n) {
1428      bool showTypes = false;
1429      bool skipAuto = false;
1430      String *autodoc = Getattr(n, "feature:autodoc");
1431      autodoc_l dlevel = autodoc_level(autodoc);
1432      switch (dlevel) {
1433      case NO_AUTODOC:
1434	break;
1435      case NAMES_AUTODOC:
1436	showTypes = false;
1437	break;
1438      case TYPES_AUTODOC:
1439	showTypes = true;
1440	break;
1441      case EXTEND_AUTODOC:
1442	extended = 1;
1443	showTypes = false;
1444	break;
1445      case EXTEND_TYPES_AUTODOC:
1446	extended = 1;
1447	showTypes = true;
1448	break;
1449      case STRING_AUTODOC:
1450	Append(doc, autodoc);
1451	skipAuto = true;
1452	break;
1453      }
1454
1455      if (!skipAuto) {
1456	String *symname = Getattr(n, "sym:name");
1457	SwigType *type = Getattr(n, "type");
1458	String *type_str = NULL;
1459
1460	if (type) {
1461	  if (Strcmp(type, "void") == 0) {
1462	    type_str = NULL;
1463	  } else {
1464	    Node *nn = classLookup(type);
1465	    type_str = nn ? Copy(Getattr(nn, "sym:name")) : SwigType_str(type, 0);
1466	  }
1467	}
1468
1469	switch (ad_type) {
1470	case AUTODOC_CLASS:
1471	  {
1472	    // Only do the autodoc if there isn't a docstring for the class
1473	    String *str = Getattr(n, "feature:docstring");
1474	    if (!str || Len(str) == 0) {
1475	      if (CPlusPlus) {
1476		Printf(doc, "Proxy of C++ %s class", real_classname);
1477	      } else {
1478		Printf(doc, "Proxy of C %s struct", real_classname);
1479	      }
1480	    }
1481	  }
1482	  break;
1483	case AUTODOC_CTOR:
1484	  if (Strcmp(class_name, symname) == 0) {
1485	    String *paramList = make_autodocParmList(n, showTypes);
1486	    Printf(doc, "__init__(");
1487	    if (showTypes)
1488	      Printf(doc, "%s ", getClassName());
1489	    if (Len(paramList))
1490	      Printf(doc, "self, %s) -> %s", paramList, class_name);
1491	    else
1492	      Printf(doc, "self) -> %s", class_name);
1493	  } else
1494	    Printf(doc, "%s(%s) -> %s", symname, make_autodocParmList(n, showTypes), class_name);
1495	  break;
1496
1497	case AUTODOC_DTOR:
1498	  if (showTypes)
1499	    Printf(doc

Large files files are truncated, but you can click here to view the full file