PageRenderTime 106ms CodeModel.GetById 22ms RepoModel.GetById 11ms app.codeStats 0ms

/trunk/Source/Modules/python.cxx

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