interfaceMakerPythonNative.cxx 114 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113
  1. // Filename: interfaceMakerPythonNative.cxx
  2. ////////////////////////////////////////////////////////////////////
  3. //
  4. // PANDA 3D SOFTWARE
  5. // Copyright (c) 2001 - 2004, Disney Enterprises, Inc. All rights reserved
  6. //
  7. // All use of this software is subject to the terms of the Panda 3d
  8. // Software license. You should have received a copy of this license
  9. // along with this source code; you will also find a current copy of
  10. // the license at http://etc.cmu.edu/panda3d/docs/license/ .
  11. //
  12. // To contact the maintainers of this program write to
  13. // [email protected] .
  14. //
  15. ////////////////////////////////////////////////////////////////////
  16. #include "interfaceMakerPythonNative.h"
  17. #include "interrogateBuilder.h"
  18. #include "interrogate.h"
  19. #include "functionRemap.h"
  20. #include "parameterRemapUnchanged.h"
  21. #include "typeManager.h"
  22. #include "interrogateDatabase.h"
  23. #include "interrogateType.h"
  24. #include "interrogateFunction.h"
  25. #include "cppFunctionType.h"
  26. #include "cppPointerType.h"
  27. #include "cppTypeDeclaration.h"
  28. #include "cppStructType.h"
  29. #include "vector"
  30. #include "cppParameterList.h"
  31. #include "algorithm"
  32. #include <set>
  33. #include <map>
  34. extern bool inside_python_native;
  35. extern InterrogateType dummy_type;
  36. extern std::string EXPORT_IMPORT_PREFEX;
  37. #define CLASS_PREFEX "Dtool_"
  38. #define INSTANCE_PREFEX "Dtool_"
  39. #define BASE_INSTANCE_NAME "Dtool_PyInstDef"
  40. /////////////////////////////////////////////////////////
  41. // Name Remaper...
  42. // Snagged from ffi py code....
  43. /////////////////////////////////////////////////////////
  44. struct RenameSet
  45. {
  46. char * _from;
  47. char * _to;
  48. int function_type;
  49. };
  50. struct FlagSet
  51. {
  52. char * _to;
  53. int function_type;
  54. };
  55. ///////////////////////////////////////////////////////////////////////////////////////
  56. RenameSet methodRenameDictionary[] = {
  57. { "operator==" , "eq", 0 },
  58. { "operator!=" , "ne", 0 },
  59. { "operator<<" , "__lshift__", 0 },
  60. { "operator>>" , "__rshift__", 0 },
  61. { "operator<" , "lessThan", 0 },
  62. { "operator>" , "greaterThan", 0 },
  63. { "operator<=" , "lessThanOrEqual", 0 },
  64. { "operator>=" , "greaterThanOrEqual", 0 },
  65. { "operator=" , "assign", 0 },
  66. { "operator()" , "__call__", 0 },
  67. { "operator[]" , "__getitem__", 0 },
  68. { "operator++" , "increment", 0 },
  69. { "operator--" , "decrement", 0 },
  70. { "operator^" , "__xor__", 0 },
  71. { "operator%" , "__mod__", 0 },
  72. { "operator!" , "logicalNot", 0 },
  73. { "operator~" , "bitwiseNot", 0 },
  74. { "operator&" , "__and__", 0 },
  75. { "operator&&" , "logicalAnd", 0 },
  76. { "operator|" , "__or__", 0 },
  77. { "operator||" , "logicalOr", 0 },
  78. { "operator+" , "__add__", 0 },
  79. { "operator-" , "__sub__", 0 },
  80. { "operator*" , "__mul__", 0 },
  81. { "operator/" , "__div__", 0 },
  82. { "operator+=" , "__iadd__", 1 },
  83. { "operator-=" , "__isub__", 1 },
  84. { "operator*=" , "__imul__", 1 },
  85. { "operator/=" , "__idiv__", 1 },
  86. { "operator," , "concatenate", 0 },
  87. { "operator|=" , "__ior__", 1 },
  88. { "operator&=" , "__iand__", 1 },
  89. { "operator^=" , "__ixor__", 1 },
  90. { "operator~=" , "bitwiseNotEqual", 0 },
  91. { "operator->" , "dereference", 0 },
  92. { "operator<<=" , "__ilshift__", 1 },
  93. { "operator>>=" , "__irshift__", 1 },
  94. { "print" , "Cprint", 0 },
  95. { "CInterval.setT" , "_priv__cSetT", 0 },
  96. { NULL, NULL, -1 }
  97. };
  98. char * InPlaceSet[] = {
  99. "__iadd__",
  100. "__isub__",
  101. "__imul__",
  102. "__idiv__",
  103. "__ior__",
  104. "__iand__",
  105. "__ixor__",
  106. "__ilshift__",
  107. "__irshift__",
  108. NULL,
  109. };
  110. ///////////////////////////////////////////////////////////////////////////////////////
  111. RenameSet classRenameDictionary[] = {
  112. { "Loader" , "PandaLoader",0 },
  113. { "String" , "CString",0 },
  114. { "LMatrix4f" , "Mat4",0 },
  115. { "LMatrix3f" , "Mat3",0 },
  116. { "LVecBase4f" , "VBase4",0 },
  117. { "LVector4f" , "Vec4",0 },
  118. { "LPoint4f" , "Point4",0 },
  119. { "LVecBase3f" , "VBase3",0 },
  120. { "LVector3f" , "Vec3",0 },
  121. { "LPoint3f" , "Point3",0 },
  122. { "LVecBase2f" , "VBase2",0 },
  123. { "LVector2f" , "Vec2",0 },
  124. { "LPoint2f" , "Point2",0 },
  125. { "LQuaternionf" , "Quat",0 },
  126. { "LMatrix4d" , "Mat4D",0 },
  127. { "LMatrix3d" , "Mat3D",0 },
  128. { "LVecBase4d" , "VBase4D",0 },
  129. { "LVector4d" , "Vec4D",0 },
  130. { "LPoint4d" , "Point4D",0 },
  131. { "LVecBase3d" , "VBase3D",0 },
  132. { "LVector3d" , "Vec3D",0 },
  133. { "LPoint3d" , "Point3D",0 },
  134. { "LVecBase2d" , "VBase2D",0 },
  135. { "LVector2d" , "Vec2D",0 },
  136. { "LPoint2d" , "Point2D",0 },
  137. { "LQuaterniond" , "QuatD",0 },
  138. { "Plane" , "PlaneBase",0 },
  139. { "Planef" , "Plane",0 },
  140. { "Planed" , "PlaneD",0 },
  141. { "Frustum" , "FrustumBase",0 },
  142. { "Frustumf" , "Frustum",0 },
  143. { "Frustumd" , "FrustumD",0 },
  144. { NULL,NULL,-1 }
  145. };
  146. ///////////////////////////////////////////////////////////////////////////////////////
  147. ///////////////////////////////////////////////////////////////////////////////////////
  148. char * pythonKeywords[] = {
  149. "and",
  150. "del",
  151. "for",
  152. "is",
  153. "raise",
  154. "assert",
  155. "elif",
  156. "from",
  157. "lambda",
  158. "return",
  159. "break",
  160. "else",
  161. "global",
  162. "not",
  163. "try",
  164. "class",
  165. "except",
  166. "if",
  167. "or",
  168. "while",
  169. "continue",
  170. "exec",
  171. "import",
  172. "pass",
  173. "def",
  174. "finally",
  175. "in",
  176. "print",
  177. NULL};
  178. ///////////////////////////////////////////////////////////////////////////////////////
  179. std::string checkKeyword(std::string & cppName)
  180. {
  181. for(int x = 0; pythonKeywords[x] != NULL; x++)
  182. {
  183. if(cppName == pythonKeywords[x])
  184. {
  185. return std::string("_")+cppName;
  186. }
  187. }
  188. return cppName;
  189. }
  190. ///////////////////////////////////////////////////////////////////////////////////////
  191. ///////////////////////////////////////////////////////////////////////////////////////
  192. std::string classNameFromCppName(const std::string &cppName)
  193. {
  194. //# initialize to empty string
  195. std::string className = "";
  196. //# These are the characters we want to strip out of the name
  197. const std::string badChars("!@#$%^&*()<>,.-=+~{}? ");
  198. int nextCap = 0;
  199. int firstChar = 1;
  200. for(std::string::const_iterator chr = cppName.begin(); chr != cppName.end(); chr++)
  201. {
  202. if (badChars.find(*chr) != std::string::npos)
  203. {
  204. }
  205. else if (*chr == '_')
  206. {
  207. nextCap = 1;
  208. }
  209. else if (nextCap || firstChar)
  210. {
  211. className += toupper(*chr);
  212. nextCap = 0;
  213. firstChar = 0;
  214. }
  215. else
  216. {
  217. className += * chr;
  218. }
  219. }
  220. for(int x = 0; classRenameDictionary[x]._from != NULL; x++)
  221. {
  222. if(className == classRenameDictionary[x]._from)
  223. className = classRenameDictionary[x]._to;
  224. }
  225. if (className.empty())
  226. {
  227. std::string text = "** ERROR ** Renaming class: " + cppName + " to empty string";
  228. printf("%s",text.c_str());
  229. }
  230. //# FFIConstants.notify.debug('Renaming class: ' + cppName + ' to: ' + className)
  231. //# Note we do not have to check for keywords because class name are capitalized
  232. return className;
  233. }
  234. ///////////////////////////////////////////////////////////////////////////////////////
  235. ///////////////////////////////////////////////////////////////////////////////////////
  236. std::string nonClassNameFromCppName(const std::string &cppName_in)
  237. {
  238. std::string className = classNameFromCppName(cppName_in);
  239. //# Make the first character lowercase
  240. std::string newName;
  241. int pass = 0;
  242. for(std::string::const_iterator chr = className.begin(); chr != className.end(); chr++)
  243. {
  244. if(pass == 0)
  245. newName += toupper(*chr);
  246. else
  247. newName += tolower(*chr);
  248. pass++;
  249. }
  250. //# Mangle names that happen to be python keywords so they are not anymore
  251. //newName = checkKeyword(newName)
  252. return newName;
  253. }
  254. ///////////////////////////////////////////////////////////////////////////////////////
  255. ///////////////////////////////////////////////////////////////////////////////////////
  256. std::string methodNameFromCppName(std::string cppName, const std::string &className)
  257. {
  258. std::string methodName;
  259. std::string badChars(" ");
  260. int nextCap = 0;
  261. for(std::string::const_iterator chr = cppName.begin(); chr != cppName.end(); chr++)
  262. {
  263. if (badChars.find(*chr) != std::string::npos)
  264. {
  265. }
  266. else if (*chr == '_')
  267. {
  268. nextCap = 1;
  269. }
  270. else if (nextCap)
  271. {
  272. methodName += toupper(*chr);
  273. nextCap = 0;
  274. }
  275. else
  276. {
  277. methodName += *chr;
  278. }
  279. }
  280. std::string LookUpName = methodName;
  281. for(int x = 0; classRenameDictionary[x]._from != NULL; x++)
  282. {
  283. if(methodName == methodRenameDictionary[x]._from || (cppName == methodRenameDictionary[x]._from && methodRenameDictionary[x].function_type != 0) )
  284. {
  285. methodName = methodRenameDictionary[x]._to;
  286. }
  287. }
  288. if(className.size() > 0)
  289. {
  290. LookUpName = className + '.' + methodName;
  291. for(int x = 0; classRenameDictionary[x]._from != NULL; x++)
  292. {
  293. if(methodName == methodRenameDictionary[x]._from)
  294. methodName = methodRenameDictionary[x]._to;
  295. }
  296. }
  297. // # Mangle names that happen to be python keywords so they are not anymore
  298. methodName = checkKeyword(methodName);
  299. return methodName;
  300. }
  301. ///////////////////////////////////////////////////////////////////////////////////////
  302. ///////////////////////////////////////////////////////////////////////////////////////
  303. ///////////////////////////////////////////////////////////////////////////////
  304. ///////////////////////////////////////////////////////////////////////////////
  305. ///////////////////////////////////////////////////////////////////////////////
  306. std::string make_safe_name(const std::string & name)
  307. {
  308. return InterrogateBuilder::clean_identifier(name);
  309. /*
  310. static const char safe_chars2[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
  311. std::string result = name;
  312. size_t pos = result.find_first_not_of(safe_chars2);
  313. while (pos != std::string::npos)
  314. {
  315. result[pos] = '_';
  316. pos = result.find_first_not_of(safe_chars2);
  317. }
  318. return result;
  319. */
  320. }
  321. bool isInplaceFunction(const std::string &cppName)
  322. {
  323. std::string wname = methodNameFromCppName(cppName,"");
  324. for(int x = 0; InPlaceSet[x] != NULL; x++)
  325. if(InPlaceSet[x] == wname)
  326. return true;
  327. return false;
  328. }
  329. ///////////////////////////////////////////////////////////////////////////////
  330. ///////////////////////////////////////////////////////////////////////////////
  331. void InterfaceMakerPythonNative::GetValideChildClasses( std::map< std::string ,CastDetails > &answer, CPPStructType * inclass, const std::string &up_cast_seed, bool downcastposible)
  332. {
  333. if(inclass == NULL)
  334. return;
  335. CPPStructType::Derivation::const_iterator bi;
  336. for (bi = inclass->_derivation.begin();
  337. bi != inclass->_derivation.end();
  338. ++bi)
  339. {
  340. const CPPStructType::Base &base = (*bi);
  341. // if (base._vis <= V_public)
  342. // downcastposible = false;
  343. CPPStructType *base_type = TypeManager::resolve_type(base._base)->as_struct_type();
  344. if(base_type != NULL)
  345. {
  346. std::string scoped_name = base_type->get_fully_scoped_name();
  347. if(answer.find(scoped_name) == answer.end())
  348. {
  349. answer[scoped_name]._can_downcast = downcastposible;
  350. answer[scoped_name]._to_class_name = scoped_name;
  351. answer[scoped_name]._structType = base_type;
  352. if(base._is_virtual)
  353. answer[scoped_name]._can_downcast = false;
  354. std::string local_up_cast("( ");
  355. local_up_cast += scoped_name + " *)"+ up_cast_seed +"";
  356. answer[scoped_name]._up_cast_string = local_up_cast;
  357. answer[scoped_name]._is_legal_py_class = isCppTypeLegal(base_type);
  358. }
  359. else
  360. {
  361. answer[scoped_name]._can_downcast = false;
  362. }
  363. GetValideChildClasses(answer,base_type, answer[scoped_name]._up_cast_string,answer[scoped_name]._can_downcast);
  364. }
  365. }
  366. }
  367. ///////////////////////////////////////////////////////////////////////////////
  368. // Function : WriteReturnInstance
  369. //
  370. ///////////////////////////////////////////////////////////////////////////////
  371. void InterfaceMakerPythonNative::WriteReturnInstance(ostream &out, int indent_level, std::string &return_expr, std::string &ows_memory_flag, const std::string &class_name, CPPType *ctype, bool inplace)
  372. {
  373. if(inplace == true)
  374. {
  375. indent(out, indent_level)<<"Py_INCREF(self);\n";
  376. indent(out, indent_level)<<"return self;\n";
  377. }
  378. else
  379. {
  380. indent(out, indent_level)<<"if("<< return_expr<< " == NULL)\n";
  381. indent(out, indent_level)<<"{\n";
  382. indent(out, indent_level)<<" Py_INCREF(Py_None);\n";
  383. indent(out, indent_level)<<" return Py_None;\n";
  384. indent(out, indent_level)<<"}\n";
  385. if(IsPandaTypedObject(ctype->as_struct_type()))
  386. {
  387. std::string typestr = "((TypedObject *)" + return_expr + ")->get_type_index()";
  388. indent(out, indent_level)<<"return DTool_CreatePyInstanceTyped((void *)" << return_expr <<"," << CLASS_PREFEX << make_safe_name(class_name) << ","<< ows_memory_flag<<","<<typestr<<");\n";
  389. }
  390. else
  391. {
  392. // indent(out, indent_level)<< "if(" << return_expr <<"!= NULL)\n";
  393. indent(out, indent_level)
  394. <<"return DTool_CreatePyInstance((void *)" << return_expr <<"," << CLASS_PREFEX << make_safe_name(class_name) << ","<<ows_memory_flag<<");\n";
  395. }
  396. }
  397. }
  398. ////////////////////////////////////////////////////////////////////
  399. // Function: InterfaceMakerPythonNative::Constructor
  400. // Access: Public
  401. // Description:
  402. ////////////////////////////////////////////////////////////////////
  403. InterfaceMakerPythonNative::
  404. InterfaceMakerPythonNative(InterrogateModuleDef *def) :
  405. InterfaceMakerPython(def)
  406. {
  407. }
  408. ////////////////////////////////////////////////////////////////////
  409. // Function: InterfaceMakerPythonNative::Destructor
  410. // Access: Public, Virtual
  411. // Description:
  412. ////////////////////////////////////////////////////////////////////
  413. InterfaceMakerPythonNative::
  414. ~InterfaceMakerPythonNative() {
  415. }
  416. ////////////////////////////////////////////////////////////////////
  417. // Function: InterfaceMakerPythonNative::write_prototypes
  418. // Access: Public, Virtual
  419. // Description: Generates the list of function prototypes
  420. // corresponding to the functions that will be output in
  421. // write_functions().
  422. ////////////////////////////////////////////////////////////////////
  423. void InterfaceMakerPythonNative::write_prototypes(ostream &out_code,ostream *out_h)
  424. {
  425. inside_python_native = true;
  426. Functions::iterator fi;
  427. if(out_h != NULL)
  428. *out_h << "#include \"py_panda.h\"\n\n";
  429. out_code << "//********************************************************************\n";
  430. out_code << "//*** prototypes for .. Glabal\n";
  431. out_code << "//********************************************************************\n";
  432. /*
  433. for (fi = _functions.begin(); fi != _functions.end(); ++fi)
  434. {
  435. Function *func = (*fi);
  436. if(!func->_itype.is_global() && isFunctionLegal(func))
  437. write_prototype_for(out_code, func);
  438. }
  439. */
  440. Objects::iterator oi;
  441. for (oi = _objects.begin(); oi != _objects.end(); ++oi)
  442. {
  443. Object *object = (*oi).second;
  444. if(object->_itype.is_class() ||object->_itype.is_struct())
  445. {
  446. if(isCppTypeLegal(object->_itype._cpptype))
  447. {
  448. if(isExportThisRun(object->_itype._cpptype))
  449. {
  450. write_prototypes_class(out_code,out_h,object);
  451. }
  452. else
  453. //write_prototypes_class_external(out_code,object);
  454. _external_imports.insert(make_safe_name(object->_itype.get_scoped_name()));
  455. }
  456. }
  457. }
  458. out_code << "//********************************************************************\n";
  459. out_code << "//*** prototypes for .. Extrernal Objects \n";
  460. out_code << "//********************************************************************\n";
  461. for(std::set< std::string >::iterator ii = _external_imports.begin(); ii != _external_imports.end(); ii++)
  462. out_code << "IMPORT_THIS struct Dtool_PyTypedObject Dtool_" <<*ii <<";\n";
  463. inside_python_native = false;
  464. }
  465. /////////////////////////////////////////////////////////////////////////////////////////////
  466. // Function : write_prototypes_class_external
  467. //
  468. // Description : Output enough enformation to a declartion of a externally
  469. // generated dtool type object
  470. /////////////////////////////////////////////////////////////////////////////////////////////
  471. void InterfaceMakerPythonNative::write_prototypes_class_external(ostream &out, Object * obj)
  472. {
  473. std::string class_name = make_safe_name(obj->_itype.get_scoped_name());
  474. std::string c_class_name = obj->_itype.get_true_name();
  475. out << "//********************************************************************\n";
  476. out << "//*** prototypes for external.. " << class_name <<"\n";
  477. out << "//********************************************************************\n";
  478. out << "typedef "<< c_class_name <<" "<< class_name <<"_localtype;\n";
  479. out << "Define_Module_Class_Forward("<< _def->module_name << ", "<< class_name << "," << class_name <<"_localtype,"<< classNameFromCppName(c_class_name) << ");\n";
  480. }
  481. ///////////////////////////////////////// ////////////////////////////////////////////////////
  482. // Function : write_prototypes_class
  483. //
  484. /////////////////////////////////////////////////////////////////////////////////////////////
  485. void InterfaceMakerPythonNative::write_prototypes_class(ostream &out_code,ostream *out_h, Object * obj)
  486. {
  487. std::string ClassName = make_safe_name(obj->_itype.get_scoped_name());
  488. Functions::iterator fi;
  489. out_code << "//********************************************************************\n";
  490. out_code << "//*** prototypes for .. " << ClassName <<"\n";
  491. out_code << "//********************************************************************\n";
  492. /*
  493. for (fi = obj->_methods.begin(); fi != obj->_methods.end(); ++fi)
  494. {
  495. Function *func = (*fi);
  496. write_prototype_for(out_code, func);
  497. }
  498. */
  499. /*
  500. for (fi = obj->_constructors.begin(); fi != obj->_constructors.end(); ++fi)
  501. {
  502. Function *func = (*fi);
  503. std::string fname = "int Dtool_Init_"+ClassName+"(PyObject *self, PyObject *args, PyObject *kwds)";
  504. write_prototype_for_name(out_code, func,fname);
  505. }
  506. */
  507. write_ClasseDeclarations(out_code,out_h,obj);
  508. }
  509. ////////////////////////////////////////////////////////////////////
  510. // Function: InterfaceMakerPythonNative::write_functions
  511. // Access: Public, Virtual
  512. // Description: Generates the list of functions that are appropriate
  513. // for this interface. This function is called *before*
  514. // write_prototypes(), above.
  515. ////////////////////////////////////////////////////////////////////
  516. void InterfaceMakerPythonNative::write_functions(ostream &out)
  517. {
  518. inside_python_native = true;
  519. out << "//********************************************************************\n";
  520. out << "//*** Functions for .. Global \n" ;
  521. out << "//********************************************************************\n";
  522. Functions::iterator fi;
  523. for (fi = _functions.begin(); fi != _functions.end(); ++fi)
  524. {
  525. Function *func = (*fi);
  526. if(!func->_itype.is_global() && isFunctionLegal(func))
  527. write_function_for_top(out, func,"");
  528. }
  529. Objects::iterator oi;
  530. for (oi = _objects.begin(); oi != _objects.end(); ++oi)
  531. {
  532. Object *object = (*oi).second;
  533. if(object->_itype.is_class() ||object->_itype.is_struct())
  534. {
  535. if(isCppTypeLegal(object->_itype._cpptype))
  536. if(isExportThisRun(object->_itype._cpptype))
  537. write_ClasseDetails(out,object);
  538. }
  539. }
  540. // Objects::iterator oi;
  541. for (oi = _objects.begin(); oi != _objects.end(); ++oi)
  542. {
  543. Object *object = (*oi).second;
  544. if(!object->_itype.get_outer_class())
  545. {
  546. if(object->_itype.is_class() ||object->_itype.is_struct())
  547. if(isCppTypeLegal(object->_itype._cpptype))
  548. if(isExportThisRun(object->_itype._cpptype))
  549. write_module_class(out,object);
  550. }
  551. }
  552. inside_python_native = true;
  553. }
  554. ////////////////////////////////////////////////////////////
  555. // Function : write_ClasseDetails
  556. ////////////////////////////////////////////////////////////
  557. void InterfaceMakerPythonNative::write_ClasseDetails(ostream &out, Object * obj)
  558. {
  559. Functions::iterator fi;
  560. //std::string cClassName = obj->_itype.get_scoped_name();
  561. std::string ClassName = make_safe_name(obj->_itype.get_scoped_name());
  562. std::string cClassName = obj->_itype.get_true_name();
  563. out << "//********************************************************************\n";
  564. out << "//*** Functions for .. "<< cClassName <<" \n" ;
  565. out << "//********************************************************************\n";
  566. for (fi = obj->_methods.begin(); fi != obj->_methods.end(); ++fi)
  567. {
  568. Function *func = (*fi);
  569. if( (func))
  570. {
  571. ostringstream GetThis;
  572. GetThis << " "<<cClassName << " * local_this = NULL;\n";
  573. GetThis << " DTOOL_Call_ExtractThisPointerForType(self,&Dtool_"<< ClassName<<",(void **)&local_this);\n";
  574. GetThis << " if(local_this == NULL) {\n";
  575. GetThis << " // This might happen if Python called a reverse operator like __rsub__().\n";
  576. GetThis << " Py_INCREF(Py_NotImplemented);\n";
  577. GetThis << " return Py_NotImplemented;\n";
  578. GetThis << " }\n";
  579. write_function_for_top(out, func,GetThis.str());
  580. }
  581. }
  582. // bool AnyLeganConstructors;
  583. if(obj->_constructors.size() == 0)
  584. {
  585. std::string fname = "int Dtool_Init_"+ClassName+"(PyObject *self, PyObject *args, PyObject *kwds)";
  586. out << fname << "\n";
  587. out << "{\n";
  588. out << " PyErr_SetString(PyExc_TypeError, \"Error Can Not Init Constant Class (" << cClassName << ")\");\n";
  589. out << " return -1;\n" ;
  590. out << "}\n";
  591. }
  592. else
  593. {
  594. for (fi = obj->_constructors.begin(); fi != obj->_constructors.end(); ++fi)
  595. {
  596. Function *func = (*fi);
  597. std::string fname = "int Dtool_Init_"+ClassName+"(PyObject *self, PyObject *args, PyObject *kwds) ";
  598. write_function_for_name(out, func,fname,"",ClassName);
  599. }
  600. }
  601. std::map< string ,CastDetails > details;
  602. std::map< string ,CastDetails >::iterator di;
  603. builder.get_type(TypeManager::unwrap(TypeManager::resolve_type(obj->_itype._cpptype)),false);
  604. GetValideChildClasses(details,obj->_itype._cpptype->as_struct_type());
  605. for(di = details.begin(); di != details.end(); di++)
  606. {
  607. //InterrogateType ptype =idb->get_type(di->first);
  608. if(di->second._is_legal_py_class && !isExportThisRun(di->second._structType))
  609. _external_imports.insert(make_safe_name(di->second._to_class_name));
  610. //out << "IMPORT_THIS struct Dtool_PyTypedObject Dtool_" << make_safe_name(di->second._to_class_name) <<";\n";
  611. }
  612. { // the Cast Converter
  613. out << "inline void * Dtool_UpcastInterface_"<< ClassName << "(PyObject *self, Dtool_PyTypedObject *requested_type)\n";
  614. out << "{\n";
  615. out << " Dtool_PyTypedObject *SelfType = ((Dtool_PyInstDef *)self)->_My_Type;\n";
  616. out << " if(SelfType != &Dtool_" << ClassName <<")\n";
  617. out << " {\n";
  618. out << " printf(\""<<ClassName<<" ** Bad Source Type-- Requesting Conversion from %s to %s\\n\",((Dtool_PyInstDef *)self)->_My_Type->_name,requested_type->_name);fflush(NULL);\n";;
  619. out << " return NULL;\n";
  620. out << " }\n";
  621. out << " \n";
  622. out << " "<<cClassName<<" * local_this = (" << cClassName<<" *)((Dtool_PyInstDef *)self)->_ptr_to_object;\n";
  623. out << " if(requested_type == &Dtool_"<<ClassName<<")\n";
  624. out << " return local_this;\n";
  625. for(di = details.begin(); di != details.end(); di++)
  626. {
  627. if(di->second._is_legal_py_class)
  628. {
  629. out << " if(requested_type == &Dtool_"<<make_safe_name(di->second._to_class_name)<<")\n";
  630. out << " return "<< di->second._up_cast_string << " local_this;\n";
  631. }
  632. }
  633. out << " return NULL;\n";
  634. out << "}\n";
  635. out << "inline void * Dtool_DowncastInterface_"<< ClassName << "(void *from_this, Dtool_PyTypedObject *from_type)\n";
  636. out << "{\n";
  637. out << " if(from_this == NULL || from_type == NULL)\n";
  638. out << " return NULL;\n";
  639. out << " if(from_type == &Dtool_" << ClassName<<")\n";
  640. out << " return from_this;\n";
  641. for(di = details.begin(); di != details.end(); di++)
  642. {
  643. if(di->second._can_downcast && di->second._is_legal_py_class)
  644. {
  645. out << " if(from_type == &Dtool_"<<make_safe_name(di->second._to_class_name)<<")\n";
  646. out << " {\n";
  647. out << " "<< di->second._to_class_name << "* other_this = ("<< di->second._to_class_name << "*)from_this;\n" ;
  648. out << " return ("<< cClassName << "*)other_this;\n";
  649. out << " }\n";
  650. }
  651. }
  652. out << " return (void *) NULL;\n";
  653. out << "}\n";
  654. }
  655. }
  656. ////////////////////////////////////////////////////////////
  657. /// Function : write_ClasseDeclarations
  658. //
  659. //
  660. ////////////////////////////////////////////////////////////
  661. void InterfaceMakerPythonNative::write_ClasseDeclarations(ostream &out, ostream *out_h,Object * obj )
  662. {
  663. const InterrogateType &itype = obj->_itype;
  664. std::string class_name = make_safe_name(obj->_itype.get_scoped_name());
  665. std::string c_class_name = itype.get_true_name();
  666. std::string class_struct_name = std::string(CLASS_PREFEX) +class_name;
  667. out << "typedef "<< c_class_name <<" "<< class_name <<"_localtype;\n";
  668. if(obj->_itype.has_destructor() ||
  669. obj->_itype.destructor_is_inherited())
  670. {
  671. if(TypeManager::is_reference_count(obj->_itype._cpptype))
  672. {
  673. out << "Define_Module_ClassRef("<< _def->module_name<<"," << class_name << "," << class_name <<"_localtype,"<< classNameFromCppName(c_class_name) <<");\n";
  674. }
  675. else
  676. {
  677. out << "Define_Module_Class("<<_def->module_name << "," << class_name << "," <<class_name <<"_localtype,"<< classNameFromCppName(c_class_name) <<");\n";
  678. }
  679. }
  680. else
  681. {
  682. if(TypeManager::is_reference_count(obj->_itype._cpptype))
  683. {
  684. out << "Define_Module_ClassRef_Private("<<_def->module_name << "," << class_name << "," << class_name <<"_localtype,"<< classNameFromCppName(c_class_name) <<");\n";
  685. }
  686. else
  687. {
  688. out << "Define_Module_Class_Private("<<_def->module_name<< "," << class_name << "," << class_name <<"_localtype,"<< classNameFromCppName(c_class_name) << ");\n";
  689. }
  690. }
  691. if(out_h != NULL)
  692. *out_h << "extern \"C\" " << EXPORT_IMPORT_PREFEX << " struct Dtool_PyTypedObject Dtool_" << class_name <<";\n";
  693. }
  694. ////////////////////////////////////////////////////////////////////
  695. // Function: InterfaceMakerPythonNative::write_module
  696. // Access: Public, Virtual
  697. // Description: Generates whatever additional code is required to
  698. // support a module file.
  699. ////////////////////////////////////////////////////////////////////
  700. void InterfaceMakerPythonNative::write_sub_module(ostream &out, Object *obj)
  701. {
  702. //Object * obj = _objects[_embeded_index] ;
  703. std::string ClassName = make_safe_name(obj->_itype.get_scoped_name());
  704. out << "//********************************************************************\n";
  705. out << "//*** Module Init Updcall .." << obj->_itype.get_scoped_name() << "\n";
  706. out << "//********************************************************************\n";
  707. out << " Dtool_PyModuleClassInit_"<< ClassName <<"(module);\n";
  708. }
  709. /////////////////////////////////////////////////////////////////////////////
  710. // Function : write_module_support
  711. /////////////////////////////////////////////////////////////////////////////
  712. void InterfaceMakerPythonNative::write_module_support(ostream &out,ostream *out_h,InterrogateModuleDef *moduledefdef)
  713. {
  714. out << "//********************************************************************\n";
  715. out << "//*** Module Object Linker .. \n";
  716. out << "//********************************************************************\n";
  717. out << "static void BuildInstants(PyObject * module)\n";
  718. out << "{\n";
  719. Objects::iterator oi;
  720. for (oi = _objects.begin(); oi != _objects.end(); ++oi)
  721. {
  722. Object *object = (*oi).second;
  723. if(!object->_itype.get_outer_class())
  724. {
  725. if(object->_itype.is_enum())
  726. {
  727. int enum_count = object->_itype.number_of_enum_values();
  728. if(enum_count > 0)
  729. {
  730. out << "//********************************************************************\n";
  731. out << "//*** Module Enums .." << object->_itype.get_scoped_name() << "\n";
  732. out << "//********************************************************************\n";
  733. }
  734. for(int xx = 0; xx< enum_count; xx++)
  735. out << " PyModule_AddIntConstant(module,\"" << classNameFromCppName(object->_itype.get_enum_value_name(xx)) <<"\","<< object->_itype.get_enum_value(xx) << ");\n";
  736. }
  737. }
  738. }
  739. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  740. int num_manifests = idb->get_num_global_manifests();
  741. for (int mi = 0; mi < num_manifests; mi++)
  742. {
  743. ManifestIndex manifest_index = idb->get_global_manifest(mi);
  744. const InterrogateManifest &iman = idb->get_manifest(manifest_index);
  745. if (iman.has_getter())
  746. {
  747. FunctionIndex func_index = iman.get_getter();
  748. record_function(dummy_type, func_index);
  749. }
  750. if(iman.has_int_value())
  751. out << " PyModule_AddIntConstant(module,\"" << classNameFromCppName(iman.get_name()) <<"\","<< iman.get_int_value() << ");\n";
  752. else
  753. out << " PyModule_AddStringConstant(module,\"" << classNameFromCppName(iman.get_name()) <<"\",\""<< iman.get_definition().c_str() << "\");\n";
  754. }
  755. for (oi = _objects.begin(); oi != _objects.end(); ++oi)
  756. {
  757. Object *object = (*oi).second;
  758. if(!object->_itype.get_outer_class())
  759. {
  760. if(object->_itype.is_class() ||object->_itype.is_struct())
  761. if(isCppTypeLegal(object->_itype._cpptype))
  762. if(isExportThisRun(object->_itype._cpptype))
  763. write_sub_module(out,object);
  764. }
  765. }
  766. out << "//********************************************************************\n";
  767. out << "//*** Module Init Updcall .. Externally Defined Class\n";
  768. out << "//********************************************************************\n";
  769. // for(std::set< std::string >::iterator ii = _external_imports.begin(); ii != _external_imports.end(); ii++)
  770. // out << "Dtool_" <<*ii <<"._Dtool_ClassInit(NULL);\n";
  771. out << "}\n";
  772. bool force_base_functions = true;
  773. out << "static PyMethodDef python_simple_funcs[] = {\n";
  774. Functions::iterator fi;
  775. for (fi = _functions.begin(); fi != _functions.end(); ++fi)
  776. {
  777. Function *func = (*fi);
  778. if(!func->_itype.is_global() && isFunctionLegal(func))
  779. {
  780. {
  781. out << " { \"" << methodNameFromCppName( func->_ifunc.get_name(),"") << "\", (PyCFunction) &"
  782. << func->_name << ", METH_VARARGS| METH_KEYWORDS ," << func->_name << "_comment},\n";
  783. }
  784. }
  785. }
  786. if(force_base_functions)
  787. {
  788. out << " //Support Function For Dtool_types ... for know in each module ??\n";
  789. out << " {\"Dtool_BarrowThisRefrence\", &Dtool_BarrowThisRefrence,METH_VARARGS,\"Used to barrow 'this' poiner ( to, from)\\n Assumes no ownership\"}, \n";
  790. out << " {\"Dtool_AddToDictionary\", &Dtool_AddToDictionary,METH_VARARGS,\"Used to Items Into a types (tp_dict)\"}, \n";
  791. }
  792. out << " { NULL, NULL ,0,NULL}\n" << "};\n\n";
  793. out << "struct LibrayDef " << moduledefdef->library_name <<"_moddef = {python_simple_funcs,BuildInstants};\n";
  794. if(out_h != NULL)
  795. *out_h << "extern struct LibrayDef " << moduledefdef->library_name <<"_moddef;\n";
  796. }
  797. /////////////////////////////////////////////////////////////////////////////
  798. ///// Function : write_module
  799. /////////////////////////////////////////////////////////////////////////////
  800. void InterfaceMakerPythonNative::write_module(ostream &out,ostream *out_h, InterrogateModuleDef *moduledefdef)
  801. {
  802. InterfaceMakerPython::write_module(out,out_h, moduledefdef);
  803. Objects::iterator oi;
  804. out << "//********************************************************************\n";
  805. out << "//*** Py Init Code For .. GlobalScope\n" ;
  806. out << "//********************************************************************\n";
  807. out << "#ifdef _WIN32\n"
  808. << "extern \"C\" __declspec(dllexport) void init" << moduledefdef->module_name << "();\n"
  809. << "#else\n"
  810. << "extern \"C\" void init" << moduledefdef->module_name << "();\n"
  811. << "#endif\n\n";
  812. out << "void init" << moduledefdef->module_name << "() {\n";
  813. out << " LibrayDef * refs[] = {&" << moduledefdef->library_name << "_moddef,NULL};\n";
  814. out << " Dtool_PyModuleInitHelper(refs,\"" << moduledefdef->module_name << "\");\n";
  815. out << "}\n\n";
  816. }
  817. ////////////////////////////////////////////////////////////////////
  818. /// Function : GetSlotedFunctinDef
  819. //
  820. // This function is used to define special behavior for class functions..
  821. // main use is to encode the slot pointer logic and function call
  822. // conventions for the slaot interface..
  823. ////////////////////////////////////////////////////////////////////
  824. bool GetSlotedFunctinDef(const std::string &thimputstring, std::string &answer_location, int &wraper_type)
  825. {
  826. wraper_type = -1;
  827. if(thimputstring.size() > 4 && thimputstring[0] == '_' && thimputstring[1] == '_')
  828. {
  829. if(thimputstring == "__add__")
  830. {
  831. answer_location = "tp_as_number->nb_add";
  832. wraper_type = 3;
  833. return true;
  834. }
  835. if(thimputstring == "__sub__")
  836. {
  837. answer_location = "tp_as_number->nb_subtract";
  838. wraper_type = 3;
  839. return true;
  840. }
  841. if(thimputstring == "__mul__")
  842. {
  843. answer_location = "tp_as_number->nb_multiply";
  844. wraper_type = 3;
  845. return true;
  846. }
  847. if(thimputstring == "__div__")
  848. {
  849. answer_location = "tp_as_number->nb_divide";
  850. wraper_type = 3;
  851. return true;
  852. }
  853. if(thimputstring == "__mod__")
  854. {
  855. answer_location = "tp_as_number->nb_remainder";
  856. wraper_type = 3;
  857. return true;
  858. }
  859. if(thimputstring == "__lshift__")
  860. {
  861. answer_location = "tp_as_number->nb_lshift";
  862. wraper_type = 3;
  863. return true;
  864. }
  865. if(thimputstring == "__rshift__")
  866. {
  867. answer_location = "tp_as_number->nb_rshift";
  868. wraper_type = 3;
  869. return true;
  870. }
  871. if(thimputstring == "__xor__")
  872. {
  873. answer_location = "tp_as_number->nb_xor";
  874. wraper_type = 3;
  875. return true;
  876. }
  877. if(thimputstring == "__and__")
  878. {
  879. answer_location = "tp_as_number->nb_and";
  880. wraper_type = 3;
  881. return true;
  882. }
  883. if(thimputstring == "__or__")
  884. {
  885. answer_location = "tp_as_number->nb_or";
  886. wraper_type = 3;
  887. return true;
  888. }
  889. if(thimputstring == "__iadd__")
  890. {
  891. answer_location = "tp_as_number->nb_inplace_add";
  892. wraper_type = 3;
  893. return true;
  894. }
  895. if(thimputstring == "__isub__")
  896. {
  897. answer_location = "tp_as_number->nb_inplace_subtract";
  898. wraper_type = 3;
  899. return true;
  900. }
  901. if(thimputstring == "__imul__")
  902. {
  903. answer_location = "tp_as_number->nb_inplace_multiply";
  904. wraper_type = 3;
  905. return true;
  906. }
  907. if(thimputstring == "__idiv__")
  908. {
  909. answer_location = "tp_as_number->nb_inplace_divide";
  910. wraper_type = 3;
  911. return true;
  912. }
  913. if(thimputstring == "__imod__")
  914. {
  915. answer_location = ".tp_as_number->nb_inplace_remainder";
  916. wraper_type = 3;
  917. return true;
  918. }
  919. if(thimputstring == "__ilshift__")
  920. {
  921. answer_location = "tp_as_number->nb_inplace_lshift";
  922. wraper_type = 3;
  923. return true;
  924. }
  925. if(thimputstring == "__irshift__")
  926. {
  927. answer_location = "tp_as_number->nb_inplace_rshift";
  928. wraper_type = 3;
  929. return true;
  930. }
  931. if(thimputstring == "__iand__")
  932. {
  933. answer_location = "tp_as_number->nb_inplace_and";
  934. wraper_type = 3;
  935. return true;
  936. }
  937. if(thimputstring == "__ixor__")
  938. {
  939. answer_location = "tp_as_number->nb_inplace_xor";
  940. wraper_type = 3;
  941. return true;
  942. }
  943. if(thimputstring == "__int__")
  944. {
  945. answer_location = "tp_as_number->nb_int";
  946. wraper_type = 2;
  947. return true;
  948. }
  949. // if(thimputstring == "__coerce__")
  950. // {
  951. // answer_location = "tp_as_number->nb_coerce";
  952. // return true;
  953. // }
  954. // mapping methods
  955. if(thimputstring == "__getitem__")
  956. {
  957. answer_location = "tp_as_mapping->mp_subscript";
  958. wraper_type = 3;
  959. return true;
  960. }
  961. //Direct methods
  962. if(thimputstring == "__call__")
  963. {
  964. answer_location = "tp_call";
  965. //wraper_type = 1;
  966. return true;
  967. }
  968. }
  969. return false;
  970. };
  971. /////////////////////////////////////////////////////////////////////////////////////////////
  972. // Function :write_module_class
  973. /////////////////////////////////////////////////////////////////////////////////////////////
  974. void InterfaceMakerPythonNative::
  975. write_module_class(ostream &out, Object *obj) {
  976. bool has_local_hash = false;
  977. bool has_local_repr = false;
  978. bool has_local_str = false;
  979. {
  980. int num_nested = obj->_itype.number_of_nested_types();
  981. for (int ni = 0; ni < num_nested; ni++)
  982. {
  983. TypeIndex nested_index = obj->_itype.get_nested_type(ni);
  984. Object * nested_obj = _objects[nested_index];
  985. if(nested_obj->_itype.is_class() ||nested_obj->_itype.is_struct())
  986. {
  987. write_module_class(out,nested_obj);
  988. }
  989. }
  990. }
  991. bool is_runtime_typed = IsPandaTypedObject(obj->_itype._cpptype->as_struct_type());
  992. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  993. std::string ClassName = make_safe_name(obj->_itype.get_scoped_name());
  994. std::string cClassName = obj->_itype.get_true_name();
  995. std::string export_calss_name = classNameFromCppName(obj->_itype.get_name());
  996. Functions::iterator fi;
  997. out << "//********************************************************************\n";
  998. out << "//*** Py Init Code For .. "<< ClassName <<" | " << export_calss_name <<"\n" ;
  999. out << "//********************************************************************\n";
  1000. out << "PyMethodDef Dtool_Methods_"<< ClassName << "[]= {\n";
  1001. std::map<int , Function * > static_functions;
  1002. std::map<Function *, std::string > normal_Operator_functions;
  1003. std::map<Function *, std::pair< std::string , int> > wraped_Operator_functions;
  1004. // function Table
  1005. int x;
  1006. for (x = 0, fi = obj->_methods.begin(); fi != obj->_methods.end(); ++fi,x++)
  1007. {
  1008. Function *func = (*fi);
  1009. std::string temp0;
  1010. int temp1;
  1011. if(!GetSlotedFunctinDef( methodNameFromCppName( func->_ifunc.get_name(),export_calss_name),temp0,temp1))
  1012. {
  1013. out << " { \"" << methodNameFromCppName( func->_ifunc.get_name(),export_calss_name) << "\",(PyCFunction ) &"
  1014. << func->_name << ", METH_VARARGS| METH_KEYWORDS ," << func->_name << "_comment},\n";
  1015. if(!isFunctionWithThis(func))
  1016. static_functions[x] = func;
  1017. }
  1018. else
  1019. {
  1020. if(temp1 > 0)
  1021. {
  1022. wraped_Operator_functions[func] = std::pair< std::string, int>(temp0,temp1);
  1023. out << " { \"" << methodNameFromCppName( func->_ifunc.get_name(),export_calss_name) << "\",(PyCFunction ) &"
  1024. << func->_name << ", METH_VARARGS| METH_KEYWORDS ," << func->_name << "_comment},\n";
  1025. if(!isFunctionWithThis(func))
  1026. static_functions[x] = func;
  1027. }
  1028. else
  1029. {
  1030. normal_Operator_functions[func] = temp0;
  1031. out << " { \"" << methodNameFromCppName( func->_ifunc.get_name(),export_calss_name) << "\",(PyCFunction ) &"
  1032. << func->_name << ", METH_VARARGS| METH_KEYWORDS ," << func->_name << "_comment},\n";
  1033. if(!isFunctionWithThis(func))
  1034. static_functions[x] = func;
  1035. }
  1036. }
  1037. }
  1038. out << " { NULL, NULL }\n"
  1039. << "};\n\n";
  1040. int num_derivations = obj->_itype.number_of_derivations();
  1041. int di;
  1042. for (di = 0; di < num_derivations; di++)
  1043. {
  1044. TypeIndex d_type_Index = obj->_itype.get_derivation(di);
  1045. if(!interrogate_type_is_unpublished(d_type_Index))
  1046. {
  1047. const InterrogateType &d_itype = idb->get_type(d_type_Index);
  1048. if(isCppTypeLegal(d_itype._cpptype))
  1049. {
  1050. if(!isExportThisRun(d_itype._cpptype))
  1051. {
  1052. _external_imports.insert(make_safe_name(d_itype.get_scoped_name().c_str()));
  1053. //out << "IMPORT_THIS struct Dtool_PyTypedObject Dtool_" << make_safe_name(d_itype.get_scoped_name().c_str()) <<";\n";
  1054. }
  1055. }
  1056. }
  1057. }
  1058. std::vector< std::string > bases;
  1059. for (di = 0; di < num_derivations; di++)
  1060. {
  1061. TypeIndex d_type_Index = obj->_itype.get_derivation(di);
  1062. if(!interrogate_type_is_unpublished(d_type_Index))
  1063. {
  1064. const InterrogateType &d_itype = idb->get_type(d_type_Index);
  1065. if(isCppTypeLegal(d_itype._cpptype))
  1066. {
  1067. bases.push_back(make_safe_name(d_itype.get_scoped_name().c_str()));
  1068. }
  1069. }
  1070. }
  1071. if(bases.empty())
  1072. bases.push_back("DTOOL_SUPPER_BASE");
  1073. {
  1074. std::map<Function *, std::pair< std::string , int> >::iterator rfi; // wraped_Operator_functions;
  1075. for(rfi = wraped_Operator_functions.begin(); rfi != wraped_Operator_functions.end(); rfi++)
  1076. {
  1077. if(rfi->second.second == 1)
  1078. {
  1079. Function *func = rfi->first;
  1080. out << "//////////////////\n";
  1081. out << "// Required TO Convert the calling Conventions.. \n";
  1082. out << "// " <<ClassName<< " ..." << rfi->second.first <<" = "<< methodNameFromCppName( func->_ifunc.get_name(),export_calss_name) <<"\n";
  1083. out << "//////////////////\n";
  1084. out << "static PyObject * " << func->_name << methodNameFromCppName( func->_ifunc.get_name(),export_calss_name) << "( PyObject * self, PyObject * args, PyObject *dict)\n";
  1085. out << "{\n";
  1086. out << " return "<< func->_name <<"(self,args);\n";
  1087. out << "}\n\n";
  1088. }
  1089. else if(rfi->second.second == 2)
  1090. {
  1091. Function *func = rfi->first;
  1092. out << "//////////////////\n";
  1093. out << "// Required TO Convert the calling Conventions.. \n";
  1094. out << "// " <<ClassName<< " ..." << rfi->second.first <<" = "<< methodNameFromCppName( func->_ifunc.get_name(),export_calss_name) <<"\n";
  1095. out << "//////////////////\n";
  1096. out << "static PyObject * " << func->_name << methodNameFromCppName( func->_ifunc.get_name(),export_calss_name) << "( PyObject * self)\n";
  1097. out << "{\n";
  1098. out << " return "<< func->_name <<"(self,Py_None,Py_None);\n";
  1099. out << "}\n\n";
  1100. }
  1101. if(rfi->second.second == 3)
  1102. {
  1103. Function *func = rfi->first;
  1104. out << "//////////////////\n";
  1105. out << "// Required TO Convert the calling Conventions.. \n";
  1106. out << "// " <<ClassName<< " ..." << rfi->second.first <<" = "<< methodNameFromCppName( func->_ifunc.get_name(),export_calss_name) <<"\n";
  1107. out << "//////////////////\n";
  1108. out << "static PyObject * " << func->_name << methodNameFromCppName( func->_ifunc.get_name(),export_calss_name) << "( PyObject * self, PyObject * args)\n";
  1109. out << "{\n";
  1110. out << " return "<< func->_name <<"(self,args,Py_None);\n";
  1111. out << "}\n\n";
  1112. }
  1113. }
  1114. if(HasAGetKeyFunction(obj->_itype))
  1115. {
  1116. out << "//////////////////\n";
  1117. out << "// A LocalHash(getKey) Function for this type";
  1118. out << "// " <<ClassName << "\n";
  1119. out << "//////////////////\n";
  1120. out << "static long DTool_HashKey_"<<ClassName << "(PyObject * self)\n";
  1121. out << "{\n";
  1122. out << " "<<cClassName << " * local_this = NULL;\n";
  1123. out << " DTOOL_Call_ExtractThisPointerForType(self,&Dtool_"<< ClassName<<",(void **)&local_this);\n";
  1124. out << " if(local_this == NULL)\n";
  1125. out << " {\n";
  1126. out << " return -1;\n";
  1127. out << " };\n";
  1128. out << " return local_this->get_key();\n";
  1129. out << "}\n\n";
  1130. has_local_hash = true;
  1131. }
  1132. else
  1133. {
  1134. if(bases.size() == 0)
  1135. {
  1136. out << "//////////////////\n";
  1137. out << "// A LocalHash(This Pointer) Function for this type";
  1138. out << "// " <<ClassName << "\n";
  1139. out << "//////////////////\n";
  1140. out << "static long DTool_HashKey_"<<ClassName << "(PyObject * self)\n";
  1141. out << "{\n";
  1142. out << " "<<cClassName << " * local_this = NULL;\n";
  1143. out << " DTOOL_Call_ExtractThisPointerForType(self,&Dtool_"<< ClassName<<",(void **)&local_this);\n";
  1144. out << " if(local_this == NULL)\n";
  1145. out << " {\n";
  1146. out << " return -1;\n";
  1147. out << " };\n";
  1148. out << " return (long)local_this;\n";
  1149. out << "}\n\n";
  1150. has_local_hash = true;
  1151. }
  1152. }
  1153. int need_repr = NeedsAReprFunction(obj->_itype);
  1154. if(need_repr > 0)
  1155. {
  1156. out << "//////////////////\n";
  1157. out << "// A __repr__ Function\n";
  1158. out << "// " <<ClassName << "\n";
  1159. out << "//////////////////\n";
  1160. out << "static PyObject * Dtool_Repr_"<<ClassName << "(PyObject * self)\n";
  1161. out << "{\n";
  1162. out << " "<<cClassName << " * local_this = NULL;\n";
  1163. out << " DTOOL_Call_ExtractThisPointerForType(self,&Dtool_"<< ClassName<<",(void **)&local_this);\n";
  1164. out << " if(local_this != NULL)\n";
  1165. out << " {\n";
  1166. out << " ostringstream os;\n";
  1167. if (need_repr == 2) {
  1168. out << " local_this->output(os);\n";
  1169. } else {
  1170. out << " local_this->python_repr(os, \""
  1171. << classNameFromCppName(ClassName) << "\");\n";
  1172. }
  1173. out << " std::string ss = os.str();\n";
  1174. out << " return PyString_FromStringAndSize(ss.data(),ss.length());\n";
  1175. out << " };\n";
  1176. out << " return Py_BuildValue(\"\");\n";
  1177. out << "}\n";
  1178. has_local_repr = true;
  1179. }
  1180. int need_str = NeedsAStrFunction(obj->_itype);
  1181. if(need_str > 0)
  1182. {
  1183. out << "//////////////////\n";
  1184. out << "// A __str__ Function\n";
  1185. out << "// " <<ClassName << "\n";
  1186. out << "//////////////////\n";
  1187. out << "static PyObject * Dtool_Str_"<<ClassName << "(PyObject * self)\n";
  1188. out << "{\n";
  1189. out << " "<<cClassName << " * local_this = NULL;\n";
  1190. out << " DTOOL_Call_ExtractThisPointerForType(self,&Dtool_"<< ClassName<<",(void **)&local_this);\n";
  1191. out << " if(local_this != NULL)\n";
  1192. out << " {\n";
  1193. out << " ostringstream os;\n";
  1194. if(need_str == 2)
  1195. out << " local_this->write(os,0);\n";
  1196. else
  1197. out << " local_this->write(os);\n";
  1198. out << " std::string ss = os.str();\n";
  1199. out << " return PyString_FromStringAndSize(ss.data(),ss.length());\n";
  1200. out << " };\n";
  1201. out << " return Py_BuildValue(\"\");\n";
  1202. out << "}\n";
  1203. has_local_str = true;
  1204. }
  1205. }
  1206. out << "void Dtool_PyModuleClassInit_" << ClassName << "(PyObject *module)\n";
  1207. out << "{\n";
  1208. out << " static bool initdone = false;\n";
  1209. out << " if(!initdone)\n";
  1210. out << " {\n";
  1211. out << " initdone = true;\n";
  1212. // out << " memset(Dtool_"<< ClassName << ".As_PyTypeObject().tp_as_number,0,sizeof(PyNumberMethods));\n";
  1213. // out << " memset(Dtool_"<< ClassName << ".As_PyTypeObject().tp_as_mapping,0,sizeof(PyMappingMethods));\n";
  1214. // out << " static Dtool_PyTypedObject *InheritsFrom[] = {";
  1215. // add doc string
  1216. if (obj->_itype.has_comment()) {
  1217. out << "#ifndef NDEBUG\n";
  1218. out << " // Class documentation string\n";
  1219. out << " Dtool_" << ClassName
  1220. << ".As_PyTypeObject().tp_doc =\n";
  1221. output_quoted(out, 10, obj->_itype.get_comment());
  1222. out << ";\n"
  1223. << "#endif\n";
  1224. }
  1225. // add bases///
  1226. if(bases.size() > 0)
  1227. {
  1228. out << " // Dependent Objects \n";
  1229. std::string format1= "";
  1230. std::string format2= "";
  1231. for(std::vector< std::string >::iterator bi = bases.begin(); bi != bases.end(); bi++)
  1232. {
  1233. format1 += "O";
  1234. format2 += ",&Dtool_" + *bi + ".As_PyTypeObject()";
  1235. out << " Dtool_"<< make_safe_name(*bi) << "._Dtool_ClassInit(NULL);\n";
  1236. }
  1237. out << " Dtool_"<<ClassName<<".As_PyTypeObject().tp_bases = Py_BuildValue(\"(" << format1 << ")\""<< format2 << ");\n";
  1238. }
  1239. // get dictionary
  1240. out << " Dtool_" << ClassName << ".As_PyTypeObject().tp_dict = PyDict_New();\n";
  1241. out << " PyDict_SetItemString(Dtool_"<<ClassName <<".As_PyTypeObject().tp_dict,\"DtoolClassDict\",Dtool_"<<ClassName <<".As_PyTypeObject().tp_dict);\n";
  1242. // the standard call functions
  1243. std::map<Function *, std::string >::iterator ofi;
  1244. for(ofi = normal_Operator_functions.begin(); ofi != normal_Operator_functions.end(); ofi++)
  1245. {
  1246. Function *func = ofi->first;
  1247. out << " // " << ofi->second <<" = "<< methodNameFromCppName( func->_ifunc.get_name(),export_calss_name) <<"\n";
  1248. out << " Dtool_" << ClassName <<".As_PyTypeObject()." << ofi->second <<" = &" << func->_name <<";\n";
  1249. }
  1250. // wraped functions...
  1251. {
  1252. std::map<Function *, std::pair< std::string , int> >::iterator rfi; // wraped_Operator_functions;
  1253. for(rfi = wraped_Operator_functions.begin(); rfi != wraped_Operator_functions.end(); rfi++)
  1254. {
  1255. Function *func = rfi->first;
  1256. out << " // " << rfi->second.first <<" = "<< methodNameFromCppName( func->_ifunc.get_name(),export_calss_name) <<"\n";
  1257. out << " Dtool_" << ClassName <<".As_PyTypeObject()." << rfi->second.first <<" = &" << func->_name << methodNameFromCppName( func->_ifunc.get_name(),export_calss_name)<<";\n";
  1258. }
  1259. }
  1260. // compare and hash work together in PY inherit behavior hmm grrr
  1261. // __hash__
  1262. if(has_local_hash == true)
  1263. {
  1264. out << " // __hash__\n";
  1265. out << " Dtool_" << ClassName <<".As_PyTypeObject().tp_hash = &DTool_HashKey_"<<ClassName <<";\n";
  1266. out << " Dtool_" << ClassName <<".As_PyTypeObject().tp_compare = &DTOOL_PyObject_Compare;\n";
  1267. }
  1268. if(has_local_repr == true)
  1269. {
  1270. out << " // __repr__\n";
  1271. out << " Dtool_" << ClassName <<".As_PyTypeObject().tp_repr = & Dtool_Repr_"<<ClassName <<";\n";
  1272. }
  1273. if(has_local_str == true)
  1274. {
  1275. out << " // __str__\n";
  1276. out << " Dtool_" << ClassName <<".As_PyTypeObject().tp_str = & Dtool_Str_"<<ClassName <<";\n";
  1277. }
  1278. else if(has_local_repr == true)
  1279. {
  1280. out << " // __str__ Repr Proxy\n";
  1281. out << " Dtool_" << ClassName <<".As_PyTypeObject().tp_str = & Dtool_Repr_"<<ClassName <<";\n";
  1282. }
  1283. int num_nested = obj->_itype.number_of_nested_types();
  1284. for (int ni = 0; ni < num_nested; ni++)
  1285. {
  1286. TypeIndex nested_index = obj->_itype.get_nested_type(ni);
  1287. Object * nested_obj = _objects[nested_index];
  1288. if(nested_obj->_itype.is_class() ||nested_obj->_itype.is_struct())
  1289. {
  1290. std::string ClassName1 = make_safe_name(nested_obj->_itype.get_scoped_name());
  1291. std::string ClassName2 = make_safe_name(nested_obj->_itype.get_name());
  1292. out << " // Nested Object "<< ClassName1 << ";\n";
  1293. out << " Dtool_" << ClassName1 << "._Dtool_ClassInit(NULL);\n";
  1294. out << " PyDict_SetItemString(Dtool_" << ClassName << ".As_PyTypeObject().tp_dict,\"" << classNameFromCppName(ClassName2) <<"\",(PyObject *)&Dtool_" << ClassName1 << ".As_PyTypeObject());\n";
  1295. }
  1296. else
  1297. {
  1298. if(nested_obj->_itype.is_enum())
  1299. {
  1300. out << " // Enum "<< nested_obj->_itype.get_scoped_name() << ";\n";
  1301. int enum_count = nested_obj->_itype.number_of_enum_values();
  1302. for(int xx = 0; xx< enum_count; xx++)
  1303. out << " PyDict_SetItemString(Dtool_" << ClassName << ".As_PyTypeObject().tp_dict,\"" << classNameFromCppName(nested_obj->_itype.get_enum_value_name(xx)) <<"\",PyInt_FromLong("<< nested_obj->_itype.get_enum_value(xx) << "));\n";
  1304. }
  1305. }
  1306. }
  1307. out << " if(PyType_Ready(&Dtool_"<< ClassName << ".As_PyTypeObject()) < 0)\n";
  1308. out << " {\n";
  1309. out << " PyErr_SetString(PyExc_TypeError, \"PyType_Ready("<< ClassName << ")\");\n";
  1310. out << " printf(\" Error In PyType_Ready" << ClassName << "\");\n";
  1311. out << " return;\n";
  1312. out << " }\n";
  1313. out << " Py_INCREF(&Dtool_"<< ClassName << ".As_PyTypeObject());\n";
  1314. out << " PyDict_SetItemString(Dtool_"<<ClassName <<".As_PyTypeObject().tp_dict,\""<<export_calss_name<< "\",&Dtool_"<<ClassName <<".As_PyObject());\n";
  1315. // static function into dictionary with bogus self..
  1316. //
  1317. std::map<int , Function * >::iterator sfi;
  1318. for(sfi= static_functions.begin(); sfi != static_functions.end(); sfi++)
  1319. {
  1320. out << " // Static Method " << methodNameFromCppName( sfi->second->_ifunc.get_name(),export_calss_name) << "\n";
  1321. out << " PyDict_SetItemString(Dtool_" << ClassName << ".As_PyTypeObject().tp_dict,\"" ;
  1322. out << methodNameFromCppName( sfi->second->_ifunc.get_name(),export_calss_name) ;
  1323. out << "\",PyCFunction_New(&Dtool_Methods_"<< ClassName <<"[" << sfi->first << "],&Dtool_"<< ClassName<< ".As_PyObject()));\n";
  1324. }
  1325. if(is_runtime_typed)
  1326. out << " RegisterRuntimeClass(&Dtool_"<<ClassName<<","<< cClassName <<"::get_class_type().get_index());\n";
  1327. else
  1328. out << " RegisterRuntimeClass(&Dtool_"<<ClassName<<",-1);\n";
  1329. out << " }\n";
  1330. out << " if(module != NULL)\n";
  1331. out << " {\n";
  1332. out << " Py_INCREF(&Dtool_"<< ClassName << ".As_PyTypeObject());\n";
  1333. out << " PyModule_AddObject(module, \""<<export_calss_name<<"\",(PyObject *)&Dtool_"<< ClassName << ".As_PyTypeObject());\n";
  1334. out << " }\n";
  1335. out << "}\n";
  1336. }
  1337. ////////////////////////////////////////////////////////////////////
  1338. // Function: InterfaceMakerPythonNative::synthesize_this_parameter
  1339. // Access: Public, Virtual
  1340. // Description: This method should be overridden and redefined to
  1341. // return true for interfaces that require the implicit
  1342. // "this" parameter, if present, to be passed as the
  1343. // first parameter to any wrapper functions.
  1344. ////////////////////////////////////////////////////////////////////
  1345. bool InterfaceMakerPythonNative::
  1346. synthesize_this_parameter() {
  1347. return true;
  1348. }
  1349. ////////////////////////////////////////////////////////////////////
  1350. // Function: InterfaceMakerPythonNative::get_wrapper_prefix
  1351. // Access: Protected, Virtual
  1352. // Description: Returns the prefix string used to generate wrapper
  1353. // function names.
  1354. ////////////////////////////////////////////////////////////////////
  1355. string InterfaceMakerPythonNative::
  1356. get_wrapper_prefix() {
  1357. return "Dtool_";
  1358. }
  1359. ////////////////////////////////////////////////////////////////////
  1360. // Function: InterfaceMakerPythonNative::get_unique_prefix
  1361. // Access: Protected, Virtual
  1362. // Description: Returns the prefix string used to generate unique
  1363. // symbolic names, which are not necessarily C-callable
  1364. // function names.
  1365. ////////////////////////////////////////////////////////////////////
  1366. string InterfaceMakerPythonNative::get_unique_prefix()
  1367. {
  1368. return "Dtool_";
  1369. }
  1370. ////////////////////////////////////////////////////////////////////
  1371. // Function: InterfaceMakerPythonNative::record_function_wrapper
  1372. // Access: Protected, Virtual
  1373. // Description: Associates the function wrapper with its function in
  1374. // the appropriate structures in the database.
  1375. ////////////////////////////////////////////////////////////////////
  1376. void InterfaceMakerPythonNative::record_function_wrapper(InterrogateFunction &ifunc, FunctionWrapperIndex wrapper_index)
  1377. {
  1378. ifunc._python_wrappers.push_back(wrapper_index);
  1379. }
  1380. ////////////////////////////////////////////////////////////////////
  1381. // Function: InterfaceMakerPythonNative::write_prototype_for
  1382. // Access: Private
  1383. // Description: Writes the prototype for the indicated function.
  1384. ////////////////////////////////////////////////////////////////////
  1385. void InterfaceMakerPythonNative::write_prototype_for(ostream &out, InterfaceMaker::Function *func)
  1386. {
  1387. std::string fname = "PyObject *"+func->_name+"(PyObject *self, PyObject *args)";
  1388. write_prototype_for_name(out,func,fname);
  1389. }
  1390. ////////////////////////////////////////////////////////////////////
  1391. ////////////////////////////////////////////////////////////////////
  1392. ////////////////////////////////////////////////////////////////////
  1393. void InterfaceMakerPythonNative::write_prototype_for_name(ostream &out, InterfaceMaker::Function *func, const std::string &function_namename)
  1394. {
  1395. Function::Remaps::const_iterator ri;
  1396. // for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri) {
  1397. // FunctionRemap *remap = (*ri);
  1398. if (!output_function_names) {
  1399. // If we're not saving the function names, don't export it from
  1400. // the library.
  1401. out << "static ";
  1402. } else {
  1403. out << "extern \"C\" ";
  1404. }
  1405. out << function_namename <<";\n";
  1406. // }
  1407. }
  1408. ////////////////////////////////////////////////////////////////////
  1409. // Function: InterfaceMakerPythonNative::write_function_for
  1410. // Access: Private
  1411. // Description: Writes the definition for a function that will call
  1412. // the indicated C++ function or method.
  1413. ////////////////////////////////////////////////////////////////////
  1414. void InterfaceMakerPythonNative::write_function_for_top(ostream &out, InterfaceMaker::Function *func, const std::string &PreProcess)
  1415. {
  1416. std::string fname = "static PyObject *"+func->_name+"(PyObject *self, PyObject *args,PyObject *kwds)";
  1417. write_function_for_name(out,func,fname,PreProcess,"");
  1418. }
  1419. ////////////////////////////////////////////////////////////////////
  1420. /// Function : write_function_for_name
  1421. //
  1422. // Wrap a complete name override function for Py.....
  1423. ////////////////////////////////////////////////////////////////////
  1424. void InterfaceMakerPythonNative::
  1425. write_function_for_name(ostream &out1, InterfaceMaker::Function *func,
  1426. const std::string &function_name,
  1427. const std::string &PreProcess,
  1428. const std::string &ClassName) {
  1429. ostringstream forward_decl;
  1430. ostringstream out;
  1431. std::map<int , std::set<FunctionRemap *> > MapSets;
  1432. std::map<int , std::set<FunctionRemap *> >::iterator mii;
  1433. std::set<FunctionRemap *>::iterator sii;
  1434. Function::Remaps::const_iterator ri;
  1435. out1 << "/******************************************************************\n" << " * Python type method wrapper for\n";
  1436. for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri) {
  1437. FunctionRemap *remap = (*ri);
  1438. if (isRemapLegal(*remap)) {
  1439. int parameter_size = remap->_parameters.size();
  1440. if(remap->_has_this && remap->_type != FunctionRemap::T_constructor)
  1441. parameter_size --;
  1442. MapSets[parameter_size].insert(remap);
  1443. out1 << " * ";
  1444. remap->write_orig_prototype(out1, 0);
  1445. out1 << "\n";
  1446. } else {
  1447. out1 << " * Rejected Remap [";
  1448. remap->write_orig_prototype(out1, 0);
  1449. out1 << "]\n";
  1450. }
  1451. }
  1452. out1 << " *******************************************************************/\n";
  1453. out << function_name << " {\n";
  1454. if (isFunctionWithThis(func)) {
  1455. out << PreProcess;
  1456. }
  1457. bool is_inplace = isInplaceFunction(func->_ifunc.get_name());
  1458. if (MapSets.empty()) {
  1459. return;
  1460. }
  1461. std::string FunctionComment = func->_ifunc._comment;
  1462. std::string FunctionComment1;
  1463. if (FunctionComment.size() > 2) {
  1464. FunctionComment += "\n";
  1465. }
  1466. bool constructor = false;
  1467. if (MapSets.size() > 1) {
  1468. string expected_params;
  1469. indent(out,4) << "int parameter_count = 1;\n";
  1470. indent(out,4) << "if(PyTuple_Check(args))\n";
  1471. indent(out,4) << "{\n";
  1472. indent(out,4) << " parameter_count = PyTuple_Size(args);\n" ;
  1473. indent(out,4) << " if(kwds != NULL && PyDict_Check(kwds))\n";
  1474. indent(out,4) << " parameter_count += PyDict_Size(kwds);\n" ;
  1475. indent(out,4) << "}\n";
  1476. indent(out,4) << "switch(parameter_count)\n";
  1477. indent(out,4) << "{\n";
  1478. for (mii = MapSets.begin(); mii != MapSets.end(); mii ++) {
  1479. indent(out,4) << "case(" << mii->first << "):\n";
  1480. indent(out,8) << "{\n";
  1481. write_function_forset(out,func,mii->second,expected_params,8,forward_decl,ClassName + function_name, is_inplace);
  1482. if ((*mii->second.begin())->_type == FunctionRemap::T_constructor) {
  1483. constructor = true;
  1484. }
  1485. indent(out,8)<< "}\n";
  1486. indent(out,8)<< "break;\n";
  1487. }
  1488. indent(out,4)<< "default:\n";
  1489. indent(out,8)<< "{\n";
  1490. indent(out,12)
  1491. << "PyErr_Format(PyExc_TypeError, \""
  1492. << func->_remaps[0]->_cppfunc->get_local_name(&parser)
  1493. << "() takes ";
  1494. // We add one to the parameter count for "self", following the
  1495. // Python convention.
  1496. int add_self = func->_has_this ? 1 : 0;
  1497. size_t mic;
  1498. for (mic = 0, mii = MapSets.begin();
  1499. mii != MapSets.end();
  1500. ++mii, ++mic) {
  1501. if (mic == MapSets.size() - 1) {
  1502. if (mic == 1) {
  1503. out << " or ";
  1504. } else {
  1505. out << ", or ";
  1506. }
  1507. } else if (mic != 0) {
  1508. out << ", ";
  1509. }
  1510. out << mii->first + add_self;
  1511. }
  1512. out << " arguments (%d given)\", parameter_count + " << add_self << ");\n";
  1513. if (constructor)
  1514. indent(out,12) << "return -1;\n";
  1515. else
  1516. indent(out,12) << "return (PyObject *) NULL; \n";
  1517. indent(out,8)<< "}\n";
  1518. indent(out,8)<< "break;\n";
  1519. indent(out,4)<< "}\n";
  1520. out << " if(!PyErr_Occurred()) // let error pass on \n";
  1521. out << " PyErr_SetString(PyExc_TypeError, \n";
  1522. out << " \"Arguments must match one of:\\n\"\n";
  1523. output_quoted(out, 10, expected_params);
  1524. out << ");\n";
  1525. if (constructor)
  1526. indent(out,4) << "return -1;\n";
  1527. else
  1528. indent(out,4) << "return (PyObject *) NULL; \n";
  1529. if(!expected_params.empty() && FunctionComment1.empty())
  1530. FunctionComment1 += "C++ Interface:\n";
  1531. FunctionComment1 += expected_params;
  1532. } else {
  1533. string expected_params = "";
  1534. for (mii = MapSets.begin(); mii != MapSets.end(); mii ++) {
  1535. write_function_forset(out,func,mii->second,expected_params,4,forward_decl,ClassName + function_name,is_inplace);
  1536. if((*mii->second.begin())->_type == FunctionRemap::T_constructor) {
  1537. constructor = true;
  1538. }
  1539. }
  1540. out << " if(!PyErr_Occurred())\n";
  1541. out << " PyErr_SetString(PyExc_TypeError,\n";
  1542. out << " \"Must Match :\\n\"\n";
  1543. output_quoted(out, 10, expected_params);
  1544. out << ");\n";
  1545. if (constructor)
  1546. indent(out,4) << "return -1;\n";
  1547. else
  1548. indent(out,4) << "return (PyObject *) NULL; \n";
  1549. if (!expected_params.empty() && FunctionComment1.empty()) {
  1550. FunctionComment1 += "C++ Interface:\n";
  1551. }
  1552. FunctionComment1 += expected_params;
  1553. }
  1554. out << "}\n\n";
  1555. if (!FunctionComment1.empty()) {
  1556. FunctionComment = FunctionComment1 + "\n" + FunctionComment;
  1557. }
  1558. if (!constructor) {
  1559. // Write out the function doc string. We only do this if it is
  1560. // not a constructor, since we don't have a place to put the
  1561. // constructor doc string.
  1562. out << "#ifndef NDEBUG\n";
  1563. out << "static char * " << func->_name << "_comment =\n";
  1564. output_quoted(out, 4, FunctionComment);
  1565. out << ";\n";
  1566. out << "#else\n";
  1567. out << "static char * " << func->_name << "_comment = NULL;\n";
  1568. out << "#endif\n";
  1569. }
  1570. out << "\n";
  1571. out1 << forward_decl.str();
  1572. out1 << out.str();
  1573. }
  1574. ////////////////////////////////////////////////////////
  1575. // Function : GetParnetDepth
  1576. //
  1577. // Support Function used to Sort the name based overrides.. For know must be complex to simple
  1578. ////////////////////////////////////////////////////////
  1579. int GetParnetDepth(CPPType *type)
  1580. {
  1581. int answer = 0;
  1582. // printf(" %s\n",type->get_local_name().c_str());
  1583. if (TypeManager::is_basic_string_char(type)) {
  1584. } else if (TypeManager::is_basic_string_wchar(type)) {
  1585. } else if (TypeManager::is_bool(type)) {
  1586. } else if (TypeManager::is_unsigned_longlong(type)) {
  1587. } else if (TypeManager::is_longlong(type)) {
  1588. } else if (TypeManager::is_integer(type)) {
  1589. } else if (TypeManager::is_float(type)) {
  1590. } else if (TypeManager::is_char_pointer(type)) {
  1591. } else if (TypeManager::is_pointer_to_PyObject(type)) {
  1592. } else if (TypeManager::is_pointer(type) ||TypeManager::is_reference(type) || TypeManager::is_struct(type) )
  1593. {
  1594. answer ++;
  1595. int deepest = 0;
  1596. TypeIndex type_index = builder.get_type(TypeManager::unwrap(TypeManager::resolve_type(type)),false);
  1597. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  1598. const InterrogateType &itype = idb->get_type(type_index);
  1599. if(itype.is_class() ||itype.is_struct())
  1600. {
  1601. int num_derivations = itype.number_of_derivations();
  1602. for (int di = 0; di < num_derivations; di++)
  1603. {
  1604. TypeIndex d_type_Index = itype.get_derivation(di);
  1605. const InterrogateType &d_itype = idb->get_type(d_type_Index);
  1606. int this_one = GetParnetDepth(d_itype._cpptype);
  1607. if(this_one > deepest)
  1608. deepest = this_one;
  1609. }
  1610. }
  1611. answer += deepest;
  1612. // printf(" Class Name %s %d\n",itype.get_name().c_str(),answer);
  1613. }
  1614. // printf(" Class Name %s %d\n",itype.get_name().c_str(),answer);
  1615. return answer;
  1616. }
  1617. ////////////////////////////////////////////////////////
  1618. // The Core sort function for remap calling orders..
  1619. //////////////////////////////////////////////////////////
  1620. int RemapCompareLesss(FunctionRemap * in1 , FunctionRemap * in2)
  1621. {
  1622. if(in1->_parameters.size() != in2->_parameters.size())
  1623. return (in1->_parameters.size() > in2->_parameters.size());
  1624. int pcount = in1->_parameters.size();
  1625. for(int x = 0; x< pcount; x++)
  1626. {
  1627. CPPType *orig_type1 = in1->_parameters[x]._remap->get_orig_type();
  1628. CPPType *orig_type2 = in2->_parameters[x]._remap->get_orig_type();
  1629. int pd1 = GetParnetDepth(orig_type1);
  1630. int pd2 = GetParnetDepth(orig_type2);
  1631. if(pd1 != pd2)
  1632. return pd1> pd2;
  1633. }
  1634. // ok maybe something to do with return strength..
  1635. return false;
  1636. }
  1637. //////////////////////////////////////////////////////////
  1638. // Convience for the sort behavior..
  1639. ///////////////////////////////////////////////////////////
  1640. std::vector< FunctionRemap * > SortFunctionSet(std::set< FunctionRemap *> &remaps)
  1641. {
  1642. std::vector< FunctionRemap * > out;
  1643. for(std::set< FunctionRemap *>::iterator ii = remaps.begin(); ii!= remaps.end(); ii++)
  1644. out.push_back(*ii);
  1645. std::sort(out.begin(), out.end(), RemapCompareLesss);
  1646. return out;
  1647. }
  1648. ///////////////////////////////////////////////////////////
  1649. // Function : write_function_forset
  1650. //
  1651. // A set is defined as all rempas that have the same number of paramaters..
  1652. ///////////////////////////////////////////////////////////
  1653. void InterfaceMakerPythonNative::write_function_forset(ostream &out, InterfaceMaker::Function *func,
  1654. std::set< FunctionRemap *> &remapsin, string &expected_params, int indent_level,ostream &forward_decl, const std::string &functionname, bool is_inplace)
  1655. {
  1656. if(remapsin.size() > 1)
  1657. {
  1658. // printf("---------------------------- Start Sort ----- %s , %s\n",func->_name.c_str(),functionname.c_str());
  1659. std::vector<FunctionRemap *> remaps = SortFunctionSet(remapsin);
  1660. std::vector<FunctionRemap *>::iterator sii;
  1661. for(sii = remaps.begin(); sii != remaps.end(); sii ++)
  1662. {
  1663. FunctionRemap *remap = (*sii);
  1664. if(isRemapLegal(*remap))
  1665. {
  1666. indent(out,indent_level)<< "{ // -2 " ;
  1667. remap->write_orig_prototype(out, 0); out << "\n" ;
  1668. write_function_instance(out, func, remap,expected_params,indent_level+4,false,forward_decl, func->_name, is_inplace);
  1669. indent(out,indent_level+4)<< "PyErr_Clear(); \n";
  1670. indent(out,indent_level)<< "}\n\n";
  1671. }
  1672. }
  1673. }
  1674. else
  1675. {
  1676. std::set<FunctionRemap *>::iterator sii;
  1677. for(sii = remapsin.begin(); sii != remapsin.end(); sii ++)
  1678. {
  1679. FunctionRemap *remap = (*sii);
  1680. if(isRemapLegal(*remap))
  1681. {
  1682. indent(out,indent_level)<< "// 1-" ;remap->write_orig_prototype(out, 0); out << "\n" ;
  1683. // indent(out,indent_level)<< "do{\n";
  1684. write_function_instance(out, func, remap,expected_params,indent_level+4,true,forward_decl, func->_name, is_inplace);
  1685. // indent(out,indent_level)<< "}while(false);\n";
  1686. }
  1687. }
  1688. }
  1689. }
  1690. ////////////////////////////////////////////////////////////////////
  1691. // Function: InterfaceMakerPythonNative::write_function_instance
  1692. // Access: Private
  1693. // Description: Writes out the particular function that handles a
  1694. // single instance of an overloaded function.
  1695. ////////////////////////////////////////////////////////////////////
  1696. void InterfaceMakerPythonNative::write_function_instance(ostream &out, InterfaceMaker::Function *func1,
  1697. FunctionRemap *remap, string &expected_params, int indent_level, bool errors_fatal, ostream &ForwardDeclrs, const std::string &functionnamestr, bool is_inplace)
  1698. {
  1699. string format_specifiers;
  1700. std::string keyword_list;
  1701. string parameter_list;
  1702. string container;
  1703. vector_string pexprs;
  1704. string extra_convert;
  1705. string extra_param_check;
  1706. string extra_cleanup;
  1707. string pname_for_pyobject;
  1708. bool is_constructor = false;
  1709. if (remap->_type == FunctionRemap::T_constructor) {
  1710. is_constructor = true;
  1711. }
  1712. // Make one pass through the parameter list. We will output a
  1713. // one-line temporary variable definition for each parameter, while
  1714. // simultaneously building the ParseTuple() function call and also
  1715. // the parameter expression list for call_function().
  1716. expected_params += remap->_cppfunc->get_simple_name();
  1717. expected_params += "(";
  1718. int pn;
  1719. for (pn = 0; pn < (int)remap->_parameters.size(); pn++) {
  1720. if(pn > 0) {
  1721. expected_params += ", ";
  1722. }
  1723. CPPType *orig_type = remap->_parameters[pn]._remap->get_orig_type();
  1724. CPPType *type = remap->_parameters[pn]._remap->get_new_type();
  1725. string param_name = remap->get_parameter_name(pn);
  1726. // This is the string to convert our local variable to the
  1727. // appropriate C++ type. Normally this is just a cast.
  1728. string pexpr_string =
  1729. "(" + type->get_local_name(&parser) + ")" + param_name;
  1730. if (!remap->_has_this || pn != 0) {
  1731. keyword_list += "\""+remap->_parameters[pn]._name + "\", ";
  1732. }
  1733. if (remap->_parameters[pn]._remap->new_type_is_atomic_string()) {
  1734. if (TypeManager::is_char_pointer(orig_type)) {
  1735. indent(out,indent_level)<< "char *" << param_name;
  1736. format_specifiers += "s";
  1737. parameter_list += ", &" + param_name;
  1738. } else if (TypeManager::is_wstring(orig_type)) {
  1739. indent(out,indent_level) << "Py_UNICODE *" << param_name
  1740. << "_str; int " << param_name << "_len";
  1741. format_specifiers += "u#";
  1742. parameter_list += ", &" + param_name
  1743. + "_str, &" + param_name + "_len";
  1744. pexpr_string = "basic_string<wchar_t>((wchar_t *)" +
  1745. param_name + "_str, " +
  1746. param_name + "_len)";
  1747. } else {
  1748. indent(out,indent_level) << "char *" << param_name
  1749. << "_str; int " << param_name << "_len";
  1750. format_specifiers += "s#";
  1751. parameter_list += ", &" + param_name
  1752. + "_str, &" + param_name + "_len";
  1753. pexpr_string = "basic_string<char>(" +
  1754. param_name + "_str, " +
  1755. param_name + "_len)";
  1756. }
  1757. expected_params += "string";
  1758. } else if (TypeManager::is_bool(type)) {
  1759. indent(out,indent_level) << "PyObject *" << param_name;
  1760. format_specifiers += "O";
  1761. parameter_list += ", &" + param_name;
  1762. pexpr_string = "(PyObject_IsTrue(" + param_name + ")!=0)";
  1763. expected_params += "bool";
  1764. pname_for_pyobject += param_name;
  1765. } else if (TypeManager::is_unsigned_longlong(type)) {
  1766. indent(out,indent_level) << "PyObject *" << param_name;
  1767. format_specifiers += "O";
  1768. parameter_list += ", &" + param_name;
  1769. extra_convert += " PyObject *" + param_name + "_long = PyNumber_Long(" + param_name + ");";
  1770. extra_param_check += "|| (" + param_name + "_long == NULL)";
  1771. pexpr_string = "PyLong_AsUnsignedLongLong(" + param_name + "_long)";
  1772. extra_cleanup += " Py_XDECREF(" + param_name + "_long);";
  1773. expected_params += "unsigned long long";
  1774. pname_for_pyobject += param_name;
  1775. } else if (TypeManager::is_longlong(type)) {
  1776. indent(out,indent_level) << "PyObject *" << param_name;
  1777. format_specifiers += "O";
  1778. parameter_list += ", &" + param_name;
  1779. extra_convert += " PyObject *" + param_name + "_long = PyNumber_Long(" + param_name + ");";
  1780. extra_param_check += "|| (" + param_name + "_long == NULL)";
  1781. pexpr_string = "PyLong_AsLongLong(" + param_name + "_long)";
  1782. extra_cleanup += " Py_XDECREF(" + param_name + "_long);";
  1783. expected_params += "long long";
  1784. pname_for_pyobject += param_name;
  1785. } else if (TypeManager::is_unsigned_integer(type)) {
  1786. indent(out,indent_level) << "PyObject *" << param_name;
  1787. format_specifiers += "O";
  1788. parameter_list += ", &" + param_name;
  1789. extra_convert += " PyObject *" + param_name + "_uint = PyNumber_Long(" + param_name + ");";
  1790. extra_param_check += "|| (" + param_name + "_uint == NULL)";
  1791. pexpr_string = "PyLong_AsUnsignedLong(" + param_name + "_uint)";
  1792. extra_cleanup += " Py_XDECREF(" + param_name + "_uint);";
  1793. expected_params += "unsigned int";
  1794. pname_for_pyobject += param_name;
  1795. } else if (TypeManager::is_integer(type)) {
  1796. indent(out,indent_level) << "int " << param_name;
  1797. format_specifiers += "i";
  1798. parameter_list += ", &" + param_name;
  1799. expected_params += "int";
  1800. } else if (TypeManager::is_float(type)) {
  1801. indent(out,indent_level) << "double " << param_name;
  1802. format_specifiers += "d";
  1803. parameter_list += ", &" + param_name;
  1804. expected_params += "float ";
  1805. } else if (TypeManager::is_char_pointer(type)) {
  1806. indent(out,indent_level) << "char *" << param_name;
  1807. format_specifiers += "s";
  1808. parameter_list += ", &" + param_name;
  1809. expected_params += "string";
  1810. } else if (TypeManager::is_pointer_to_PyObject(type)) {
  1811. indent(out,indent_level) << "PyObject *" << param_name;
  1812. format_specifiers += "O";
  1813. parameter_list += ", &" + param_name;
  1814. pexpr_string = param_name;
  1815. pname_for_pyobject += param_name;
  1816. expected_params += "PyObject";
  1817. } else if (TypeManager::is_pointer(type)) {
  1818. expected_params += type->get_preferred_name();
  1819. if (!remap->_has_this || pn != 0) {
  1820. indent(out, indent_level)
  1821. << "PyObject *" << param_name;
  1822. format_specifiers += "O";
  1823. parameter_list += ", &" + param_name;
  1824. pname_for_pyobject += param_name;
  1825. TypeIndex p_type_index = builder.get_type(TypeManager::unwrap(TypeManager::resolve_type(type)),false);
  1826. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  1827. const InterrogateType &p_itype = idb->get_type(p_type_index);
  1828. //make_safe_name(itype.get_scoped_name())
  1829. extra_convert += p_itype.get_scoped_name()+" *" + param_name + "_this = ("+p_itype.get_scoped_name()+" *)";
  1830. // need to a forward scope for this class..
  1831. if(!isExportThisRun(p_itype._cpptype)) {
  1832. _external_imports.insert(make_safe_name(p_itype.get_scoped_name()));
  1833. //ForwardDeclrs << "IMPORT_THIS struct Dtool_PyTypedObject Dtool_" << make_safe_name(p_itype.get_scoped_name()) << ";\n";
  1834. }
  1835. ostringstream str;
  1836. str << "DTOOL_Call_GetPointerThisClass(" << param_name
  1837. << ", &Dtool_" << make_safe_name(p_itype.get_scoped_name())
  1838. << ", " << pn << ", \""
  1839. << remap->_cppfunc->get_local_name(&parser)
  1840. << "\");\n";
  1841. extra_convert += str.str();
  1842. extra_param_check += "|| (" + param_name + "_this == NULL)";
  1843. pexpr_string = param_name + "_this";
  1844. }
  1845. } else {
  1846. // Ignore a parameter.
  1847. indent(out,indent_level) << "PyObject *" << param_name;
  1848. format_specifiers += "O";
  1849. parameter_list += ", &" + param_name;
  1850. expected_params += "any";
  1851. pname_for_pyobject += param_name;
  1852. }
  1853. if (remap->_parameters[pn]._has_name) {
  1854. expected_params += " " + remap->_parameters[pn]._name;
  1855. }
  1856. if (remap->_has_this && pn == 0) {
  1857. container = "local_this";
  1858. } else {
  1859. out << ";\n";
  1860. }
  1861. pexprs.push_back(pexpr_string);
  1862. }
  1863. expected_params += ")\n";
  1864. /*if (!format_specifiers.empty()) */ {
  1865. std::string format_specifiers1 = format_specifiers + ":" + remap->_cppfunc->get_local_name(&parser);
  1866. indent(out,indent_level)
  1867. << "static char * key_word_list[] = {" << keyword_list << "NULL};\n";
  1868. if (remap->_parameters.size() == 1 ||
  1869. (remap->_has_this && remap->_parameters.size() == 2)) {
  1870. indent(out,indent_level)
  1871. << "// Special Case to Make operator work \n";
  1872. indent(out,indent_level)
  1873. << "if(PyTuple_Check(args) || (kwds != NULL && PyDict_Check(kwds)))\n";
  1874. indent(out,indent_level)
  1875. << " (PyArg_ParseTupleAndKeywords(args,kwds, \""
  1876. << format_specifiers1 << "\", key_word_list" << parameter_list
  1877. << "));\n";
  1878. indent(out,indent_level)
  1879. << "else\n";
  1880. indent(out,indent_level)
  1881. << " (PyArg_Parse(args, \"" << format_specifiers1 << "\""
  1882. << parameter_list << "));\n";
  1883. indent(out,indent_level)
  1884. << "if(!PyErr_Occurred())\n";
  1885. } else {
  1886. indent(out,indent_level)
  1887. << "if (PyArg_ParseTupleAndKeywords(args,kwds, \""
  1888. << format_specifiers1 << "\", key_word_list"
  1889. << parameter_list << "))\n";
  1890. }
  1891. }
  1892. indent(out,indent_level) << "{\n";
  1893. if (!extra_convert.empty()) {
  1894. indent(out,indent_level+4)
  1895. << extra_convert << "\n";
  1896. }
  1897. int extra_indent_level = indent_level+4;
  1898. if (!extra_param_check.empty()) {
  1899. indent(out,extra_indent_level)
  1900. << "if (!(" << extra_param_check.substr(3) << "))\n";
  1901. indent(out,extra_indent_level)
  1902. <<"{\n";
  1903. extra_indent_level+=4;
  1904. }
  1905. if (!remap->_void_return &&
  1906. remap->_return_type->new_type_is_atomic_string()) {
  1907. // Treat strings as a special case. We don't want to format the
  1908. // return expression.
  1909. string tt;
  1910. string return_expr = remap->call_function(out, extra_indent_level, false, container, pexprs);
  1911. CPPType *type = remap->_return_type->get_orig_type();
  1912. indent(out,extra_indent_level);
  1913. type->output_instance(out, "return_value", &parser);
  1914. // type->output_instance(tt, "return_value", &parser);
  1915. out << " = " << return_expr << ";\n";
  1916. if (track_interpreter) {
  1917. indent(out,extra_indent_level) << "in_interpreter = 1;\n";
  1918. }
  1919. if (!extra_cleanup.empty()) {
  1920. indent(out,extra_indent_level) << extra_cleanup << "\n";
  1921. }
  1922. return_expr = manage_return_value(out, 4, remap, "return_value");
  1923. do_assert_init(out, extra_indent_level,is_constructor);
  1924. pack_return_value(out, extra_indent_level, remap, return_expr,ForwardDeclrs,is_inplace);
  1925. } else {
  1926. string return_expr = remap->call_function(out, extra_indent_level, true, container, pexprs);
  1927. if (return_expr.empty()) {
  1928. if (track_interpreter) {
  1929. indent(out,extra_indent_level) << "in_interpreter = 1;\n";
  1930. }
  1931. if (!extra_cleanup.empty()) {
  1932. indent(out,extra_indent_level) << extra_cleanup << "\n";
  1933. }
  1934. do_assert_init(out, extra_indent_level,is_constructor);
  1935. indent(out,extra_indent_level) << "return Py_BuildValue(\"\");\n";
  1936. } else {
  1937. CPPType *type = remap->_return_type->get_temporary_type();
  1938. if(!is_inplace) {
  1939. indent(out,extra_indent_level);
  1940. type->output_instance(out, "return_value", &parser);
  1941. out << " = " << return_expr << ";\n";
  1942. }
  1943. if (track_interpreter) {
  1944. indent(out,extra_indent_level) << "in_interpreter = 1;\n";
  1945. }
  1946. if (!extra_cleanup.empty()) {
  1947. indent(out,extra_indent_level) << extra_cleanup << "\n";
  1948. }
  1949. return_expr = manage_return_value(out, extra_indent_level, remap, "return_value");
  1950. do_assert_init(out, extra_indent_level,is_constructor);
  1951. pack_return_value(out, extra_indent_level, remap, remap->_return_type->temporary_to_return(return_expr),ForwardDeclrs,is_inplace);
  1952. }
  1953. }
  1954. if (!extra_param_check.empty()) {
  1955. extra_indent_level-=4;
  1956. indent(out,extra_indent_level)<< "}\n";
  1957. }
  1958. indent(out,indent_level) << "}\n";
  1959. }
  1960. ////////////////////////////////////////////////////////////////////
  1961. // Function: InterfaceMakerPythonNative::pack_return_value
  1962. // Access: Private
  1963. // Description: Outputs a command to pack the indicated expression,
  1964. // of the return_type type, as a Python return value.
  1965. ////////////////////////////////////////////////////////////////////
  1966. void InterfaceMakerPythonNative::pack_return_value(ostream &out, int indent_level,
  1967. FunctionRemap *remap, string return_expr, ostream &ForwardDeclrs, bool is_inplace)
  1968. {
  1969. CPPType *orig_type = remap->_return_type->get_orig_type();
  1970. CPPType *type = remap->_return_type->get_new_type();
  1971. if (remap->_return_type->new_type_is_atomic_string()) {
  1972. if (TypeManager::is_char_pointer(orig_type)) {
  1973. indent(out, indent_level)
  1974. << "return PyString_FromString(" << return_expr << ");\n";
  1975. } else if (TypeManager::is_wstring(orig_type)) {
  1976. indent(out, indent_level)
  1977. << "return PyUnicode_FromWideChar("
  1978. << return_expr << ".data(), (int)" << return_expr << ".length());\n";
  1979. } else {
  1980. indent(out, indent_level)
  1981. << "return PyString_FromStringAndSize("
  1982. << return_expr << ".data(), (int)" << return_expr << ".length());\n";
  1983. }
  1984. } else if (TypeManager::is_unsigned_longlong(type)) {
  1985. indent(out, indent_level)
  1986. << "return PyLong_FromUnsignedLongLong(" << return_expr << ");\n";
  1987. } else if (TypeManager::is_longlong(type)) {
  1988. indent(out, indent_level)
  1989. << "return PyLong_FromLongLong(" << return_expr << ");\n";
  1990. } else if(TypeManager::is_unsigned_integer(type)){
  1991. indent(out, indent_level)
  1992. << "return PyLong_FromUnsignedLong(" << return_expr << ");\n";
  1993. }else if (TypeManager::is_integer(type)) {
  1994. indent(out, indent_level)
  1995. << "return PyInt_FromLong(" << return_expr << ");\n";
  1996. } else if (TypeManager::is_float(type)) {
  1997. indent(out, indent_level)
  1998. << "return PyFloat_FromDouble(" << return_expr << ");\n";
  1999. } else if (TypeManager::is_char_pointer(type)) {
  2000. indent(out, indent_level)
  2001. << "return PyString_FromString(" << return_expr << ");\n";
  2002. }
  2003. else if (TypeManager::is_pointer_to_PyObject(type))
  2004. {
  2005. indent(out, indent_level)
  2006. << "return "<< return_expr << ";\n";
  2007. }
  2008. else if (TypeManager::is_pointer(type))
  2009. {
  2010. if (TypeManager::is_struct(orig_type) || TypeManager::is_ref_to_anything(orig_type))
  2011. {
  2012. if( TypeManager::is_ref_to_anything(orig_type))
  2013. {
  2014. TypeIndex type_index = builder.get_type(TypeManager::unwrap(TypeManager::resolve_type(type)),false);
  2015. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2016. const InterrogateType &itype = idb->get_type(type_index);
  2017. std::string ows_memory_flag("true");
  2018. if(remap->_return_value_needs_management)
  2019. ows_memory_flag = "true";
  2020. else
  2021. ows_memory_flag = "false";
  2022. if(!isExportThisRun(itype._cpptype))
  2023. {
  2024. _external_imports.insert(make_safe_name(itype.get_scoped_name()));
  2025. //ForwardDeclrs << "IMPORT_THIS struct Dtool_PyTypedObject Dtool_" << make_safe_name(itype.get_scoped_name()) << ";\n";
  2026. }
  2027. WriteReturnInstance(out,indent_level,return_expr,ows_memory_flag,itype.get_scoped_name(),itype._cpptype,is_inplace);
  2028. // indent(out, indent_level)
  2029. // <<"return DTool_CreatePyInstance((void *)" << return_expr <<"," << CLASS_PREFEX << make_safe_name(itype.get_scoped_name()) << ","<<ows_memory_flag<<");\n";
  2030. }
  2031. else
  2032. {
  2033. if (remap->_type == FunctionRemap::T_constructor )
  2034. {
  2035. // should only reach this in the INIT function a a Class .. IE the PY exists before the CPP object
  2036. // this is were we type to returned a class/struct.. ie CPP TYpe
  2037. TypeIndex type_index = builder.get_type(TypeManager::unwrap(TypeManager::resolve_type(orig_type)),false);
  2038. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2039. const InterrogateType &itype = idb->get_type(type_index);
  2040. indent(out, indent_level)
  2041. <<"return DTool_PyInit_Finalize(self, " << return_expr <<",&"<<CLASS_PREFEX << make_safe_name(itype.get_scoped_name()) << ",true);\n";
  2042. }
  2043. else
  2044. {
  2045. std::string ows_memory_flag("true");
  2046. if(remap->_return_value_needs_management)
  2047. ows_memory_flag = "true";
  2048. else
  2049. ows_memory_flag = "false";
  2050. if(remap->_manage_reference_count)
  2051. {
  2052. TypeIndex type_index = builder.get_type(TypeManager::unwrap(TypeManager::resolve_type(type)),false);
  2053. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2054. const InterrogateType &itype = idb->get_type(type_index);
  2055. if(!isExportThisRun(itype._cpptype))
  2056. {
  2057. _external_imports.insert(make_safe_name(itype.get_scoped_name()));
  2058. //ForwardDeclrs << "IMPORT_THIS struct Dtool_PyTypedObject Dtool_" << make_safe_name(itype.get_scoped_name()) << ";\n";
  2059. }
  2060. // ForwardDeclrs << "extern \"C\" struct Dtool_PyTypedObject Dtool_" << make_safe_name(itype.get_scoped_name()) << ";\n";
  2061. WriteReturnInstance(out,indent_level,return_expr,ows_memory_flag,itype.get_scoped_name(),itype._cpptype,is_inplace);
  2062. //indent(out, indent_level)
  2063. // <<"return DTool_CreatePyInstance((void *)" << return_expr <<"," << CLASS_PREFEX << make_safe_name(itype.get_scoped_name()) << ","<<ows_memory_flag<<");\n";
  2064. }
  2065. else
  2066. {
  2067. TypeIndex type_index = builder.get_type(TypeManager::unwrap(TypeManager::resolve_type(orig_type)),false);
  2068. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2069. const InterrogateType &itype = idb->get_type(type_index);
  2070. if(!isExportThisRun(itype._cpptype))
  2071. {
  2072. _external_imports.insert(make_safe_name(itype.get_scoped_name()));
  2073. //ForwardDeclrs << "IMPORT_THIS struct Dtool_PyTypedObject Dtool_" << make_safe_name(itype.get_scoped_name()) << ";\n";
  2074. }
  2075. // ForwardDeclrs << "extern \"C\" struct Dtool_PyTypedObject Dtool_" << make_safe_name(itype.get_scoped_name()) << ";\n";
  2076. //indent(out, indent_level)
  2077. // <<"return DTool_CreatePyInstance((void *)" << return_expr <<"," << CLASS_PREFEX << make_safe_name(itype.get_scoped_name()) << ","<<ows_memory_flag<<");\n";
  2078. WriteReturnInstance(out,indent_level,return_expr,ows_memory_flag,itype.get_scoped_name(),itype._cpptype,is_inplace);
  2079. }
  2080. }
  2081. }
  2082. }
  2083. else if( TypeManager::is_struct(orig_type->as_pointer_type()->_pointing_at) )
  2084. {
  2085. TypeIndex type_index = builder.get_type(TypeManager::unwrap(TypeManager::resolve_type(orig_type)),false);
  2086. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2087. const InterrogateType &itype = idb->get_type(type_index);
  2088. std::string ows_memory_flag("true");
  2089. if(remap->_return_value_needs_management)
  2090. ows_memory_flag ="true";
  2091. else
  2092. ows_memory_flag = "false";
  2093. if(!isExportThisRun(itype._cpptype))
  2094. {
  2095. _external_imports.insert(make_safe_name(itype.get_scoped_name()));
  2096. //ForwardDeclrs << "IMPORT_THIS struct Dtool_PyTypedObject Dtool_" << make_safe_name(itype.get_scoped_name()) << ";\n";
  2097. }
  2098. // ForwardDeclrs << "extern \"C\" struct Dtool_PyTypedObject Dtool_" << make_safe_name(itype.get_scoped_name()) << ";\n";
  2099. WriteReturnInstance(out,indent_level,return_expr,ows_memory_flag,itype.get_scoped_name(),itype._cpptype,is_inplace);
  2100. //indent(out, indent_level)
  2101. // << "return DTool_CreatePyInstance((void *)" << return_expr <<","<<CLASS_PREFEX << make_safe_name(itype.get_scoped_name()) <<","<< ows_memory_flag<< ");\n";
  2102. }
  2103. else
  2104. {
  2105. indent(out, indent_level)<<" Shouln Never Reach This InterfaceMakerPythonNative::pack_return_value";
  2106. //<< "return PyInt_FromLong((int)" << return_expr << ");\n";
  2107. }
  2108. } else {
  2109. // Return None.
  2110. indent(out, indent_level)
  2111. << "return Py_BuildValue(\"\");\n";
  2112. }
  2113. }
  2114. ////////////////////////////////////////////////////////////////////
  2115. ////////////////////////////////////////////////////////////////////
  2116. // Function: InterfaceMakerPythonNative::record_object
  2117. // Access: Protected
  2118. // Description: Records the indicated type, which may be a struct
  2119. // type, along with all of its associated methods, if
  2120. // any.
  2121. ////////////////////////////////////////////////////////////////////
  2122. InterfaceMaker::Object *InterfaceMakerPythonNative::record_object(TypeIndex type_index)
  2123. {
  2124. if (type_index == 0) {
  2125. return (Object *)NULL;
  2126. }
  2127. Objects::iterator oi = _objects.find(type_index);
  2128. if (oi != _objects.end()) {
  2129. return (*oi).second;
  2130. }
  2131. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2132. const InterrogateType &itype = idb->get_type(type_index);
  2133. if(!isCppTypeLegal(itype._cpptype))
  2134. {
  2135. return (Object *)NULL;
  2136. }
  2137. Object *object = new Object(itype);
  2138. bool inserted = _objects.insert(Objects::value_type(type_index, object)).second;
  2139. assert(inserted);
  2140. Function *function;
  2141. int num_constructors = itype.number_of_constructors();
  2142. for (int ci = 0; ci < num_constructors; ci++)
  2143. {
  2144. function = record_function(itype, itype.get_constructor(ci));
  2145. if(isFunctionLegal(function))
  2146. object->_constructors.push_back(function);
  2147. }
  2148. int num_methods = itype.number_of_methods();
  2149. int mi;
  2150. for (mi = 0; mi < num_methods; mi++)
  2151. {
  2152. function = record_function(itype, itype.get_method(mi));
  2153. if(isFunctionLegal(function))
  2154. object->_methods.push_back(function);
  2155. }
  2156. int num_casts = itype.number_of_casts();
  2157. for (mi = 0; mi < num_casts; mi++)
  2158. {
  2159. function = record_function(itype, itype.get_cast(mi));
  2160. if(isFunctionLegal(function))
  2161. object->_methods.push_back(function);
  2162. }
  2163. int num_derivations = itype.number_of_derivations();
  2164. for (int di = 0; di < num_derivations; di++)
  2165. {
  2166. TypeIndex d_type_Index = itype.get_derivation(di);
  2167. idb->get_type(d_type_Index);
  2168. if(!interrogate_type_is_unpublished(d_type_Index))
  2169. {
  2170. if (itype.derivation_has_upcast(di))
  2171. {
  2172. function = record_function(itype, itype.derivation_get_upcast(di));
  2173. if(isFunctionLegal(function))
  2174. object->_methods.push_back(function);
  2175. }
  2176. if (itype.derivation_has_downcast(di))
  2177. {
  2178. // Downcasts are methods of the base class, not the child class.
  2179. TypeIndex base_type_index = itype.get_derivation(di);
  2180. const InterrogateType &base_type = idb->get_type(base_type_index);
  2181. function = record_function(base_type, itype.derivation_get_downcast(di));
  2182. if(isFunctionLegal(function))
  2183. {
  2184. Object * pobject = record_object(base_type_index);
  2185. if(pobject != NULL)
  2186. pobject->_methods.push_back(function);
  2187. }
  2188. }
  2189. }
  2190. }
  2191. int num_elements = itype.number_of_elements();
  2192. for (int ei = 0; ei < num_elements; ei++)
  2193. {
  2194. ElementIndex element_index = itype.get_element(ei);
  2195. const InterrogateElement &ielement = idb->get_element(element_index);
  2196. if (ielement.has_getter())
  2197. {
  2198. FunctionIndex func_index = ielement.get_getter();
  2199. record_function(itype, func_index);
  2200. }
  2201. if (ielement.has_setter())
  2202. {
  2203. FunctionIndex func_index = ielement.get_setter();
  2204. record_function(itype, func_index);
  2205. }
  2206. }
  2207. int num_nested = itype.number_of_nested_types();
  2208. for (int ni = 0; ni < num_nested; ni++)
  2209. {
  2210. TypeIndex nested_index = itype.get_nested_type(ni);
  2211. record_object(nested_index);
  2212. }
  2213. return object;
  2214. }
  2215. ////////////////////////////////////////////////////////////////////
  2216. // Function: InterfaceMaker::generate_wrappers
  2217. // Access: Public, Virtual
  2218. // Description: Walks through the set of functions in the database
  2219. // and generates wrappers for each function, storing
  2220. // these in the database. No actual code should be
  2221. // output yet; this just updates the database with the
  2222. // wrapper information.
  2223. ////////////////////////////////////////////////////////////////////
  2224. void InterfaceMakerPythonNative::generate_wrappers()
  2225. {
  2226. inside_python_native = true;
  2227. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2228. // We use a while loop rather than a simple for loop, because we
  2229. // might increase the number of types recursively during the
  2230. // traversal.
  2231. int ti = 0;
  2232. while (ti < idb->get_num_all_types())
  2233. {
  2234. TypeIndex type_index = idb->get_all_type(ti);
  2235. record_object(type_index);
  2236. ++ti;
  2237. }
  2238. int num_global_elements = idb->get_num_global_elements();
  2239. for (int gi = 0; gi < num_global_elements; ++gi) {
  2240. printf(" Global Type = %d",gi);
  2241. TypeIndex type_index = idb->get_global_element(gi);
  2242. record_object(type_index);
  2243. }
  2244. int num_functions = idb->get_num_global_functions();
  2245. for (int fi = 0; fi < num_functions; fi++)
  2246. {
  2247. FunctionIndex func_index = idb->get_global_function(fi);
  2248. record_function(dummy_type, func_index);
  2249. }
  2250. int num_manifests = idb->get_num_global_manifests();
  2251. for (int mi = 0; mi < num_manifests; mi++)
  2252. {
  2253. ManifestIndex manifest_index = idb->get_global_manifest(mi);
  2254. const InterrogateManifest &iman = idb->get_manifest(manifest_index);
  2255. if (iman.has_getter())
  2256. {
  2257. FunctionIndex func_index = iman.get_getter();
  2258. record_function(dummy_type, func_index);
  2259. }
  2260. }
  2261. int num_elements = idb->get_num_global_elements();
  2262. for (int ei = 0; ei < num_elements; ei++)
  2263. {
  2264. printf(" Element %d\n",ei);
  2265. ElementIndex element_index = idb->get_global_element(ei);
  2266. const InterrogateElement &ielement = idb->get_element(element_index);
  2267. if (ielement.has_getter())
  2268. {
  2269. FunctionIndex func_index = ielement.get_getter();
  2270. record_function(dummy_type, func_index);
  2271. }
  2272. if (ielement.has_setter())
  2273. {
  2274. FunctionIndex func_index = ielement.get_setter();
  2275. record_function(dummy_type, func_index);
  2276. }
  2277. }
  2278. inside_python_native = false;
  2279. }
  2280. //////////////////////////////////////////////
  2281. // Function :isCppTypeLegal
  2282. //
  2283. // is the cpp object supported by by the dtool_py interface..
  2284. //////////////////////////////////////////////
  2285. bool InterfaceMakerPythonNative::isCppTypeLegal(CPPType *in_ctype)
  2286. {
  2287. if(in_ctype == NULL)
  2288. return false;
  2289. if(builder.in_ignoretype(in_ctype->get_local_name(&parser)))
  2290. {
  2291. return false;
  2292. }
  2293. //bool answer = false;
  2294. CPPType *type = TypeManager::unwrap(TypeManager::resolve_type(in_ctype));
  2295. type = TypeManager::unwrap(type);
  2296. //CPPType *type = ctype;
  2297. if(TypeManager::is_basic_string_char(type))
  2298. {
  2299. return true;
  2300. }
  2301. else if(TypeManager::is_basic_string_wchar(type))
  2302. {
  2303. return true;
  2304. }
  2305. else if(TypeManager::is_simple(type))
  2306. {
  2307. return true;
  2308. }
  2309. else if(builder.in_forcetype(in_ctype->get_local_name(&parser)))
  2310. {
  2311. return true;
  2312. }
  2313. else if(TypeManager::IsExported(type) == true)
  2314. {
  2315. return true;
  2316. }
  2317. else if(TypeManager::is_pointer_to_PyObject(in_ctype) == true)
  2318. {
  2319. return true;
  2320. }
  2321. //if(answer == false)
  2322. // printf(" -------------------- Bad Type ?? %s \n",type->get_local_name().c_str());
  2323. return false;
  2324. }
  2325. //////////////////////////////////////////////
  2326. // Function :isExportThisRun
  2327. //
  2328. //////////////////////////////////////////////
  2329. bool InterfaceMakerPythonNative::isExportThisRun(CPPType *ctype)
  2330. {
  2331. CPPType *type = TypeManager::unwrap(ctype);
  2332. if(TypeManager::IsLocal(type))
  2333. return true;
  2334. if(builder.in_forcetype(type->get_local_name(&parser)))
  2335. return true;
  2336. return false;
  2337. }
  2338. //////////////////////////////////////////////
  2339. // Function : isExportThisRun
  2340. /////////////////////////////////////////////
  2341. bool InterfaceMakerPythonNative::isExportThisRun(Function *func)
  2342. {
  2343. if(func == NULL || !isFunctionLegal(func))
  2344. return false;
  2345. Function::Remaps::const_iterator ri;
  2346. for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri)
  2347. {
  2348. FunctionRemap *remap = (*ri);
  2349. return isExportThisRun(remap->_cpptype);
  2350. }
  2351. return false;
  2352. }
  2353. //////////////////////////////////////////////
  2354. // Function : isRemapLegal
  2355. //////////////////////////////////////////////
  2356. bool InterfaceMakerPythonNative::isRemapLegal( FunctionRemap &remap)
  2357. {
  2358. // return must be legal and managable..
  2359. if(!isCppTypeLegal(remap._return_type->get_orig_type()))
  2360. {
  2361. // printf(" isRemapLegal Return Is Bad %s\n",remap._return_type->get_orig_type()->get_fully_scoped_name().c_str());
  2362. return false;
  2363. }
  2364. // ouch .. bad things will happen here .. do not even try..
  2365. if(remap._ForcedVoidReturn)
  2366. return false;
  2367. // all params must be legal
  2368. for (int pn = 0; pn < (int)remap._parameters.size(); pn++)
  2369. {
  2370. CPPType *orig_type = remap._parameters[pn]._remap->get_orig_type();
  2371. if(!isCppTypeLegal(orig_type))
  2372. return false;
  2373. }
  2374. // ok all looks ok.
  2375. return true;
  2376. }
  2377. ////////////////////////////////////////////////////////////////////////
  2378. // Function : isFunctionLegal
  2379. ////////////////////////////////////////////////////////////////////////
  2380. bool InterfaceMakerPythonNative::isFunctionLegal( Function *func)
  2381. {
  2382. Function::Remaps::const_iterator ri;
  2383. for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri)
  2384. {
  2385. FunctionRemap *remap = (*ri);
  2386. if(isRemapLegal(*remap))
  2387. {
  2388. // printf(" Function Is Marked Legal %s\n",func->_name.c_str());
  2389. return true;
  2390. }
  2391. }
  2392. // printf(" Function Is Marked Illegal %s\n",func->_name.c_str());
  2393. return false;
  2394. }
  2395. ////////////////////////////////////////////////////////////////////////
  2396. // Function : isFunctionWithThis
  2397. //
  2398. // If any rempas have a this .. this function has a this..( of self) to python..
  2399. ////////////////////////////////////////////////////////////////////////
  2400. bool InterfaceMakerPythonNative::isFunctionWithThis( Function *func)
  2401. {
  2402. Function::Remaps::const_iterator ri;
  2403. for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri)
  2404. {
  2405. FunctionRemap *remap = (*ri);
  2406. if(remap->_has_this)
  2407. return true;
  2408. }
  2409. return false;
  2410. }
  2411. ////////////////////////////////////////////////////////////////////
  2412. // Function: InterfaceMakerPython::test_assert
  2413. // Access: Protected
  2414. // Description: Outputs code to check to see if an assertion has
  2415. // failed while the C++ code was executing, and report
  2416. // this failure back to Python.
  2417. ////////////////////////////////////////////////////////////////////
  2418. void InterfaceMakerPythonNative::do_assert_init(ostream &out, int indent_level, bool constructor) const {
  2419. if (watch_asserts) {
  2420. out << "#ifndef NDEBUG\n";
  2421. indent(out, indent_level)
  2422. << "Notify *notify = Notify::ptr();\n";
  2423. indent(out, indent_level)
  2424. << "if (notify->has_assert_failed()) {\n";
  2425. indent(out, indent_level + 2)
  2426. << "PyErr_SetString(PyExc_AssertionError, notify->get_assert_error_message().c_str());\n";
  2427. indent(out, indent_level + 2)
  2428. << "notify->clear_assert_failed();\n";
  2429. if(constructor)
  2430. indent(out, indent_level + 2) << "return -1;\n";
  2431. else
  2432. indent(out, indent_level + 2) << "return (PyObject *)NULL;\n";
  2433. indent(out, indent_level)
  2434. << "}\n";
  2435. indent(out, indent_level)
  2436. << "if (PyErr_Occurred()) {\n";
  2437. if(constructor)
  2438. indent(out, indent_level + 2) << "return -1;\n";
  2439. else
  2440. indent(out, indent_level + 2) << "return (PyObject *)NULL;\n";
  2441. indent(out, indent_level)
  2442. << "}\n";
  2443. out << "#endif\n";
  2444. }
  2445. }
  2446. ////////////////////////////////////////////////////////
  2447. // Function : IsRunTimeTyped
  2448. ///////////////////////////////////////////////////////
  2449. bool InterfaceMakerPythonNative::IsRunTimeTyped(const InterrogateType &itype)
  2450. {
  2451. TypeIndex ptype_id = itype.get_outer_class();
  2452. if(ptype_id > 0)
  2453. {
  2454. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2455. InterrogateType ptype = idb->get_type(ptype_id);
  2456. return IsRunTimeTyped(ptype);
  2457. }
  2458. if(itype.get_name() == "TypedObject")
  2459. return true;
  2460. return false;
  2461. };
  2462. //////////////////////////////////////////////////////////
  2463. // Function : DoesInheritFromIsClass
  2464. //
  2465. // Helper function to check cpp class inharatience..
  2466. ///////////////////////////////////////////////////////////
  2467. bool InterfaceMakerPythonNative::DoesInheritFromIsClass( const CPPStructType * inclass, const std::string &name)
  2468. {
  2469. if(inclass == NULL)
  2470. return false;
  2471. CPPStructType::Derivation::const_iterator bi;
  2472. for (bi = inclass->_derivation.begin();
  2473. bi != inclass->_derivation.end();
  2474. ++bi)
  2475. {
  2476. const CPPStructType::Base &base = (*bi);
  2477. CPPStructType *base_type = TypeManager::resolve_type(base._base)->as_struct_type();
  2478. if(base_type != NULL)
  2479. {
  2480. std::string scoped_name = base_type->get_fully_scoped_name();
  2481. if(scoped_name == name)
  2482. return true;
  2483. if(DoesInheritFromIsClass(base_type,name) == true)
  2484. return true;
  2485. }
  2486. }
  2487. return false;
  2488. }
  2489. ////////////////////////////////////////////////////////////////////////////////////////////
  2490. // Function : HasAGetKeyFunction
  2491. //
  2492. // does the class have a supportable GetKey for hash usage..
  2493. //////////////////////////////////////////////////////////////////////////////////////////
  2494. bool InterfaceMakerPythonNative::HasAGetKeyFunction(const InterrogateType &itype_class)
  2495. {
  2496. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2497. int num_methods = itype_class.number_of_methods();
  2498. int mi;
  2499. for (mi = 0; mi < num_methods; mi++)
  2500. {
  2501. FunctionIndex func_index = itype_class.get_method(mi);
  2502. const InterrogateFunction &ifunc = idb->get_function(func_index);
  2503. if(ifunc.get_name() == "get_key")
  2504. {
  2505. if (ifunc._instances != (InterrogateFunction::Instances *)NULL)
  2506. {
  2507. InterrogateFunction::Instances::const_iterator ii;
  2508. for (ii = ifunc._instances->begin();ii != ifunc._instances->end();++ii)
  2509. {
  2510. CPPInstance *cppinst = (*ii).second;
  2511. CPPFunctionType *cppfunc = cppinst->_type->as_function_type();
  2512. if(cppfunc != NULL)
  2513. {
  2514. if(cppfunc->_parameters != NULL && cppfunc->_return_type != NULL && TypeManager::is_integer(cppfunc->_return_type))
  2515. {
  2516. if(cppfunc->_parameters->_parameters.size() == 0)
  2517. {
  2518. return true;
  2519. }
  2520. }
  2521. }
  2522. }
  2523. }
  2524. }
  2525. }
  2526. return false;
  2527. };
  2528. ////////////////////////////////////////////////////////////////////
  2529. // Function: InterfaceMakerPythonNative::NeedsAStrFunction
  2530. // Access: Private
  2531. // Description: Returns -1 if the class does not define write() (and
  2532. // therefore cannot support a __str__ function).
  2533. //
  2534. // Returns 1 if the class defines write(ostream).
  2535. //
  2536. // Returns 2 if the class defines write(ostream, int).
  2537. ////////////////////////////////////////////////////////////////////
  2538. int InterfaceMakerPythonNative::
  2539. NeedsAStrFunction(const InterrogateType &itype_class) {
  2540. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2541. int num_methods = itype_class.number_of_methods();
  2542. int mi;
  2543. for (mi = 0; mi < num_methods; ++mi) {
  2544. FunctionIndex func_index = itype_class.get_method(mi);
  2545. const InterrogateFunction &ifunc = idb->get_function(func_index);
  2546. if (ifunc.get_name() == "write") {
  2547. if (ifunc._instances != (InterrogateFunction::Instances *)NULL) {
  2548. InterrogateFunction::Instances::const_iterator ii;
  2549. for (ii = ifunc._instances->begin();
  2550. ii != ifunc._instances->end();
  2551. ++ii) {
  2552. CPPInstance *cppinst = (*ii).second;
  2553. CPPFunctionType *cppfunc = cppinst->_type->as_function_type();
  2554. if (cppfunc != NULL) {
  2555. if (cppfunc->_parameters != NULL &&
  2556. cppfunc->_return_type != NULL &&
  2557. TypeManager::is_void(cppfunc->_return_type)) {
  2558. if (cppfunc->_parameters->_parameters.size() == 1) {
  2559. CPPInstance *inst1 = cppfunc->_parameters->_parameters[0];
  2560. if (TypeManager::is_pointer_to_ostream(inst1->_type)) {
  2561. // write(ostream)
  2562. return 1;
  2563. }
  2564. }
  2565. if (cppfunc->_parameters->_parameters.size() == 2) {
  2566. CPPInstance *inst1 = cppfunc->_parameters->_parameters[0];
  2567. if (TypeManager::is_pointer_to_ostream(inst1->_type)) {
  2568. inst1 = cppfunc->_parameters->_parameters[1];
  2569. if (inst1->_initializer != NULL) {
  2570. // write(ostream, int = 0)
  2571. return 1;
  2572. }
  2573. if (TypeManager::is_integer(inst1->_type)) {
  2574. // write(ostream, int)
  2575. return 2;
  2576. }
  2577. }
  2578. }
  2579. }
  2580. }
  2581. }
  2582. }
  2583. }
  2584. }
  2585. return -1;
  2586. }
  2587. ////////////////////////////////////////////////////////////////////
  2588. // Function: InterfaceMakerPythonNative::NeedsAReprFunction
  2589. // Access: Private
  2590. // Description: Returns -1 if the class does not define output() or
  2591. // python_repr() (and therefore cannot support a
  2592. // __repr__ function).
  2593. //
  2594. // Returns 1 if the class defines python_repr(ostream, string).
  2595. //
  2596. // Returns 2 if the class defines output(ostream).
  2597. ////////////////////////////////////////////////////////////////////
  2598. int InterfaceMakerPythonNative::
  2599. NeedsAReprFunction(const InterrogateType &itype_class) {
  2600. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2601. int num_methods = itype_class.number_of_methods();
  2602. int mi;
  2603. for (mi = 0; mi < num_methods; ++mi) {
  2604. FunctionIndex func_index = itype_class.get_method(mi);
  2605. const InterrogateFunction &ifunc = idb->get_function(func_index);
  2606. if (ifunc.get_name() == "python_repr") {
  2607. if (ifunc._instances != (InterrogateFunction::Instances *)NULL) {
  2608. InterrogateFunction::Instances::const_iterator ii;
  2609. for (ii = ifunc._instances->begin();
  2610. ii != ifunc._instances->end();
  2611. ++ii) {
  2612. CPPInstance *cppinst = (*ii).second;
  2613. CPPFunctionType *cppfunc = cppinst->_type->as_function_type();
  2614. if (cppfunc != NULL) {
  2615. if (cppfunc->_parameters != NULL &&
  2616. cppfunc->_return_type != NULL &&
  2617. TypeManager::is_void(cppfunc->_return_type)) {
  2618. if (cppfunc->_parameters->_parameters.size() == 2) {
  2619. CPPInstance *inst1 = cppfunc->_parameters->_parameters[0];
  2620. if (TypeManager::is_pointer_to_ostream(inst1->_type)) {
  2621. inst1 = cppfunc->_parameters->_parameters[1];
  2622. if (TypeManager::is_string(inst1->_type) ||
  2623. TypeManager::is_char_pointer(inst1->_type)) {
  2624. // python_repr(ostream, string)
  2625. return 1;
  2626. }
  2627. }
  2628. }
  2629. }
  2630. }
  2631. }
  2632. }
  2633. }
  2634. }
  2635. for (mi = 0; mi < num_methods; ++mi) {
  2636. FunctionIndex func_index = itype_class.get_method(mi);
  2637. const InterrogateFunction &ifunc = idb->get_function(func_index);
  2638. if (ifunc.get_name() == "output") {
  2639. if (ifunc._instances != (InterrogateFunction::Instances *)NULL) {
  2640. InterrogateFunction::Instances::const_iterator ii;
  2641. for (ii = ifunc._instances->begin();
  2642. ii != ifunc._instances->end();
  2643. ++ii) {
  2644. CPPInstance *cppinst = (*ii).second;
  2645. CPPFunctionType *cppfunc = cppinst->_type->as_function_type();
  2646. if (cppfunc != NULL) {
  2647. if (cppfunc->_parameters != NULL &&
  2648. cppfunc->_return_type != NULL &&
  2649. TypeManager::is_void(cppfunc->_return_type)) {
  2650. if (cppfunc->_parameters->_parameters.size() == 1) {
  2651. CPPInstance *inst1 = cppfunc->_parameters->_parameters[0];
  2652. if (TypeManager::is_pointer_to_ostream(inst1->_type)) {
  2653. // output(ostream)
  2654. return 2;
  2655. }
  2656. }
  2657. if (cppfunc->_parameters->_parameters.size() >= 2) {
  2658. CPPInstance *inst1 = cppfunc->_parameters->_parameters[0];
  2659. if (TypeManager::is_pointer_to_ostream(inst1->_type)) {
  2660. inst1 = cppfunc->_parameters->_parameters[1];
  2661. if (inst1->_initializer != NULL) {
  2662. // output(ostream, foo = bar, ...)
  2663. return 2;
  2664. }
  2665. }
  2666. }
  2667. }
  2668. }
  2669. }
  2670. }
  2671. }
  2672. }
  2673. return -1;
  2674. }
  2675. ////////////////////////////////////////////////////////////////////
  2676. // Function: InterfaceMakerPythonNative::output_quoted
  2677. // Access: Private
  2678. // Description: Outputs the indicated string as a single quoted,
  2679. // multi-line string to the generated C++ source code.
  2680. // The output point is left on the last line of the
  2681. // string, following the trailing quotation mark.
  2682. ////////////////////////////////////////////////////////////////////
  2683. void InterfaceMakerPythonNative::
  2684. output_quoted(ostream &out, int indent_level, const std::string &str) {
  2685. indent(out, indent_level)
  2686. << '"';
  2687. std::string::const_iterator si;
  2688. for (si = str.begin(); si != str.end(); ++si) {
  2689. switch (*si) {
  2690. case '"':
  2691. case '\\':
  2692. out << '\\' << *si;
  2693. break;
  2694. case '\n':
  2695. out << "\\n\"\n";
  2696. indent(out, indent_level)
  2697. << '"';
  2698. break;
  2699. default:
  2700. if (!isprint(*si)) {
  2701. out << "\\" << oct << setw(3) << setfill('0') << (unsigned int)(*si)
  2702. << dec;
  2703. } else {
  2704. out << *si;
  2705. }
  2706. }
  2707. }
  2708. out << '"';
  2709. }