PageRenderTime 55ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/trunk/Source/Modules/ruby.cxx

#
C++ | 2137 lines | 1935 code | 101 blank | 101 comment | 145 complexity | 98f00cb5c0518d222270d2e3ee10f02c 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. * ruby.cxx
  10. *
  11. * Ruby language module for SWIG.
  12. * ----------------------------------------------------------------------------- */
  13. char cvsroot_ruby_cxx[] = "$Id: ruby.cxx 12883 2011-12-22 21:14:09Z wsfulton $";
  14. #include "swigmod.h"
  15. #include "cparse.h"
  16. static int treduce = SWIG_cparse_template_reduce(0);
  17. #define SWIG_PROTECTED_TARGET_METHODS 1
  18. #include <ctype.h>
  19. #include <string.h>
  20. #include <limits.h> /* for INT_MAX */
  21. class RClass {
  22. private:
  23. String *temp;
  24. public:
  25. String *name; /* class name (renamed) */
  26. String *cname; /* original C class/struct name */
  27. String *mname; /* Mangled name */
  28. /**
  29. * The C variable name used in the SWIG-generated wrapper code to refer to
  30. * this class; usually it is of the form "SwigClassXXX.klass", where SwigClassXXX
  31. * is a swig_class struct instance and klass is a member of that struct.
  32. */
  33. String *vname;
  34. /**
  35. * The C variable name used in the SWIG-generated wrapper code to refer to
  36. * the module that implements this class's methods (when we're trying to
  37. * support C++ multiple inheritance). Usually it is of the form
  38. * "SwigClassClassName.mImpl", where SwigClassXXX is a swig_class struct instance
  39. * and mImpl is a member of that struct.
  40. */
  41. String *mImpl;
  42. String *type;
  43. String *prefix;
  44. String *init;
  45. int constructor_defined;
  46. int destructor_defined;
  47. RClass() {
  48. temp = NewString("");
  49. name = NewString("");
  50. cname = NewString("");
  51. mname = NewString("");
  52. vname = NewString("");
  53. mImpl = NewString("");
  54. type = NewString("");
  55. prefix = NewString("");
  56. init = NewString("");
  57. constructor_defined = 0;
  58. destructor_defined = 0;
  59. }
  60. ~RClass() {
  61. Delete(name);
  62. Delete(cname);
  63. Delete(vname);
  64. Delete(mImpl);
  65. Delete(mname);
  66. Delete(type);
  67. Delete(prefix);
  68. Delete(init);
  69. Delete(temp);
  70. }
  71. void set_name(const_String_or_char_ptr cn, const_String_or_char_ptr rn, const_String_or_char_ptr valn) {
  72. /* Original C/C++ class (or struct) name */
  73. Clear(cname);
  74. Append(cname, cn);
  75. /* Mangled name */
  76. Delete(mname);
  77. mname = Swig_name_mangle(cname);
  78. /* Renamed class name */
  79. Clear(name);
  80. Append(name, valn);
  81. /* Variable name for the VALUE that refers to the Ruby Class object */
  82. Clear(vname);
  83. Printf(vname, "SwigClass%s.klass", name);
  84. /* Variable name for the VALUE that refers to the Ruby Class object */
  85. Clear(mImpl);
  86. Printf(mImpl, "SwigClass%s.mImpl", name);
  87. /* Prefix */
  88. Clear(prefix);
  89. Printv(prefix, (rn ? rn : cn), "_", NIL);
  90. }
  91. char *strip(const_String_or_char_ptr s) {
  92. Clear(temp);
  93. Append(temp, s);
  94. if (Strncmp(s, prefix, Len(prefix)) == 0) {
  95. Replaceall(temp, prefix, "");
  96. }
  97. return Char(temp);
  98. }
  99. };
  100. /* flags for the make_autodoc function */
  101. enum autodoc_t {
  102. AUTODOC_CLASS,
  103. AUTODOC_CTOR,
  104. AUTODOC_DTOR,
  105. AUTODOC_STATICFUNC,
  106. AUTODOC_FUNC,
  107. AUTODOC_METHOD,
  108. AUTODOC_GETTER,
  109. AUTODOC_SETTER
  110. };
  111. static const char *usage = (char *) "\
  112. Ruby Options (available with -ruby)\n\
  113. -autorename - Enable renaming of classes and methods to follow Ruby coding standards\n\
  114. -cppcast - Enable C++ casting operators (default)\n\
  115. -globalmodule - Wrap everything into the global module\n\
  116. -initname <name>- Set entry function to Init_<name> (used by `require')\n\
  117. -minherit - Attempt to support multiple inheritance\n\
  118. -noautorename - Disable renaming of classes and methods (default)\n\
  119. -nocppcast - Disable C++ casting operators, useful for generating bugs\n\
  120. -prefix <name> - Set a prefix <name> to be prepended to all names\n\
  121. ";
  122. #define RCLASS(hash, name) (RClass*)(Getattr(hash, name) ? Data(Getattr(hash, name)) : 0)
  123. #define SET_RCLASS(hash, name, klass) Setattr(hash, name, NewVoid(klass, 0))
  124. class RUBY:public Language {
  125. private:
  126. String *module;
  127. String *modvar;
  128. String *feature;
  129. String *prefix;
  130. int current;
  131. Hash *classes; /* key=cname val=RClass */
  132. RClass *klass; /* Currently processing class */
  133. Hash *special_methods; /* Python style special method name table */
  134. File *f_directors;
  135. File *f_directors_h;
  136. File *f_directors_helpers;
  137. File *f_begin;
  138. File *f_runtime;
  139. File *f_runtime_h;
  140. File *f_header;
  141. File *f_wrappers;
  142. File *f_init;
  143. File *f_initbeforefunc;
  144. bool useGlobalModule;
  145. bool multipleInheritance;
  146. // Wrap modes
  147. enum WrapperMode {
  148. NO_CPP,
  149. MEMBER_FUNC,
  150. CONSTRUCTOR_ALLOCATE,
  151. CONSTRUCTOR_INITIALIZE,
  152. DESTRUCTOR,
  153. MEMBER_VAR,
  154. CLASS_CONST,
  155. STATIC_FUNC,
  156. STATIC_VAR
  157. };
  158. /* ------------------------------------------------------------
  159. * autodoc level declarations
  160. * ------------------------------------------------------------ */
  161. enum autodoc_l {
  162. NO_AUTODOC = -2, // no autodoc
  163. STRING_AUTODOC = -1, // use provided string
  164. NAMES_AUTODOC = 0, // only parameter names
  165. TYPES_AUTODOC = 1, // parameter names and types
  166. EXTEND_AUTODOC = 2, // extended documentation and parameter names
  167. EXTEND_TYPES_AUTODOC = 3 // extended documentation and parameter types + names
  168. };
  169. autodoc_t last_mode;
  170. String* last_autodoc;
  171. autodoc_l autodoc_level(String *autodoc) {
  172. autodoc_l dlevel = NO_AUTODOC;
  173. if (autodoc) {
  174. char *c = Char(autodoc);
  175. if (c && isdigit(c[0])) {
  176. dlevel = (autodoc_l) atoi(c);
  177. } else {
  178. if (strcmp(c, "extended") == 0) {
  179. dlevel = EXTEND_AUTODOC;
  180. } else {
  181. dlevel = STRING_AUTODOC;
  182. }
  183. }
  184. }
  185. return dlevel;
  186. }
  187. /* ------------------------------------------------------------
  188. * have_docstring()
  189. * Check if there is a docstring directive and it has text,
  190. * or there is an autodoc flag set
  191. * ------------------------------------------------------------ */
  192. bool have_docstring(Node *n) {
  193. String *str = Getattr(n, "feature:docstring");
  194. return (str && Len(str) > 0) || (Getattr(n, "feature:autodoc") && !GetFlag(n, "feature:noautodoc"));
  195. }
  196. /* ------------------------------------------------------------
  197. * docstring()
  198. * Get the docstring text, stripping off {} if neccessary,
  199. * and enclose in triple double quotes. If autodoc is also
  200. * set then it will build a combined docstring.
  201. * ------------------------------------------------------------ */
  202. String *docstring(Node *n, autodoc_t ad_type) {
  203. String *str = Getattr(n, "feature:docstring");
  204. bool have_ds = (str && Len(str) > 0);
  205. bool have_auto = (Getattr(n, "feature:autodoc") && !GetFlag(n, "feature:noautodoc"));
  206. String *autodoc = NULL;
  207. String *doc = NULL;
  208. if (have_ds) {
  209. char *t = Char(str);
  210. if (*t == '{') {
  211. Delitem(str, 0);
  212. Delitem(str, DOH_END);
  213. }
  214. }
  215. if (have_auto) {
  216. autodoc = make_autodoc(n, ad_type);
  217. have_auto = (autodoc && Len(autodoc) > 0);
  218. }
  219. // If there is more than one line then make docstrings like this:
  220. //
  221. // This is line1
  222. // And here is line2 followed by the rest of them
  223. //
  224. // otherwise, put it all on a single line
  225. //
  226. if (have_auto && have_ds) { // Both autodoc and docstring are present
  227. doc = NewString("");
  228. Printv(doc, "\n", autodoc, "\n", str, NIL);
  229. } else if (!have_auto && have_ds) { // only docstring
  230. if (Strchr(str, '\n') == 0) {
  231. doc = NewString(str);
  232. } else {
  233. doc = NewString("");
  234. Printv(doc, str, NIL);
  235. }
  236. } else if (have_auto && !have_ds) { // only autodoc
  237. if (Strchr(autodoc, '\n') == 0) {
  238. doc = NewStringf("%s", autodoc);
  239. } else {
  240. doc = NewString("");
  241. Printv(doc, "\n", autodoc, NIL);
  242. }
  243. } else
  244. doc = NewString("");
  245. // Save the generated strings in the parse tree in case they are used later
  246. // by post processing tools
  247. Setattr(n, "ruby:docstring", doc);
  248. Setattr(n, "ruby:autodoc", autodoc);
  249. return doc;
  250. }
  251. /* -----------------------------------------------------------------------------
  252. * addMissingParameterNames()
  253. * For functions that have not had nameless parameters set in the Language class.
  254. *
  255. * Inputs:
  256. * plist - entire parameter list
  257. * arg_offset - argument number for first parameter
  258. * Side effects:
  259. * The "lname" attribute in each parameter in plist will be contain a parameter name
  260. * ----------------------------------------------------------------------------- */
  261. void addMissingParameterNames(ParmList *plist, int arg_offset) {
  262. Parm *p = plist;
  263. int i = arg_offset;
  264. while (p) {
  265. if (!Getattr(p, "lname")) {
  266. String *pname = Swig_cparm_name(p, i);
  267. Delete(pname);
  268. }
  269. i++;
  270. p = nextSibling(p);
  271. }
  272. }
  273. /* ------------------------------------------------------------
  274. * make_autodocParmList()
  275. * Generate the documentation for the function parameters
  276. * ------------------------------------------------------------ */
  277. String *make_autodocParmList(Node *n, bool showTypes) {
  278. String *doc = NewString("");
  279. String *pdocs = 0;
  280. ParmList *plist = CopyParmList(Getattr(n, "parms"));
  281. Parm *p;
  282. Parm *pnext;
  283. int lines = 0;
  284. int start_arg_num = is_wrapping_class() ? 1 : 0;
  285. const int maxwidth = 80;
  286. addMissingParameterNames(plist, start_arg_num); // for $1_name substitutions done in Swig_typemap_attach_parms
  287. Swig_typemap_attach_parms("in", plist, 0);
  288. Swig_typemap_attach_parms("doc", plist, 0);
  289. if (Strcmp(ParmList_protostr(plist), "void") == 0) {
  290. //No parameters actually
  291. return doc;
  292. }
  293. for (p = plist; p; p = pnext) {
  294. String *tm = Getattr(p, "tmap:in");
  295. if (tm) {
  296. pnext = Getattr(p, "tmap:in:next");
  297. if (checkAttribute(p, "tmap:in:numinputs", "0")) {
  298. continue;
  299. }
  300. } else {
  301. pnext = nextSibling(p);
  302. }
  303. String *name = 0;
  304. String *type = 0;
  305. String *value = 0;
  306. String *pdoc = Getattr(p, "tmap:doc");
  307. if (pdoc) {
  308. name = Getattr(p, "tmap:doc:name");
  309. type = Getattr(p, "tmap:doc:type");
  310. value = Getattr(p, "tmap:doc:value");
  311. }
  312. // Note: the generated name should be consistent with that in kwnames[]
  313. name = name ? name : Getattr(p, "name");
  314. name = name ? name : Getattr(p, "lname");
  315. name = Swig_name_make(p, 0, name, 0, 0); // rename parameter if a keyword
  316. type = type ? type : Getattr(p, "type");
  317. value = value ? value : Getattr(p, "value");
  318. if (SwigType_isvarargs(type))
  319. break;
  320. // Skip the 'self' parameter which in ruby is implicit
  321. if ( Cmp(name, "self") == 0 )
  322. continue;
  323. // Make __p parameters just p (as used in STL)
  324. Replace( name, "__", "", DOH_REPLACE_FIRST );
  325. if (Len(doc)) {
  326. // add a comma to the previous one if any
  327. Append(doc, ", ");
  328. // Do we need to wrap a long line?
  329. if ((Len(doc) - lines * maxwidth) > maxwidth) {
  330. Printf(doc, "\n%s", tab4);
  331. lines += 1;
  332. }
  333. }
  334. // Do the param type too?
  335. Node *nn = classLookup(Getattr(p, "type"));
  336. String *type_str = nn ? Copy(Getattr(nn, "sym:name")) : SwigType_str(type, 0);
  337. if (showTypes)
  338. Printf(doc, "%s ", type_str);
  339. Append(doc, name);
  340. if (pdoc) {
  341. if (!pdocs)
  342. pdocs = NewString("Parameters:\n");
  343. Printf(pdocs, " %s.\n", pdoc);
  344. }
  345. if (value) {
  346. String *new_value = convertValue(value, Getattr(p, "type"));
  347. if (new_value) {
  348. value = new_value;
  349. } else {
  350. Node *lookup = Swig_symbol_clookup(value, 0);
  351. if (lookup)
  352. value = Getattr(lookup, "sym:name");
  353. }
  354. Printf(doc, "=%s", value);
  355. }
  356. Delete(type_str);
  357. Delete(name);
  358. }
  359. if (pdocs)
  360. Setattr(n, "feature:pdocs", pdocs);
  361. Delete(plist);
  362. return doc;
  363. }
  364. /* ------------------------------------------------------------
  365. * make_autodoc()
  366. * Build a docstring for the node, using parameter and other
  367. * info in the parse tree. If the value of the autodoc
  368. * attribute is "0" then do not include parameter types, if
  369. * it is "1" (the default) then do. If it has some other
  370. * value then assume it is supplied by the extension writer
  371. * and use it directly.
  372. * ------------------------------------------------------------ */
  373. String *make_autodoc(Node *n, autodoc_t ad_type) {
  374. int extended = 0;
  375. // If the function is overloaded then this funciton is called
  376. // for the last one. Rewind to the first so the docstrings are
  377. // in order.
  378. while (Getattr(n, "sym:previousSibling"))
  379. n = Getattr(n, "sym:previousSibling");
  380. Node *pn = Swig_methodclass(n);
  381. String* super_names = NewString("");
  382. String* class_name = Getattr(pn, "sym:name") ;
  383. if ( !class_name ) {
  384. class_name = NewString("");
  385. } else {
  386. class_name = Copy(class_name);
  387. List *baselist = Getattr(pn, "bases");
  388. if (baselist && Len(baselist)) {
  389. Iterator base = First(baselist);
  390. while (base.item && GetFlag(base.item, "feature:ignore")) {
  391. base = Next(base);
  392. }
  393. int count = 0;
  394. for ( ;base.item; ++count) {
  395. if ( count ) Append(super_names, ", ");
  396. String *basename = Getattr(base.item, "sym:name");
  397. String* basenamestr = NewString(basename);
  398. Node* parent = parentNode(base.item);
  399. while (parent)
  400. {
  401. String *parent_name = Copy( Getattr(parent, "sym:name") );
  402. if ( !parent_name ) {
  403. Node* mod = Getattr(parent, "module");
  404. if ( mod )
  405. parent_name = Copy( Getattr(mod, "name") );
  406. if ( parent_name )
  407. (Char(parent_name))[0] = (char)toupper((Char(parent_name))[0]);
  408. }
  409. if ( parent_name ) {
  410. Insert(basenamestr, 0, "::");
  411. Insert(basenamestr, 0, parent_name);
  412. Delete(parent_name);
  413. }
  414. parent = parentNode(parent);
  415. }
  416. Append(super_names, basenamestr );
  417. Delete(basenamestr);
  418. base = Next(base);
  419. }
  420. }
  421. }
  422. String* full_name;
  423. if ( module ) {
  424. full_name = NewString(module);
  425. if (class_name && Len(class_name) > 0)
  426. Append(full_name, "::");
  427. }
  428. else
  429. full_name = NewString("");
  430. Append(full_name, class_name);
  431. String* symname = Getattr(n, "sym:name");
  432. if ( Getattr( special_methods, symname ) )
  433. symname = Getattr( special_methods, symname );
  434. String* methodName = NewString(full_name);
  435. Append(methodName, symname);
  436. // Each overloaded function will try to get documented,
  437. // so we keep the name of the last overloaded function and its type.
  438. // Documenting just from functionWrapper() is not possible as
  439. // sym:name has already been changed to include the class name
  440. if ( last_mode == ad_type && Cmp(methodName, last_autodoc) == 0 ) {
  441. Delete(full_name);
  442. Delete(class_name);
  443. Delete(super_names);
  444. Delete(methodName);
  445. return NewString("");
  446. }
  447. last_mode = ad_type;
  448. last_autodoc = Copy(methodName);
  449. String *doc = NewString("/*\n");
  450. int counter = 0;
  451. bool skipAuto = false;
  452. Node* on = n;
  453. for ( ; n; ++counter ) {
  454. String *type_str = NULL;
  455. skipAuto = false;
  456. bool showTypes = false;
  457. String *autodoc = Getattr(n, "feature:autodoc");
  458. autodoc_l dlevel = autodoc_level(autodoc);
  459. switch (dlevel) {
  460. case NO_AUTODOC:
  461. break;
  462. case NAMES_AUTODOC:
  463. showTypes = false;
  464. break;
  465. case TYPES_AUTODOC:
  466. showTypes = true;
  467. break;
  468. case EXTEND_AUTODOC:
  469. extended = 1;
  470. showTypes = false;
  471. break;
  472. case EXTEND_TYPES_AUTODOC:
  473. extended = 1;
  474. showTypes = true;
  475. break;
  476. case STRING_AUTODOC:
  477. skipAuto = true;
  478. break;
  479. }
  480. SwigType *type = Getattr(n, "type");
  481. if (type) {
  482. if (Strcmp(type, "void") == 0) {
  483. type_str = NULL;
  484. } else {
  485. SwigType *qt = SwigType_typedef_resolve_all(type);
  486. if (SwigType_isenum(qt)) {
  487. type_str = NewString("int");
  488. } else {
  489. Node *nn = classLookup(type);
  490. type_str = nn ? Copy(Getattr(nn, "sym:name")) : SwigType_str(type, 0);
  491. }
  492. }
  493. }
  494. if (counter == 0) {
  495. switch (ad_type) {
  496. case AUTODOC_CLASS:
  497. Printf(doc, " Document-class: %s", full_name);
  498. if ( Len(super_names) > 0 )
  499. Printf( doc, " < %s", super_names);
  500. Append(doc, "\n\n");
  501. break;
  502. case AUTODOC_CTOR:
  503. Printf(doc, " Document-method: %s.new\n\n", full_name);
  504. break;
  505. case AUTODOC_DTOR:
  506. break;
  507. case AUTODOC_STATICFUNC:
  508. Printf(doc, " Document-method: %s.%s\n\n", full_name, symname);
  509. break;
  510. case AUTODOC_FUNC:
  511. case AUTODOC_METHOD:
  512. case AUTODOC_GETTER:
  513. Printf(doc, " Document-method: %s.%s\n\n", full_name, symname);
  514. break;
  515. case AUTODOC_SETTER:
  516. Printf(doc, " Document-method: %s.%s=\n\n", full_name, symname);
  517. break;
  518. }
  519. }
  520. if (skipAuto) {
  521. if ( counter == 0 ) Printf(doc, " call-seq:\n");
  522. switch( ad_type )
  523. {
  524. case AUTODOC_STATICFUNC:
  525. case AUTODOC_FUNC:
  526. case AUTODOC_METHOD:
  527. case AUTODOC_GETTER:
  528. {
  529. String *paramList = make_autodocParmList(n, showTypes);
  530. if (Len(paramList))
  531. Printf(doc, " %s(%s)", symname, paramList);
  532. else
  533. Printf(doc, " %s", symname);
  534. if (type_str)
  535. Printf(doc, " -> %s", type_str);
  536. break;
  537. }
  538. case AUTODOC_SETTER:
  539. {
  540. Printf(doc, " %s=(x)", symname);
  541. if (type_str)
  542. Printf(doc, " -> %s", type_str);
  543. break;
  544. }
  545. default:
  546. break;
  547. }
  548. } else {
  549. switch (ad_type) {
  550. case AUTODOC_CLASS:
  551. {
  552. // Only do the autodoc if there isn't a docstring for the class
  553. String *str = Getattr(n, "feature:docstring");
  554. if (counter == 0 && (str == 0 || Len(str) == 0)) {
  555. if (CPlusPlus) {
  556. Printf(doc, " Proxy of C++ %s class", full_name);
  557. } else {
  558. Printf(doc, " Proxy of C %s struct", full_name);
  559. }
  560. }
  561. }
  562. break;
  563. case AUTODOC_CTOR:
  564. if (counter == 0)
  565. Printf(doc, " call-seq:\n");
  566. if (Strcmp(class_name, symname) == 0) {
  567. String *paramList = make_autodocParmList(n, showTypes);
  568. if (Len(paramList))
  569. Printf(doc, " %s.new(%s)", class_name, paramList);
  570. else
  571. Printf(doc, " %s.new", class_name);
  572. } else {
  573. Printf(doc, " %s.new(%s)", class_name, make_autodocParmList(n, showTypes));
  574. }
  575. break;
  576. case AUTODOC_DTOR:
  577. break;
  578. case AUTODOC_STATICFUNC:
  579. case AUTODOC_FUNC:
  580. case AUTODOC_METHOD:
  581. case AUTODOC_GETTER:
  582. {
  583. if (counter == 0)
  584. Printf(doc, " call-seq:\n");
  585. String *paramList = make_autodocParmList(n, showTypes);
  586. if (Len(paramList))
  587. Printf(doc, " %s(%s)", symname, paramList);
  588. else
  589. Printf(doc, " %s", symname);
  590. if (type_str)
  591. Printf(doc, " -> %s", type_str);
  592. break;
  593. }
  594. case AUTODOC_SETTER:
  595. {
  596. Printf(doc, " call-seq:\n");
  597. Printf(doc, " %s=(x)", symname);
  598. if (type_str)
  599. Printf(doc, " -> %s", type_str);
  600. break;
  601. }
  602. }
  603. }
  604. // if it's overloaded then get the next decl and loop around again
  605. n = Getattr(n, "sym:nextSibling");
  606. if (n)
  607. Append(doc, "\n");
  608. Delete(type_str);
  609. }
  610. Printf(doc, "\n\n");
  611. if (!skipAuto) {
  612. switch (ad_type) {
  613. case AUTODOC_CLASS:
  614. case AUTODOC_DTOR:
  615. break;
  616. case AUTODOC_CTOR:
  617. Printf(doc, "Class constructor.\n");
  618. break;
  619. case AUTODOC_STATICFUNC:
  620. Printf(doc, "A class method.\n");
  621. break;
  622. case AUTODOC_FUNC:
  623. Printf(doc, "A module function.\n");
  624. break;
  625. case AUTODOC_METHOD:
  626. Printf(doc, "An instance method.\n");
  627. break;
  628. case AUTODOC_GETTER:
  629. Printf(doc, "Get value of attribute.\n");
  630. break;
  631. case AUTODOC_SETTER:
  632. Printf(doc, "Set new value for attribute.\n");
  633. break;
  634. }
  635. }
  636. n = on;
  637. while ( n ) {
  638. String *autodoc = Getattr(n, "feature:autodoc");
  639. autodoc_l dlevel = autodoc_level(autodoc);
  640. symname = Getattr(n, "sym:name");
  641. if ( Getattr( special_methods, symname ) )
  642. symname = Getattr( special_methods, symname );
  643. switch (dlevel) {
  644. case NO_AUTODOC:
  645. case NAMES_AUTODOC:
  646. case TYPES_AUTODOC:
  647. extended = 0;
  648. break;
  649. case STRING_AUTODOC:
  650. extended = 2;
  651. Replaceall( autodoc, "$class", class_name );
  652. Printv(doc, autodoc, ".", NIL);
  653. break;
  654. case EXTEND_AUTODOC:
  655. case EXTEND_TYPES_AUTODOC:
  656. extended = 1;
  657. break;
  658. }
  659. if (extended) {
  660. String *pdocs = Getattr(n, "feature:pdocs");
  661. if (pdocs) {
  662. Printv(doc, "\n\n", pdocs, NULL);
  663. break;
  664. }
  665. if ( extended == 2 ) break;
  666. }
  667. n = Getattr(n, "sym:nextSibling");
  668. }
  669. Append(doc, "\n*/\n");
  670. Delete(full_name);
  671. Delete(class_name);
  672. Delete(super_names);
  673. Delete(methodName);
  674. return doc;
  675. }
  676. /* ------------------------------------------------------------
  677. * convertValue()
  678. * Check if string v can be a Ruby value literal,
  679. * (eg. number or string), or translate it to a Ruby literal.
  680. * ------------------------------------------------------------ */
  681. String *convertValue(String *v, SwigType *t) {
  682. if (v && Len(v) > 0) {
  683. char fc = (Char(v))[0];
  684. if (('0' <= fc && fc <= '9') || '\'' == fc || '"' == fc) {
  685. /* number or string (or maybe NULL pointer) */
  686. if (SwigType_ispointer(t) && Strcmp(v, "0") == 0)
  687. return NewString("None");
  688. else
  689. return v;
  690. }
  691. if (Strcmp(v, "NULL") == 0)
  692. return SwigType_ispointer(t) ? NewString("nil") : NewString("0");
  693. else if (Strcmp(v, "true") == 0 || Strcmp(v, "TRUE") == 0)
  694. return NewString("true");
  695. else if (Strcmp(v, "false") == 0 || Strcmp(v, "FALSE") == 0)
  696. return NewString("false");
  697. if (Strcmp(v, "true") == 0 || Strcmp(v, "FALSE") == 0)
  698. return NewString("True");
  699. if (Strcmp(v, "false") == 0 || Strcmp(v, "FALSE") == 0)
  700. return NewString("False");
  701. }
  702. return 0;
  703. }
  704. public:
  705. /* ---------------------------------------------------------------------
  706. * RUBY()
  707. *
  708. * Initialize member data
  709. * --------------------------------------------------------------------- */
  710. RUBY() {
  711. module = 0;
  712. modvar = 0;
  713. feature = 0;
  714. prefix = 0;
  715. last_autodoc = NewString("");
  716. current = NO_CPP;
  717. classes = 0;
  718. klass = 0;
  719. special_methods = 0;
  720. f_begin = 0;
  721. f_runtime = 0;
  722. f_header = 0;
  723. f_wrappers = 0;
  724. f_init = 0;
  725. f_initbeforefunc = 0;
  726. useGlobalModule = false;
  727. multipleInheritance = false;
  728. director_prot_ctor_code = NewString("");
  729. Printv(director_prot_ctor_code,
  730. "if ( $comparison ) { /* subclassed */\n",
  731. " $director_new \n",
  732. "} else {\n", " rb_raise(rb_eRuntimeError,\"accessing abstract class or protected constructor\"); \n", " return Qnil;\n", "}\n", NIL);
  733. director_multiple_inheritance = 0;
  734. director_language = 1;
  735. }
  736. /* ---------------------------------------------------------------------
  737. * main()
  738. *
  739. * Parse command line options and initializes variables.
  740. * --------------------------------------------------------------------- */
  741. virtual void main(int argc, char *argv[]) {
  742. int cppcast = 1;
  743. int autorename = 0;
  744. /* Set location of SWIG library */
  745. SWIG_library_directory("ruby");
  746. /* Look for certain command line options */
  747. for (int i = 1; i < argc; i++) {
  748. if (argv[i]) {
  749. if (strcmp(argv[i], "-initname") == 0) {
  750. if (argv[i + 1]) {
  751. char *name = argv[i + 1];
  752. feature = NewString(name);
  753. Swig_mark_arg(i);
  754. Swig_mark_arg(i + 1);
  755. i++;
  756. } else {
  757. Swig_arg_error();
  758. }
  759. }
  760. else if (strcmp(argv[i], "-feature") == 0) {
  761. fprintf( stderr, "Warning: Ruby -feature option is deprecated, "
  762. "please use -initname instead.\n");
  763. if (argv[i + 1]) {
  764. char *name = argv[i + 1];
  765. feature = NewString(name);
  766. Swig_mark_arg(i);
  767. Swig_mark_arg(i + 1);
  768. i++;
  769. } else {
  770. Swig_arg_error();
  771. }
  772. } else if (strcmp(argv[i], "-globalmodule") == 0) {
  773. useGlobalModule = true;
  774. Swig_mark_arg(i);
  775. } else if (strcmp(argv[i], "-minherit") == 0) {
  776. multipleInheritance = true;
  777. director_multiple_inheritance = 1;
  778. Swig_mark_arg(i);
  779. } else if (strcmp(argv[i], "-cppcast") == 0) {
  780. cppcast = 1;
  781. Swig_mark_arg(i);
  782. } else if (strcmp(argv[i], "-nocppcast") == 0) {
  783. cppcast = 0;
  784. Swig_mark_arg(i);
  785. } else if (strcmp(argv[i], "-autorename") == 0) {
  786. autorename = 1;
  787. Swig_mark_arg(i);
  788. } else if (strcmp(argv[i], "-noautorename") == 0) {
  789. autorename = 0;
  790. Swig_mark_arg(i);
  791. } else if (strcmp(argv[i], "-prefix") == 0) {
  792. if (argv[i + 1]) {
  793. char *name = argv[i + 1];
  794. prefix = NewString(name);
  795. Swig_mark_arg(i);
  796. Swig_mark_arg(i + 1);
  797. i++;
  798. } else {
  799. Swig_arg_error();
  800. }
  801. } else if (strcmp(argv[i], "-help") == 0) {
  802. Printf(stdout, "%s\n", usage);
  803. }
  804. }
  805. }
  806. if (cppcast) {
  807. /* Turn on cppcast mode */
  808. Preprocessor_define((DOH *) "SWIG_CPLUSPLUS_CAST", 0);
  809. }
  810. if (autorename) {
  811. /* Turn on the autorename mode */
  812. Preprocessor_define((DOH *) "SWIG_RUBY_AUTORENAME", 0);
  813. }
  814. /* Add a symbol to the parser for conditional compilation */
  815. Preprocessor_define("SWIGRUBY 1", 0);
  816. /* Add typemap definitions */
  817. SWIG_typemap_lang("ruby");
  818. SWIG_config_file("ruby.swg");
  819. allow_overloading();
  820. }
  821. /**
  822. * Generate initialization code to define the Ruby module(s),
  823. * accounting for nested modules as necessary.
  824. */
  825. void defineRubyModule() {
  826. List *modules = Split(module, ':', INT_MAX);
  827. if (modules != 0 && Len(modules) > 0) {
  828. String *mv = 0;
  829. Iterator m;
  830. m = First(modules);
  831. while (m.item) {
  832. if (Len(m.item) > 0) {
  833. if (mv != 0) {
  834. Printv(f_init, tab4, modvar, " = rb_define_module_under(", modvar, ", \"", m.item, "\");\n", NIL);
  835. } else {
  836. Printv(f_init, tab4, modvar, " = rb_define_module(\"", m.item, "\");\n", NIL);
  837. mv = NewString(modvar);
  838. }
  839. }
  840. m = Next(m);
  841. }
  842. Delete(mv);
  843. Delete(modules);
  844. }
  845. }
  846. void registerMagicMethods() {
  847. special_methods = NewHash();
  848. /* Python->Ruby style special method name. */
  849. /* Basic */
  850. Setattr(special_methods, "__repr__", "inspect");
  851. Setattr(special_methods, "__str__", "to_s");
  852. Setattr(special_methods, "__cmp__", "<=>");
  853. Setattr(special_methods, "__hash__", "hash");
  854. Setattr(special_methods, "__nonzero__", "nonzero?");
  855. /* Callable */
  856. Setattr(special_methods, "__call__", "call");
  857. /* Collection */
  858. Setattr(special_methods, "__len__", "length");
  859. Setattr(special_methods, "__getitem__", "[]");
  860. Setattr(special_methods, "__setitem__", "[]=");
  861. /* Operators */
  862. Setattr(special_methods, "__add__", "+");
  863. Setattr(special_methods, "__pos__", "+@");
  864. Setattr(special_methods, "__sub__", "-");
  865. Setattr(special_methods, "__neg__", "-@");
  866. Setattr(special_methods, "__mul__", "*");
  867. Setattr(special_methods, "__div__", "/");
  868. Setattr(special_methods, "__mod__", "%");
  869. Setattr(special_methods, "__lshift__", "<<");
  870. Setattr(special_methods, "__rshift__", ">>");
  871. Setattr(special_methods, "__and__", "&");
  872. Setattr(special_methods, "__or__", "|");
  873. Setattr(special_methods, "__xor__", "^");
  874. Setattr(special_methods, "__invert__", "~");
  875. Setattr(special_methods, "__lt__", "<");
  876. Setattr(special_methods, "__le__", "<=");
  877. Setattr(special_methods, "__gt__", ">");
  878. Setattr(special_methods, "__ge__", ">=");
  879. Setattr(special_methods, "__eq__", "==");
  880. /* Other numeric */
  881. Setattr(special_methods, "__divmod__", "divmod");
  882. Setattr(special_methods, "__pow__", "**");
  883. Setattr(special_methods, "__abs__", "abs");
  884. Setattr(special_methods, "__int__", "to_i");
  885. Setattr(special_methods, "__float__", "to_f");
  886. Setattr(special_methods, "__coerce__", "coerce");
  887. }
  888. /* ---------------------------------------------------------------------
  889. * top()
  890. * --------------------------------------------------------------------- */
  891. virtual int top(Node *n) {
  892. /**
  893. * See if any Ruby module options have been specified as options
  894. * to the %module directive.
  895. */
  896. Node *swigModule = Getattr(n, "module");
  897. if (swigModule) {
  898. Node *options = Getattr(swigModule, "options");
  899. if (options) {
  900. if (Getattr(options, "directors")) {
  901. allow_directors();
  902. }
  903. if (Getattr(options, "dirprot")) {
  904. allow_dirprot();
  905. }
  906. if (Getattr(options, "ruby_globalmodule")) {
  907. useGlobalModule = true;
  908. }
  909. if (Getattr(options, "ruby_minherit")) {
  910. multipleInheritance = true;
  911. director_multiple_inheritance = 1;
  912. }
  913. }
  914. }
  915. /* Set comparison with none for ConstructorToFunction */
  916. setSubclassInstanceCheck(NewStringf("strcmp(rb_obj_classname(self), classname) != 0"));
  917. // setSubclassInstanceCheck(NewString("CLASS_OF(self) != cFoo.klass"));
  918. /* Initialize all of the output files */
  919. String *outfile = Getattr(n, "outfile");
  920. String *outfile_h = Getattr(n, "outfile_h");
  921. if (!outfile) {
  922. Printf(stderr, "Unable to determine outfile\n");
  923. SWIG_exit(EXIT_FAILURE);
  924. }
  925. f_begin = NewFile(outfile, "w", SWIG_output_files());
  926. if (!f_begin) {
  927. FileErrorDisplay(outfile);
  928. SWIG_exit(EXIT_FAILURE);
  929. }
  930. f_runtime = NewString("");
  931. f_init = NewString("");
  932. f_header = NewString("");
  933. f_wrappers = NewString("");
  934. f_directors_h = NewString("");
  935. f_directors = NewString("");
  936. f_directors_helpers = NewString("");
  937. f_initbeforefunc = NewString("");
  938. if (directorsEnabled()) {
  939. if (!outfile_h) {
  940. Printf(stderr, "Unable to determine outfile_h\n");
  941. SWIG_exit(EXIT_FAILURE);
  942. }
  943. f_runtime_h = NewFile(outfile_h, "w", SWIG_output_files());
  944. if (!f_runtime_h) {
  945. FileErrorDisplay(outfile_h);
  946. SWIG_exit(EXIT_FAILURE);
  947. }
  948. }
  949. /* Register file targets with the SWIG file handler */
  950. Swig_register_filebyname("header", f_header);
  951. Swig_register_filebyname("wrapper", f_wrappers);
  952. Swig_register_filebyname("begin", f_begin);
  953. Swig_register_filebyname("runtime", f_runtime);
  954. Swig_register_filebyname("init", f_init);
  955. Swig_register_filebyname("director", f_directors);
  956. Swig_register_filebyname("director_h", f_directors_h);
  957. Swig_register_filebyname("director_helpers", f_directors_helpers);
  958. Swig_register_filebyname("initbeforefunc", f_initbeforefunc);
  959. modvar = 0;
  960. current = NO_CPP;
  961. klass = 0;
  962. classes = NewHash();
  963. registerMagicMethods();
  964. Swig_banner(f_begin);
  965. Printf(f_runtime, "\n");
  966. Printf(f_runtime, "#define SWIGRUBY\n");
  967. if (directorsEnabled()) {
  968. Printf(f_runtime, "#define SWIG_DIRECTORS\n");
  969. }
  970. Printf(f_runtime, "\n");
  971. /* typedef void *VALUE */
  972. SwigType *value = NewSwigType(T_VOID);
  973. SwigType_add_pointer(value);
  974. SwigType_typedef(value, (char *) "VALUE");
  975. Delete(value);
  976. /* Set module name */
  977. set_module(Char(Getattr(n, "name")));
  978. if (directorsEnabled()) {
  979. /* Build a version of the module name for use in a C macro name. */
  980. String *module_macro = Copy(module);
  981. Replaceall(module_macro, "::", "__");
  982. Swig_banner(f_directors_h);
  983. Printf(f_directors_h, "\n");
  984. Printf(f_directors_h, "#ifndef SWIG_%s_WRAP_H_\n", module_macro);
  985. Printf(f_directors_h, "#define SWIG_%s_WRAP_H_\n\n", module_macro);
  986. Printf(f_directors_h, "namespace Swig {\n");
  987. Printf(f_directors_h, " class Director;\n");
  988. Printf(f_directors_h, "}\n\n");
  989. Printf(f_directors_helpers, "/* ---------------------------------------------------\n");
  990. Printf(f_directors_helpers, " * C++ director class helpers\n");
  991. Printf(f_directors_helpers, " * --------------------------------------------------- */\n\n");
  992. Printf(f_directors, "\n\n");
  993. Printf(f_directors, "/* ---------------------------------------------------\n");
  994. Printf(f_directors, " * C++ director class methods\n");
  995. Printf(f_directors, " * --------------------------------------------------- */\n\n");
  996. if (outfile_h)
  997. Printf(f_directors, "#include \"%s\"\n\n", Swig_file_filename(outfile_h));
  998. Delete(module_macro);
  999. }
  1000. Printf(f_header, "#define SWIG_init Init_%s\n", feature);
  1001. Printf(f_header, "#define SWIG_name \"%s\"\n\n", module);
  1002. Printf(f_header, "static VALUE %s;\n", modvar);
  1003. /* Start generating the initialization function */
  1004. String* docs = docstring(n, AUTODOC_CLASS);
  1005. Printf(f_init, "/*\n%s\n*/", docs );
  1006. Printv(f_init, "\n", "#ifdef __cplusplus\n", "extern \"C\"\n", "#endif\n", "SWIGEXPORT void Init_", feature, "(void) {\n", "size_t i;\n", "\n", NIL);
  1007. Printv(f_init, tab4, "SWIG_InitRuntime();\n", NIL);
  1008. if (!useGlobalModule)
  1009. defineRubyModule();
  1010. Printv(f_init, "\n", "SWIG_InitializeModule(0);\n", "for (i = 0; i < swig_module.size; i++) {\n", "SWIG_define_class(swig_module.types[i]);\n", "}\n", NIL);
  1011. Printf(f_init, "\n");
  1012. /* Initialize code to keep track of objects */
  1013. Printf(f_init, "SWIG_RubyInitializeTrackings();\n");
  1014. Language::top(n);
  1015. if (directorsEnabled()) {
  1016. // Insert director runtime into the f_runtime file (make it occur before %header section)
  1017. Swig_insert_file("director.swg", f_runtime);
  1018. }
  1019. /* Finish off our init function */
  1020. Printf(f_init, "}\n");
  1021. SwigType_emit_type_table(f_runtime, f_wrappers);
  1022. /* Close all of the files */
  1023. Dump(f_runtime, f_begin);
  1024. Dump(f_header, f_begin);
  1025. if (directorsEnabled()) {
  1026. Dump(f_directors_helpers, f_begin);
  1027. Dump(f_directors, f_begin);
  1028. Dump(f_directors_h, f_runtime_h);
  1029. Printf(f_runtime_h, "\n");
  1030. Printf(f_runtime_h, "#endif\n");
  1031. Close(f_runtime_h);
  1032. }
  1033. Dump(f_wrappers, f_begin);
  1034. Dump(f_initbeforefunc, f_begin);
  1035. Wrapper_pretty_print(f_init, f_begin);
  1036. Delete(f_header);
  1037. Delete(f_wrappers);
  1038. Delete(f_init);
  1039. Delete(f_initbeforefunc);
  1040. Close(f_begin);
  1041. Delete(f_runtime);
  1042. Delete(f_begin);
  1043. return SWIG_OK;
  1044. }
  1045. /* -----------------------------------------------------------------------------
  1046. * importDirective()
  1047. * ----------------------------------------------------------------------------- */
  1048. virtual int importDirective(Node *n) {
  1049. String *modname = Getattr(n, "module");
  1050. if (modname) {
  1051. if (prefix) {
  1052. Insert(modname, 0, prefix);
  1053. }
  1054. List *modules = Split(modname, ':', INT_MAX);
  1055. if (modules && Len(modules) > 0) {
  1056. modname = NewString("");
  1057. String *last = NULL;
  1058. Iterator m = First(modules);
  1059. while (m.item) {
  1060. if (Len(m.item) > 0) {
  1061. if (last) {
  1062. Append(modname, "/");
  1063. }
  1064. Append(modname, m.item);
  1065. last = m.item;
  1066. }
  1067. m = Next(m);
  1068. }
  1069. Printf(f_init, "rb_require(\"%s\");\n", modname);
  1070. Delete(modname);
  1071. }
  1072. Delete(modules);
  1073. }
  1074. return Language::importDirective(n);
  1075. }
  1076. /* ---------------------------------------------------------------------
  1077. * set_module(const char *mod_name)
  1078. *
  1079. * Sets the module name. Does nothing if it's already set (so it can
  1080. * be overridden as a command line option).
  1081. *---------------------------------------------------------------------- */
  1082. void set_module(const char *s) {
  1083. String *mod_name = NewString(s);
  1084. if (module == 0) {
  1085. /* Start with the empty string */
  1086. module = NewString("");
  1087. if (prefix) {
  1088. Insert(mod_name, 0, prefix);
  1089. }
  1090. /* Account for nested modules */
  1091. List *modules = Split(mod_name, ':', INT_MAX);
  1092. if (modules != 0 && Len(modules) > 0) {
  1093. String *last = 0;
  1094. Iterator m = First(modules);
  1095. while (m.item) {
  1096. if (Len(m.item) > 0) {
  1097. String *cap = NewString(m.item);
  1098. (Char(cap))[0] = (char)toupper((Char(cap))[0]);
  1099. if (last != 0) {
  1100. Append(module, "::");
  1101. }
  1102. Append(module, cap);
  1103. last = m.item;
  1104. }
  1105. m = Next(m);
  1106. }
  1107. if (feature == 0) {
  1108. feature = Copy(last);
  1109. }
  1110. (Char(last))[0] = (char)toupper((Char(last))[0]);
  1111. modvar = NewStringf("m%s", last);
  1112. Delete(modules);
  1113. }
  1114. }
  1115. Delete(mod_name);
  1116. }
  1117. /* --------------------------------------------------------------------------
  1118. * nativeWrapper()
  1119. * -------------------------------------------------------------------------- */
  1120. virtual int nativeWrapper(Node *n) {
  1121. String *funcname = Getattr(n, "wrap:name");
  1122. Swig_warning(WARN_LANG_NATIVE_UNIMPL, input_file, line_number, "Adding native function %s not supported (ignored).\n", funcname);
  1123. return SWIG_NOWRAP;
  1124. }
  1125. /**
  1126. * Process the comma-separated list of aliases (if any).
  1127. */
  1128. void defineAliases(Node *n, const_String_or_char_ptr iname) {
  1129. String *aliasv = Getattr(n, "feature:alias");
  1130. if (aliasv) {
  1131. List *aliases = Split(aliasv, ',', INT_MAX);
  1132. if (aliases && Len(aliases) > 0) {
  1133. Iterator alias = First(aliases);
  1134. while (alias.item) {
  1135. if (Len(alias.item) > 0) {
  1136. if (multipleInheritance) {
  1137. Printv(klass->init, tab4, "rb_define_alias(", klass->mImpl, ", \"", alias.item, "\", \"", iname, "\");\n", NIL);
  1138. } else {
  1139. Printv(klass->init, tab4, "rb_define_alias(", klass->vname, ", \"", alias.item, "\", \"", iname, "\");\n", NIL);
  1140. }
  1141. }
  1142. alias = Next(alias);
  1143. }
  1144. }
  1145. Delete(aliases);
  1146. }
  1147. }
  1148. /* ---------------------------------------------------------------------
  1149. * create_command(Node *n, char *iname)
  1150. *
  1151. * Creates a new command from a C function.
  1152. * iname = Name of function in scripting language
  1153. *
  1154. * A note about what "protected" and "private" mean in Ruby:
  1155. *
  1156. * A private method is accessible only within the class or its subclasses,
  1157. * and it is callable only in "function form", with 'self' (implicit or
  1158. * explicit) as a receiver.
  1159. *
  1160. * A protected method is callable only from within its class, but unlike
  1161. * a private method, it can be called with a receiver other than self, such
  1162. * as another instance of the same class.
  1163. * --------------------------------------------------------------------- */
  1164. void create_command(Node *n, const_String_or_char_ptr iname) {
  1165. String *alloc_func = Swig_name_wrapper(iname);
  1166. String *wname = Swig_name_wrapper(iname);
  1167. if (CPlusPlus) {
  1168. Insert(wname, 0, "VALUEFUNC(");
  1169. Append(wname, ")");
  1170. }
  1171. if (current != NO_CPP)
  1172. iname = klass->strip(iname);
  1173. if (Getattr(special_methods, iname)) {
  1174. iname = GetChar(special_methods, iname);
  1175. }
  1176. String *s = NewString("");
  1177. String *temp = NewString("");
  1178. #ifdef SWIG_PROTECTED_TARGET_METHODS
  1179. const char *rb_define_method = is_public(n) ? "rb_define_method" : "rb_define_protected_method";
  1180. #else
  1181. const char *rb_define_method = "rb_define_method";
  1182. #endif
  1183. switch (current) {
  1184. case MEMBER_FUNC:
  1185. {
  1186. if (multipleInheritance) {
  1187. Printv(klass->init, tab4, rb_define_method, "(", klass->mImpl, ", \"", iname, "\", ", wname, ", -1);\n", NIL);
  1188. } else {
  1189. Printv(klass->init, tab4, rb_define_method, "(", klass->vname, ", \"", iname, "\", ", wname, ", -1);\n", NIL);
  1190. }
  1191. }
  1192. break;
  1193. case CONSTRUCTOR_ALLOCATE:
  1194. Printv(s, tab4, "rb_define_alloc_func(", klass->vname, ", ", alloc_func, ");\n", NIL);
  1195. Replaceall(klass->init, "$allocator", s);
  1196. break;
  1197. case CONSTRUCTOR_INITIALIZE:
  1198. Printv(s, tab4, rb_define_method, "(", klass->vname, ", \"initialize\", ", wname, ", -1);\n", NIL);
  1199. Replaceall(klass->init, "$initializer", s);
  1200. break;
  1201. case MEMBER_VAR:
  1202. Append(temp, iname);
  1203. /* Check for _set or _get at the end of the name. */
  1204. if (Len(temp) > 4) {
  1205. const char *p = Char(temp) + (Len(temp) - 4);
  1206. if (strcmp(p, "_set") == 0) {
  1207. Delslice(temp, Len(temp) - 4, DOH_END);
  1208. Append(temp, "=");
  1209. } else if (strcmp(p, "_get") == 0) {
  1210. Delslice(temp, Len(temp) - 4, DOH_END);
  1211. }
  1212. }
  1213. if (multipleInheritance) {
  1214. Printv(klass->init, tab4, "rb_define_method(", klass->mImpl, ", \"", temp, "\", ", wname, ", -1);\n", NIL);
  1215. } else {
  1216. Printv(klass->init, tab4, "rb_define_method(", klass->vname, ", \"", temp, "\", ", wname, ", -1);\n", NIL);
  1217. }
  1218. break;
  1219. case STATIC_FUNC:
  1220. Printv(klass->init, tab4, "rb_define_singleton_method(", klass->vname, ", \"", iname, "\", ", wname, ", -1);\n", NIL);
  1221. break;
  1222. case NO_CPP:
  1223. if (!useGlobalModule) {
  1224. Printv(s, tab4, "rb_define_module_function(", modvar, ", \"", iname, "\", ", wname, ", -1);\n", NIL);
  1225. Printv(f_init, s, NIL);
  1226. } else {
  1227. Printv(s, tab4, "rb_define_global_function(\"", iname, "\", ", wname, ", -1);\n", NIL);
  1228. Printv(f_init, s, NIL);
  1229. }
  1230. break;
  1231. case DESTRUCTOR:
  1232. case CLASS_CONST:
  1233. case STATIC_VAR:
  1234. assert(false); // Should not have gotten here for these types
  1235. default:
  1236. assert(false);
  1237. }
  1238. defineAliases(n, iname);
  1239. Delete(temp);
  1240. Delete(s);
  1241. Delete(wname);
  1242. Delete(alloc_func);
  1243. }
  1244. /* ---------------------------------------------------------------------
  1245. * applyInputTypemap()
  1246. *
  1247. * Look up the appropriate "in" typemap for this parameter (p),
  1248. * substitute the correct strings for the $target and $input typemap
  1249. * parameters, and dump the resulting code to the wrapper file.
  1250. * --------------------------------------------------------------------- */
  1251. Parm *applyInputTypemap(Parm *p, String *ln, String *source, Wrapper *f, String *symname) {
  1252. String *tm;
  1253. SwigType *pt = Getattr(p, "type");
  1254. if ((tm = Getattr(p, "tmap:in"))) {
  1255. Replaceall(tm, "$target", ln);
  1256. Replaceall(tm, "$source", source);
  1257. Replaceall(tm, "$input", source);
  1258. Replaceall(tm, "$symname", symname);
  1259. if (Getattr(p, "wrap:disown") || (Getattr(p, "tmap:in:disown"))) {
  1260. Replaceall(tm, "$disown", "SWIG_POINTER_DISOWN");
  1261. } else {
  1262. Replaceall(tm, "$disown", "0");
  1263. }
  1264. Setattr(p, "emit:input", Copy(source));
  1265. Printf(f->code, "%s\n", tm);
  1266. p = Getattr(p, "tmap:in:next");
  1267. } else {
  1268. Swig_warning(WARN_TYPEMAP_IN_UNDEF, input_file, line_number, "Unable to use type %s as a function argument.\n", SwigType_str(pt, 0));
  1269. p = nextSibling(p);
  1270. }
  1271. return p;
  1272. }
  1273. Parm *skipIgnoredArgs(Parm *p) {
  1274. while (checkAttribute(p, "tmap:in:numinputs", "0")) {
  1275. p = Getattr(p, "tmap:in:next");
  1276. }
  1277. return p;
  1278. }
  1279. /* ---------------------------------------------------------------------
  1280. * marshalInputArgs()
  1281. *
  1282. * Process all of the arguments passed into the scripting language
  1283. * method and convert them into C/C++ function arguments using the
  1284. * supplied typemaps.
  1285. * --------------------------------------------------------------------- */
  1286. void marshalInputArgs(Node *n, ParmList *l, int numarg, int numreq, String *kwargs, bool allow_kwargs, Wrapper *f) {
  1287. int i;
  1288. Parm *p;
  1289. String *tm;
  1290. String *source;
  1291. String *target;
  1292. source = NewString("");
  1293. target = NewString("");
  1294. bool ctor_director = (current == CONSTRUCTOR_INITIALIZE && Swig_directorclass(n));
  1295. /**
  1296. * The 'start' value indicates which of the C/C++ function arguments
  1297. * produced here corresponds to the first value in Ruby's argv[] array.
  1298. * The value of start is either zero or one. If start is zero, then
  1299. * the first argument (with name arg1) is based on the value of argv[0].
  1300. * If start is one, then arg1 is based on the value of argv[1].
  1301. */
  1302. int start = (current == MEMBER_FUNC || current == MEMBER_VAR || ctor_director) ? 1 : 0;
  1303. int varargs = emit_isvarargs(l);
  1304. Printf(kwargs, "{ ");
  1305. for (i = 0, p = l; i < numarg; i++) {
  1306. p = skipIgnoredArgs(p);
  1307. String *pn = Getattr(p, "name");
  1308. String *ln = Getattr(p, "lname");
  1309. /* Produce string representation of source argument */
  1310. Clear(source);
  1311. /* First argument is a special case */
  1312. if (i == 0) {
  1313. Printv(source, (start == 0) ? "argv[0]" : "self", NIL);
  1314. } else {
  1315. Printf(source, "argv[%d]", i - start);
  1316. }
  1317. /* Produce string representation of target argument */
  1318. Clear(target);
  1319. Printf(target, "%s", Char(ln));
  1320. if (i >= (numreq)) { /* Check if parsing an optional argument */
  1321. Printf(f->code, " if (argc > %d) {\n", i - start);
  1322. }
  1323. /* Record argument name for keyword argument handling */
  1324. if (Len(pn)) {
  1325. Printf(kwargs, "\"%s\",", pn);
  1326. } else {
  1327. Printf(kwargs, "\"arg%d\",", i + 1);
  1328. }
  1329. /* Look for an input typemap */
  1330. p = applyInputTypemap(p, ln, source, f, Getattr(n, "name"));
  1331. if (i >= numreq) {
  1332. Printf(f->code, "}\n");
  1333. }
  1334. }
  1335. /* Finish argument marshalling */
  1336. Printf(kwargs, " NULL }");
  1337. if (allow_kwargs) {
  1338. Printv(f->locals, tab4, "const char *kwnames[] = ", kwargs, ";\n", NIL);
  1339. }
  1340. /* Trailing varargs */
  1341. if (varargs) {
  1342. if (p && (tm = Getattr(p, "tmap:in"))) {
  1343. Clear(source);
  1344. Printf(source, "argv[%d]", i - start);
  1345. Replaceall(tm, "$input", source);
  1346. Setattr(p, "emit:input", Copy(source));
  1347. Printf(f->code, "if (argc > %d) {\n", i - start);
  1348. Printv(f->code, tm, "\n", NIL);
  1349. Printf(f->code, "}\n");
  1350. }
  1351. }
  1352. Delete(source);
  1353. Delete(target);
  1354. }
  1355. /* ---------------------------------------------------------------------
  1356. * insertConstraintCheckingCode(ParmList *l, Wrapper *f)
  1357. *
  1358. * Checks each of the parameters in the parameter list for a "check"
  1359. * typemap and (if it finds one) inserts the typemapping code into
  1360. * the function wrapper.
  1361. * --------------------------------------------------------------------- */
  1362. void insertConstraintCheckingCode(ParmList *l, Wrapper *f) {
  1363. Parm *p;
  1364. String *tm;
  1365. for (p = l; p;) {
  1366. if ((tm = Getattr(p, "tmap:check"))) {
  1367. Replaceall(tm, "$target", Getattr(p, "lname"));
  1368. Printv(f->code, tm, "\n", NIL);
  1369. p = Getattr(p, "tmap:check:next");
  1370. } else {
  1371. p = nextSibling(p);
  1372. }
  1373. }
  1374. }
  1375. /* ---------------------------------------------------------------------
  1376. * insertCleanupCode(ParmList *l, String *cleanup)
  1377. *
  1378. * Checks each of the parameters in the parameter list for a "freearg"
  1379. * typemap and (if it finds one) inserts the typemapping code into
  1380. * the function wrapper.
  1381. * --------------------------------------------------------------------- */
  1382. void insertCleanupCode(ParmList *l, String *cleanup) {
  1383. String *tm;
  1384. for (Parm *p = l; p;) {
  1385. if ((tm = Getattr(p, "tmap:freearg"))) {
  1386. if (Len(tm) != 0) {
  1387. Replaceall(tm, "$source", Getattr(p, "lname"));
  1388. Printv(cleanup, tm, "\n", NIL);
  1389. }
  1390. p = Getattr(p, "tmap:freearg:next");
  1391. } else {
  1392. p = nextSibling(p);
  1393. }
  1394. }
  1395. }
  1396. /* ---------------------------------------------------------------------
  1397. * insertArgOutputCode(ParmList *l, String *outarg, int& need_result)
  1398. *
  1399. * Checks each of the parameters in the parameter list for a "argout"
  1400. * typemap and (if it finds one) inserts the typemapping code into
  1401. * the function wrapper.
  1402. * --------------------------------------------------------------------- */
  1403. void insertArgOutputCode(ParmList *l, String *outarg, int &need_result) {
  1404. String *tm;
  1405. for (Parm *p = l; p;) {
  1406. if ((tm = Getattr(p, "tmap:argout"))) {
  1407. Replaceall(tm, "$source", Getattr(p, "lname"));
  1408. Replaceall(tm, "$target", "vresult");
  1409. Replaceall(tm, "$result", "vresult");
  1410. Replaceall(tm, "$arg", Getattr(p, "emit:input"));
  1411. Replaceall(tm, "$input", Getattr(p, "emit:input"));
  1412. Printv(outarg, tm, "\n", NIL);
  1413. need_result += 1;
  1414. p = Getattr(p, "tmap:argout:next");
  1415. } else {
  1416. p = nextSibling(p);
  1417. }
  1418. }
  1419. }
  1420. /* ---------------------------------------------------------------------
  1421. * validIdentifier()
  1422. *
  1423. * Is this a valid identifier in the scripting language?
  1424. * Ruby method names can include any combination of letters, numbers
  1425. * and underscores. A Ruby method name may optionally end with
  1426. * a question mark ("?"), exclamation point ("!") or equals sign ("=").
  1427. *
  1428. * Methods whose names end with question marks are, by convention,
  1429. * predicate methods that return true or false (e.g. Array#empty?).
  1430. *
  1431. * Methods whose names end with exclamation points are, by convention,
  1432. * called bang methods that modify the instance in place (e.g. Array#sort!).
  1433. *
  1434. * Methods whose names end with an equals sign are attribute setters
  1435. * (e.g. Thread#critical=).
  1436. * --------------------------------------------------------------------- */
  1437. virtual int validIdentifier(String *s) {
  1438. char *c = Char(s);
  1439. while (*c) {
  1440. if (!(isalnum(*c) || (*c == '_') || (*c == '?') || (*c == '!') || (*c == '=')))
  1441. return 0;
  1442. c++;
  1443. }
  1444. return 1;
  1445. }
  1446. /* ---------------------------------------------------------------------
  1447. * functionWrapper()
  1448. *
  1449. * Create a function declaration and register it with the interpreter.
  1450. * --------------------------------------------------------------------- */
  1451. virtual int functionWrapper(Node *n) {
  1452. String *nodeType;
  1453. bool destructor;
  1454. String *symname = Copy(Getattr(n, "sym:name"));
  1455. SwigType *t = Getattr(n, "type");
  1456. ParmList *l = Getattr(n, "parms");
  1457. int director_method = 0;
  1458. String *tm;
  1459. int need_result = 0;
  1460. /* Ruby needs no destructor wrapper */
  1461. if (current == DESTRUCTOR)
  1462. return SWIG_NOWRAP;
  1463. nodeType = Getattr(n, "nodeType");
  1464. destructor = (!Cmp(nodeType, "destructor"));
  1465. /* If the C++ class constructor is overloaded, we only want to
  1466. * write out the "new" singleton method once since it is always
  1467. * the same. (It's the "initialize" method that will handle the
  1468. * overloading). */
  1469. if (current == CONSTRUCTOR_ALLOCATE && Swig_symbol_isoverloaded(n) && Getattr(n, "sym:nextSibling") != 0)
  1470. return SWIG_OK;
  1471. String *overname = 0;
  1472. if (Getattr(n, "sym:overloaded")) {
  1473. overname = Getattr(n, "sym:overname");
  1474. } else {
  1475. if (!addSymbol(symname, n))
  1476. return SWIG_ERROR;
  1477. }
  1478. String *cleanup = NewString("");
  1479. String *outarg = NewString("");
  1480. String *kwargs = NewString("");
  1481. Wrapper *f = NewWrapper();
  1482. /* Rename predicate methods */
  1483. if (GetFlag(n, "feature:predicate")) {
  1484. Append(symname, "?");
  1485. }
  1486. /* Rename bang methods */
  1487. if (GetFlag(n, "feature:bang")) {
  1488. Append(symname, "!");
  1489. }
  1490. /* Determine the name of the SWIG wrapper function */
  1491. String *wname = Swig_name_wrapper(symname);
  1492. if (overname && current != CONSTRUCTOR_ALLOCATE) {
  1493. Append(wname, overname);
  1494. }
  1495. /* Emit arguments */
  1496. if (current != CONSTRUCTOR_ALLOCATE) {
  1497. emit_parameter_variables(l, f);
  1498. }
  1499. /* Attach standard typemaps */
  1500. if (current != CONSTRUCTOR_ALLOCATE) {
  1501. emit_attach_parmmaps(l, f);
  1502. }
  1503. Setattr(n, "wrap:parms", l);
  1504. /* Get number of arguments */
  1505. int numarg = emit_num_arguments(l);
  1506. int numreq = emit_num_required(l);
  1507. int varargs = emit_isvarargs(l);
  1508. bool allow_kwargs = GetFlag(n, "feature:kwargs") ? true : false;
  1509. bool ctor_director = (current == CONSTRUCTOR_INITIALIZE && Swig_directorclass(n));
  1510. int start = (current == MEMBER_FUNC || current == MEMBER_VAR || ctor_director) ? 1 : 0;
  1511. /* Now write the wrapper function itself */
  1512. if (current == CONSTRUCTOR_ALLOCATE) {
  1513. Printf(f->def, "#ifdef HAVE_RB_DEFINE_ALLOC_FUNC\n");
  1514. Printv(f->def, "SWIGINTERN VALUE\n", wname, "(VALUE self) {", NIL);
  1515. Printf(f->def, "#else\n");
  1516. Printv(f->def, "SWIGINTERN VALUE\n", wname, "(int argc, VALUE *argv, VALUE self) {", NIL);
  1517. Printf(f->def, "#endif\n");
  1518. } else if (current == CONSTRUCTOR_INITIALIZE) {
  1519. Printv(f->def, "SWIGINTERN VALUE\n", wname, "(int argc, VALUE *argv, VALUE self) {", NIL);
  1520. if (!varargs) {
  1521. Printf(f->code, "if ((argc < %d) || (argc > %d)) ", numreq - start, numarg - start);
  1522. } else {
  1523. Printf(f->code, "if (argc < %d) ", numreq - start);
  1524. }
  1525. Printf(f->code, "{rb_raise(rb_eArgError, \"wrong # of arguments(%%d for %d)\",argc); SWIG_fail;}\n", numreq - start);
  1526. } else {
  1527. if ( current == NO_CPP )
  1528. {
  1529. String* docs = docstring(n, AUTODOC_FUNC);
  1530. Printf(f_wrappers, "%s", docs);
  1531. Delete(docs);
  1532. }
  1533. Printv(f->def, "SWIGINTERN VALUE\n", wname, "(int argc, VALUE *argv, VALUE self) {", NIL);
  1534. if (!varargs) {
  1535. Printf(f->code, "if ((argc < %d) || (argc > %d)) ", numreq - start, numarg - start);
  1536. } else {
  1537. Printf(f->code, "if (argc < %d) ", numreq - start);
  1538. }
  1539. Printf(f->code, "{rb_raise(rb_eArgError, \"wrong # of arguments(%%d for %d)\",argc); SWIG_fail;}\n", numreq - start);
  1540. }
  1541. /* Now walk the function parameter list and generate code */
  1542. /* to get arguments */
  1543. if (current != CONSTRUCTOR_ALLOCATE) {
  1544. marshalInputArgs(n, l, numarg, numreq, kwargs, allow_kwargs, f);
  1545. }
  1546. // FIXME?
  1547. if (ctor_director) {
  1548. numarg--;
  1549. numreq--;
  1550. }
  1551. /* Insert constraint checking code */
  1552. insertConstraintCheckingCode(l, f);
  1553. /* Insert cleanup code */
  1554. insertCleanupCode(l, cleanup);
  1555. /* Insert argument output code */
  1556. insertArgOutputCode(l, outarg, need_result);
  1557. /* if the object is a director, and the method call originated from its
  1558. * underlying Ruby object, resolve the call by going up the c++
  1559. * inheritance chain. otherwise try to resolve the method in python.
  1560. * without this check an infinite loop is set up between the director and
  1561. * shadow class method calls.
  1562. */
  1563. // NOTE: this code should only be inserted if this class is the
  1564. // base class of a director class. however, in general we haven't
  1565. // yet analyzed all classes derived from this one to see if they are
  1566. // directors. furthermore, this class may be used as the base of
  1567. // a director class defined in a completely different module at a
  1568. // later time, so this test must be included whether or not directorbase
  1569. // is true. we do skip this code if directors have not been enabled
  1570. // at the command line to preserve source-level compatibility with
  1571. // non-polymorphic swig. also, if this wrapper is for a smart-pointer
  1572. // method, there is no need to perform the test since the calling object
  1573. // (the smart-pointer) and the director object (the "pointee") are
  1574. // distinct.
  1575. director_method = is_member_director(n) && !is_smart_pointer() && !destructor;
  1576. if (director_method) {
  1577. Wrapper_add_local(f, "director", "Swig::Director *director = 0");
  1578. Printf(f->code, "director = dynamic_cast<Swig::Director *>(arg1);\n");
  1579. Wrapper_add_local(f, "upcall", "bool upcall = false");
  1580. Append(f->code, "upcall = (director && (director->swig_get_self() == self));\n");
  1581. }
  1582. /* Now write code to make the function call */
  1583. if (current != CONSTRUCTOR_ALLOCATE) {
  1584. if (current == CONSTRUCTOR_INITIALIZE) {
  1585. Node *pn = Swig_methodclass(n);
  1586. String *symname = Getattr(pn, "sym:name");
  1587. String *action = Getattr(n, "wrap:action");
  1588. if (directorsEnabled()) {
  1589. String *classname = NewStringf("const char *classname SWIGUNUSED = \"%s::%s\"", module, symname);
  1590. Wrapper_add_local(f, "classname", classname);
  1591. }
  1592. if (action) {
  1593. Printf(action, "\nDATA_PTR(self) = %s;", Swig_cresult_name());
  1594. if (GetFlag(pn, "feature:trackobjects")) {
  1595. Printf(action, "\nSWIG_RubyAddTracking(%s, self);", Swig_cresult_name());
  1596. }
  1597. }
  1598. }
  1599. /* Emit the function call */
  1600. if (director_method) {
  1601. Printf(f->code, "try {\n");
  1602. }
  1603. Setattr(n, "wrap:name", wname);
  1604. Swig_director_emit_dynamic_cast(n, f);
  1605. String *actioncode = emit_action(n);
  1606. if (director_method) {
  1607. Printf(actioncode, "} catch (Swig::DirectorException& e) {\n");
  1608. Printf(actioncode, " rb_exc_raise(e.getError());\n");
  1609. Printf(actioncode, " SWIG_fail;\n");
  1610. Printf(actioncode, "}\n");
  1611. }
  1612. /* Return value if necessary */
  1613. if (SwigType_type(t) != T_VOID && current != CONSTRUCTOR_INITIALIZE) {
  1614. need_result = 1;
  1615. if (GetFlag(n, "feature:predicate")) {
  1616. Printv(actioncode, tab4, "vresult = (", Swig_cresult_name(), " ? Qtrue : Qfalse);\n", NIL);
  1617. } else {
  1618. tm = Swig_typemap_lookup_out("out", n, Swig_cresult_name(), f, actioncode);
  1619. actioncode = 0;
  1620. if (tm) {
  1621. Replaceall(tm, "$result", "vresult");
  1622. Replaceall(tm, "$source", Swig_cresult_name());
  1623. Replaceall(tm, "$target", "vresult");
  1624. if (GetFlag(n, "feature:new"))
  1625. Replaceall(tm, "$owner", "SWIG_POINTER_OWN");
  1626. else
  1627. Replaceall(tm, "$owner", "0");
  1628. #if 1
  1629. // FIXME: this will not try to unwrap directors returned as non-director
  1630. // base class pointers!
  1631. /* New addition to unwrap director return values so that the original
  1632. * Ruby object is returned instead.
  1633. */
  1634. bool unwrap = false;
  1635. String *decl = Getattr(n, "decl");
  1636. int is_pointer = SwigType_ispointer_return(decl);
  1637. int is_reference = SwigType_isreference_return(decl);
  1638. if (is_pointer || is_reference) {
  1639. String *type = Getattr(n, "type");
  1640. Node *parent = Swig_methodclass(n);
  1641. Node *modname = Getattr(parent, "module");
  1642. Node *target = Swig_directormap(modname, type);
  1643. if (target)
  1644. unwrap = true;
  1645. }
  1646. if (unwrap) {
  1647. Wrapper_add_local(f, "director", "Swig::Director *director = 0");
  1648. Printf(f->code, "director = dynamic_cast<Swig::Director *>(%s);\n", Swig_cresult_name());
  1649. Printf(f->code, "if (director) {\n");
  1650. Printf(f->code, " vresult = director->swig_get_self();\n");
  1651. Printf(f->code, "} else {\n");
  1652. Printf(f->code, "%s\n", tm);
  1653. Printf(f->code, "}\n");
  1654. director_method = 0;
  1655. } else {
  1656. Printf(f->code, "%s\n", tm);
  1657. }
  1658. #else
  1659. Printf(f->code, "%s\n", tm);
  1660. #endif
  1661. Delete(tm);
  1662. } else {
  1663. Swig_warning(WARN_TYPEMAP_OUT_UNDEF, input_file, line_number, "Unable to use return type %s.\n", SwigType_str(t, 0));
  1664. }
  1665. }
  1666. }
  1667. if (actioncode) {
  1668. Append(f->code, actioncode);
  1669. Delete(actioncode);
  1670. }
  1671. emit_return_variable(n, t, f);
  1672. }
  1673. /* Extra code needed for new and initialize methods */
  1674. if (current == CONSTRUCTOR_ALLOCATE) {
  1675. need_result = 1;
  1676. Printf(f->code, "VALUE vresult = SWIG_NewClassInstance(self, SWIGTYPE%s);\n", Char(SwigType_manglestr(t)));
  1677. Printf(f->code, "#ifndef HAVE_RB_DEFINE_ALLOC_FUNC\n");
  1678. Printf(f->code, "rb_obj_call_init(vresult, argc, argv);\n");
  1679. Printf(f->code, "#endif\n");
  1680. } else if (current == CONSTRUCTOR_INITIALIZE) {
  1681. need_result = 1;
  1682. }
  1683. else
  1684. {
  1685. if ( need_result > 1 ) {
  1686. if ( SwigType_type(t) == T_VOID )
  1687. Printf(f->code, "vresult = rb_ary_new();\n");
  1688. else
  1689. {
  1690. Printf(f->code, "if (vresult == Qnil) vresult = rb_ary_new();\n");
  1691. Printf(f->code, "else vresult = SWIG_Ruby_AppendOutput( "
  1692. "rb_ary_new(), vresult);\n");
  1693. }
  1694. }
  1695. }
  1696. /* Dump argument output code; */
  1697. Printv(f->code, outarg, NIL);
  1698. /* Dump the argument cleanup code */
  1699. int need_cleanup = (current != CONSTRUCTOR_ALLOCATE) && (Len(cleanup) != 0);
  1700. if (need_cleanup) {
  1701. Printv(f->code, cleanup, NIL);
  1702. }
  1703. /* Look for any remaining cleanup. This processes the %new directive */
  1704. if (current != CONSTRUCTOR_ALLOCATE && GetFlag(n, "feature:new")) {
  1705. tm = Swig_typemap_lookup("newfree", n, Swig_cresult_name(), 0);
  1706. if (tm) {
  1707. Replaceall(tm, "$source", Swig_cresult_name());
  1708. Printv(f->code, tm, "\n", NIL);
  1709. Delete(tm);
  1710. }
  1711. }
  1712. /* Special processing on return value. */
  1713. tm = Swig_typemap_lookup("ret", n, Swig_cresult_name(), 0);
  1714. if (tm) {
  1715. Replaceall(tm, "$source", Swig_cresult_name());
  1716. Printv(f->code, tm, NIL);
  1717. Delete(tm);
  1718. }
  1719. if (director_method) {
  1720. if ((tm = Swig_typemap_lookup("directorfree", n, Swig_cresult_name(), 0))) {
  1721. Replaceall(tm, "$input", Swig_cresult_name());
  1722. Replaceall(tm, "$result", "vresult");
  1723. Printf(f->code, "%s\n", tm);
  1724. }
  1725. }
  1726. /* Wrap things up (in a manner of speaking) */
  1727. if (need_result) {
  1728. if (current == CONSTRUCTOR_ALLOCATE) {
  1729. Printv(f->code, tab4, "return vresult;\n", NIL);
  1730. } else if (current == CONSTRUCTOR_INITIALIZE) {
  1731. Printv(f->code, tab4, "return self;\n", NIL);
  1732. Printv(f->code, "fail:\n", NIL);
  1733. if (need_cleanup) {
  1734. Printv(f->code, cleanup, NIL);
  1735. }
  1736. Printv(f->code, tab4, "return Qnil;\n", NIL);
  1737. } else {
  1738. Wrapper_add_local(f, "vresult", "VALUE vresult = Qnil");
  1739. Printv(f->code, tab4, "return vresult;\n", NIL);
  1740. Printv(f->code, "fail:\n", NIL);
  1741. if (need_cleanup) {
  1742. Printv(f->code, cleanup, NIL);
  1743. }
  1744. Printv(f->code, tab4, "return Qnil;\n", NIL);
  1745. }
  1746. } else {
  1747. Printv(f->code, tab4, "return Qnil;\n", NIL);
  1748. Printv(f->code, "fail:\n", NIL);
  1749. if (need_cleanup) {
  1750. Printv(f->code, cleanup, NIL);
  1751. }
  1752. Printv(f->code, tab4, "return Qnil;\n", NIL);
  1753. }
  1754. Printf(f->code, "}\n");
  1755. /* Substitute the cleanup code */
  1756. Replaceall(f->code, "$cleanup", cleanup);
  1757. /* Substitute the function name */
  1758. Replaceall(f->code, "$symname", symname);
  1759. /* Emit the function */
  1760. Wrapper_print(f, f_wrappers);
  1761. /* Now register the function with the interpreter */
  1762. if (!Swig_symbol_isoverloaded(n)) {
  1763. create_command(n, symname);
  1764. } else {
  1765. if (current == CONSTRUCTOR_ALLOCATE) {
  1766. create_command(n, symname);
  1767. } else {
  1768. if (!Getattr(n, "sym:nextSibling"))
  1769. dispatchFunction(n);
  1770. }
  1771. }
  1772. Delete(kwargs);
  1773. Delete(cleanup);
  1774. Delete(outarg);
  1775. DelWrapper(f);
  1776. Delete(symname);
  1777. return SWIG_OK;
  1778. }
  1779. /* ------------------------------------------------------------
  1780. * dispatchFunction()
  1781. * ------------------------------------------------------------ */
  1782. void dispatchFunction(Node *n) {
  1783. /* Last node in overloaded chain */
  1784. int maxargs;
  1785. String *tmp = NewString("");
  1786. String *dispatch = Swig_overload_dispatch(n, "return %s(nargs, args, self);", &maxargs);
  1787. /* Generate a dispatch wrapper for all overloaded functions */
  1788. Wrapper *f = NewWrapper();
  1789. String *symname = Getattr(n, "sym:name");
  1790. String *wname = Swig_name_wrapper(symname);
  1791. Printv(f->def, "SWIGINTERN VALUE ", wname, "(int nargs, VALUE *args, VALUE self) {", NIL);
  1792. Wrapper_add_local(f, "argc", "int argc");
  1793. bool ctor_director = (current == CONSTRUCTOR_INITIALIZE && Swig_directorclass(n));
  1794. if (current == MEMBER_FUNC || current == MEMBER_VAR || ctor_director) {
  1795. Printf(tmp, "VALUE argv[%d]", maxargs + 1);
  1796. } else {
  1797. Printf(tmp, "VALUE argv[%d]", maxargs);
  1798. }
  1799. Wrapper_add_local(f, "argv", tmp);
  1800. Wrapper_add_local(f, "ii", "int ii");
  1801. if (current == MEMBER_FUNC || current == MEMBER_VAR || ctor_director) {
  1802. maxargs += 1;
  1803. Printf(f->code, "argc = nargs + 1;\n");
  1804. Printf(f->code, "argv[0] = self;\n");
  1805. Printf(f->code, "if (argc > %d) SWIG_fail;\n", maxargs);
  1806. Printf(f->code, "for (ii = 1; (ii < argc); ++ii) {\n");
  1807. Printf(f->code, "argv[ii] = args[ii-1];\n");
  1808. Printf(f->code, "}\n");
  1809. } else {
  1810. Printf(f->code, "argc = nargs;\n");
  1811. Printf(f->code, "if (argc > %d) SWIG_fail;\n", maxargs);
  1812. Printf(f->code, "for (ii = 0; (ii < argc); ++ii) {\n");
  1813. Printf(f->code, "argv[ii] = args[ii];\n");
  1814. Printf(f->code, "}\n");
  1815. }
  1816. Replaceall(dispatch, "$args", "nargs, args, self");
  1817. Printv(f->code, dispatch, "\n", NIL);
  1818. // Generate prototype list, go to first node
  1819. Node *sibl = n;
  1820. String* type = SwigType_str(Getattr(sibl,"type"),NULL);
  1821. while (Getattr(sibl, "sym:previousSibling"))
  1822. sibl = Getattr(sibl, "sym:previousSibling"); // go all the way up
  1823. // Constructors will be treated specially
  1824. const bool isCtor = Cmp(Getattr(sibl,"feature:new"), "1") == 0;
  1825. const bool isMethod = ( Cmp(Getattr(sibl, "ismember"), "1") == 0 &&
  1826. (!isCtor) );
  1827. // Construct real method name
  1828. String* methodName = NewString("");
  1829. if ( isMethod ) {
  1830. // Sometimes a method node has no parent (SF#3034054).
  1831. // This value is used in an exception message, so just skip the class
  1832. // name in this case so at least we don't segfault. This is probably
  1833. // just working around a problem elsewhere though.
  1834. Node *parent_node = parentNode(sibl);
  1835. if (parent_node)
  1836. Printv( methodName, Getattr(parent_node,"sym:name"), ".", NIL );
  1837. }
  1838. Append( methodName, Getattr(sibl,"sym:name" ) );
  1839. if ( isCtor ) Append( methodName, ".new" );
  1840. // Generate prototype list
  1841. String *protoTypes = NewString("");
  1842. do {
  1843. Append( protoTypes, "\n\" ");
  1844. if ( !isCtor ) Printv( protoTypes, type, " ", NIL );
  1845. Printv(protoTypes, methodName, NIL );
  1846. Parm* p = Getattr(sibl, "wrap:parms");
  1847. if (p && (current == MEMBER_FUNC || current == MEMBER_VAR ||
  1848. ctor_director) )
  1849. p = nextSibling(p); // skip self
  1850. Append( protoTypes, "(" );
  1851. while(p)
  1852. {
  1853. Append( protoTypes, SwigType_str(Getattr(p,"type"), Getattr(p,"name")) );
  1854. if ( ( p = nextSibling(p)) ) Append(protoTypes, ", ");
  1855. }
  1856. Append( protoTypes, ")\\n\"" );
  1857. } while ((sibl = Getattr(sibl, "sym:nextSibling")));
  1858. Ap