1/* ----------------------------------------------------------------------------- 2 * See the LICENSE file for information on copyright, usage and redistribution 3 * of SWIG, and the README file for authors - http://www.swig.org/release.html. 4 * 5 * python.cxx 6 * 7 * Python language module for SWIG. 8 * ----------------------------------------------------------------------------- */ 9 10char cvsroot_python_cxx[] = "$Id: python.cxx 11518 2009-08-08 22:56:10Z wsfulton $"; 11 12#include "swigmod.h" 13#include "cparse.h" 14 15static int treduce = SWIG_cparse_template_reduce(0); 16 17#include <ctype.h> 18 19#define PYSHADOW_MEMBER 0x2 20 21static String *const_code = 0; 22static String *module = 0; 23static String *package = 0; 24static String *mainmodule = 0; 25static String *interface = 0; 26static String *global_name = 0; 27static int shadow = 1; 28static int use_kw = 0; 29static int director_method_index = 0; 30 31static File *f_begin = 0; 32static File *f_runtime = 0; 33static File *f_runtime_h = 0; 34static File *f_header = 0; 35static File *f_wrappers = 0; 36static File *f_directors = 0; 37static File *f_directors_h = 0; 38static File *f_init = 0; 39static File *f_shadow_py = 0; 40static String *f_shadow = 0; 41static String *f_shadow_imports = 0; 42static String *f_shadow_stubs = 0; 43 44static String *methods; 45static String *class_name; 46static String *shadow_indent = 0; 47static int in_class = 0; 48static int classic = 0; 49static int modern = 0; 50static int new_repr = 1; 51static int no_header_file = 0; 52 53static int py3 = 0; 54 55/* C++ Support + Shadow Classes */ 56 57static int have_constructor; 58static int have_repr; 59static String *real_classname; 60 61/* Thread Support */ 62static int threads = 0; 63static int nothreads = 0; 64static int classptr = 0; 65/* Other options */ 66static int shadowimport = 1; 67static int buildnone = 0; 68static int nobuildnone = 0; 69static int safecstrings = 0; 70static int dirvtable = 0; 71static int proxydel = 1; 72static int fastunpack = 0; 73static int fastproxy = 0; 74static int fastquery = 0; 75static int fastinit = 0; 76static int olddefs = 0; 77static int modernargs = 0; 78static int aliasobj0 = 0; 79static int castmode = 0; 80static int extranative = 0; 81static int outputtuple = 0; 82static int nortti = 0; 83 84/* flags for the make_autodoc function */ 85enum autodoc_t { 86 AUTODOC_CLASS, 87 AUTODOC_CTOR, 88 AUTODOC_DTOR, 89 AUTODOC_STATICFUNC, 90 AUTODOC_FUNC, 91 AUTODOC_METHOD 92}; 93 94 95static const char *usage1 = (char *) "\ 96Python Options (available with -python)\n\ 97 -aliasobj0 - Alias obj0 when using fastunpack, needed for some old typemaps \n\ 98 -buildnone - Use Py_BuildValue(" ") to obtain Py_None (default in Windows)\n\ 99 -castmode - Enable the casting mode, which allows implicit cast between types in python\n\ 100 -classic - Use classic classes only\n\ 101 -classptr - Generate shadow 'ClassPtr' as in older swig versions\n\ 102 -cppcast - Enable C++ casting operators (default) \n\ 103 -dirvtable - Generate a pseudo virtual table for directors for faster dispatch \n\ 104 -extranative - Return extra native C++ wraps for std containers when possible \n\ 105 -fastinit - Use fast init mechanism for classes (default)\n\ 106 -fastunpack - Use fast unpack mechanism to parse the argument functions \n\ 107 -fastproxy - Use fast proxy mechanism for member methods \n\ 108 -fastquery - Use fast query mechanism for types \n\ 109 -globals <name> - Set <name> used to access C global variable [default: 'cvar']\n\ 110 -interface <lib>- Set the lib name to <lib>\n\ 111 -keyword - Use keyword arguments\n\ 112 -modern - Use modern python features only, without compatibility code\n\ 113 -modernargs - Use \"modern\" args mechanism to pack/unpack the function arguments\n"; 114static const char *usage2 = (char *) "\ 115 -newrepr - Use more informative version of __repr__ in proxy classes (default) \n\ 116 -newvwm - New value wrapper mode, use only when everything else fails \n\ 117 -noaliasobj0 - Don't generate an obj0 alias when using fastunpack (default) \n\ 118 -nobuildnone - Access Py_None directly (default in non-Windows systems)\n\ 119 -nocastmode - Disable the casting mode (default)\n\ 120 -nocppcast - Disable C++ casting operators, useful for generating bugs\n\ 121 -nodirvtable - Don't use the virtual table feature, resolve the python method each time (default)\n\ 122 -noexcept - No automatic exception handling\n\ 123 -noextranative - Don't use extra native C++ wraps for std containers when possible (default) \n\ 124 -nofastinit - Use traditional init mechanism for classes \n\ 125 -nofastunpack - Use traditional UnpackTuple method to parse the argument functions (default) \n\ 126 -nofastproxy - Use traditional proxy mechanism for member methods (default) \n\ 127 -nofastquery - Use traditional query mechanism for types (default) \n\ 128 -noh - Don't generate the output header file\n\ 129 -nomodern - Don't use modern python features which are not back compatible \n\ 130 -nomodernargs - Use classic ParseTuple/CallFunction methods to pack/unpack the function arguments (default) \n"; 131static const char *usage3 = (char *) "\ 132 -noolddefs - Don't emit the old method definitions even when using fastproxy (default) \n\ 133 -nooutputtuple - Use a PyList for appending output values (default) \n\ 134 -noproxy - Don't generate proxy classes \n\ 135 -noproxydel - Don't generate the redundant __del__ method \n\ 136 -noproxyimport - Don't insert proxy import statements derived from the %import directive \n\ 137 -nortti - Disable the use of the native C++ RTTI with directors\n\ 138 -nosafecstrings - Avoid extra strings copies when possible (default)\n\ 139 -nothreads - Disable thread support for the entire interface\n\ 140 -olddefs - Keep the old method definitions even when using fastproxy\n\ 141 -oldrepr - Use shorter and old version of __repr__ in proxy classes\n\ 142 -outputtuple - Use a PyTuple for outputs instead of a PyList (use carefully with legacy interfaces) \n\ 143 -proxydel - Generate a __del__ method even though it is now redundant (default) \n\ 144 -safecstrings - Use safer (but slower) C string mapping, generating copies from Python -> C/C++\n\ 145 -threads - Add thread support for all the interface\n\ 146 -O - Enable all the optimization options: \n\ 147 -modern -fastdispatch -dirvtable -nosafecstrings -fvirtual -noproxydel \n\ 148 -fastproxy -fastinit -fastunpack -fastquery -modernargs -nobuildnone \n\ 149 -py3 - Generate code with Python 3 specific features:\n\ 150 Function annotation \n\ 151\n"; 152 153class PYTHON:public Language { 154public: 155 PYTHON() { 156 /* Add code to manage protected constructors and directors */ 157 director_prot_ctor_code = NewString(""); 158 Printv(director_prot_ctor_code, 159 "if ( $comparison ) { /* subclassed */\n", 160 " $director_new \n", 161 "} else {\n", " SWIG_SetErrorMsg(PyExc_RuntimeError,\"accessing abstract class or protected constructor\"); \n", " SWIG_fail;\n", "}\n", NIL); 162 director_multiple_inheritance = 1; 163 director_language = 1; 164 } 165 166 /* ------------------------------------------------------------ 167 * Thread Implementation 168 * ------------------------------------------------------------ */ 169 170 int threads_enable(Node *n) const { 171 return threads && !GetFlagAttr(n, "feature:nothread"); 172 } 173 174 int initialize_threads(String *f_init) { 175 if (!threads) { 176 return SWIG_OK; 177 } 178 Printf(f_init, "\n"); 179 Printf(f_init, "/* Initialize threading */\n"); 180 Printf(f_init, "SWIG_PYTHON_INITIALIZE_THREADS;\n"); 181 182 return SWIG_OK; 183 } 184 185 virtual void thread_begin_block(Node *n, String *f) { 186 if (!GetFlag(n, "feature:nothreadblock")) { 187 String *bb = Getattr(n, "feature:threadbeginblock"); 188 if (bb) { 189 Append(f, bb); 190 } else { 191 Append(f, "SWIG_PYTHON_THREAD_BEGIN_BLOCK;\n"); 192 } 193 } 194 } 195 196 virtual void thread_end_block(Node *n, String *f) { 197 if (!GetFlag(n, "feature:nothreadblock")) { 198 String *eb = Getattr(n, "feature:threadendblock"); 199 if (eb) { 200 Append(f, eb); 201 } else { 202 Append(f, "SWIG_PYTHON_THREAD_END_BLOCK;\n"); 203 } 204 } 205 } 206 207 virtual void thread_begin_allow(Node *n, String *f) { 208 if (!GetFlag(n, "feature:nothreadallow")) { 209 String *bb = Getattr(n, "feature:threadbeginallow"); 210 if (bb) { 211 Append(f, bb); 212 } else { 213 Append(f, "SWIG_PYTHON_THREAD_BEGIN_ALLOW;\n"); 214 } 215 } 216 } 217 218 virtual void thread_end_allow(Node *n, String *f) { 219 if (!GetFlag(n, "feature:nothreadallow")) { 220 String *eb = Getattr(n, "feature:threadendallow"); 221 if (eb) { 222 Append(f, eb); 223 } else { 224 Append(f, "SWIG_PYTHON_THREAD_END_ALLOW;\n"); 225 } 226 } 227 } 228 229 /* ------------------------------------------------------------ 230 * main() 231 * ------------------------------------------------------------ */ 232 233 virtual void main(int argc, char *argv[]) { 234 int cppcast = 1; 235 236 SWIG_library_directory("python"); 237 238 for (int i = 1; i < argc; i++) { 239 if (argv[i]) { 240 if (strcmp(argv[i], "-interface") == 0) { 241 if (argv[i + 1]) { 242 interface = NewString(argv[i + 1]); 243 Swig_mark_arg(i); 244 Swig_mark_arg(i + 1); 245 i++; 246 } else { 247 Swig_arg_error(); 248 } 249 /* end added */ 250 } else if (strcmp(argv[i], "-globals") == 0) { 251 if (argv[i + 1]) { 252 global_name = NewString(argv[i + 1]); 253 Swig_mark_arg(i); 254 Swig_mark_arg(i + 1); 255 i++; 256 } else { 257 Swig_arg_error(); 258 } 259 } else if ((strcmp(argv[i], "-shadow") == 0) || ((strcmp(argv[i], "-proxy") == 0))) { 260 shadow = 1; 261 Swig_mark_arg(i); 262 } else if ((strcmp(argv[i], "-new_repr") == 0) || (strcmp(argv[i], "-newrepr") == 0)) { 263 new_repr = 1; 264 Swig_mark_arg(i); 265 } else if ((strcmp(argv[i], "-old_repr") == 0) || (strcmp(argv[i], "-oldrepr") == 0)) { 266 new_repr = 0; 267 Swig_mark_arg(i); 268 } else if (strcmp(argv[i], "-classptr") == 0) { 269 classptr = 1; 270 Swig_mark_arg(i); 271 } else if ((strcmp(argv[i], "-noproxy") == 0)) { 272 shadow = 0; 273 Swig_mark_arg(i); 274 } else if ((strcmp(argv[i], "-noproxyimport") == 0)) { 275 shadowimport = 0; 276 Swig_mark_arg(i); 277 } else if (strcmp(argv[i], "-keyword") == 0) { 278 use_kw = 1; 279 SWIG_cparse_set_compact_default_args(1); 280 Swig_mark_arg(i); 281 } else if (strcmp(argv[i], "-classic") == 0) { 282 classic = 1; 283 modernargs = 0; 284 modern = 0; 285 Swig_mark_arg(i); 286 } else if (strcmp(argv[i], "-cppcast") == 0) { 287 cppcast = 1; 288 Swig_mark_arg(i); 289 } else if (strcmp(argv[i], "-nocppcast") == 0) { 290 cppcast = 0; 291 Swig_mark_arg(i); 292 } else if (strcmp(argv[i], "-outputtuple") == 0) { 293 outputtuple = 1; 294 Swig_mark_arg(i); 295 } else if (strcmp(argv[i], "-nooutputtuple") == 0) { 296 outputtuple = 0; 297 Swig_mark_arg(i); 298 } else if (strcmp(argv[i], "-nortti") == 0) { 299 nortti = 1; 300 Swig_mark_arg(i); 301 } else if (strcmp(argv[i], "-threads") == 0) { 302 threads = 1; 303 Swig_mark_arg(i); 304 } else if (strcmp(argv[i], "-nothreads") == 0) { 305 /* Turn off thread suppor mode */ 306 nothreads = 1; 307 Swig_mark_arg(i); 308 } else if (strcmp(argv[i], "-safecstrings") == 0) { 309 safecstrings = 1; 310 Swig_mark_arg(i); 311 } else if (strcmp(argv[i], "-nosafecstrings") == 0) { 312 safecstrings = 0; 313 Swig_mark_arg(i); 314 } else if (strcmp(argv[i], "-buildnone") == 0) { 315 buildnone = 1; 316 nobuildnone = 0; 317 Swig_mark_arg(i); 318 } else if (strcmp(argv[i], "-nobuildnone") == 0) { 319 buildnone = 0; 320 nobuildnone = 1; 321 Swig_mark_arg(i); 322 } else if (strcmp(argv[i], "-dirvtable") == 0) { 323 dirvtable = 1; 324 Swig_mark_arg(i); 325 } else if (strcmp(argv[i], "-nodirvtable") == 0) { 326 dirvtable = 0; 327 Swig_mark_arg(i); 328 } else if (strcmp(argv[i], "-fastunpack") == 0) { 329 fastunpack = 1; 330 Swig_mark_arg(i); 331 } else if (strcmp(argv[i], "-nofastunpack") == 0) { 332 fastunpack = 0; 333 Swig_mark_arg(i); 334 } else if (strcmp(argv[i], "-fastproxy") == 0) { 335 fastproxy = 1; 336 Swig_mark_arg(i); 337 } else if (strcmp(argv[i], "-nofastproxy") == 0) { 338 fastproxy = 0; 339 Swig_mark_arg(i); 340 } else if (strcmp(argv[i], "-fastquery") == 0) { 341 fastquery = 1; 342 Swig_mark_arg(i); 343 } else if (strcmp(argv[i], "-nofastquery") == 0) { 344 fastquery = 0; 345 Swig_mark_arg(i); 346 } else if (strcmp(argv[i], "-fastinit") == 0) { 347 fastinit = 1; 348 Swig_mark_arg(i); 349 } else if (strcmp(argv[i], "-nofastinit") == 0) { 350 fastinit = 0; 351 Swig_mark_arg(i); 352 } else if (strcmp(argv[i], "-olddefs") == 0) { 353 olddefs = 1; 354 Swig_mark_arg(i); 355 } else if (strcmp(argv[i], "-noolddefs") == 0) { 356 olddefs = 0; 357 Swig_mark_arg(i); 358 } else if (strcmp(argv[i], "-castmode") == 0) { 359 castmode = 1; 360 Swig_mark_arg(i); 361 } else if (strcmp(argv[i], "-nocastmode") == 0) { 362 castmode = 0; 363 Swig_mark_arg(i); 364 } else if (strcmp(argv[i], "-extranative") == 0) { 365 extranative = 1; 366 Swig_mark_arg(i); 367 } else if (strcmp(argv[i], "-noextranative") == 0) { 368 extranative = 0; 369 Swig_mark_arg(i); 370 } else if (strcmp(argv[i], "-modernargs") == 0) { 371 modernargs = 1; 372 Swig_mark_arg(i); 373 } else if (strcmp(argv[i], "-nomodernargs") == 0) { 374 modernargs = 0; 375 Swig_mark_arg(i); 376 } else if (strcmp(argv[i], "-aliasobj0") == 0) { 377 aliasobj0 = 1; 378 Swig_mark_arg(i); 379 } else if (strcmp(argv[i], "-noaliasobj0") == 0) { 380 aliasobj0 = 0; 381 Swig_mark_arg(i); 382 } else if (strcmp(argv[i], "-proxydel") == 0) { 383 proxydel = 1; 384 Swig_mark_arg(i); 385 } else if (strcmp(argv[i], "-noproxydel") == 0) { 386 proxydel = 0; 387 Swig_mark_arg(i); 388 } else if (strcmp(argv[i], "-modern") == 0) { 389 classic = 0; 390 modern = 1; 391 modernargs = 1; 392 Swig_mark_arg(i); 393 } else if (strcmp(argv[i], "-nomodern") == 0) { 394 modern = 0; 395 modernargs = 0; 396 Swig_mark_arg(i); 397 } else if (strcmp(argv[i], "-noh") == 0) { 398 no_header_file = 1; 399 Swig_mark_arg(i); 400 } else if ((strcmp(argv[i], "-new_vwm") == 0) || (strcmp(argv[i], "-newvwm") == 0)) { 401 /* Turn on new value wrapper mpde */ 402 Swig_value_wrapper_mode(1); 403 no_header_file = 1; 404 Swig_mark_arg(i); 405 } else if (strcmp(argv[i], "-O") == 0) { 406 classic = 0; 407 modern = 1; 408 dirvtable = 1; 409 safecstrings = 0; 410 buildnone = 0; 411 nobuildnone = 1; 412 classptr = 0; 413 proxydel = 0; 414 fastunpack = 1; 415 fastproxy = 1; 416 fastinit = 1; 417 fastquery = 1; 418 modernargs = 1; 419 Wrapper_fast_dispatch_mode_set(1); 420 Wrapper_virtual_elimination_mode_set(1); 421 Swig_mark_arg(i); 422 } else if (strcmp(argv[i], "-help") == 0) { 423 fputs(usage1, stdout); 424 fputs(usage2, stdout); 425 fputs(usage3, stdout); 426 } else if (strcmp(argv[i], "-py3") == 0) { 427 py3 = 1; 428 Swig_mark_arg(i); 429 } 430 431 } 432 } /* for */ 433 434 if (py3) { 435 /* force disable features that not compatible with Python 3.x */ 436 classic = 0; 437 } 438 439 if (cppcast) { 440 Preprocessor_define((DOH *) "SWIG_CPLUSPLUS_CAST", 0); 441 } 442 443 if (!global_name) 444 global_name = NewString("cvar"); 445 Preprocessor_define("SWIGPYTHON 1", 0); 446 SWIG_typemap_lang("python"); 447 SWIG_config_file("python.swg"); 448 allow_overloading(); 449 } 450 451 452 /* ------------------------------------------------------------ 453 * top() 454 * ------------------------------------------------------------ */ 455 456 virtual int top(Node *n) { 457 /* check if directors are enabled for this module. note: this 458 * is a "master" switch, without which no director code will be 459 * emitted. %feature("director") statements are also required 460 * to enable directors for individual classes or methods. 461 * 462 * use %module(directors="1") modulename at the start of the 463 * interface file to enable director generation. 464 */ 465 String *mod_docstring = NULL; 466 { 467 Node *mod = Getattr(n, "module"); 468 if (mod) { 469 Node *options = Getattr(mod, "options"); 470 if (options) { 471 int dirprot = 0; 472 if (Getattr(options, "dirprot")) { 473 dirprot = 1; 474 } 475 if (Getattr(options, "nodirprot")) { 476 dirprot = 0; 477 } 478 if (Getattr(options, "directors")) { 479 allow_directors(); 480 if (dirprot) 481 allow_dirprot(); 482 } 483 if (Getattr(options, "threads")) { 484 threads = 1; 485 } 486 if (Getattr(options, "castmode")) { 487 castmode = 1; 488 } 489 if (Getattr(options, "nocastmode")) { 490 castmode = 0; 491 } 492 if (Getattr(options, "extranative")) { 493 extranative = 1; 494 } 495 if (Getattr(options, "noextranative")) { 496 extranative = 0; 497 } 498 if (Getattr(options, "outputtuple")) { 499 outputtuple = 1; 500 } 501 if (Getattr(options, "nooutputtuple")) { 502 outputtuple = 0; 503 } 504 mod_docstring = Getattr(options, "docstring"); 505 package = Getattr(options, "package"); 506 } 507 } 508 } 509 510 /* Set comparison with none for ConstructorToFunction */ 511 setSubclassInstanceCheck(NewString("$arg != Py_None")); 512 513 /* Initialize all of the output files */ 514 String *outfile = Getattr(n, "outfile"); 515 String *outfile_h = !no_header_file ? Getattr(n, "outfile_h") : 0; 516 517 f_begin = NewFile(outfile, "w", SWIG_output_files()); 518 if (!f_begin) { 519 FileErrorDisplay(outfile); 520 SWIG_exit(EXIT_FAILURE); 521 } 522 f_runtime = NewString(""); 523 f_init = NewString(""); 524 f_header = NewString(""); 525 f_wrappers = NewString(""); 526 f_directors_h = NewString(""); 527 f_directors = NewString(""); 528 529 if (directorsEnabled()) { 530 if (!no_header_file) { 531 f_runtime_h = NewFile(outfile_h, "w", SWIG_output_files()); 532 if (!f_runtime_h) { 533 FileErrorDisplay(outfile_h); 534 SWIG_exit(EXIT_FAILURE); 535 } 536 } else { 537 f_runtime_h = f_runtime; 538 } 539 } 540 541 /* Register file targets with the SWIG file handler */ 542 Swig_register_filebyname("header", f_header); 543 Swig_register_filebyname("wrapper", f_wrappers); 544 Swig_register_filebyname("begin", f_begin); 545 Swig_register_filebyname("runtime", f_runtime); 546 Swig_register_filebyname("init", f_init); 547 Swig_register_filebyname("director", f_directors); 548 Swig_register_filebyname("director_h", f_directors_h); 549 550 const_code = NewString(""); 551 methods = NewString(""); 552 553 Swig_banner(f_begin); 554 555 Printf(f_runtime, "\n"); 556 Printf(f_runtime, "#define SWIGPYTHON\n"); 557 558 if (directorsEnabled()) { 559 Printf(f_runtime, "#define SWIG_DIRECTORS\n"); 560 } 561 562 if (nothreads) { 563 Printf(f_runtime, "#define SWIG_PYTHON_NO_THREADS\n"); 564 } else if (threads) { 565 Printf(f_runtime, "#define SWIG_PYTHON_THREADS\n"); 566 } 567 568 if (safecstrings) { 569 Printf(f_runtime, "#define SWIG_PYTHON_SAFE_CSTRINGS\n"); 570 } 571 572 if (buildnone) { 573 Printf(f_runtime, "#define SWIG_PYTHON_BUILD_NONE\n"); 574 } 575 576 if (nobuildnone) { 577 Printf(f_runtime, "#define SWIG_PYTHON_NO_BUILD_NONE\n"); 578 } 579 580 if (!dirvtable) { 581 Printf(f_runtime, "#define SWIG_PYTHON_DIRECTOR_NO_VTABLE\n"); 582 } 583 584 if (outputtuple) { 585 Printf(f_runtime, "#define SWIG_PYTHON_OUTPUT_TUPLE\n"); 586 } 587 588 if (nortti) { 589 Printf(f_runtime, "#ifndef SWIG_DIRECTOR_NORTTI\n"); 590 Printf(f_runtime, "#define SWIG_DIRECTOR_NORTTI\n"); 591 Printf(f_runtime, "#endif\n"); 592 } 593 594 if (castmode) { 595 Printf(f_runtime, "#define SWIG_CASTRANK_MODE\n"); 596 Printf(f_runtime, "#define SWIG_PYTHON_CAST_MODE\n"); 597 } 598 599 if (extranative) { 600 Printf(f_runtime, "#define SWIG_PYTHON_EXTRA_NATIVE_CONTAINERS\n"); 601 } 602 603 if (classic) { 604 Printf(f_runtime, "#define SWIG_PYTHON_CLASSIC\n"); 605 } 606 607 Printf(f_runtime, "\n"); 608 609 Printf(f_header, "#if (PY_VERSION_HEX <= 0x02000000)\n"); 610 Printf(f_header, "# if !defined(SWIG_PYTHON_CLASSIC)\n"); 611 Printf(f_header, "# error \"This python version requires swig to be run with the '-classic' option\"\n"); 612 Printf(f_header, "# endif\n"); 613 Printf(f_header, "#endif\n"); 614 615 if (modern) { 616 Printf(f_header, "#if (PY_VERSION_HEX <= 0x02020000)\n"); 617 Printf(f_header, "# error \"This python version requires swig to be run with the '-nomodern' option\"\n"); 618 Printf(f_header, "#endif\n"); 619 } 620 621 if (modernargs) { 622 Printf(f_header, "#if (PY_VERSION_HEX <= 0x02020000)\n"); 623 Printf(f_header, "# error \"This python version requires swig to be run with the '-nomodernargs' option\"\n"); 624 Printf(f_header, "#endif\n"); 625 } 626 627 if (fastunpack) { 628 Printf(f_header, "#ifndef METH_O\n"); 629 Printf(f_header, "# error \"This python version requires swig to be run with the '-nofastunpack' option\"\n"); 630 Printf(f_header, "#endif\n"); 631 } 632 633 if (fastquery) { 634 Printf(f_header, "#ifdef SWIG_TypeQuery\n"); 635 Printf(f_header, "# undef SWIG_TypeQuery\n"); 636 Printf(f_header, "#endif\n"); 637 Printf(f_header, "#define SWIG_TypeQuery SWIG_Python_TypeQuery\n"); 638 } 639 640 641 /* Set module name */ 642 module = Copy(Getattr(n, "name")); 643 mainmodule = Getattr(n, "name"); 644 645 if (directorsEnabled()) { 646 Swig_banner(f_directors_h); 647 Printf(f_directors_h, "\n"); 648 Printf(f_directors_h, "#ifndef SWIG_%s_WRAP_H_\n", module); 649 Printf(f_directors_h, "#define SWIG_%s_WRAP_H_\n\n", module); 650 if (dirprot_mode()) { 651 Printf(f_directors_h, "#include <map>\n"); 652 Printf(f_directors_h, "#include <string>\n\n"); 653 } 654 655 Printf(f_directors, "\n\n"); 656 Printf(f_directors, "/* ---------------------------------------------------\n"); 657 Printf(f_directors, " * C++ director class methods\n"); 658 Printf(f_directors, " * --------------------------------------------------- */\n\n"); 659 if (outfile_h) 660 Printf(f_directors, "#include \"%s\"\n\n", Swig_file_filename(outfile_h)); 661 } 662 663 /* If shadow classing is enabled, we're going to change the module name to "_module" */ 664 if (shadow) { 665 String *filen = NewStringf("%s%s.py", SWIG_output_directory(), Char(module)); 666 // If we don't have an interface then change the module name X to _X 667 if (interface) 668 module = interface; 669 else 670 Insert(module, 0, "_"); 671 if ((f_shadow_py = NewFile(filen, "w", SWIG_output_files())) == 0) { 672 FileErrorDisplay(filen); 673 SWIG_exit(EXIT_FAILURE); 674 } 675 Delete(filen); 676 filen = NULL; 677 678 f_shadow = NewString(""); 679 f_shadow_imports = NewString(""); 680 f_shadow_stubs = NewString(""); 681 682 Swig_register_filebyname("shadow", f_shadow); 683 Swig_register_filebyname("python", f_shadow); 684 685 Swig_banner_target_lang(f_shadow, "#"); 686 687 if (!modern) { 688 Printv(f_shadow, "# This file is compatible with both classic and new-style classes.\n", NIL); 689 } 690 691 if (mod_docstring && Len(mod_docstring)) { 692 Printv(f_shadow, "\n\"\"\"\n", mod_docstring, "\n\"\"\"\n", NIL); 693 Delete(mod_docstring); 694 mod_docstring = NULL; 695 } 696 697 Printv(f_shadow, "\nfrom sys import version_info\n", NULL); 698 699 if(fastproxy) 700 { 701 Printv(f_shadow, "if version_info >= (3,0,0):\n", NULL); 702 Printf(f_shadow, tab4 "new_instancemethod = lambda func, inst, cls: %s.SWIG_PyInstanceMethod_New(func)\n", module); 703 Printv(f_shadow, "else:\n", NULL); 704 Printv(f_shadow, tab4, "from new import instancemethod as new_instancemethod\n", NULL); 705 } 706 /* Import the C-extension module. This should be a relative import, 707 * since the shadow module may also have been imported by a relative 708 * import, and there is thus no guarantee that the C-extension is on 709 * sys.path. Relative imports must be explicitly specified from 2.6.0 710 * onwards (implicit relative imports will raise a DeprecationWarning 711 * in 2.6, and fail in 2.7 onwards), but the relative import syntax 712 * isn't available in python 2.4 or earlier, so we have to write some 713 * code conditional on the python version. 714 */ 715 Printv(f_shadow, "if version_info >= (2,6,0):\n", NULL); 716 Printv(f_shadow, tab4, "def swig_import_helper():\n", NULL); 717 Printv(f_shadow, tab8, "from os.path import dirname\n", NULL); 718 Printv(f_shadow, tab8, "import imp\n", NULL); 719 Printv(f_shadow, tab8, "fp = None\n", NULL); 720 Printv(f_shadow, tab8, "try:\n", NULL); 721 Printf(f_shadow, tab4 tab8 "fp, pathname, description = imp.find_module('%s', [dirname(__file__)])\n", module); 722 Printf(f_shadow, tab8 "except ImportError:\n"); 723 /* At here, the module may already loaded, so simply import it. */ 724 Printf(f_shadow, tab4 tab8 "import %s\n", module); 725 Printf(f_shadow, tab4 tab8 "return %s\n", module); 726 Printv(f_shadow, tab8 "if fp is not None:\n", NULL); 727 Printv(f_shadow, tab4 tab8 "try:\n", NULL); 728 Printf(f_shadow, tab8 tab8 "_mod = imp.load_module('%s', fp, pathname, description)\n", module); 729 Printv(f_shadow, tab4 tab8, "finally:\n", NULL); 730 Printv(f_shadow, tab8 tab8, "fp.close()\n", NULL); 731 Printv(f_shadow, tab4 tab8, "return _mod\n", NULL); 732 Printf(f_shadow, tab4 "%s = swig_import_helper()\n", module); 733 Printv(f_shadow, tab4, "del swig_import_helper\n", NULL); 734 Printv(f_shadow, "else:\n", NULL); 735 Printf(f_shadow, tab4 "import %s\n", module); 736 737 /* Delete the version_info symbol since we don't use it elsewhere in the 738 * module. */ 739 Printv(f_shadow, "del version_info\n", NULL); 740 741 if (modern || !classic) { 742 Printv(f_shadow, "try:\n", tab4, "_swig_property = property\n", "except NameError:\n", tab4, "pass # Python < 2.2 doesn't have 'property'.\n", NULL); 743 } 744 /* if (!modern) */ 745 /* always needed, a class can be forced to be no-modern, such as an exception */ 746 { 747 // Python-2.2 object hack 748 Printv(f_shadow, 749 "def _swig_setattr_nondynamic(self,class_type,name,value,static=1):\n", 750 tab4, "if (name == \"thisown\"): return self.this.own(value)\n", 751 tab4, "if (name == \"this\"):\n", tab4, tab4, "if type(value).__name__ == 'SwigPyObject':\n", tab4, tab8, "self.__dict__[name] = value\n", 752#ifdef USE_THISOWN 753 tab4, tab8, "if hasattr(value,\"thisown\"): self.__dict__[\"thisown\"] = value.thisown\n", tab4, tab8, "del value.thisown\n", 754#endif 755 tab4, tab8, "return\n", tab4, "method = class_type.__swig_setmethods__.get(name,None)\n", tab4, "if method: return method(self,value)\n", 756#ifdef USE_THISOWN 757 tab4, "if (not static) or hasattr(self,name) or (name == \"thisown\"):\n", 758#else 759 tab4, "if (not static) or hasattr(self,name):\n", 760#endif 761 tab4, tab4, "self.__dict__[name] = value\n", 762 tab4, "else:\n", 763 tab4, tab4, "raise AttributeError(\"You cannot add attributes to %s\" % self)\n\n", 764 "def _swig_setattr(self,class_type,name,value):\n", tab4, "return _swig_setattr_nondynamic(self,class_type,name,value,0)\n\n", NIL); 765 766 Printv(f_shadow, 767 "def _swig_getattr(self,class_type,name):\n", 768 tab4, "if (name == \"thisown\"): return self.this.own()\n", 769 tab4, "method = class_type.__swig_getmethods__.get(name,None)\n", 770 tab4, "if method: return method(self)\n", tab4, "raise AttributeError(name)\n\n", NIL); 771 772 Printv(f_shadow, 773 "def _swig_repr(self):\n", 774 tab4, "try: strthis = \"proxy of \" + self.this.__repr__()\n", 775 tab4, "except: strthis = \"\"\n", tab4, "return \"<%s.%s; %s >\" % (self.__class__.__module__, self.__class__.__name__, strthis,)\n\n", NIL); 776 777 if (!classic) { 778 /* Usage of types.ObjectType is deprecated. 779 * But don't sure wether this would broken old Python? 780 */ 781 Printv(f_shadow, 782// "import types\n", 783 "try:\n", 784// " _object = types.ObjectType\n", 785 " _object = object\n", 786 " _newclass = 1\n", "except AttributeError:\n", " class _object : pass\n", " _newclass = 0\n", 787// "del types\n", 788 "\n\n", NIL); 789 } 790 } 791 if (modern) { 792 Printv(f_shadow, "def _swig_setattr_nondynamic_method(set):\n", tab4, "def set_attr(self,name,value):\n", 793#ifdef USE_THISOWN 794 tab4, tab4, "if hasattr(self,name) or (name in (\"this\", \"thisown\")):\n", 795#else 796 tab4, tab4, "if (name == \"thisown\"): return self.this.own(value)\n", tab4, tab4, "if hasattr(self,name) or (name == \"this\"):\n", 797#endif 798 tab4, tab4, tab4, "set(self,name,value)\n", 799 tab4, tab4, "else:\n", 800 tab4, tab4, tab4, "raise AttributeError(\"You cannot add attributes to %s\" % self)\n", tab4, "return set_attr\n\n\n", NIL); 801 } 802 803 if (directorsEnabled()) { 804 // Try loading weakref.proxy, which is only available in Python 2.1 and higher 805 Printv(f_shadow, 806 "try:\n", tab4, "import weakref\n", tab4, "weakref_proxy = weakref.proxy\n", "except:\n", tab4, "weakref_proxy = lambda x: x\n", "\n\n", NIL); 807 } 808 // Include some information in the code 809 Printf(f_header, "\n/*-----------------------------------------------\n @(target):= %s.so\n\ 810 ------------------------------------------------*/\n", module); 811 812 } 813 814 Printf(f_header, "#if PY_VERSION_HEX >= 0x03000000\n"); 815 Printf(f_header, "# define SWIG_init PyInit_%s\n\n", module); 816 Printf(f_header, "#else\n"); 817 Printf(f_header, "# define SWIG_init init%s\n\n", module); 818 Printf(f_header, "#endif\n"); 819 Printf(f_header, "#define SWIG_name \"%s\"\n", module); 820 821 Printf(f_wrappers, "#ifdef __cplusplus\n"); 822 Printf(f_wrappers, "extern \"C\" {\n"); 823 Printf(f_wrappers, "#endif\n"); 824 Append(const_code, "static swig_const_info swig_const_table[] = {\n"); 825 Append(methods, "static PyMethodDef SwigMethods[] = {\n"); 826 827 /* the method exported for replacement of new.instancemethod in Python 3 */ 828 add_pyinstancemethod_new(); 829 830 /* emit code */ 831 Language::top(n); 832 833 if (directorsEnabled()) { 834 // Insert director runtime into the f_runtime file (make it occur before %header section) 835 Swig_insert_file("director.swg", f_runtime); 836 } 837 838 /* Close language module */ 839 Append(methods, "\t { NULL, NULL, 0, NULL }\n"); 840 Append(methods, "};\n"); 841 Printf(f_wrappers, "%s\n", methods); 842 843 SwigType_emit_type_table(f_runtime, f_wrappers); 844 845 Append(const_code, "{0, 0, 0, 0.0, 0, 0}};\n"); 846 Printf(f_wrappers, "%s\n", const_code); 847 initialize_threads(f_init); 848 849 Printf(f_init, "#if PY_VERSION_HEX >= 0x03000000\n"); 850 Printf(f_init, " return m;\n"); 851 Printf(f_init, "#else\n"); 852 Printf(f_init, " return;\n"); 853 Printf(f_init, "#endif\n"); 854 Printf(f_init, "}\n"); 855 856 Printf(f_wrappers, "#ifdef __cplusplus\n"); 857 Printf(f_wrappers, "}\n"); 858 Printf(f_wrappers, "#endif\n"); 859 860 if (shadow) { 861 Printv(f_shadow_py, f_shadow, "\n", NIL); 862 Printv(f_shadow_py, f_shadow_stubs, "\n", NIL); 863 864 Close(f_shadow_py); 865 Delete(f_shadow_py); 866 } 867 868 /* Close all of the files */ 869 Dump(f_runtime, f_begin); 870 Dump(f_header, f_begin); 871 872 if (directorsEnabled()) { 873 Dump(f_directors_h, f_runtime_h); 874 Printf(f_runtime_h, "\n"); 875 Printf(f_runtime_h, "#endif\n"); 876 if (f_runtime_h != f_begin) 877 Close(f_runtime_h); 878 Dump(f_directors, f_begin); 879 } 880 881 Dump(f_wrappers, f_begin); 882 Wrapper_pretty_print(f_init, f_begin); 883 884 Delete(f_header); 885 Delete(f_wrappers); 886 Delete(f_init); 887 Delete(f_directors); 888 Delete(f_directors_h); 889 890 Close(f_begin); 891 Delete(f_runtime); 892 Delete(f_begin); 893 894 return SWIG_OK; 895 } 896 897 /* ------------------------------------------------------------ 898 * Emit the wrapper for PyInstanceMethod_New to MethodDef array. 899 * This wrapper is used to implement -fastproxy, 900 * as a replacement of new.instancemethod in Python 3. 901 * ------------------------------------------------------------ */ 902 int add_pyinstancemethod_new() 903 { 904 String* name = NewString("SWIG_PyInstanceMethod_New"); 905 Printf(methods, "\t { (char *)\"%s\", (PyCFunction)%s, METH_O, NULL},\n", name, name); 906 Delete(name); 907 return 0; 908 } 909 910 /* ------------------------------------------------------------ 911 * importDirective() 912 * ------------------------------------------------------------ */ 913 914 virtual int importDirective(Node *n) { 915 if (shadow) { 916 String *modname = Getattr(n, "module"); 917 918 if (modname) { 919 String *import = NewString("import "); 920 921 // Find the module node for this imported module. It should be the 922 // first child but search just in case. 923 Node *mod = firstChild(n); 924 while (mod && Strcmp(nodeType(mod), "module") != 0) 925 mod = nextSibling(mod); 926 927 // Is the imported module in another package? (IOW, does it use the 928 // %module(package="name") option and it's different than the package 929 // of this module.) 930 Node *options = Getattr(mod, "options"); 931 String *pkg = options ? Getattr(options, "package") : 0; 932 if (pkg && (!package || Strcmp(pkg, package) != 0)) { 933 Printf(import, "%s.", pkg); 934 } 935 // finally, output the name of the imported module 936 if (shadowimport) { 937 if (!options || (!Getattr(options, "noshadow") && !Getattr(options, "noproxy"))) { 938 Printf(import, "_%s\n", modname); 939 if (!Strstr(f_shadow_imports, import)) { 940 if (pkg && (!package || Strcmp(pkg, package) != 0)) { 941 Printf(f_shadow, "import %s.%s\n", pkg, modname); 942 } else { 943 Printf(f_shadow, "import %s\n", modname); 944 } 945 Printv(f_shadow_imports, import, NULL); 946 } 947 } 948 } 949 950 Delete(import); 951 } 952 } 953 return Language::importDirective(n); 954 } 955 956 /* ------------------------------------------------------------ 957 * funcCall() 958 * Emit shadow code to call a function in the extension 959 * module. Using proper argument and calling style for 960 * given node n. 961 * ------------------------------------------------------------ */ 962 String *funcCall(String *name, String *parms) { 963 String *str = NewString(""); 964 965 Printv(str, module, ".", name, "(", parms, ")", NIL); 966 return str; 967 } 968 969 970 /* ------------------------------------------------------------ 971 * pythoncode() - Output python code into the shadow file 972 * ------------------------------------------------------------ */ 973 974 String *pythoncode(String *code, const_String_or_char_ptr indent) { 975 String *out = NewString(""); 976 String *temp; 977 char *t; 978 if (!indent) 979 indent = ""; 980 981 temp = NewString(code); 982 983 t = Char(temp); 984 if (*t == '{') { 985 Delitem(temp, 0); 986 Delitem(temp, DOH_END); 987 } 988 989 /* Split the input text into lines */ 990 List *clist = DohSplitLines(temp); 991 Delete(temp); 992 int initial = 0; 993 String *s = 0; 994 Iterator si; 995 /* Get the initial indentation */ 996 997 for (si = First(clist); si.item; si = Next(si)) { 998 s = si.item; 999 if (Len(s)) { 1000 char *c = Char(s); 1001 while (*c) { 1002 if (!isspace(*c)) 1003 break; 1004 initial++; 1005 c++; 1006 } 1007 if (*c && !isspace(*c)) 1008 break; 1009 else { 1010 initial = 0; 1011 } 1012 } 1013 } 1014 while (si.item) { 1015 s = si.item; 1016 if (Len(s) > initial) { 1017 char *c = Char(s); 1018 c += initial; 1019 Printv(out, indent, c, "\n", NIL); 1020 } else { 1021 Printv(out, "\n", NIL); 1022 } 1023 si = Next(si); 1024 } 1025 Delete(clist); 1026 return out; 1027 } 1028 1029 1030 /* ------------------------------------------------------------ 1031 * autodoc level declarations 1032 * ------------------------------------------------------------ */ 1033 1034 enum autodoc_l { 1035 NO_AUTODOC = -2, // no autodoc 1036 STRING_AUTODOC = -1, // use provided string 1037 NAMES_AUTODOC = 0, // only parameter names 1038 TYPES_AUTODOC = 1, // parameter names and types 1039 EXTEND_AUTODOC = 2, // extended documentation and parameter names 1040 EXTEND_TYPES_AUTODOC = 3 // extended documentation and parameter types + names 1041 }; 1042 1043 1044 autodoc_l autodoc_level(String *autodoc) { 1045 autodoc_l dlevel = NO_AUTODOC; 1046 if (autodoc) { 1047 char *c = Char(autodoc); 1048 if (c && isdigit(c[0])) { 1049 dlevel = (autodoc_l) atoi(c); 1050 } else { 1051 if (strcmp(c, "extended") == 0) { 1052 dlevel = EXTEND_AUTODOC; 1053 } else { 1054 dlevel = STRING_AUTODOC; 1055 } 1056 } 1057 } 1058 return dlevel; 1059 } 1060 1061 1062 /* ------------------------------------------------------------ 1063 * have_docstring() 1064 * Check if there is a docstring directive and it has text, 1065 * or there is an autodoc flag set 1066 * ------------------------------------------------------------ */ 1067 1068 bool have_docstring(Node *n) { 1069 String *str = Getattr(n, "feature:docstring"); 1070 return (str != NULL && Len(str) > 0) || (Getattr(n, "feature:autodoc") && !GetFlag(n, "feature:noautodoc")); 1071 } 1072 1073 /* ------------------------------------------------------------ 1074 * docstring() 1075 * Get the docstring text, stripping off {} if neccessary, 1076 * and enclose in triple double quotes. If autodoc is also 1077 * set then it will build a combined docstring. 1078 * ------------------------------------------------------------ */ 1079 1080 String *docstring(Node *n, autodoc_t ad_type, const String *indent, bool use_triple = true) { 1081 String *str = Getattr(n, "feature:docstring"); 1082 bool have_ds = (str != NULL && Len(str) > 0); 1083 bool have_auto = (Getattr(n, "feature:autodoc") && !GetFlag(n, "feature:noautodoc")); 1084 const char *triple_double = use_triple ? "\"\"\"" : ""; 1085 String *autodoc = NULL; 1086 String *doc = NULL; 1087 1088 if (have_ds) { 1089 char *t = Char(str); 1090 if (*t == '{') { 1091 Delitem(str, 0); 1092 Delitem(str, DOH_END); 1093 } 1094 } 1095 1096 if (have_auto) { 1097 autodoc = make_autodoc(n, ad_type); 1098 have_auto = (autodoc != NULL && Len(autodoc) > 0); 1099 } 1100 // If there is more than one line then make docstrings like this: 1101 // 1102 // """ 1103 // This is line1 1104 // And here is line2 followed by the rest of them 1105 // """ 1106 // 1107 // otherwise, put it all on a single line 1108 // 1109 if (have_auto && have_ds) { // Both autodoc and docstring are present 1110 doc = NewString(""); 1111 Printv(doc, triple_double, "\n", pythoncode(autodoc, indent), "\n", pythoncode(str, indent), indent, triple_double, NIL); 1112 } else if (!have_auto && have_ds) { // only docstring 1113 if (Strchr(str, '\n') == NULL) { 1114 doc = NewStringf("%s%s%s", triple_double, str, triple_double); 1115 } else { 1116 doc = NewString(""); 1117 Printv(doc, triple_double, "\n", pythoncode(str, indent), indent, triple_double, NIL); 1118 } 1119 } else if (have_auto && !have_ds) { // only autodoc 1120 if (Strchr(autodoc, '\n') == NULL) { 1121 doc = NewStringf("%s%s%s", triple_double, autodoc, triple_double); 1122 } else { 1123 doc = NewString(""); 1124 Printv(doc, triple_double, "\n", pythoncode(autodoc, indent), indent, triple_double, NIL); 1125 } 1126 } else 1127 doc = NewString(""); 1128 1129 // Save the generated strings in the parse tree in case they are used later 1130 // by post processing tools 1131 Setattr(n, "python:docstring", doc); 1132 Setattr(n, "python:autodoc", autodoc); 1133 return doc; 1134 } 1135 1136 /* ----------------------------------------------------------------------------- 1137 * makeParameterName() 1138 * Note: the generated name should consist with that in kwnames[] 1139 * 1140 * Inputs: 1141 * n - Node 1142 * p - parameter node 1143 * arg_num - parameter argument number 1144 * Return: 1145 * arg - a unique parameter name 1146 * ----------------------------------------------------------------------------- */ 1147 1148 String *makeParameterName(ParmList *plist, Parm *p, int arg_num) { 1149 String *arg = 0; 1150 String *pn = Swig_name_make(p, 0, Getattr(p, "name"), 0, 0); 1151 // Use C parameter name unless it is a duplicate or an empty parameter name 1152 int count = 0; 1153 if ( SwigType_isvarargs(Getattr(p, "type")) ) { 1154 return NewString("*args"); 1155 } 1156 while (plist) { 1157 if ((Cmp(pn, Getattr(plist, "name")) == 0)) 1158 count++; 1159 plist = nextSibling(plist); 1160 } 1161 arg = (!pn || !Len(pn) || (count > 1)) ? NewStringf("arg%d", arg_num) : Copy(pn); 1162 return arg; 1163 } 1164 1165 1166 /* ------------------------------------------------------------ 1167 * make_autodocParmList() 1168 * Generate the documentation for the function parameters 1169 * Parameters: 1170 * func_annotation: Function annotation support 1171 * ------------------------------------------------------------ */ 1172 1173 String *make_autodocParmList(Node *n, bool showTypes, bool calling=false, bool func_annotation=false) { 1174 1175 1176 String *doc = NewString(""); 1177 String *pdocs = Copy(Getattr(n, "feature:pdocs")); 1178 ParmList *plist = CopyParmList(Getattr(n, "parms")); 1179 Parm *p; 1180 Parm *pnext; 1181 Node *lookup; 1182 1183 1184 int lines = 0; 1185 int arg_num = 0; 1186 const int maxwidth = 50; 1187 1188 if(calling) 1189 func_annotation = false; 1190 1191 if (pdocs) 1192 Append(pdocs, "\n"); 1193 1194 Swig_typemap_attach_parms("in", plist, 0); 1195 Swig_typemap_attach_parms("doc", plist, 0); 1196 1197 if (Strcmp(ParmList_protostr(plist), "void")==0) { 1198 //No parameters actually 1199 return doc; 1200 } 1201 1202 for (p = plist; p; p = pnext) { 1203 1204 String *tm = Getattr(p, "tmap:in"); 1205 if (tm) { 1206 pnext = Getattr(p, "tmap:in:next"); 1207 if (checkAttribute(p, "tmap:in:numinputs", "0")) { 1208 continue; 1209 } 1210 } else { 1211 pnext = nextSibling(p); 1212 } 1213 1214 String *name = 0; 1215 String *type = 0; 1216 String *value = 0; 1217 String *ptype = 0; 1218 String *pdoc = Getattr(p, "tmap:doc"); 1219 if (pdoc) { 1220 name = Getattr(p, "tmap:doc:name"); 1221 type = Getattr(p, "tmap:doc:type"); 1222 value = Getattr(p, "tmap:doc:value"); 1223 ptype = Getattr(p, "tmap:doc:pytype"); 1224 } 1225 1226 name = name ? name : Getattr(p, "name"); 1227 type = type ? type : Getattr(p, "type"); 1228 value = value ? value : Getattr(p, "value"); 1229 1230 name = makeParameterName(plist, p, arg_num); 1231 // Reset it for convinient in further use. (mainly for makeParameterName()) 1232 // Since the plist is created by CopyParmList, 1233 // we can hope that the set would have no side effect 1234 Setattr(p, "name", name); 1235 1236 arg_num++; 1237 1238 1239 if (Len(doc)) { 1240 // add a comma to the previous one if any 1241 Append(doc, ", "); 1242 1243 // Do we need to wrap a long line? 1244 if ((Len(doc) - lines * maxwidth) > maxwidth) { 1245 Printf(doc, "\n%s", tab4); 1246 lines += 1; 1247 } 1248 } 1249 1250 type = SwigType_base(type); 1251 lookup = Swig_symbol_clookup(type, 0); 1252 if (lookup) 1253 type = Getattr(lookup, "sym:name"); 1254 1255 // Do the param type too? 1256 if (showTypes) 1257 Printf(doc, "%s ", type); 1258 1259 1260 Append(doc, name); 1261 if (pdoc) { 1262 if (!pdocs) 1263 pdocs = NewString("Parameters:\n"); 1264 Printf(pdocs, " %s\n", pdoc); 1265 } 1266 1267 // Write the function annoation 1268 if (func_annotation) 1269 Printf(doc, " : '%s'", type); 1270 1271 // Write default value 1272 if (value && !calling) { 1273 String* pv = pyvalue(value, Getattr(p, "type")); 1274 if (pv) 1275 value = pv; 1276 else { 1277 lookup = Swig_symbol_clookup(value, 0); 1278 if (lookup) { 1279 value = Getattr(lookup, "sym:name"); 1280 } 1281 } 1282 Printf(doc, " = %s", value); 1283 } 1284 } 1285 if (pdocs) 1286 Setattr(n, "feature:pdocs", pdocs); 1287 Delete(plist); 1288 return doc; 1289 } 1290 1291 /* ------------------------------------------------------------ 1292 * make_autodoc() 1293 * Build a docstring for the node, using parameter and other 1294 * info in the parse tree. If the value of the autodoc 1295 * attribute is "0" then do not include parameter types, if 1296 * it is "1" (the default) then do. If it has some other 1297 * value then assume it is supplied by the extension writer 1298 * and use it directly. 1299 * ------------------------------------------------------------ */ 1300 1301 String *make_autodoc(Node *n, autodoc_t ad_type) { 1302 int extended = 0; 1303 // If the function is overloaded then this funciton is called 1304 // for the last one. Rewind to the first so the docstrings are 1305 // in order. 1306 while (Getattr(n, "sym:previousSibling")) 1307 n = Getattr(n, "sym:previousSibling"); 1308 1309 String *doc = NewString(""); 1310 while (n) { 1311 bool showTypes = false; 1312 bool skipAuto = false; 1313 String *autodoc = Getattr(n, "feature:autodoc"); 1314 autodoc_l dlevel = autodoc_level(autodoc); 1315 switch (dlevel) { 1316 case NO_AUTODOC: 1317 break; 1318 case NAMES_AUTODOC: 1319 showTypes = false; 1320 break; 1321 case TYPES_AUTODOC: 1322 showTypes = true; 1323 break; 1324 case EXTEND_AUTODOC: 1325 extended = 1; 1326 showTypes = false; 1327 break; 1328 case EXTEND_TYPES_AUTODOC: 1329 extended = 1; 1330 showTypes = true; 1331 break; 1332 case STRING_AUTODOC: 1333 Append(doc, autodoc); 1334 skipAuto = true; 1335 break; 1336 } 1337 1338 if (!skipAuto) { 1339 String *symname = Getattr(n, "sym:name"); 1340 SwigType *type = Getattr(n, "type"); 1341 1342 if (type) { 1343 if (Strcmp(type, "void") == 0) 1344 type = NULL; 1345 else { 1346 type = SwigType_base(type); 1347 Node *lookup = Swig_symbol_clookup(type, 0); 1348 if (lookup) 1349 type = Getattr(lookup, "sym:name"); 1350 } 1351 } 1352 1353 switch (ad_type) { 1354 case AUTODOC_CLASS: 1355 { 1356 // Only do the autodoc if there isn't a docstring for the class 1357 String *str = Getattr(n, "feature:docstring"); 1358 if (str == NULL || Len(str) == 0) { 1359 if (CPlusPlus) { 1360 Printf(doc, "Proxy of C++ %s class", real_classname); 1361 } else { 1362 Printf(doc, "Proxy of C %s struct", real_classname); 1363 } 1364 } 1365 } 1366 break; 1367 case AUTODOC_CTOR: 1368 if (Strcmp(class_name, symname) == 0) { 1369 String *paramList = make_autodocParmList(n, showTypes); 1370 if (Len(paramList)) 1371 Printf(doc, "__init__(self, %s) -> %s", paramList, class_name); 1372 else 1373 Printf(doc, "__init__(self) -> %s", class_name); 1374 } else 1375 Printf(doc, "%s(%s) -> %s", symname, make_autodocParmList(n, showTypes), class_name); 1376 break; 1377 1378 case AUTODOC_DTOR: 1379 Append(doc, "__del__(self)"); 1380 break; 1381 1382 case AUTODOC_STATICFUNC: 1383 Printf(doc, "%s(%s)", symname, make_autodocParmList(n, showTypes)); 1384 if (type) 1385 Printf(doc, " -> %s", type); 1386 break; 1387 1388 case AUTODOC_FUNC: 1389 Printf(doc, "%s(%s)", symname, make_autodocParmList(n, showTypes)); 1390 if (type) 1391 Printf(doc, " -> %s", type); 1392 break; 1393 1394 case AUTODOC_METHOD: 1395 String *paramList = make_autodocParmList(n, showTypes); 1396 if (Len(paramList)) 1397 Printf(doc, "%s(self, %s)", symname, paramList); 1398 else 1399 Printf(doc, "%s(self)", symname); 1400 if (type) 1401 Printf(doc, " -> %s", type); 1402 break; 1403 } 1404 } 1405 if (extended) { 1406 String *pdocs = Getattr(n, "feature:pdocs"); 1407 if (pdocs) { 1408 Printv(doc, "\n", pdocs, NULL); 1409 } 1410 } 1411 1412 // if it's overloaded then get the next decl and loop around again 1413 n = Getattr(n, "sym:nextSibling"); 1414 if (n) 1415 Append(doc, "\n"); 1416 } 1417 1418 return doc; 1419 } 1420 1421 /* ------------------------------------------------------------ 1422 * pyvalue() 1423 * Check if string v can be a Python value literal, 1424 * (eg. number or string), or translate it to a Python literal. 1425 * ------------------------------------------------------------ */ 1426 String* pyvalue(String *v, SwigType *t) 1427 { 1428 if (v && Len(v)>0) { 1429 char fc = (Char(v))[0]; 1430 if (('0'<=fc && fc<='9') || '\''==fc || '"'==fc) { 1431 /* number or string (or maybe NULL pointer)*/ 1432 if (SwigType_ispointer(t) && Strcmp(v, "0")==0) 1433 return NewString("None"); 1434 else 1435 return v; 1436 } 1437 if (Strcmp(v, "true")==0 || Strcmp(v, "FALSE")==0) 1438 return NewString("True"); 1439 if (Strcmp(v, "false")==0 || Strcmp(v, "FALSE")==0) 1440 return NewString("False"); 1441 if (Strcmp(v, "NULL")==0) 1442 return NewString("None"); 1443 } 1444 return 0; 1445 } 1446 /* ------------------------------------------------------------ 1447 * is_primitive_defaultargs() 1448 * Check if all the default args have primitive type. 1449 * (So we can generate proper parameter list with default 1450 * values..) 1451 * ------------------------------------------------------------ */ 1452 bool is_primitive_defaultargs(Node *n) 1453 { 1454 ParmList *plist = CopyParmList(Getattr(n, "parms")); 1455 Parm *p; 1456 Parm *pnext; 1457 1458 Swig_typemap_attach_parms("in", plist, 0); 1459 for (p = plist; p; p = pnext) { 1460 String *tm = Getattr(p, "tmap:in"); 1461 if (tm) { 1462 pnext = Getattr(p, "tmap:in:next"); 1463 if (checkAttribute(p, "tmap:in:numinputs", "0")) { 1464 continue; 1465 } 1466 } else { 1467 pnext = nextSibling(p); 1468 } 1469 String *type = Getattr(p, "type"); 1470 String *value = Getattr(p, "value"); 1471 if (!pyvalue(value, type)) 1472 return false; 1473 } 1474 return true; 1475 } 1476 1477 1478 /* ------------------------------------------------------------ 1479 * is_real_overloaded() 1480 * Check if the function is overloaded, but not just have some 1481 * siblings generated due to the original function have 1482 * default arguments. 1483 * ------------------------------------------------------------ */ 1484 bool is_real_overloaded(Node *n) 1485 { 1486 Node *h = Getattr(n, "sym:overloaded"); 1487 Node *i; 1488 if (!h) 1489 return false; 1490 1491 i = Getattr(h, "sym:nextSibling"); 1492 while (i) { 1493 Node *nn = Getattr(i, "defaultargs"); 1494 if (nn != h) { 1495 /* Check if overloaded function has defaultargs and 1496 * pointed to the first overloaded. */ 1497 return true; 1498 } 1499 i = Getattr(i, "sym:nextSibling"); 1500 } 1501 1502 return false; 1503 } 1504 1505 /* ------------------------------------------------------------ 1506 * make_pyParmList() 1507 * Generate parameter list for Python functions or methods, 1508 * reuse make_autodocParmList() to do so. 1509 * ------------------------------------------------------------ */ 1510 String* make_pyParmList(Node *n, bool in_class, bool is_calling, int kw) 1511 { 1512 /* Get the original function for a defaultargs copy, 1513 * see default_arguments() in parser.y. */ 1514 Node *nn = Getattr(n, "defaultargs"); 1515 if (nn) n = nn; 1516 1517 /* For overloaded function, just use *args */ 1518 if (is_real_overloaded(n) || 1519 GetFlag(n, "feature:compactdefaultargs") || 1520 !is_primitive_defaultargs(n)) 1521 { 1522 String *parms = NewString(""); 1523 if(in_class) 1524 Printf(parms, "self, "); 1525 Printf(parms, "*args"); 1526 if (kw) 1527 Printf(parms, ", **kwargs"); 1528 return parms; 1529 } 1530 1531 bool funcanno = py3 ? true : false; 1532 String *params = NewString(""); 1533 String *_params = make_autodocParmList(n, false, is_calling, funcanno); 1534 1535 if (in_class) 1536 { 1537 Printf(params, "self"); 1538 if(Len(_params) > 0) 1539 Printf(params, ", "); 1540 } 1541 1542 Printv(params, _params, NULL); 1543 1544 return params; 1545 } 1546 1547 /* ------------------------------------------------------------ 1548 * have_pythonprepend() 1549 * Check if there is a %pythonprepend directive and it has text 1550 * ------------------------------------------------------------ */ 1551 1552 bool have_pythonprepend(Node *n) { 1553 String *str = Getattr(n, "feature:pythonprepend"); 1554 return (str != NULL && Len(str) > 0); 1555 } 1556 1557 /* ------------------------------------------------------------ 1558 * pythonprepend() 1559 * Get the %pythonprepend code, stripping off {} if neccessary 1560 * ------------------------------------------------------------ */ 1561 1562 String *pythonprepend(Node *n) { 1563 String *str = Getattr(n, "feature:pythonprepend"); 1564 char *t = Char(str); 1565 if (*t == '{') { 1566 Delitem(str, 0); 1567 Delitem(str, DOH_END); 1568 } 1569 return str; 1570 } 1571 1572 /* ------------------------------------------------------------ 1573 * have_pythonappend() 1574 * Check if there is a %pythonappend directive and it has text 1575 * ------------------------------------------------------------ */ 1576 1577 bool have_pythonappend(Node *n) { 1578 String *str = Getattr(n, "feature:pythonappend"); 1579 if (!str) 1580 str = Getattr(n, "feature:addtofunc"); 1581 return (str != NULL && Len(str) > 0); 1582 } 1583 1584 /* ------------------------------------------------------------ 1585 * pythonappend() 1586 * Get the %pythonappend code, stripping off {} if neccessary 1587 * ------------------------------------------------------------ */ 1588 1589 String *pythonappend(Node *n) { 1590 String *str = Getattr(n, "feature:pythonappend"); 1591 if (!str) 1592 str = Getattr(n, "feature:addtofunc"); 1593 1594 char *t = Char(str); 1595 if (*t == '{') { 1596 Delitem(str, 0); 1597 Delitem(str, DOH_END); 1598 } 1599 return str; 1600 } 1601 1602 /* ------------------------------------------------------------ 1603 * have_addtofunc() 1604 * Check if there is a %addtofunc directive and it has text 1605 * ------------------------------------------------------------ */ 1606 1607 bool have_addtofunc(Node *n) { 1608 return have_pythonappend(n) || have_pythonprepend(n) || have_docstring(n); 1609 } 1610 1611 1612 /* ------------------------------------------------------------ 1613 * returnTypeAnnotation() 1614 * Helper function for constructing the function annotation 1615 * of the returning type, return a empty string for Python 2.x 1616 * ------------------------------------------------------------ */ 1617 String* returnTypeAnnotation(Node *n) 1618 { 1619 String *ret=0; 1620 Parm *p = Getattr(n, "parms"); 1621 String *tm; 1622 /* Try to guess the returning type by argout typemap, 1623 * however the result may not accurate. */ 1624 while (p) { 1625 if ((tm=Getattr(p, "tmap:argout:match_type"))) { 1626 tm = SwigType_str(tm, 0); 1627 if (ret) 1628 Printv(ret, ", ", tm, NULL); 1629 else 1630 ret = tm; 1631 p = Getattr(p, "tmap:argout:next"); 1632 } else { 1633 p = nextSibling(p); 1634 } 1635 } 1636 /* If no argout typemap, then get the returning type from 1637 * the function prototype. */ 1638 if (!ret) { 1639 ret = Getattr(n, "type"); 1640 if (ret) ret = SwigType_str(ret, 0); 1641 } 1642 return (ret && py3) ? NewStringf(" -> \"%s\" ", ret) 1643 : NewString(""); 1644 } 1645 1646 /* ------------------------------------------------------------ 1647 * emitFunctionShadowHelper() 1648 * Refactoring some common code out of functionWrapper and 1649 * dispatchFunction that writes the proxy code for non-member 1650 * functions. 1651 * ------------------------------------------------------------ */ 1652 1653 void emitFunctionShadowHelper(Node *n, File *f_dest, String *name, int kw) { 1654 String *parms = make_pyParmList(n, false, false, kw); 1655 String *callParms = make_pyParmList(n, false, true, kw); 1656 /* Make a wrapper function to insert the code into */ 1657 Printv(f_dest, "\ndef ", name, "(", parms, ")", returnTypeAnnotation(n), ":\n", NIL); 1658 if (have_docstring(n)) 1659 Printv(f_dest, " ", docstring(n, AUTODOC_FUNC, tab4), "\n", NIL); 1660 if (have_pythonprepend(n)) 1661 Printv(f_dest, pythoncode(pythonprepend(n), " "), "\n", NIL); 1662 if (have_pythonappend(n)) { 1663 Printv(f_dest, " val = ", funcCall(name, callParms), "\n", NIL); 1664 Printv(f_dest, pythoncode(pythonappend(n), " "), "\n", NIL); 1665 Printv(f_dest, " return val\n", NIL); 1666 } else { 1667 Printv(f_dest, " return ", funcCall(name, callParms), "\n", NIL); 1668 } 1669 1670 if (Getattr(n, "feature:python:callback") || !have_addtofunc(n)) { 1671 /* If there is no addtofunc directive then just assign from the extension module (for speed up) */ 1672 Printv(f_dest, name, " = ", module, ".", name, "\n", NIL); 1673 } 1674 } 1675 1676 1677 /* ------------------------------------------------------------ 1678 * check_kwargs() 1679 * check if using kwargs is allowed for this Node 1680 * ------------------------------------------------------------ */ 1681 1682 int check_kwargs(Node *n) { 1683 return (use_kw || GetFlag(n, "feature:kwargs")) 1684 && !GetFlag(n, "memberset") && !GetFlag(n, "memberget"); 1685 } 1686 1687 1688 1689 /* ------------------------------------------------------------ 1690 * add_method() 1691 * ------------------------------------------------------------ */ 1692 1693 void add_method(String *name, String *function, int kw, Node *n = 0, int funpack = 0, int num_required = -1, int num_arguments = -1) { 1694 if (!kw) { 1695 if (n && funpack) { 1696 if (num_required == 0 && num_arguments == 0) { 1697 Printf(methods, "\t { (char *)\"%s\", (PyCFunction)%s, METH_NOARGS, ", name, function); 1698 } else if (num_required == 1 && num_arguments == 1) { 1699 Printf(methods, "\t { (char *)\"%s\", (PyCFunction)%s, METH_O, ", name, function); 1700 } else { 1701 Printf(methods, "\t { (char *)\"%s\", %s, METH_VARARGS, ", name, function); 1702 } 1703 } else { 1704 Printf(methods, "\t { (char *)\"%s\", %s, METH_VARARGS, ", name, function); 1705 } 1706 } else { 1707 Printf(methods, "\t { (char *)\"%s\", (PyCFunction) %s, METH_VARARGS | METH_KEYWORDS, ", name, function); 1708 } 1709 1710 if (!n) { 1711 Append(methods, "NULL"); 1712 } else if (Getattr(n, "feature:callback")) { 1713 if (have_docstring(n)) { 1714 String *ds = docstring(n, AUTODOC_FUNC, "", false); 1715 Replaceall(ds, "\\", "\\\\"); 1716 Replaceall(ds, "\"", "\\\""); 1717 Replaceall(ds, "\n", "\\n\"\n\t\t\""); 1718 Printf(methods, "(char *)\"%s\\nswig_ptr: %s\"", ds, Getattr(n, "feature:callback:name")); 1719 } else { 1720 Printf(methods, "(char *)\"swig_ptr: %s\"", Getattr(n, "feature:callback:name")); 1721 } 1722 } else if (have_docstring(n)) { 1723 String *ds = docstring(n, AUTODOC_FUNC, "", false); 1724 Replaceall(ds, "\\", "\\\\"); 1725 Replaceall(ds, "\"", "\\\""); 1726 Replaceall(ds, "\n", "\\n\"\n\t\t\""); 1727 Printf(methods, "(char *)\"%s\"", ds); 1728 } else { 1729 Append(methods, "NULL"); 1730 } 1731 1732 Append(methods, "},\n"); 1733 } 1734 1735 /* ------------------------------------------------------------ 1736 * dispatchFunction() 1737 * ------------------------------------------------------------ */ 1738 void dispatchFunction(Node *n, int funpack = 0) { 1739 /* Last node in overloaded chain */ 1740 1741 int maxargs; 1742 1743 String *tmp = NewString(""); 1744 String *dispatch; 1745 const char *dispatch_code = funpack ? "return %s(self, argc, argv);" : "return %s(self, args);"; 1746 1747 if (castmode) { 1748 dispatch = Swig_overload_dispatch_cast(n, dispatch_code, &maxargs); 1749 } else { 1750 dispatch = Swig_overload_dispatch(n, dispatch_code, &maxargs); 1751 } 1752 1753 /* Generate a dispatch wrapper for all overloaded functions */ 1754 1755 Wrapper *f = NewWrapper(); 1756 String *symname = Getattr(n, "sym:name"); 1757 String *wname = Swig_name_wrapper(symname); 1758 1759 Printv(f->def, "SWIGINTERN PyObject *", wname, "(PyObject *self, PyObject *args) {", NIL); 1760 1761 Wrapper_add_local(f, "argc", "int argc"); 1762 Printf(tmp, "PyObject *argv[%d]", maxargs + 1); 1763 Wrapper_add_local(f, "argv", tmp); 1764 1765 if (!fastunpack) { 1766 Wrapper_add_local(f, "ii", "int ii"); 1767 Append(f->code, "if (!PyTuple_Check(args)) SWIG_fail;\n"); 1768 Append(f->code, "argc = (int)PyObject_Length(args);\n"); 1769 Printf(f->code, "for (ii = 0; (ii < argc) && (ii < %d); ii++) {\n", maxargs); 1770 Append(f->code, "argv[ii] = PyTuple_GET_ITEM(args,ii);\n"); 1771 Append(f->code, "}\n"); 1772 } else { 1773 String *iname = Getattr(n, "sym:name"); 1774 Printf(f->code, "if (!(argc = SWIG_Python_UnpackTuple(args,\"%s\",0,%d,argv))) SWIG_fail;\n", iname, maxargs); 1775 Append(f->code, "--argc;\n"); 1776 } 1777 1778 Replaceall(dispatch, "$args", "self,args"); 1779 1780 Printv(f->code, dispatch, "\n", NIL); 1781 1782 if (GetFlag(n, "feature:python:maybecall")) { 1783 Append(f->code, "fail:\n"); 1784 Append(f->code, "Py_INCREF(Py_NotImplemented);\n"); 1785 Append(f->code, "return Py_NotImplemented;\n"); 1786 } else { 1787 Node *sibl = n; 1788 while (Getattr(sibl, "sym:previousSibling")) 1789 sibl = Getattr(sibl, "sym:previousSibling"); // go all the way up 1790 String *protoTypes = NewString(""); 1791 do { 1792 Printf(protoTypes, "\n\" %s(%s)\\n\"", SwigType_str(Getattr(sibl, "name"), 0), ParmList_protostr(Getattr(sibl, "wrap:parms"))); 1793 } while ((sibl = Getattr(sibl, "sym:nextSibling"))); 1794 Append(f->code, "fail:\n"); 1795 Printf(f->code, "SWIG_SetErrorMsg(PyExc_NotImplementedError," 1796 "\"Wrong number of arguments for overloaded function '%s'.\\n\"" "\n\" Possible C/C++ prototypes are:\\n\"%s);\n", symname, protoTypes); 1797 Append(f->code, "return NULL;\n"); 1798 Delete(protoTypes); 1799 } 1800 Printv(f->code, "}\n", NIL); 1801 Wrapper_print(f, f_wrappers); 1802 Node *p = Getattr(n, "sym:previousSibling"); 1803 add_method(symname, wname, 0, p); 1804 1805 /* Create a shadow for this function (if enabled and not in a member function) */ 1806 if ((shadow) && (!(shadow & PYSHADOW_MEMBER))) { 1807 emitFunctionShadowHelper(n, f_shadow_stubs, symname, 0); 1808 } 1809 DelWrapper(f); 1810 Delete(dispatch); 1811 Delete(tmp); 1812 Delete(wname); 1813 } 1814 1815 /* ------------------------------------------------------------ 1816 * functionWrapper() 1817 * ------------------------------------------------------------ */ 1818 1819 1820 const char *get_implicitconv_flag(Node *klass) { 1821 int conv = 0; 1822 if (klass && GetFlag(klass, "feature:implicitconv")) { 1823 conv = 1; 1824 } 1825 return conv ? "SWIG_POINTER_IMPLICIT_CONV" : "0"; 1826 } 1827 1828 1829 virtual int functionWrapper(Node *n) { 1830 1831 String *name = Getattr(n, "name"); 1832 String *iname = Getattr(n, "sym:name"); 1833 SwigType *d = Getattr(n, "type"); 1834 ParmList *l = Getattr(n, "parms"); 1835 int director_method = 0; 1836 1837 Parm *p; 1838 int i; 1839 char source[64]; 1840 Wrapper *f; 1841 String *parse_args; 1842 String *arglist; 1843 String *get_pointers; 1844 String *cleanup; 1845 String *outarg; 1846 String *kwargs; 1847 String *tm; 1848 String *overname = 0; 1849 1850 int num_required; 1851 int num_arguments; 1852 int varargs = 0; 1853 int allow_kwargs = check_kwargs(n); 1854 1855 String *nodeType = Getattr(n, "nodeType"); 1856 int constructor = (!Cmp(nodeType, "constructor")); 1857 int destructor = (!Cmp(nodeType, "destructor")); 1858 String *storage = Getattr(n, "storage"); 1859 /* Only the first constructor is handled as init method. Others 1860 constructor can be emitted via %rename */ 1861 int handled_as_init = 0; 1862 if (!have_constructor && (constructor || Getattr(n, "handled_as_constructor")) 1863 && ((shadow & PYSHADOW_MEMBER))) { 1864 String *nname = Getattr(n, "sym:name"); 1865 String *sname = Getattr(getCurrentClass(), "sym:name"); 1866 String *cname = Swig_name_construct(sname); 1867 handled_as_init = (Strcmp(nname, sname) == 0) || (Strcmp(nname, cname) == 0); 1868 Delete(cname); 1869 } 1870 1871 1872 if (Getattr(n, "sym:overloaded")) { 1873 overname = Getattr(n, "sym:overname"); 1874 } else { 1875 if (!addSymbol(iname, n)) 1876 return SWIG_ERROR; 1877 } 1878 1879 f = NewWrapper(); 1880 parse_args = NewString(""); 1881 arglist = NewString(""); 1882 get_pointers = NewString(""); 1883 cleanup = NewString(""); 1884 outarg = NewString(""); 1885 kwargs = NewString(""); 1886 1887 int allow_thread = threads_enable(n); 1888 1889 Wrapper_add_local(f, "resultobj", "PyObject *resultobj = 0"); 1890 1891 // Emit all of the local variables for holding arguments. 1892 emit_parameter_variables(l, f); 1893 1894 /* Attach the standard typemaps */ 1895 emit_attach_parmmaps(l, f); 1896 Setattr(n, "wrap:parms", l); 1897 /* Get number of required and total arguments */ 1898 num_arguments = emit_num_arguments(l); 1899 num_required = emit_num_required(l); 1900 if (((num_arguments == 0) && (num_required == 0)) || ((num_arguments == 1) && (num_required == 1) && Getattr(l, "self"))) 1901 allow_kwargs = 0; 1902 varargs = emit_isvarargs(l); 1903 1904 String *wname = Swig_name_wrapper(iname); 1905 if (overname) { 1906 Append(wname, overname); 1907 } 1908 1909 if (!allow_kwargs || Getattr(n, "sym:overloaded")) { 1910 if (!varargs) { 1911 Printv(f->def, "SWIGINTERN PyObject *", wname, "(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {", NIL); 1912 } else { 1913 Printv(f->def, "SWIGINTERN PyObject *", wname, "__varargs__", "(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *varargs) {", NIL); 1914 } 1915 if (allow_kwargs) { 1916 Swig_warning(WARN_LANG_OVERLOAD_KEYWORD, input_file, line_number, "Can't use keyword arguments with overloaded functions (%s).\n", Swig_name_decl(n)); 1917 allow_kwargs = 0; 1918 } 1919 } else { 1920 if (varargs) { 1921 Swig_warning(WARN_LANG_VARARGS_KEYWORD, input_file, line_number, "Can't wrap varargs with keyword arguments enabled\n"); 1922 varargs = 0; 1923 } 1924 Printv(f->def, "SWIGINTERN PyObject *", wname, "(PyObject *SWIGUNUSEDPARM(self), PyObject *args, PyObject *kwargs) {", NIL); 1925 } 1926 if (!allow_kwargs) { 1927 Append(parse_args, " if (!PyArg_ParseTuple(args,(char *)\""); 1928 } else { 1929 Append(parse_args, " if (!PyArg_ParseTupleAndKeywords(args,kwargs,(char *)\""); 1930 Append(arglist, ",kwnames"); 1931 } 1932 1933 int funpack = modernargs && fastunpack && !varargs && !allow_kwargs; 1934 int noargs = funpack && (num_required == 0 && num_arguments == 0); 1935 int onearg = funpack && (num_required == 1 && num_arguments == 1); 1936 1937 /* Generate code for argument marshalling */ 1938 if (funpack) { 1939 if (overname) { 1940 if (aliasobj0) { 1941 Append(f->code, "#define obj0 (swig_obj[0])\n"); 1942 } 1943 } else if (num_arguments) { 1944 sprintf(source, "PyObject *swig_obj[%d]", num_arguments); 1945 Wrapper_add_localv(f, "swig_obj", source, NIL); 1946 if (aliasobj0) { 1947 Append(f->code, "#define obj0 (swig_obj[0])\n"); 1948 } 1949 } 1950 } 1951 1952 1953 if (constructor && num_arguments == 1 && num_required == 1) { 1954 if (Cmp(storage, "explicit") == 0) { 1955 Node *parent = Swig_methodclass(n); 1956 if (GetFlag(parent, "feature:implicitconv")) { 1957 String *desc = NewStringf("SWIGTYPE%s", SwigType_manglestr(Getattr(n, "type"))); 1958 Printf(f->code, "if (SWIG_CheckImplicit(%s)) SWIG_fail;\n", desc); 1959 Delete(desc); 1960 } 1961 } 1962 } 1963 1964 int use_parse = 0; 1965 Append(kwargs, "{"); 1966 for (i = 0, p = l; i < num_arguments; i++) { 1967 while (checkAttribute(p, "tmap:in:numinputs", "0")) { 1968 p = Getattr(p, "tmap:in:next"); 1969 } 1970 1971 SwigType *pt = Getattr(p, "type"); 1972 String *pn = Getattr(p, "name"); 1973 String *ln = Getattr(p, "lname"); 1974 if (funpack) { 1975 sprintf(source, "swig_obj[%d]", i); 1976 } else { 1977 sprintf(source, "obj%d", i); 1978 } 1979 1980 1981 Putc(',', arglist); 1982 if (i == num_required) 1983 Putc('|', parse_args); /* Optional argument separator */ 1984 1985 /* Keyword argument handling */ 1986 if (allow_kwargs) { 1987 if (Len(pn)) { 1988 String *tmp = 0; 1989 String *name = pn; 1990 if (!Getattr(p,"hidden")) { 1991 name = tmp = Swig_name_make(p, 0, pn, 0, 0); 1992 } 1993 Printf(kwargs, "(char *) \"%s\",", name); 1994 if (tmp) 1995 Delete(tmp); 1996 } else { 1997 Printf(kwargs, "(char *)\"arg%d\",", i + 1); 1998 } 1999 } 2000 2001 /* Look for an input typemap */ 2002 if ((tm = Getattr(p, "tmap:in"))) { 2003 String *parse = Getattr(p, "tmap:in:parse"); 2004 if (!parse) { 2005 if (funpack) { 2006 Replaceall(tm, "$self", "swig_obj[0]"); 2007 } else { 2008 Replaceall(tm, "$self", "obj0"); 2009 } 2010 Replaceall(tm, "$source", source); 2011 Replaceall(tm, "$target", ln); 2012 Replaceall(tm, "$input", source); 2013 Setattr(p, "emit:input", source); /* Save the location of the object */ 2014 2015 if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) { 2016 Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); 2017 } else { 2018 Replaceall(tm, "$disown", "0"); 2019 } 2020 2021 if (Getattr(p, "tmap:in:implicitconv")) { 2022 const char *convflag = "0"; 2023 if (!Getattr(p,"hidden")) { 2024 SwigType *ptype = Getattr(p, "type"); 2025 convflag = get_implicitconv_flag(classLookup(ptype)); 2026 } 2027 Replaceall(tm, "$implicitconv", convflag); 2028 Setattr(p, "implicitconv", convflag); 2029 } 2030 2031 Putc('O', parse_args); 2032 if (!funpack) { 2033 Wrapper_add_localv(f, source, "PyObject *", source, "= 0", NIL); 2034 Printf(arglist, "&%s", source); 2035 } 2036 if (i >= num_required) 2037 Printv(get_pointers, "if (", source, ") {\n", NIL); 2038 Printv(get_pointers, tm, "\n", NIL); 2039 if (i >= num_required) 2040 Printv(get_pointers, "}\n", NIL); 2041 2042 } else { 2043 use_parse = 1; 2044 Append(parse_args, parse); 2045 Printf(arglist, "&%s", ln); 2046 } 2047 p = Getattr(p, "tmap:in:next"); 2048 continue; 2049 } else { 2050 Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0)); 2051 break; 2052 } 2053 } 2054 2055 /* finish argument marshalling */ 2056 Append(kwargs, " NULL }"); 2057 if (allow_kwargs) { 2058 Printv(f->locals, " char * kwnames[] = ", kwargs, ";\n", NIL); 2059 } 2060 2061 if (use_parse || allow_kwargs || !modernargs) { 2062 Printf(parse_args, ":%s\"", iname); 2063 Printv(parse_args, arglist, ")) SWIG_fail;\n", NIL); 2064 funpack = 0; 2065 } else { 2066 Clear(parse_args); 2067 if (funpack) { 2068 Clear(f->def); 2069 if (overname) { 2070 if (noargs) { 2071 Printv(f->def, "SWIGINTERN PyObject *", wname, "(PyObject *SWIGUNUSEDPARM(self), int nobjs, PyObject **SWIGUNUSEDPARM(swig_obj)) {", NIL); 2072 } else { 2073 Printv(f->def, "SWIGINTERN PyObject *", wname, "(PyObject *SWIGUNUSEDPARM(self), int nobjs, PyObject **swig_obj) {", NIL); 2074 } 2075 Printf(parse_args, "if ((nobjs < %d) || (nobjs > %d)) SWIG_fail;\n", num_required, num_arguments); 2076 } else { 2077 if (noargs) { 2078 Printv(f->def, "SWIGINTERN PyObject *", wname, "(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {", NIL); 2079 } else { 2080 Printv(f->def, "SWIGINTERN PyObject *", wname, "(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {", NIL); 2081 } 2082 if (onearg) { 2083 Printf(parse_args, "if (!args) SWIG_fail;\n"); 2084 Printf(parse_args, "swig_obj[0] = args;\n"); 2085 } else if (!noargs) { 2086 Printf(parse_args, "if (!SWIG_Python_UnpackTuple(args,\"%s\",%d,%d,swig_obj)) SWIG_fail;\n", iname, num_required, num_arguments); 2087 } else if (noargs) { 2088 Printf(parse_args, "if (!SWIG_Python_UnpackTuple(args,\"%s\",%d,%d,0)) SWIG_fail;\n", iname, num_required, num_arguments); 2089 } 2090 } 2091 } else { 2092 Printf(parse_args, "if(!PyArg_UnpackTuple(args,(char *)\"%s\",%d,%d", iname, num_required, num_arguments); 2093 Printv(parse_args, arglist, ")) SWIG_fail;\n", NIL); 2094 } 2095 } 2096 2097 /* Now piece together the first part of the wrapper function */ 2098 Printv(f->code, parse_args, get_pointers, NIL); 2099 2100 /* Check for trailing varargs */ 2101 if (varargs) { 2102 if (p && (tm = Getattr(p, "tmap:in"))) { 2103 Replaceall(tm, "$input", "varargs"); 2104 Printv(f->code, tm, "\n", NIL); 2105 } 2106 } 2107 2108 /* Insert constraint checking code */ 2109 for (p = l; p;) { 2110 if ((tm = Getattr(p, "tmap:check"))) { 2111 Replaceall(tm, "$target", Getattr(p, "lname")); 2112 Printv(f->code, tm, "\n", NIL); 2113 p = Getattr(p, "tmap:check:next"); 2114 } else { 2115 p = nextSibling(p); 2116 } 2117 } 2118 2119 /* Insert cleanup code */ 2120 for (p = l; p;) { 2121 // if (!checkAttribute(p,"tmap:in:numinputs","0") && !Getattr(p,"tmap:in:parse")) { 2122 if (!Getattr(p, "tmap:in:parse") && (tm = Getattr(p, "tmap:freearg"))) { 2123 if (Getattr(p, "tmap:freearg:implicitconv")) { 2124 const char *convflag = "0"; 2125 if (!Getattr(p,"hidden")) { 2126 SwigType *ptype = Getattr(p, "type"); 2127 convflag = get_implicitconv_flag(classLookup(ptype)); 2128 } 2129 if (strcmp(convflag, "0") == 0) { 2130 tm = 0; 2131 } 2132 } 2133 if (tm && (Len(tm) != 0)) { 2134 Replaceall(tm, "$source", Getattr(p, "lname")); 2135 Printv(cleanup, tm, "\n", NIL); 2136 } 2137 p = Getattr(p, "tmap:freearg:next"); 2138 } else { 2139 p = nextSibling(p); 2140 } 2141 } 2142 2143 /* Insert argument output code */ 2144 for (p = l; p;) { 2145 if ((tm = Getattr(p, "tmap:argout"))) { 2146 Replaceall(tm, "$source", Getattr(p, "lname")); 2147 Replaceall(tm, "$target", "resultobj"); 2148 Replaceall(tm, "$arg", Getattr(p, "emit:input")); 2149 Replaceall(tm, "$input", Getattr(p, "emit:input")); 2150 Printv(outarg, tm, "\n", NIL); 2151 p = Getattr(p, "tmap:argout:next"); 2152 } else { 2153 p = nextSibling(p); 2154 } 2155 } 2156 2157 /* if the object is a director, and the method call originated from its 2158 * underlying python object, resolve the call by going up the c++ 2159 * inheritance chain. otherwise try to resolve the method in python. 2160 * without this check an infinite loop is set up between the director and 2161 * shadow class method calls. 2162 */ 2163 2164 // NOTE: this code should only be inserted if this class is the 2165 // base class of a director class. however, in general we haven't 2166 // yet analyzed all classes derived from this one to see if they are 2167 // directors. furthermore, this class may be used as the base of 2168 // a director class defined in a completely different module at a 2169 // later time, so this test must be included whether or not directorbase 2170 // is true. we do skip this code if directors have not been enabled 2171 // at the command line to preserve source-level compatibility with 2172 // non-polymorphic swig. also, if this wrapper is for a smart-pointer 2173 // method, there is no need to perform the test since the calling object 2174 // (the smart-pointer) and the director object (the "pointee") are 2175 // distinct. 2176 2177 director_method = is_member_director(n) && !is_smart_pointer() && !destructor; 2178 if (director_method) { 2179 Wrapper_add_local(f, "director", "Swig::Director *director = 0"); 2180 Append(f->code, "director = SWIG_DIRECTOR_CAST(arg1);\n"); 2181 if (dirprot_mode() && !is_public(n)) { 2182 Printf(f->code, "if (!director || !(director->swig_get_inner(\"%s\"))) {\n", name); 2183 Printf(f->code, "SWIG_SetErrorMsg(PyExc_RuntimeError,\"accessing protected member %s\");\n", name); 2184 Append(f->code, "SWIG_fail;\n"); 2185 Append(f->code, "}\n"); 2186 } 2187 Wrapper_add_local(f, "upcall", "bool upcall = false"); 2188 if (funpack) { 2189 Append(f->code, "upcall = (director && (director->swig_get_self()==swig_obj[0]));\n"); 2190 } else { 2191 Append(f->code, "upcall = (director && (director->swig_get_self()==obj0));\n"); 2192 } 2193 } 2194 2195 /* Emit the function call */ 2196 if (director_method) { 2197 Append(f->code, "try {\n"); 2198 } else { 2199 if (allow_thread) { 2200 Append(f->code, "{\n"); 2201 thread_begin_allow(n, f->code); 2202 } 2203 } 2204 2205 Setattr(n, "wrap:name", wname); 2206 2207 Swig_director_emit_dynamic_cast(n, f); 2208 String *actioncode = emit_action(n); 2209 2210 if (director_method) { 2211 Append(actioncode, "} catch (Swig::DirectorException&) {\n"); 2212 Append(actioncode, " SWIG_fail;\n"); 2213 Append(actioncode, "}\n"); 2214 } else { 2215 if (allow_thread) { 2216 thread_end_allow(n, actioncode); 2217 Append(actioncode, "}\n"); 2218 } 2219 } 2220 2221 /* This part below still needs cleanup */ 2222 2223 /* Return the function value */ 2224 if ((tm = Swig_typemap_lookup_out("out", n, "result", f, actioncode))) { 2225 if (funpack) { 2226 Replaceall(tm, "$self", "swig_obj[0]"); 2227 } else { 2228 Replaceall(tm, "$self", "obj0"); 2229 } 2230 Replaceall(tm, "$source", "result"); 2231 Replaceall(tm, "$target", "resultobj"); 2232 Replaceall(tm, "$result", "resultobj"); 2233 if (handled_as_init) { 2234 Replaceall(tm, "$owner", "SWIG_POINTER_NEW"); 2235 } else { 2236 if (GetFlag(n, "feature:new")) { 2237 Replaceall(tm, "$owner", "SWIG_POINTER_OWN"); 2238 } else { 2239 Replaceall(tm, "$owner", "0"); 2240 } 2241 } 2242 // FIXME: this will not try to unwrap directors returned as non-director 2243 // base class pointers! 2244 2245 /* New addition to unwrap director return values so that the original 2246 * python object is returned instead. 2247 */ 2248#if 1 2249 int unwrap = 0; 2250 String *decl = Getattr(n, "decl"); 2251 int is_pointer = SwigType_ispointer_return(decl); 2252 int is_reference = SwigType_isreference_return(decl); 2253 if (is_pointer || is_reference) { 2254 String *type = Getattr(n, "type"); 2255 //Node *classNode = Swig_methodclass(n); 2256 //Node *module = Getattr(classNode, "module"); 2257 Node *parent = Swig_methodclass(n); 2258 Node *module = Getattr(parent, "module"); 2259 Node *target = Swig_directormap(module, type); 2260 if (target) 2261 unwrap = 1; 2262 } 2263 if (unwrap) { 2264 Wrapper_add_local(f, "director", "Swig::Director *director = 0"); 2265 Append(f->code, "director = SWIG_DIRECTOR_CAST(result);\n"); 2266 Append(f->code, "if (director) {\n"); 2267 Append(f->code, " resultobj = director->swig_get_self();\n"); 2268 Append(f->code, " Py_INCREF(resultobj);\n"); 2269 Append(f->code, "} else {\n"); 2270 Printf(f->code, "%s\n", tm); 2271 Append(f->code, "}\n"); 2272 } else { 2273 Printf(f->code, "%s\n", tm); 2274 } 2275#else 2276 Printf(f->code, "%s\n", tm); 2277#endif 2278 Delete(tm); 2279 } else { 2280 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); 2281 } 2282 emit_return_variable(n, d, f); 2283 2284 /* Output argument output code */ 2285 Printv(f->code, outarg, NIL); 2286 2287 /* Output cleanup code */ 2288 int need_cleanup = Len(cleanup) != 0; 2289 if (need_cleanup) { 2290 Printv(f->code, cleanup, NIL); 2291 } 2292 2293 /* Look to see if there is any newfree cleanup code */ 2294 if (GetFlag(n, "feature:new")) { 2295 if ((tm = Swig_typemap_lookup("newfree", n, "result", 0))) { 2296 Replaceall(tm, "$source", "result"); 2297 Printf(f->code, "%s\n", tm); 2298 Delete(tm); 2299 } 2300 } 2301 2302 /* See if there is any return cleanup code */ 2303 if ((tm = Swig_typemap_lookup("ret", n, "result", 0))) { 2304 Replaceall(tm, "$source", "result"); 2305 Printf(f->code, "%s\n", tm); 2306 Delete(tm); 2307 } 2308 2309 if (director_method) { 2310 if ((tm = Swig_typemap_lookup("directorfree", n, "result", 0))) { 2311 Replaceall(tm, "$input", "result"); 2312 Replaceall(tm, "$result", "resultobj"); 2313 Printf(f->code, "%s\n", tm); 2314 Delete(tm); 2315 } 2316 } 2317 2318 Append(f->code, " return resultobj;\n"); 2319 2320 /* Error handling code */ 2321 2322 Append(f->code, "fail:\n"); 2323 if (need_cleanup) { 2324 Printv(f->code, cleanup, NIL); 2325 } 2326 Printv(f->code, " return NULL;\n", NIL); 2327 2328 2329 if (funpack) { 2330 if (aliasobj0) { 2331 Append(f->code, "#if defined(obj0)\n"); 2332 Append(f->code, "#undef obj0\n"); 2333 Append(f->code, "#endif\n"); 2334 } 2335 } 2336 2337 2338 Append(f->code, "}\n"); 2339 2340 /* Substitute the cleanup code */ 2341 Replaceall(f->code, "$cleanup", cleanup); 2342 2343 /* Substitute the function name */ 2344 Replaceall(f->code, "$symname", iname); 2345 Replaceall(f->code, "$result", "resultobj"); 2346 2347 if (funpack) { 2348 Replaceall(f->code, "$self", "swig_obj[0]"); 2349 } else { 2350 Replaceall(f->code, "$self", "obj0"); 2351 } 2352 2353 /* Dump the function out */ 2354 Wrapper_print(f, f_wrappers); 2355 2356 /* If varargs. Need to emit a varargs stub */ 2357 if (varargs) { 2358 DelWrapper(f); 2359 f = NewWrapper(); 2360 Printv(f->def, "SWIGINTERN PyObject *", wname, "(PyObject *self, PyObject *args) {", NIL); 2361 Wrapper_add_local(f, "resultobj", "PyObject *resultobj"); 2362 Wrapper_add_local(f, "varargs", "PyObject *varargs"); 2363 Wrapper_add_local(f, "newargs", "PyObject *newargs"); 2364 Printf(f->code, "newargs = PyTuple_GetSlice(args,0,%d);\n", num_arguments); 2365 Printf(f->code, "varargs = PyTuple_GetSlice(args,%d,PyTuple_Size(args)+1);\n", num_arguments); 2366 Printf(f->code, "resultobj = %s__varargs__(self,newargs,varargs);\n", wname); 2367 Append(f->code, "Py_XDECREF(newargs);\n"); 2368 Append(f->code, "Py_XDECREF(varargs);\n"); 2369 Append(f->code, "return resultobj;\n"); 2370 Append(f->code, "}\n"); 2371 Wrapper_print(f, f_wrappers); 2372 } 2373 2374 /* Now register the function with the interpreter. */ 2375 if (!Getattr(n, "sym:overloaded")) { 2376 add_method(iname, wname, allow_kwargs, n, funpack, num_required, num_arguments); 2377 2378 /* Create a shadow for this function (if enabled and not in a member function) */ 2379 if ((shadow) && (!(shadow & PYSHADOW_MEMBER))) { 2380 emitFunctionShadowHelper(n, in_class ? f_shadow_stubs : f_shadow, iname, allow_kwargs); 2381 } 2382 } else { 2383 if (!Getattr(n, "sym:nextSibling")) { 2384 dispatchFunction(n, funpack); 2385 } 2386 } 2387 Delete(parse_args); 2388 Delete(arglist); 2389 Delete(get_pointers); 2390 Delete(cleanup); 2391 Delete(outarg); 2392 Delete(kwargs); 2393 Delete(wname); 2394 DelWrapper(f); 2395 return SWIG_OK; 2396 } 2397 2398 2399 2400 /* ------------------------------------------------------------ 2401 * variableWrapper() 2402 * ------------------------------------------------------------ */ 2403 2404 virtual int variableWrapper(Node *n) { 2405 String *name = Getattr(n, "name"); 2406 String *iname = Getattr(n, "sym:name"); 2407 SwigType *t = Getattr(n, "type"); 2408 2409 static int have_globals = 0; 2410 String *tm; 2411 Wrapper *getf, *setf; 2412 2413 if (!addSymbol(iname, n)) 2414 return SWIG_ERROR; 2415 2416 getf = NewWrapper(); 2417 setf = NewWrapper(); 2418 2419 /* If this is our first call, add the globals variable to the 2420 Python dictionary. */ 2421 2422 if (!have_globals) { 2423 Printf(f_init, "\t PyDict_SetItemString(d,(char*)\"%s\", SWIG_globals());\n", global_name); 2424 have_globals = 1; 2425 if ((shadow) && (!(shadow & PYSHADOW_MEMBER))) { 2426 Printf(f_shadow_stubs, "%s = %s.%s\n", global_name, module, global_name); 2427 } 2428 } 2429 int assignable = is_assignable(n); 2430 2431 if ((shadow) && !assignable) { 2432 if (!in_class) { 2433 Printf(f_shadow_stubs, "%s = %s.%s\n", iname, global_name, iname); 2434 } 2435 } 2436 2437 String *getname = Swig_name_get(iname); 2438 String *setname = Swig_name_set(iname); 2439 String *vargetname = NewStringf("Swig_var_%s", getname); 2440 String *varsetname = NewStringf("Swig_var_%s", setname); 2441 2442 /* Create a function for setting the value of the variable */ 2443 if (assignable) { 2444 Setattr(n, "wrap:name", varsetname); 2445 Printf(setf->def, "SWIGINTERN int %s(PyObject *_val) {", varsetname); 2446 if ((tm = Swig_typemap_lookup("varin", n, name, 0))) { 2447 Replaceall(tm, "$source", "_val"); 2448 Replaceall(tm, "$target", name); 2449 Replaceall(tm, "$input", "_val"); 2450 if (Getattr(n, "tmap:varin:implicitconv")) { 2451 Replaceall(tm, "$implicitconv", get_implicitconv_flag(n)); 2452 } 2453 emit_action_code(n, setf->code, tm); 2454 Delete(tm); 2455 } else { 2456 Swig_warning(WARN_TYPEMAP_VARIN_UNDEF, input_file, line_number, "Unable to set variable of type %s.\n", SwigType_str(t, 0)); 2457 } 2458 Printv(setf->code, " return 0;\n", NULL); 2459 Append(setf->code, "fail:\n"); 2460 Printv(setf->code, " return 1;\n", NULL); 2461 } else { 2462 /* Is a readonly variable. Issue an error */ 2463 if (CPlusPlus) { 2464 Printf(setf->def, "SWIGINTERN int %s(PyObject *) {", varsetname); 2465 } else { 2466 Printf(setf->def, "SWIGINTERN int %s(PyObject *_val SWIGUNUSED) {", varsetname); 2467 } 2468 Printv(setf->code, " SWIG_Error(SWIG_AttributeError,\"Variable ", iname, " is read-only.\");\n", " return 1;\n", NIL); 2469 } 2470 2471 Append(setf->code, "}\n"); 2472 Wrapper_print(setf, f_wrappers); 2473 2474 /* Create a function for getting the value of a variable */ 2475 Setattr(n, "wrap:name", vargetname); 2476 int addfail = 0; 2477 Printf(getf->def, "SWIGINTERN PyObject *%s(void) {", vargetname); 2478 Wrapper_add_local(getf, "pyobj", "PyObject *pyobj = 0"); 2479 if ((tm = Swig_typemap_lookup("varout", n, name, 0))) { 2480 Replaceall(tm, "$source", name); 2481 Replaceall(tm, "$target", "pyobj"); 2482 Replaceall(tm, "$result", "pyobj"); 2483 addfail = emit_action_code(n, getf->code, tm); 2484 Delete(tm); 2485 } else { 2486 Swig_warning(WARN_TYPEMAP_VAROUT_UNDEF, input_file, line_number, "Unable to read variable of type %s\n", SwigType_str(t, 0)); 2487 } 2488 Append(getf->code, " return pyobj;\n"); 2489 if (addfail) { 2490 Append(getf->code, "fail:\n"); 2491 Append(getf->code, " return NULL;\n"); 2492 } 2493 Append(getf->code, "}\n"); 2494 2495 Wrapper_print(getf, f_wrappers); 2496 2497 /* Now add this to the variable linking mechanism */ 2498 Printf(f_init, "\t SWIG_addvarlink(SWIG_globals(),(char*)\"%s\",%s, %s);\n", iname, vargetname, varsetname); 2499 2500 Delete(vargetname); 2501 Delete(varsetname); 2502 Delete(getname); 2503 Delete(setname); 2504 DelWrapper(setf); 2505 DelWrapper(getf); 2506 return SWIG_OK; 2507 } 2508 2509 /* ------------------------------------------------------------ 2510 * constantWrapper() 2511 * ------------------------------------------------------------ */ 2512 2513 virtual int constantWrapper(Node *n) { 2514 String *name = Getattr(n, "name"); 2515 String *iname = Getattr(n, "sym:name"); 2516 SwigType *type = Getattr(n, "type"); 2517 String *rawval = Getattr(n, "rawval"); 2518 String *value = rawval ? rawval : Getattr(n, "value"); 2519 String *tm; 2520 int have_tm = 0; 2521 2522 if (!addSymbol(iname, n)) 2523 return SWIG_ERROR; 2524 2525 /* Special hook for member pointer */ 2526 if (SwigType_type(type) == T_MPOINTER) { 2527 String *wname = Swig_name_wrapper(iname); 2528 String *str = SwigType_str(type, wname); 2529 Printf(f_header, "static %s = %s;\n", str, value); 2530 Delete(str); 2531 value = wname; 2532 } 2533 if ((tm = Swig_typemap_lookup("consttab", n, name, 0))) { 2534 Replaceall(tm, "$source", value); 2535 Replaceall(tm, "$target", name); 2536 Replaceall(tm, "$value", value); 2537 Printf(const_code, "%s,\n", tm); 2538 Delete(tm); 2539 have_tm = 1; 2540 } 2541 if ((tm = Swig_typemap_lookup("constcode", n, name, 0))) { 2542 Replaceall(tm, "$source", value); 2543 Replaceall(tm, "$target", name); 2544 Replaceall(tm, "$value", value); 2545 Printf(f_init, "%s\n", tm); 2546 Delete(tm); 2547 have_tm = 1; 2548 } 2549 if (!have_tm) { 2550 Swig_warning(WARN_TYPEMAP_CONST_UNDEF, input_file, line_number, "Unsupported constant value.\n"); 2551 return SWIG_NOWRAP; 2552 } 2553 if ((shadow) && (!(shadow & PYSHADOW_MEMBER))) { 2554 if (!in_class) { 2555 Printv(f_shadow, iname, " = ", module, ".", iname, "\n", NIL); 2556 } else { 2557 if (!(Getattr(n, "feature:python:callback"))) { 2558 Printv(f_shadow_stubs, iname, " = ", module, ".", iname, "\n", NIL); 2559 } 2560 } 2561 } 2562 return SWIG_OK; 2563 } 2564 2565 2566 /* ------------------------------------------------------------ 2567 * nativeWrapper() 2568 * ------------------------------------------------------------ */ 2569 2570 virtual int nativeWrapper(Node *n) { 2571 String *name = Getattr(n, "sym:name"); 2572 String *wrapname = Getattr(n, "wrap:name"); 2573 2574 if (!addSymbol(wrapname, n)) 2575 return SWIG_ERROR; 2576 2577 add_method(name, wrapname, 0); 2578 if (shadow) { 2579 Printv(f_shadow_stubs, name, " = ", module, ".", name, "\n", NIL); 2580 } 2581 return SWIG_OK; 2582 } 2583 2584 2585 2586/* ---------------------------------------------------------------------------- 2587 * BEGIN C++ Director Class modifications 2588 * ------------------------------------------------------------------------- */ 2589 2590/* C++/Python polymorphism demo code, copyright (C) 2002 Mark Rose <mrose@stm.lbl.gov> 2591 * 2592 * TODO 2593 * 2594 * Move some boilerplate code generation to Swig_...() functions. 2595 * 2596 */ 2597 2598 /* --------------------------------------------------------------- 2599 * classDirectorMethod() 2600 * 2601 * Emit a virtual director method to pass a method call on to the 2602 * underlying Python object. 2603 * ** Moved down due to gcc-2.96 internal error ** 2604 * --------------------------------------------------------------- */ 2605 2606 int classDirectorMethods(Node *n); 2607 2608 int classDirectorMethod(Node *n, Node *parent, String *super); 2609 2610 /* ------------------------------------------------------------ 2611 * classDirectorConstructor() 2612 * ------------------------------------------------------------ */ 2613 2614 int classDirectorConstructor(Node *n) { 2615 Node *parent = Getattr(n, "parentNode"); 2616 String *sub = NewString(""); 2617 String *decl = Getattr(n, "decl"); 2618 String *supername = Swig_class_name(parent); 2619 String *classname = NewString(""); 2620 Printf(classname, "SwigDirector_%s", supername); 2621 2622 /* insert self parameter */ 2623 Parm *p; 2624 ParmList *superparms = Getattr(n, "parms"); 2625 ParmList *parms = CopyParmList(superparms); 2626 String *type = NewString("PyObject"); 2627 SwigType_add_pointer(type); 2628 p = NewParm(type, NewString("self")); 2629 set_nextSibling(p, parms); 2630 parms = p; 2631 2632 if (!Getattr(n, "defaultargs")) { 2633 /* constructor */ 2634 { 2635 Wrapper *w = NewWrapper(); 2636 String *call; 2637 String *basetype = Getattr(parent, "classtype"); 2638 String *target = Swig_method_decl(0, decl, classname, parms, 0, 0); 2639 call = Swig_csuperclass_call(0, basetype, superparms); 2640 Printf(w->def, "%s::%s: %s, Swig::Director(self) { \n", classname, target, call); 2641 Printf(w->def, " SWIG_DIRECTOR_RGTR((%s *)this, this); \n", basetype); 2642 Append(w->def, "}\n"); 2643 Delete(target); 2644 Wrapper_print(w, f_directors); 2645 Delete(call); 2646 DelWrapper(w); 2647 } 2648 2649 /* constructor header */ 2650 { 2651 String *target = Swig_method_decl(0, decl, classname, parms, 0, 1); 2652 Printf(f_directors_h, " %s;\n", target); 2653 Delete(target); 2654 } 2655 } 2656 2657 Delete(sub); 2658 Delete(classname); 2659 Delete(supername); 2660 Delete(parms); 2661 return Language::classDirectorConstructor(n); 2662 } 2663 2664 /* ------------------------------------------------------------ 2665 * classDirectorDefaultConstructor() 2666 * ------------------------------------------------------------ */ 2667 2668 int classDirectorDefaultConstructor(Node *n) { 2669 String *classname = Swig_class_name(n); 2670 { 2671 Node *parent = Swig_methodclass(n); 2672 String *basetype = Getattr(parent, "classtype"); 2673 Wrapper *w = NewWrapper(); 2674 Printf(w->def, "SwigDirector_%s::SwigDirector_%s(PyObject* self) : Swig::Director(self) { \n", classname, classname); 2675 Printf(w->def, " SWIG_DIRECTOR_RGTR((%s *)this, this); \n", basetype); 2676 Append(w->def, "}\n"); 2677 Wrapper_print(w, f_directors); 2678 DelWrapper(w); 2679 } 2680 Printf(f_directors_h, " SwigDirector_%s(PyObject* self);\n", classname); 2681 Delete(classname); 2682 return Language::classDirectorDefaultConstructor(n); 2683 } 2684 2685 2686 /* ------------------------------------------------------------ 2687 * classDirectorInit() 2688 * ------------------------------------------------------------ */ 2689 2690 int classDirectorInit(Node *n) { 2691 String *declaration = Swig_director_declaration(n); 2692 Printf(f_directors_h, "\n"); 2693 Printf(f_directors_h, "%s\n", declaration); 2694 Printf(f_directors_h, "public:\n"); 2695 Delete(declaration); 2696 return Language::classDirectorInit(n); 2697 } 2698 2699 /* ------------------------------------------------------------ 2700 * classDirectorEnd() 2701 * ------------------------------------------------------------ */ 2702 2703 int classDirectorEnd(Node *n) { 2704 String *classname = Swig_class_name(n); 2705 2706 if (dirprot_mode()) { 2707 /* 2708 This implementation uses a std::map<std::string,int>. 2709 2710 It should be possible to rewrite it using a more elegant way, 2711 like copying the Java approach for the 'override' array. 2712 2713 But for now, this seems to be the least intrusive way. 2714 */ 2715 Printf(f_directors_h, "\n\n"); 2716 Printf(f_directors_h, "/* Internal Director utilities */\n"); 2717 Printf(f_directors_h, "public:\n"); 2718 Printf(f_directors_h, " bool swig_get_inner(const char* name) const {\n"); 2719 Printf(f_directors_h, " std::map<std::string, bool>::const_iterator iv = inner.find(name);\n"); 2720 Printf(f_directors_h, " return (iv != inner.end() ? iv->second : false);\n"); 2721 Printf(f_directors_h, " }\n\n"); 2722 2723 Printf(f_directors_h, " void swig_set_inner(const char* name, bool val) const\n"); 2724 Printf(f_directors_h, " { inner[name] = val;}\n\n"); 2725 Printf(f_directors_h, "private:\n"); 2726 Printf(f_directors_h, " mutable std::map<std::string, bool> inner;\n"); 2727 2728 } 2729 if (director_method_index) { 2730 Printf(f_directors_h, "\n\n"); 2731 Printf(f_directors_h, "#if defined(SWIG_PYTHON_DIRECTOR_VTABLE)\n"); 2732 Printf(f_directors_h, "/* VTable implementation */\n"); 2733 Printf(f_directors_h, " PyObject *swig_get_method(size_t method_index, const char *method_name) const {\n"); 2734 Printf(f_directors_h, " PyObject *method = vtable[method_index];\n"); 2735 Printf(f_directors_h, " if (!method) {\n"); 2736 Printf(f_directors_h, " swig::SwigVar_PyObject name = SWIG_Python_str_FromChar(method_name);\n"); 2737 Printf(f_directors_h, " method = PyObject_GetAttr(swig_get_self(), name);\n"); 2738 Printf(f_directors_h, " if (method == NULL) {\n"); 2739 Printf(f_directors_h, " std::string msg = \"Method in class %s doesn't exist, undefined \";\n", classname); 2740 Printf(f_directors_h, " msg += method_name;\n"); 2741 Printf(f_directors_h, " Swig::DirectorMethodException::raise(msg.c_str());\n"); 2742 Printf(f_directors_h, " }\n"); 2743 Printf(f_directors_h, " vtable[method_index] = method;\n"); 2744 Printf(f_directors_h, " };\n"); 2745 Printf(f_directors_h, " return method;\n"); 2746 Printf(f_directors_h, " }\n"); 2747 Printf(f_directors_h, "private:\n"); 2748 Printf(f_directors_h, " mutable swig::SwigVar_PyObject vtable[%d];\n", director_method_index); 2749 Printf(f_directors_h, "#endif\n\n"); 2750 } 2751 2752 Printf(f_directors_h, "};\n\n"); 2753 return Language::classDirectorEnd(n); 2754 } 2755 2756 2757 /* ------------------------------------------------------------ 2758 * classDirectorDisown() 2759 * ------------------------------------------------------------ */ 2760 2761 int classDirectorDisown(Node *n) { 2762 int result; 2763 int oldshadow = shadow; 2764 /* disable shadowing */ 2765 if (shadow) 2766 shadow = shadow | PYSHADOW_MEMBER; 2767 result = Language::classDirectorDisown(n); 2768 shadow = oldshadow; 2769 if (shadow) { 2770 String *symname = Getattr(n, "sym:name"); 2771 String *mrename = Swig_name_disown(symname); //Getattr(n, "name")); 2772 Printv(f_shadow, tab4, "def __disown__(self):\n", NIL); 2773#ifdef USE_THISOWN 2774 Printv(f_shadow, tab8, "self.thisown = 0\n", NIL); 2775#else 2776 Printv(f_shadow, tab8, "self.this.disown()\n", NIL); 2777#endif 2778 Printv(f_shadow, tab8, module, ".", mrename, "(self)\n", NIL); 2779 Printv(f_shadow, tab8, "return weakref_proxy(self)\n", NIL); 2780 Delete(mrename); 2781 } 2782 return result; 2783 } 2784 2785/* ---------------------------------------------------------------------------- 2786 * END of C++ Director Class modifications 2787 * ------------------------------------------------------------------------- */ 2788 2789 2790 /* ------------------------------------------------------------ 2791 * classDeclaration() 2792 * ------------------------------------------------------------ */ 2793 2794 virtual int classDeclaration(Node *n) { 2795 if (shadow && !Getattr(n, "feature:onlychildren")) { 2796 Node *mod = Getattr(n, "module"); 2797 if (mod) { 2798 String *importname = NewString(""); 2799 String *modname = Getattr(mod, "name"); 2800 if (Strcmp(modname, mainmodule) != 0) { 2801 // check if the module has a package option 2802 Node *options = Getattr(mod, "options"); 2803 String *pkg = options ? Getattr(options, "package") : 0; 2804 if (pkg && (!package || Strcmp(pkg, package) != 0)) { 2805 Printf(importname, "%s.", pkg); 2806 } 2807 Printf(importname, "%s.", modname); 2808 } 2809 Append(importname, Getattr(n, "sym:name")); 2810 Setattr(n, "python:proxy", importname); 2811 } 2812 } 2813 return Language::classDeclaration(n); 2814 } 2815 2816 /* ------------------------------------------------------------ 2817 * classHandler() 2818 * ------------------------------------------------------------ */ 2819 2820 virtual int classHandler(Node *n) { 2821 int oldclassic = classic; 2822 int oldmodern = modern; 2823 File *f_shadow_file = f_shadow; 2824 2825 if (shadow) { 2826 2827 /* Create new strings for building up a wrapper function */ 2828 have_constructor = 0; 2829 have_repr = 0; 2830 2831 if (GetFlag(n, "feature:classic")) { 2832 classic = 1; 2833 modern = 0; 2834 } 2835 if (GetFlag(n, "feature:modern")) { 2836 classic = 0; 2837 modern = 1; 2838 } 2839 if (GetFlag(n, "feature:exceptionclass")) { 2840 classic = 1; 2841 modern = 0; 2842 } 2843 2844 shadow_indent = (String *) tab4; 2845 2846 class_name = Getattr(n, "sym:name"); 2847 real_classname = Getattr(n, "name"); 2848 2849 if (!addSymbol(class_name, n)) 2850 return SWIG_ERROR; 2851 2852 /* Handle inheritance */ 2853 String *base_class = NewString(""); 2854 List *baselist = Getattr(n, "bases"); 2855 if (baselist && Len(baselist)) { 2856 Iterator b; 2857 b = First(baselist); 2858 while (b.item) { 2859 String *bname = Getattr(b.item, "python:proxy"); 2860 bool ignore = GetFlag(b.item, "feature:ignore") ? true : false; 2861 if (!bname || ignore) { 2862 if (!bname && !ignore) { 2863 Swig_warning(WARN_TYPE_UNDEFINED_CLASS, input_file, line_number, 2864 "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", SwigType_namestr(Getattr(b.item, "name"))); 2865 } 2866 b = Next(b); 2867 continue; 2868 } 2869 Printv(base_class, bname, NIL); 2870 b = Next(b); 2871 if (b.item) { 2872 Putc(',', base_class); 2873 } 2874 } 2875 } 2876 2877 /* dealing with abstract base class */ 2878 String *abcs = Getattr(n, "feature:python:abc"); 2879 if (py3 && abcs) { 2880 if (Len(base_class)) { 2881 Putc(',', base_class); 2882 } 2883 Printv(base_class, abcs, NIL); 2884 } 2885 2886 Printv(f_shadow, "class ", class_name, NIL); 2887 2888 if (Len(base_class)) { 2889 Printf(f_shadow, "(%s)", base_class); 2890 } else { 2891 if (!classic) { 2892 Printf(f_shadow, modern ? "(object)" : "(_object)"); 2893 } 2894 if (GetFlag(n, "feature:exceptionclass") ) { 2895 Printf(f_shadow, "(Exception)"); 2896 } 2897 } 2898 Printf(f_shadow, ":\n"); 2899 if (have_docstring(n)) { 2900 String *str = docstring(n, AUTODOC_CLASS, tab4); 2901 if (str != NULL && Len(str)) 2902 Printv(f_shadow, tab4, str, "\n", NIL); 2903 } 2904 if (!modern) { 2905 Printv(f_shadow, tab4, "__swig_setmethods__ = {}\n", NIL); 2906 if (Len(base_class)) { 2907 Printf(f_shadow, "%sfor _s in [%s]: __swig_setmethods__.update(getattr(_s,'__swig_setmethods__',{}))\n", tab4, base_class); 2908 } 2909 2910 if (!GetFlag(n, "feature:python:nondynamic")) { 2911 Printv(f_shadow, tab4, "__setattr__ = lambda self, name, value: _swig_setattr(self, ", class_name, ", name, value)\n", NIL); 2912 } else { 2913 Printv(f_shadow, tab4, "__setattr__ = lambda self, name, value: _swig_setattr_nondynamic(self, ", class_name, ", name, value)\n", NIL); 2914 } 2915 2916 Printv(f_shadow, tab4, "__swig_getmethods__ = {}\n", NIL); 2917 if (Len(base_class)) { 2918 Printf(f_shadow, "%sfor _s in [%s]: __swig_getmethods__.update(getattr(_s,'__swig_getmethods__',{}))\n", tab4, base_class); 2919 } 2920 2921 Printv(f_shadow, tab4, "__getattr__ = lambda self, name: _swig_getattr(self, ", class_name, ", name)\n", NIL); 2922 } else { 2923 Printv(f_shadow, tab4, "thisown = _swig_property(lambda x: x.this.own(), ", "lambda x, v: x.this.own(v), doc='The membership flag')\n", NIL); 2924 /* Add static attribute */ 2925 if (GetFlag(n, "feature:python:nondynamic")) { 2926 Printv(f_shadow_file, 2927 tab4, "__setattr__ = _swig_setattr_nondynamic_method(object.__setattr__)\n", 2928 tab4, "class __metaclass__(type):\n", tab4, tab4, "__setattr__ = _swig_setattr_nondynamic_method(type.__setattr__)\n", NIL); 2929 } 2930 } 2931 } 2932 2933 /* Emit all of the members */ 2934 2935 in_class = 1; 2936 2937 /* Overide the shadow file so we can capture its methods */ 2938 f_shadow = NewString(""); 2939 2940 Language::classHandler(n); 2941 in_class = 0; 2942 2943 /* Complete the class */ 2944 if (shadow) { 2945 /* Generate a class registration function */ 2946 { 2947 String *smartptr = Getattr(n, "feature:smartptr"); // Replace storing a pointer to underlying class with a smart pointer (intended for use with non-intrusive smart pointers) 2948 SwigType *smart = 0; 2949 if (smartptr) { 2950 SwigType *cpt = Swig_cparse_type(smartptr); 2951 if (cpt) { 2952 smart = SwigType_typedef_resolve_all(cpt); 2953 Delete(cpt); 2954 } else { 2955 // TODO: report line number of where the feature comes from 2956 Swig_error(Getfile(n), Getline(n), "Invalid type (%s) in 'smartptr' feature for class %s.\n", smartptr, real_classname); 2957 } 2958 } 2959 SwigType *ct = Copy(smart ? smart : real_classname); 2960 SwigType_add_pointer(ct); 2961 SwigType *realct = Copy(real_classname); 2962 SwigType_add_pointer(realct); 2963 SwigType_remember(realct); 2964 Printv(f_wrappers, "SWIGINTERN PyObject *", class_name, "_swigregister(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {\n", NIL); 2965 Printv(f_wrappers, " PyObject *obj;\n", NIL); 2966 if (modernargs) { 2967 if (fastunpack) { 2968 Printv(f_wrappers, " if (!SWIG_Python_UnpackTuple(args,(char*)\"swigregister\", 1, 1,&obj)) return NULL;\n", NIL); 2969 } else { 2970 Printv(f_wrappers, " if (!PyArg_UnpackTuple(args,(char*)\"swigregister\", 1, 1,&obj)) return NULL;\n", NIL); 2971 } 2972 } else { 2973 Printv(f_wrappers, " if (!PyArg_ParseTuple(args,(char*)\"O:swigregister\", &obj)) return NULL;\n", NIL); 2974 } 2975 2976 Printv(f_wrappers, 2977 " SWIG_TypeNewClientData(SWIGTYPE", SwigType_manglestr(ct), ", SWIG_NewClientData(obj));\n", 2978 " return SWIG_Py_Void();\n", "}\n\n", NIL); 2979 String *cname = NewStringf("%s_swigregister", class_name); 2980 add_method(cname, cname, 0); 2981 Delete(smart); 2982 Delete(cname); 2983 Delete(ct); 2984 Delete(realct); 2985 } 2986 if (!have_constructor) { 2987 Printv(f_shadow_file, tab4, "def __init__(self, *args, **kwargs): raise AttributeError(\"", "No constructor defined", (Getattr(n, "abstract") ? " - class is abstract" : ""), "\")\n", NIL); 2988 } else if (fastinit) { 2989 2990 Printv(f_wrappers, "SWIGINTERN PyObject *", class_name, "_swiginit(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {\n", NIL); 2991 Printv(f_wrappers, " return SWIG_Python_InitShadowInstance(args);\n", "}\n\n", NIL); 2992 String *cname = NewStringf("%s_swiginit", class_name); 2993 add_method(cname, cname, 0); 2994 Delete(cname); 2995 } 2996 if (!have_repr) { 2997 /* Supply a repr method for this class */ 2998 String *rname = SwigType_namestr(real_classname); 2999 if (new_repr) { 3000 Printv(f_shadow_file, tab4, "__repr__ = _swig_repr\n", NIL); 3001 } else { 3002 Printv(f_shadow_file, tab4, "def __repr__(self):\n", tab8, "return \"<C ", rname, " instance at 0x%x>\" % (self.this,)\n", NIL); 3003 } 3004 Delete(rname); 3005 } 3006 3007 3008 /* Now emit methods */ 3009 Printv(f_shadow_file, f_shadow, NIL); 3010 3011 /* Now the Ptr class */ 3012 if (classptr) { 3013 Printv(f_shadow_file, "\nclass ", class_name, "Ptr(", class_name, "):\n", tab4, "def __init__(self, this):\n", NIL); 3014 if (!modern) { 3015 Printv(f_shadow_file, 3016 tab8, "try: self.this.append(this)\n", 3017 tab8, "except: self.this = this\n", tab8, "self.this.own(0)\n", tab8, "self.__class__ = ", class_name, "\n\n", NIL); 3018 } else { 3019 Printv(f_shadow_file, 3020 tab8, "try: self.this.append(this)\n", 3021 tab8, "except: self.this = this\n", tab8, "self.this.own(0)\n", tab8, "self.__class__ = ", class_name, "\n\n", NIL); 3022 } 3023 } 3024 3025 if (fastproxy) { 3026 List *shadow_list = Getattr(n, "shadow_methods"); 3027 for (int i = 0; i < Len(shadow_list); ++i) { 3028 String *symname = Getitem(shadow_list, i); 3029 Printf(f_shadow_file, "%s.%s = new_instancemethod(%s.%s,None,%s)\n", class_name, symname, module, Swig_name_member(class_name, symname), class_name); 3030 } 3031 } 3032 Printf(f_shadow_file, "%s_swigregister = %s.%s_swigregister\n", class_name, module, class_name); 3033 Printf(f_shadow_file, "%s_swigregister(%s)\n", class_name, class_name); 3034 3035 shadow_indent = 0; 3036 Printf(f_shadow_file, "%s\n", f_shadow_stubs); 3037 Clear(f_shadow_stubs); 3038 } 3039 classic = oldclassic; 3040 modern = oldmodern; 3041 3042 /* Restore shadow file back to original version */ 3043 Delete(f_shadow); 3044 f_shadow = f_shadow_file; 3045 3046 return SWIG_OK; 3047 } 3048 3049 /* ------------------------------------------------------------ 3050 * functionHandler() - Mainly overloaded for callback handling 3051 * ------------------------------------------------------------ */ 3052 3053 virtual int functionHandler(Node *n) { 3054 String *pcb = GetFlagAttr(n, "feature:python:callback"); 3055 if (pcb) { 3056 if (Strcmp(pcb, "1") == 0) { 3057 SetFlagAttr(n, "feature:callback", "%s_cb_ptr"); 3058 } else { 3059 SetFlagAttr(n, "feature:callback", pcb); 3060 } 3061 autodoc_l dlevel = autodoc_level(Getattr(n, "feature:autodoc")); 3062 if (dlevel != NO_AUTODOC && dlevel > TYPES_AUTODOC) { 3063 Setattr(n, "feature:autodoc", "1"); 3064 } 3065 } 3066 return Language::functionHandler(n); 3067 } 3068 3069 /* ------------------------------------------------------------ 3070 * memberfunctionHandler() 3071 * ------------------------------------------------------------ */ 3072 3073 virtual int memberfunctionHandler(Node *n) { 3074 String *symname = Getattr(n, "sym:name"); 3075 int oldshadow; 3076 3077 /* Create the default member function */ 3078 oldshadow = shadow; /* Disable shadowing when wrapping member functions */ 3079 if (shadow) 3080 shadow = shadow | PYSHADOW_MEMBER; 3081 Language::memberfunctionHandler(n); 3082 shadow = oldshadow; 3083 3084 if (!Getattr(n, "sym:nextSibling")) { 3085 if (shadow) { 3086 int allow_kwargs = (check_kwargs(n) && !Getattr(n, "sym:overloaded")) ? 1 : 0; 3087 int fproxy = fastproxy; 3088 if (Strcmp(symname, "__repr__") == 0) { 3089 have_repr = 1; 3090 } 3091 if (Getattr(n, "feature:shadow")) { 3092 String *pycode = pythoncode(Getattr(n, "feature:shadow"), tab4); 3093 String *pyaction = NewStringf("%s.%s", module, Swig_name_member(class_name, symname)); 3094 Replaceall(pycode, "$action", pyaction); 3095 Delete(pyaction); 3096 Printv(f_shadow, pycode, "\n", NIL); 3097 Delete(pycode); 3098 fproxy = 0; 3099 } else { 3100 String *parms = make_pyParmList(n, true, false, allow_kwargs); 3101 String *callParms = make_pyParmList(n, true, true, allow_kwargs); 3102 if (!have_addtofunc(n)) { 3103 if (!fastproxy || olddefs) { 3104 Printv(f_shadow, tab4, "def ", symname, "(", parms, ")", returnTypeAnnotation(n), ":", NIL); 3105 Printv(f_shadow, " return ", funcCall(Swig_name_member(class_name, symname), callParms), "\n", NIL); 3106 } 3107 } else { 3108 Printv(f_shadow, tab4, "def ", symname, "(",parms , ")", returnTypeAnnotation(n), ":", NIL); 3109 Printv(f_shadow, "\n", NIL); 3110 if (have_docstring(n)) 3111 Printv(f_shadow, tab8, docstring(n, AUTODOC_METHOD, tab8), "\n", NIL); 3112 if (have_pythonprepend(n)) { 3113 fproxy = 0; 3114 Printv(f_shadow, pythoncode(pythonprepend(n), tab8), "\n", NIL); 3115 } 3116 if (have_pythonappend(n)) { 3117 fproxy = 0; 3118 Printv(f_shadow, tab8, "val = ", funcCall(Swig_name_member(class_name, symname), callParms), "\n", NIL); 3119 Printv(f_shadow, pythoncode(pythonappend(n), tab8), "\n", NIL); 3120 Printv(f_shadow, tab8, "return val\n\n", NIL); 3121 } else { 3122 Printv(f_shadow, tab8, "return ", funcCall(Swig_name_member(class_name, symname), callParms), "\n\n", NIL); 3123 } 3124 } 3125 } 3126 if (fproxy) { 3127 List *shadow_list = Getattr(getCurrentClass(), "shadow_methods"); 3128 if (!shadow_list) { 3129 shadow_list = NewList(); 3130 Setattr(getCurrentClass(), "shadow_methods", shadow_list); 3131 Delete(shadow_list); 3132 } 3133 Append(shadow_list, symname); 3134 } 3135 } 3136 } 3137 return SWIG_OK; 3138 } 3139 3140 /* ------------------------------------------------------------ 3141 * staticmemberfunctionHandler() 3142 * ------------------------------------------------------------ */ 3143 3144 virtual int staticmemberfunctionHandler(Node *n) { 3145 String *symname = Getattr(n, "sym:name"); 3146 Language::staticmemberfunctionHandler(n); 3147 3148 if (Getattr(n, "sym:nextSibling")) { 3149 return SWIG_OK; 3150 } 3151 3152 if (shadow) { 3153 if (!classic && !Getattr(n, "feature:python:callback") && have_addtofunc(n)) { 3154 int kw = (check_kwargs(n) && !Getattr(n, "sym:overloaded")) ? 1 : 0; 3155 String *parms = make_pyParmList(n, false, false, kw); 3156 String *callParms = make_pyParmList(n, false, true, kw); 3157 Printv(f_shadow, tab4, "def ", symname, "(", parms, ")", returnTypeAnnotation(n), ":\n", NIL); 3158 if (have_docstring(n)) 3159 Printv(f_shadow, tab8, docstring(n, AUTODOC_STATICFUNC, tab8), "\n", NIL); 3160 if (have_pythonprepend(n)) 3161 Printv(f_shadow, pythoncode(pythonprepend(n), tab8), "\n", NIL); 3162 if (have_pythonappend(n)) { 3163 Printv(f_shadow, tab8, "val = ", funcCall(Swig_name_member(class_name, symname), callParms), "\n", NIL); 3164 Printv(f_shadow, pythoncode(pythonappend(n), tab8), "\n", NIL); 3165 Printv(f_shadow, tab8, "return val\n\n", NIL); 3166 } else { 3167 Printv(f_shadow, tab8, "return ", funcCall(Swig_name_member(class_name, symname), callParms), "\n\n", NIL); 3168 } 3169 Printv(f_shadow, tab4, modern ? "" : "if _newclass:", symname, " = staticmethod(", symname, ")\n", NIL); 3170 3171 if (!modern) { 3172 Printv(f_shadow, tab4, "__swig_getmethods__[\"", symname, "\"] = lambda x: ", symname, "\n", NIL); 3173 } 3174 3175 } else { 3176 if (!modern) { 3177 Printv(f_shadow, tab4, "__swig_getmethods__[\"", symname, "\"] = lambda x: ", module, ".", Swig_name_member(class_name, symname), "\n", NIL); 3178 } 3179 if (!classic) { 3180 Printv(f_shadow, tab4, modern ? "" : "if _newclass:", symname, " = staticmethod(", module, ".", Swig_name_member(class_name, symname), ")\n", NIL); 3181 } 3182 } 3183 } 3184 return SWIG_OK; 3185 } 3186 3187 /* ------------------------------------------------------------ 3188 * constructorDeclaration() 3189 * ------------------------------------------------------------ */ 3190 3191 virtual int constructorHandler(Node *n) { 3192 String *symname = Getattr(n, "sym:name"); 3193 int oldshadow = shadow; 3194 int use_director = Swig_directorclass(n); 3195 3196 /* 3197 * If we're wrapping the constructor of a C++ director class, prepend a new parameter 3198 * to receive the scripting language object (e.g. 'self') 3199 * 3200 */ 3201 Swig_save("python:constructorHandler", n, "parms", NIL); 3202 if (use_director) { 3203 Parm *parms = Getattr(n, "parms"); 3204 Parm *self; 3205 String *name = NewString("self"); 3206 String *type = NewString("PyObject"); 3207 SwigType_add_pointer(type); 3208 self = NewParm(type, name); 3209 Delete(type); 3210 Delete(name); 3211 Setattr(self, "lname", "O"); 3212 if (parms) 3213 set_nextSibling(self, parms); 3214 Setattr(n, "parms", self); 3215 Setattr(n, "wrap:self", "1"); 3216 Setattr(n, "hidden", "1"); 3217 Delete(self); 3218 } 3219 3220 if (shadow) 3221 shadow = shadow | PYSHADOW_MEMBER; 3222 Language::constructorHandler(n); 3223 shadow = oldshadow; 3224 3225 Delattr(n, "wrap:self"); 3226 Swig_restore(n); 3227 3228 if (!Getattr(n, "sym:nextSibling")) { 3229 if (shadow) { 3230 int allow_kwargs = (check_kwargs(n) && (!Getattr(n, "sym:overloaded"))) ? 1 : 0; 3231 int handled_as_init = 0; 3232 if (!have_constructor) { 3233 String *nname = Getattr(n, "sym:name"); 3234 String *sname = Getattr(getCurrentClass(), "sym:name"); 3235 String *cname = Swig_name_construct(sname); 3236 handled_as_init = (Strcmp(nname, sname) == 0) || (Strcmp(nname, cname) == 0); 3237 Delete(cname); 3238 } 3239 3240 if (!have_constructor && handled_as_init) { 3241 if (Getattr(n, "feature:shadow")) { 3242 String *pycode = pythoncode(Getattr(n, "feature:shadow"), tab4); 3243 String *pyaction = NewStringf("%s.%s", module, Swig_name_construct(symname)); 3244 Replaceall(pycode, "$action", pyaction); 3245 Delete(pyaction); 3246 Printv(f_shadow, pycode, "\n", NIL); 3247 Delete(pycode); 3248 } else { 3249 String *pass_self = NewString(""); 3250 Node *parent = Swig_methodclass(n); 3251 String *classname = Swig_class_name(parent); 3252 String *rclassname = Swig_class_name(getCurrentClass()); 3253 assert(rclassname); 3254 3255 String *parms = make_pyParmList(n, true, false, allow_kwargs); 3256 /* Pass 'self' only if using director */ 3257 String *callParms = make_pyParmList(n, false, true, allow_kwargs); 3258 3259 if (use_director) { 3260 Insert(callParms, 0, "_self, "); 3261 Printv(pass_self, tab8, NIL); 3262 Printf(pass_self, "if self.__class__ == %s:\n", classname); 3263 //Printv(pass_self, tab8, tab4, "args = (None,) + args\n", tab8, "else:\n", tab8, tab4, "args = (self,) + args\n", NIL); 3264 Printv(pass_self, tab8, tab4, "_self = None\n", tab8, "else:\n", tab8, tab4, "_self = self\n", NIL); 3265 } 3266 3267 Printv(f_shadow, tab4, "def __init__(", parms, ")", returnTypeAnnotation(n), ": \n", NIL); 3268 if (have_docstring(n)) 3269 Printv(f_shadow, tab8, docstring(n, AUTODOC_CTOR, tab8), "\n", NIL); 3270 if (have_pythonprepend(n)) 3271 Printv(f_shadow, pythoncode(pythonprepend(n), tab8), "\n", NIL); 3272 Printv(f_shadow, pass_self, NIL); 3273 if (fastinit) { 3274 Printv(f_shadow, tab8, module, ".", class_name, "_swiginit(self,", funcCall(Swig_name_construct(symname), callParms), ")\n", NIL); 3275 } else { 3276 Printv(f_shadow, 3277 tab8, "this = ", funcCall(Swig_name_construct(symname), callParms), "\n", 3278 tab8, "try: self.this.append(this)\n", tab8, "except: self.this = this\n", NIL); 3279 } 3280 if (have_pythonappend(n)) 3281 Printv(f_shadow, pythoncode(pythonappend(n), tab8), "\n\n", NIL); 3282 Delete(pass_self); 3283 } 3284 have_constructor = 1; 3285 } else { 3286 /* Hmmm. We seem to be creating a different constructor. We're just going to create a 3287 function for it. */ 3288 3289 if (Getattr(n, "feature:shadow")) { 3290 String *pycode = pythoncode(Getattr(n, "feature:shadow"), ""); 3291 String *pyaction = NewStringf("%s.%s", module, Swig_name_construct(symname)); 3292 Replaceall(pycode, "$action", pyaction); 3293 Delete(pyaction); 3294 Printv(f_shadow_stubs, pycode, "\n", NIL); 3295 Delete(pycode); 3296 } else { 3297 String *parms = make_pyParmList(n, true, false, allow_kwargs); 3298 String *callParms = make_pyParmList(n, true, true, allow_kwargs); 3299 3300 Printv(f_shadow_stubs, "\ndef ", symname, "(", parms, ")", returnTypeAnnotation(n), ":\n", NIL); 3301 if (have_docstring(n)) 3302 Printv(f_shadow_stubs, tab4, docstring(n, AUTODOC_CTOR, tab4), "\n", NIL); 3303 if (have_pythonprepend(n)) 3304 Printv(f_shadow_stubs, pythoncode(pythonprepend(n), tab4), "\n", NIL); 3305 Printv(f_shadow_stubs, tab4, "val = ", funcCall(Swig_name_construct(symname), callParms), "\n", NIL); 3306#ifdef USE_THISOWN 3307 Printv(f_shadow_stubs, tab4, "val.thisown = 1\n", NIL); 3308#endif 3309 if (have_pythonappend(n)) 3310 Printv(f_shadow_stubs, pythoncode(pythonappend(n), tab4), "\n", NIL); 3311 Printv(f_shadow_stubs, tab4, "return val\n", NIL); 3312 } 3313 } 3314 } 3315 } 3316 return SWIG_OK; 3317 } 3318 3319 /* ------------------------------------------------------------ 3320 * destructorHandler() 3321 * ------------------------------------------------------------ */ 3322 3323 virtual int destructorHandler(Node *n) { 3324 String *symname = Getattr(n, "sym:name"); 3325 int oldshadow = shadow; 3326 3327 if (shadow) 3328 shadow = shadow | PYSHADOW_MEMBER; 3329 //Setattr(n,"emit:dealloc","1"); 3330 Language::destructorHandler(n); 3331 shadow = oldshadow; 3332 if (shadow) { 3333 if (Getattr(n, "feature:shadow")) { 3334 String *pycode = pythoncode(Getattr(n, "feature:shadow"), tab4); 3335 String *pyaction = NewStringf("%s.%s", module, Swig_name_destroy(symname)); 3336 Replaceall(pycode, "$action", pyaction); 3337 Delete(pyaction); 3338 Printv(f_shadow, pycode, "\n", NIL); 3339 Delete(pycode); 3340 } else { 3341 Printv(f_shadow, tab4, "__swig_destroy__ = ", module, ".", Swig_name_destroy(symname), "\n", NIL); 3342 if (!have_pythonprepend(n) && !have_pythonappend(n)) { 3343 if (proxydel) { 3344 Printv(f_shadow, tab4, "__del__ = lambda self : None;\n", NIL); 3345 } 3346 return SWIG_OK; 3347 } 3348 Printv(f_shadow, tab4, "def __del__(self):\n", NIL); 3349 if (have_docstring(n)) 3350 Printv(f_shadow, tab8, docstring(n, AUTODOC_DTOR, tab8), "\n", NIL); 3351 if (have_pythonprepend(n)) 3352 Printv(f_shadow, pythoncode(pythonprepend(n), tab8), "\n", NIL); 3353#ifdef USE_THISOWN 3354 Printv(f_shadow, tab8, "try:\n", NIL); 3355 Printv(f_shadow, tab8, tab4, "if self.thisown: ", module, ".", Swig_name_destroy(symname), "(self)\n", NIL); 3356 Printv(f_shadow, tab8, "except: pass\n", NIL); 3357#else 3358#endif 3359 if (have_pythonappend(n)) 3360 Printv(f_shadow, pythoncode(pythonappend(n), tab8), "\n", NIL); 3361 Printv(f_shadow, tab8, "pass\n", NIL); 3362 Printv(f_shadow, "\n", NIL); 3363 } 3364 } 3365 return SWIG_OK; 3366 } 3367 3368 /* ------------------------------------------------------------ 3369 * membervariableHandler() 3370 * ------------------------------------------------------------ */ 3371 3372 virtual int membervariableHandler(Node *n) { 3373 String *symname = Getattr(n, "sym:name"); 3374 3375 int oldshadow = shadow; 3376 if (shadow) 3377 shadow = shadow | PYSHADOW_MEMBER; 3378 Language::membervariableHandler(n); 3379 shadow = oldshadow; 3380 3381 if (shadow) { 3382 String *mname = Swig_name_member(class_name, symname); 3383 String *setname = Swig_name_set(mname); 3384 String *getname = Swig_name_get(mname); 3385 if (shadow) { 3386 int assignable = is_assignable(n); 3387 if (!modern) { 3388 if (assignable) { 3389 Printv(f_shadow, tab4, "__swig_setmethods__[\"", symname, "\"] = ", module, ".", setname, "\n", NIL); 3390 } 3391 Printv(f_shadow, tab4, "__swig_getmethods__[\"", symname, "\"] = ", module, ".", getname, "\n", NIL); 3392 } 3393 if (!classic) { 3394 if (!assignable) { 3395 Printv(f_shadow, tab4, modern ? "" : "if _newclass:", symname, " = _swig_property(", module, ".", getname, ")\n", NIL); 3396 } else { 3397 Printv(f_shadow, tab4, modern ? "" : "if _newclass:", symname, " = _swig_property(", module, ".", getname, ", ", module, ".", setname, ")\n", NIL); 3398 } 3399 } 3400 } 3401 Delete(mname); 3402 Delete(setname); 3403 Delete(getname); 3404 } 3405 3406 return SWIG_OK; 3407 } 3408 3409 /* ------------------------------------------------------------ 3410 * staticmembervariableHandler() 3411 * ------------------------------------------------------------ */ 3412 3413 virtual int staticmembervariableHandler(Node *n) { 3414 Language::staticmembervariableHandler(n); 3415 3416 if (shadow && !GetFlag(n, "wrappedasconstant")) { 3417 String *symname = Getattr(n, "sym:name"); 3418 if (GetFlag(n, "hasconsttype")) { 3419 String *mname = Swig_name_member(class_name, symname); 3420 Printf(f_shadow_stubs, "%s.%s = %s.%s.%s\n", class_name, symname, module, global_name, mname); 3421 Delete(mname); 3422 } else { 3423 String *mname = Swig_name_member(class_name, symname); 3424 String *getname = Swig_name_get(mname); 3425 String *wrapgetname = Swig_name_wrapper(getname); 3426 String *vargetname = NewStringf("Swig_var_%s", getname); 3427 String *setname = Swig_name_set(mname); 3428 String *wrapsetname = Swig_name_wrapper(setname); 3429 String *varsetname = NewStringf("Swig_var_%s", setname); 3430 3431 Wrapper *f = NewWrapper(); 3432 Printv(f->def, "SWIGINTERN PyObject *", wrapgetname, "(PyObject *SWIGUNUSEDPARM(self), PyObject *SWIGUNUSEDPARM(args)) {", NIL); 3433 Printv(f->code, " return ", vargetname, "();\n", NIL); 3434 Append(f->code, "}\n"); 3435 add_method(getname, wrapgetname, 0); 3436 Wrapper_print(f, f_wrappers); 3437 DelWrapper(f); 3438 int assignable = is_assignable(n); 3439 if (assignable) { 3440 Wrapper *f = NewWrapper(); 3441 Printv(f->def, "SWIGINTERN PyObject *", wrapsetname, "(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {", NIL); 3442 Wrapper_add_local(f, "value", "PyObject *value"); 3443 Wrapper_add_local(f, "res", "int res"); 3444 Append(f->code, "if (!PyArg_ParseTuple(args,(char *)\"O:set\",&value)) return NULL;\n"); 3445 Printv(f->code, "res = ", varsetname, "(value);\n", NIL); 3446 Append(f->code, "return !res ? SWIG_Py_Void() : NULL;\n"); 3447 Append(f->code, "}\n"); 3448 Wrapper_print(f, f_wrappers); 3449 add_method(setname, wrapsetname, 0); 3450 DelWrapper(f); 3451 } 3452 if (!modern) { 3453 if (assignable) { 3454 Printv(f_shadow, tab4, "__swig_setmethods__[\"", symname, "\"] = ", module, ".", setname, "\n", NIL); 3455 } 3456 Printv(f_shadow, tab4, "__swig_getmethods__[\"", symname, "\"] = ", module, ".", getname, "\n", NIL); 3457 } 3458 if (!classic) { 3459 if (!assignable) { 3460 Printv(f_shadow, tab4, modern ? "" : "if _newclass:", symname, " = _swig_property(", module, ".", getname, ")\n", NIL); 3461 } else { 3462 Printv(f_shadow, tab4, modern ? "" : "if _newclass:", symname, " = _swig_property(", module, ".", getname, ", ", module, ".", setname, ")\n", NIL); 3463 } 3464 } 3465 Delete(mname); 3466 Delete(getname); 3467 Delete(wrapgetname); 3468 Delete(vargetname); 3469 Delete(setname); 3470 Delete(wrapsetname); 3471 Delete(varsetname); 3472 } 3473 } 3474 return SWIG_OK; 3475 } 3476 3477 /* ------------------------------------------------------------ 3478 * memberconstantHandler() 3479 * ------------------------------------------------------------ */ 3480 3481 virtual int memberconstantHandler(Node *n) { 3482 String *symname = Getattr(n, "sym:name"); 3483 int oldshadow = shadow; 3484 if (shadow) 3485 shadow = shadow | PYSHADOW_MEMBER; 3486 Language::memberconstantHandler(n); 3487 shadow = oldshadow; 3488 3489 if (shadow) { 3490 Printv(f_shadow, tab4, symname, " = ", module, ".", Swig_name_member(class_name, symname), "\n", NIL); 3491 } 3492 return SWIG_OK; 3493 } 3494 3495 /* ------------------------------------------------------------ 3496 * insertDirective() 3497 * 3498 * Hook for %insert directive. We're going to look for special %shadow inserts 3499 * as a special case so we can do indenting correctly 3500 * ------------------------------------------------------------ */ 3501 3502 virtual int insertDirective(Node *n) { 3503 String *code = Getattr(n, "code"); 3504 String *section = Getattr(n, "section"); 3505 3506 if ((!ImportMode) && ((Cmp(section, "python") == 0) || (Cmp(section, "shadow") == 0))) { 3507 if (shadow) { 3508 String *pycode = pythoncode(code, shadow_indent); 3509 Printv(f_shadow, pycode, NIL); 3510 Delete(pycode); 3511 } 3512 } else { 3513 Language::insertDirective(n); 3514 } 3515 return SWIG_OK; 3516 } 3517 3518 virtual String *runtimeCode() { 3519 String *s = NewString(""); 3520 String *shead = Swig_include_sys("pyhead.swg"); 3521 if (!shead) { 3522 Printf(stderr, "*** Unable to open 'pyhead.swg'\n"); 3523 } else { 3524 Append(s, shead); 3525 Delete(shead); 3526 } 3527 String *serrors = Swig_include_sys("pyerrors.swg"); 3528 if (!serrors) { 3529 Printf(stderr, "*** Unable to open 'pyerrors.swg'\n"); 3530 } else { 3531 Append(s, serrors); 3532 Delete(serrors); 3533 } 3534 String *sthread = Swig_include_sys("pythreads.swg"); 3535 if (!sthread) { 3536 Printf(stderr, "*** Unable to open 'pythreads.swg'\n"); 3537 } else { 3538 Append(s, sthread); 3539 Delete(sthread); 3540 } 3541 String *sapi = Swig_include_sys("pyapi.swg"); 3542 if (!sapi) { 3543 Printf(stderr, "*** Unable to open 'pyapi.swg'\n"); 3544 } else { 3545 Append(s, sapi); 3546 Delete(sapi); 3547 } 3548 String *srun = Swig_include_sys("pyrun.swg"); 3549 if (!srun) { 3550 Printf(stderr, "*** Unable to open 'pyrun.swg'\n"); 3551 } else { 3552 Append(s, srun); 3553 Delete(srun); 3554 } 3555 return s; 3556 } 3557 3558 virtual String *defaultExternalRuntimeFilename() { 3559 return NewString("swigpyrun.h"); 3560 } 3561 3562}; 3563 3564/* --------------------------------------------------------------- 3565 * classDirectorMethod() 3566 * 3567 * Emit a virtual director method to pass a method call on to the 3568 * underlying Python object. 3569 * 3570 * ** Moved it here due to internal error on gcc-2.96 ** 3571 * --------------------------------------------------------------- */ 3572int PYTHON::classDirectorMethods(Node *n) { 3573 director_method_index = 0; 3574 return Language::classDirectorMethods(n); 3575} 3576 3577 3578int PYTHON::classDirectorMethod(Node *n, Node *parent, String *super) { 3579 int is_void = 0; 3580 int is_pointer = 0; 3581 String *decl; 3582 String *type; 3583 String *name; 3584 String *classname; 3585 String *c_classname = Getattr(parent, "name"); 3586 String *declaration; 3587 ParmList *l; 3588 Wrapper *w; 3589 String *tm; 3590 String *wrap_args = NewString(""); 3591 String *return_type; 3592 String *value = Getattr(n, "value"); 3593 String *storage = Getattr(n, "storage"); 3594 bool pure_virtual = false; 3595 int status = SWIG_OK; 3596 int idx; 3597 bool ignored_method = GetFlag(n, "feature:ignore") ? true : false; 3598 3599 if (Cmp(storage, "virtual") == 0) { 3600 if (Cmp(value, "0") == 0) { 3601 pure_virtual = true; 3602 } 3603 } 3604 3605 classname = Getattr(parent, "sym:name"); 3606 type = Getattr(n, "type"); 3607 name = Getattr(n, "name"); 3608 3609 w = NewWrapper(); 3610 declaration = NewString(""); 3611 3612 /* determine if the method returns a pointer */ 3613 decl = Getattr(n, "decl"); 3614 is_pointer = SwigType_ispointer_return(decl); 3615 is_void = (!Cmp(type, "void") && !is_pointer); 3616 3617 /* form complete return type */ 3618 return_type = Copy(type); 3619 { 3620 SwigType *t = Copy(decl); 3621 SwigType *f = 0; 3622 f = SwigType_pop_function(t); 3623 SwigType_push(return_type, t); 3624 Delete(f); 3625 Delete(t); 3626 } 3627 3628 /* virtual method definition */ 3629 l = Getattr(n, "parms"); 3630 String *target; 3631 String *pclassname = NewStringf("SwigDirector_%s", classname); 3632 String *qualified_name = NewStringf("%s::%s", pclassname, name); 3633 SwigType *rtype = Getattr(n, "conversion_operator") ? 0 : type; 3634 target = Swig_method_decl(rtype, decl, qualified_name, l, 0, 0); 3635 Printf(w->def, "%s", target); 3636 Delete(qualified_name); 3637 Delete(target); 3638 /* header declaration */ 3639 target = Swig_method_decl(rtype, decl, name, l, 0, 1); 3640 Printf(declaration, " virtual %s", target); 3641 Delete(target); 3642 3643 // Get any exception classes in the throws typemap 3644 ParmList *throw_parm_list = 0; 3645 3646 if ((throw_parm_list = Getattr(n, "throws")) || Getattr(n, "throw")) { 3647 Parm *p; 3648 int gencomma = 0; 3649 3650 Append(w->def, " throw("); 3651 Append(declaration, " throw("); 3652 3653 if (throw_parm_list) 3654 Swig_typemap_attach_parms("throws", throw_parm_list, 0); 3655 for (p = throw_parm_list; p; p = nextSibling(p)) { 3656 if ((tm = Getattr(p, "tmap:throws"))) { 3657 if (gencomma++) { 3658 Append(w->def, ", "); 3659 Append(declaration, ", "); 3660 } 3661 String *str = SwigType_str(Getattr(p, "type"), 0); 3662 Append(w->def, str); 3663 Append(declaration, str); 3664 Delete(str); 3665 } 3666 } 3667 3668 Append(w->def, ")"); 3669 Append(declaration, ")"); 3670 } 3671 3672 Append(w->def, " {"); 3673 Append(declaration, ";\n"); 3674 3675 /* declare method return value 3676 * if the return value is a reference or const reference, a specialized typemap must 3677 * handle it, including declaration of c_result ($result). 3678 */ 3679 if (!is_void) { 3680 if (!(ignored_method && !pure_virtual)) { 3681 String *cres = SwigType_lstr(return_type, "c_result"); 3682 Printf(w->code, "%s;\n", cres); 3683 Delete(cres); 3684 } 3685 } 3686 3687 if (ignored_method) { 3688 if (!pure_virtual) { 3689 if (!is_void) 3690 Printf(w->code, "return "); 3691 String *super_call = Swig_method_call(super, l); 3692 Printf(w->code, "%s;\n", super_call); 3693 Delete(super_call); 3694 } else { 3695 Printf(w->code, "Swig::DirectorPureVirtualException::raise(\"Attempted to invoke pure virtual method %s::%s\");\n", SwigType_namestr(c_classname), 3696 SwigType_namestr(name)); 3697 } 3698 } else { 3699 /* attach typemaps to arguments (C/C++ -> Python) */ 3700 String *arglist = NewString(""); 3701 String *parse_args = NewString(""); 3702 3703 /* remove the wrapper 'w' since it was producing spurious temps */ 3704 Swig_typemap_attach_parms("in", l, 0); 3705 Swig_typemap_attach_parms("directorin", l, 0); 3706 Swig_typemap_attach_parms("directorargout", l, w); 3707 3708 Parm *p; 3709 char source[256]; 3710 3711 int outputs = 0; 3712 if (!is_void) 3713 outputs++; 3714 3715 /* build argument list and type conversion string */ 3716 idx = 0; 3717 p = l; 3718 int use_parse = 0; 3719 while (p != NULL) { 3720 if (checkAttribute(p, "tmap:in:numinputs", "0")) { 3721 p = Getattr(p, "tmap:in:next"); 3722 continue; 3723 } 3724 3725 /* old style? caused segfaults without the p!=0 check 3726 in the for() condition, and seems dangerous in the 3727 while loop as well. 3728 while (Getattr(p, "tmap:ignore")) { 3729 p = Getattr(p, "tmap:ignore:next"); 3730 } 3731 */ 3732 3733 if (Getattr(p, "tmap:directorargout") != 0) 3734 outputs++; 3735 3736 String *pname = Getattr(p, "name"); 3737 String *ptype = Getattr(p, "type"); 3738 3739 Putc(',', arglist); 3740 if ((tm = Getattr(p, "tmap:directorin")) != 0) { 3741 String *parse = Getattr(p, "tmap:directorin:parse"); 3742 if (!parse) { 3743 sprintf(source, "obj%d", idx++); 3744 String *input = NewString(source); 3745 Replaceall(tm, "$input", input); 3746 Delete(input); 3747 Replaceall(tm, "$owner", "0"); 3748 /* Wrapper_add_localv(w, source, "swig::SwigVar_PyObject", source, "= 0", NIL); */ 3749 Printv(wrap_args, "swig::SwigVar_PyObject ", source, ";\n", NIL); 3750 3751 Printv(wrap_args, tm, "\n", NIL); 3752 Printv(arglist, "(PyObject *)", source, NIL); 3753 Putc('O', parse_args); 3754 } else { 3755 use_parse = 1; 3756 Append(parse_args, parse); 3757 Replaceall(tm, "$input", pname); 3758 Replaceall(tm, "$owner", "0"); 3759 if (Len(tm) == 0) 3760 Append(tm, pname); 3761 Append(arglist, tm); 3762 } 3763 p = Getattr(p, "tmap:directorin:next"); 3764 continue; 3765 } else if (Cmp(ptype, "void")) { 3766 /* special handling for pointers to other C++ director classes. 3767 * ideally this would be left to a typemap, but there is currently no 3768 * way to selectively apply the dynamic_cast<> to classes that have 3769 * directors. in other words, the type "SwigDirector_$1_lname" only exists 3770 * for classes with directors. we avoid the problem here by checking 3771 * module.wrap::directormap, but it's not clear how to get a typemap to 3772 * do something similar. perhaps a new default typemap (in addition 3773 * to SWIGTYPE) called DIRECTORTYPE? 3774 */ 3775 if (SwigType_ispointer(ptype) || SwigType_isreference(ptype)) { 3776 Node *module = Getattr(parent, "module"); 3777 Node *target = Swig_directormap(module, ptype); 3778 sprintf(source, "obj%d", idx++); 3779 String *nonconst = 0; 3780 /* strip pointer/reference --- should move to Swig/stype.c */ 3781 String *nptype = NewString(Char(ptype) + 2); 3782 /* name as pointer */ 3783 String *ppname = Copy(pname); 3784 if (SwigType_isreference(ptype)) { 3785 Insert(ppname, 0, "&"); 3786 } 3787 /* if necessary, cast away const since Python doesn't support it! */ 3788 if (SwigType_isconst(nptype)) { 3789 nonconst = NewStringf("nc_tmp_%s", pname); 3790 String *nonconst_i = NewStringf("= const_cast<%s>(%s)", SwigType_lstr(ptype, 0), ppname); 3791 Wrapper_add_localv(w, nonconst, SwigType_lstr(ptype, 0), nonconst, nonconst_i, NIL); 3792 Delete(nonconst_i); 3793 Swig_warning(WARN_LANG_DISCARD_CONST, input_file, line_number, 3794 "Target language argument '%s' discards const in director method %s::%s.\n", 3795 SwigType_str(ptype, pname), SwigType_namestr(c_classname), SwigType_namestr(name)); 3796 } else { 3797 nonconst = Copy(ppname); 3798 } 3799 Delete(nptype); 3800 Delete(ppname); 3801 String *mangle = SwigType_manglestr(ptype); 3802 if (target) { 3803 String *director = NewStringf("director_%s", mangle); 3804 Wrapper_add_localv(w, director, "Swig::Director *", director, "= 0", NIL); 3805 Wrapper_add_localv(w, source, "swig::SwigVar_PyObject", source, "= 0", NIL); 3806 Printf(wrap_args, "%s = SWIG_DIRECTOR_CAST(%s);\n", director, nonconst); 3807 Printf(wrap_args, "if (!%s) {\n", director); 3808 Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle); 3809 Append(wrap_args, "} else {\n"); 3810 Printf(wrap_args, "%s = %s->swig_get_self();\n", source, director); 3811 Printf(wrap_args, "Py_INCREF((PyObject *)%s);\n", source); 3812 Append(wrap_args, "}\n"); 3813 Delete(director); 3814 Printv(arglist, source, NIL); 3815 } else { 3816 Wrapper_add_localv(w, source, "swig::SwigVar_PyObject", source, "= 0", NIL); 3817 Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE%s, 0);\n", source, nonconst, mangle); 3818 //Printf(wrap_args, "%s = SWIG_NewPointerObj(%s, SWIGTYPE_p_%s, 0);\n", 3819 // source, nonconst, base); 3820 Printv(arglist, source, NIL); 3821 } 3822 Putc('O', parse_args); 3823 Delete(mangle); 3824 Delete(nonconst); 3825 } else { 3826 Swig_warning(WARN_TYPEMAP_DIRECTORIN_UNDEF, input_file, line_number, 3827 "Unable to use type %s as a function argument in director method %s::%s (skipping method).\n", SwigType_str(ptype, 0), 3828 SwigType_namestr(c_classname), SwigType_namestr(name)); 3829 status = SWIG_NOWRAP; 3830 break; 3831 } 3832 } 3833 p = nextSibling(p); 3834 } 3835 3836 /* add the method name as a PyString */ 3837 String *pyname = Getattr(n, "sym:name"); 3838 3839 int allow_thread = threads_enable(n); 3840 3841 if (allow_thread) { 3842 thread_begin_block(n, w->code); 3843 Append(w->code, "{\n"); 3844 } 3845 3846 /* wrap complex arguments to PyObjects */ 3847 Printv(w->code, wrap_args, NIL); 3848 3849 /* pass the method call on to the Python object */ 3850 if (dirprot_mode() && !is_public(n)) { 3851 Printf(w->code, "swig_set_inner(\"%s\", true);\n", name); 3852 } 3853 3854 3855 Append(w->code, "if (!swig_get_self()) {\n"); 3856 Printf(w->code, " Swig::DirectorException::raise(\"'self' uninitialized, maybe you forgot to call %s.__init__.\");\n", classname); 3857 Append(w->code, "}\n"); 3858 Append(w->code, "#if defined(SWIG_PYTHON_DIRECTOR_VTABLE)\n"); 3859 Printf(w->code, "const size_t swig_method_index = %d;\n", director_method_index++); 3860 Printf(w->code, "const char * const swig_method_name = \"%s\";\n", pyname); 3861 3862 Append(w->code, "PyObject* method = swig_get_method(swig_method_index, swig_method_name);\n"); 3863 if (Len(parse_args) > 0) { 3864 if (use_parse || !modernargs) { 3865 Printf(w->code, "swig::SwigVar_PyObject result = PyObject_CallFunction(method, (char *)\"(%s)\" %s);\n", parse_args, arglist); 3866 } else { 3867 Printf(w->code, "swig::SwigVar_PyObject result = PyObject_CallFunctionObjArgs(method %s, NULL);\n", arglist); 3868 } 3869 } else { 3870 if (modernargs) { 3871 Append(w->code, "swig::SwigVar_PyObject args = PyTuple_New(0);\n"); 3872 Append(w->code, "swig::SwigVar_PyObject result = PyObject_Call(method, (PyObject*) args, NULL);\n"); 3873 } else { 3874 Printf(w->code, "swig::SwigVar_PyObject result = PyObject_CallFunction(method, NULL, NULL);\n"); 3875 } 3876 } 3877 Append(w->code, "#else\n"); 3878 if (Len(parse_args) > 0) { 3879 if (use_parse || !modernargs) { 3880 Printf(w->code, "swig::SwigVar_PyObject result = PyObject_CallMethod(swig_get_self(), (char *)\"%s\", (char *)\"(%s)\" %s);\n", 3881 pyname, parse_args, arglist); 3882 } else { 3883 Printf(w->code, "swig::SwigVar_PyObject swig_method_name = SWIG_Python_str_FromChar((char *)\"%s\");\n", pyname); 3884 Printf(w->code, "swig::SwigVar_PyObject result = PyObject_CallMethodObjArgs(swig_get_self(), (PyObject *) swig_method_name %s, NULL);\n", arglist); 3885 } 3886 } else { 3887 if (!modernargs) { 3888 Printf(w->code, "swig::SwigVar_PyObject result = PyObject_CallMethod(swig_get_self(), (char *) \"%s\", NULL);\n", pyname); 3889 } else { 3890 Printf(w->code, "swig::SwigVar_PyObject swig_method_name = SWIG_Python_str_FromChar((char *)\"%s\");\n", pyname); 3891 Append(w->code, "swig::SwigVar_PyObject result = PyObject_CallMethodObjArgs(swig_get_self(), (PyObject *) swig_method_name, NULL);\n"); 3892 } 3893 } 3894 Append(w->code, "#endif\n"); 3895 3896 if (dirprot_mode() && !is_public(n)) 3897 Printf(w->code, "swig_set_inner(\"%s\", false);\n", name); 3898 3899 /* exception handling */ 3900 tm = Swig_typemap_lookup("director:except", n, "result", 0); 3901 if (!tm) { 3902 tm = Getattr(n, "feature:director:except"); 3903 if (tm) 3904 tm = Copy(tm); 3905 } 3906 Append(w->code, "if (result == NULL) {\n"); 3907 Append(w->code, " PyObject *error = PyErr_Occurred();\n"); 3908 if ((tm) && Len(tm) && (Strcmp(tm, "1") != 0)) { 3909 Replaceall(tm, "$error", "error"); 3910 Printv(w->code, Str(tm), "\n", NIL); 3911 } else { 3912 Append(w->code, " if (error != NULL) {\n"); 3913 Printf(w->code, " Swig::DirectorMethodException::raise(\"Error detected when calling '%s.%s'\");\n", classname, pyname); 3914 Append(w->code, " }\n"); 3915 } 3916 Append(w->code, "}\n"); 3917 Delete(tm); 3918 3919 /* 3920 * Python method may return a simple object, or a tuple. 3921 * for in/out aruments, we have to extract the appropriate PyObjects from the tuple, 3922 * then marshal everything back to C/C++ (return value and output arguments). 3923 * 3924 */ 3925 3926 /* marshal return value and other outputs (if any) from PyObject to C/C++ type */ 3927 3928 String *cleanup = NewString(""); 3929 String *outarg = NewString(""); 3930 3931 if (outputs > 1) { 3932 Wrapper_add_local(w, "output", "PyObject *output"); 3933 Append(w->code, "if (!PyTuple_Check(result)) {\n"); 3934 Printf(w->code, " Swig::DirectorTypeMismatchException::raise(\"Python method %s.%sfailed to return a tuple.\");\n", classname, pyname); 3935 Append(w->code, "}\n"); 3936 } 3937 3938 idx = 0; 3939 3940 /* marshal return value */ 3941 if (!is_void) { 3942 /* this seems really silly. the node's type excludes 3943 * qualifier/pointer/reference markers, which have to be retrieved 3944 * from the decl field to construct return_type. but the typemap 3945 * lookup routine uses the node's type, so we have to swap in and 3946 * out the correct type. it's not just me, similar silliness also 3947 * occurs in Language::cDeclaration(). 3948 */ 3949 Setattr(n, "type", return_type); 3950 tm = Swig_typemap_lookup("directorout", n, "result", w); 3951 Setattr(n, "type", type); 3952 if (tm != 0) { 3953 if (outputs > 1) { 3954 Printf(w->code, "output = PyTuple_GetItem(result, %d);\n", idx++); 3955 Replaceall(tm, "$input", "output"); 3956 } else { 3957 Replaceall(tm, "$input", "result"); 3958 } 3959 char temp[24]; 3960 sprintf(temp, "%d", idx); 3961 Replaceall(tm, "$argnum", temp); 3962 3963 /* TODO check this */ 3964 if (Getattr(n, "wrap:disown")) { 3965 Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN"); 3966 } else { 3967 Replaceall(tm, "$disown", "0"); 3968 } 3969 if (Getattr(n, "tmap:directorout:implicitconv")) { 3970 Replaceall(tm, "$implicitconv", get_implicitconv_flag(n)); 3971 } 3972 Replaceall(tm, "$result", "c_result"); 3973 Printv(w->code, tm, "\n", NIL); 3974 Delete(tm); 3975 } else { 3976 Swig_warning(WARN_TYPEMAP_DIRECTOROUT_UNDEF, input_file, line_number, 3977 "Unable to use return type %s in director method %s::%s (skipping method).\n", SwigType_str(return_type, 0), SwigType_namestr(c_classname), 3978 SwigType_namestr(name)); 3979 status = SWIG_ERROR; 3980 } 3981 } 3982 3983 /* marshal outputs */ 3984 for (p = l; p;) { 3985 if ((tm = Getattr(p, "tmap:directorargout")) != 0) { 3986 if (outputs > 1) { 3987 Printf(w->code, "output = PyTuple_GetItem(result, %d);\n", idx++); 3988 Replaceall(tm, "$input", "output"); 3989 } else { 3990 Replaceall(tm, "$input", "result"); 3991 } 3992 Replaceall(tm, "$result", Getattr(p, "name")); 3993 Printv(w->code, tm, "\n", NIL); 3994 p = Getattr(p, "tmap:directorargout:next"); 3995 } else { 3996 p = nextSibling(p); 3997 } 3998 } 3999 4000 /* any existing helper functions to handle this? */ 4001 if (allow_thread) { 4002 Append(w->code, "}\n"); 4003 thread_end_block(n, w->code); 4004 } 4005 4006 Delete(parse_args); 4007 Delete(arglist); 4008 Delete(cleanup); 4009 Delete(outarg); 4010 } 4011 4012 if (!is_void) { 4013 if (!(ignored_method && !pure_virtual)) { 4014 String *rettype = SwigType_str(return_type, 0); 4015 if (!SwigType_isreference(return_type)) { 4016 Printf(w->code, "return (%s) c_result;\n", rettype); 4017 } else { 4018 Printf(w->code, "return (%s) *c_result;\n", rettype); 4019 } 4020 Delete(rettype); 4021 } 4022 } 4023 4024 Append(w->code, "}\n"); 4025 4026 // We expose protected methods via an extra public inline method which makes a straight call to the wrapped class' method 4027 String *inline_extra_method = NewString(""); 4028 if (dirprot_mode() && !is_public(n) && !pure_virtual) { 4029 Printv(inline_extra_method, declaration, NIL); 4030 String *extra_method_name = NewStringf("%sSwigPublic", name); 4031 Replaceall(inline_extra_method, name, extra_method_name); 4032 Replaceall(inline_extra_method, ";\n", " {\n "); 4033 if (!is_void) 4034 Printf(inline_extra_method, "return "); 4035 String *methodcall = Swig_method_call(super, l); 4036 Printv(inline_extra_method, methodcall, ";\n }\n", NIL); 4037 Delete(methodcall); 4038 Delete(extra_method_name); 4039 } 4040 4041 /* emit the director method */ 4042 if (status == SWIG_OK) { 4043 if (!Getattr(n, "defaultargs")) { 4044 Wrapper_print(w, f_directors); 4045 Printv(f_directors_h, declaration, NIL); 4046 Printv(f_directors_h, inline_extra_method, NIL); 4047 } 4048 } 4049 4050 /* clean up */ 4051 Delete(wrap_args); 4052 Delete(return_type); 4053 Delete(pclassname); 4054 DelWrapper(w); 4055 return status; 4056} 4057 4058/* ----------------------------------------------------------------------------- 4059 * swig_python() - Instantiate module 4060 * ----------------------------------------------------------------------------- */ 4061 4062static Language *new_swig_python() { 4063 return new PYTHON(); 4064} 4065extern "C" Language *swig_python(void) { 4066 return new_swig_python(); 4067} 4068