interfaceMakerPythonNative.cxx 117 KB

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