interfaceMakerPythonNative.cxx 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273
  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. const 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. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  1011. std::string ClassName = make_safe_name(obj->_itype.get_scoped_name());
  1012. std::string cClassName = obj->_itype.get_true_name();
  1013. std::string export_calss_name = classNameFromCppName(obj->_itype.get_name());
  1014. Functions::iterator fi;
  1015. out << "//********************************************************************\n";
  1016. out << "//*** Py Init Code For .. "<< ClassName <<" | " << export_calss_name <<"\n" ;
  1017. out << "//********************************************************************\n";
  1018. out << "PyMethodDef Dtool_Methods_"<< ClassName << "[]= {\n";
  1019. std::map<int , Function * > static_functions;
  1020. std::map<Function *, std::string > normal_Operator_functions;
  1021. std::map<Function *, std::pair< std::string , int> > wraped_Operator_functions;
  1022. // function Table
  1023. int x;
  1024. for (x = 0, fi = obj->_methods.begin(); fi != obj->_methods.end(); ++fi,x++)
  1025. {
  1026. Function *func = (*fi);
  1027. std::string temp0;
  1028. int temp1;
  1029. if(!GetSlotedFunctinDef( methodNameFromCppName(func,export_calss_name),temp0,temp1))
  1030. {
  1031. out << " { \"" << methodNameFromCppName(func,export_calss_name) << "\",(PyCFunction ) &"
  1032. << func->_name << ", METH_VARARGS| METH_KEYWORDS ," << func->_name << "_comment},\n";
  1033. if(!isFunctionWithThis(func))
  1034. static_functions[x] = func;
  1035. }
  1036. else
  1037. {
  1038. if(temp1 > 0)
  1039. {
  1040. wraped_Operator_functions[func] = std::pair< std::string, int>(temp0,temp1);
  1041. out << " { \"" << methodNameFromCppName(func,export_calss_name) << "\",(PyCFunction ) &"
  1042. << func->_name << ", METH_VARARGS| METH_KEYWORDS ," << func->_name << "_comment},\n";
  1043. if(!isFunctionWithThis(func))
  1044. static_functions[x] = func;
  1045. }
  1046. else
  1047. {
  1048. normal_Operator_functions[func] = temp0;
  1049. out << " { \"" << methodNameFromCppName(func,export_calss_name) << "\",(PyCFunction ) &"
  1050. << func->_name << ", METH_VARARGS| METH_KEYWORDS ," << func->_name << "_comment},\n";
  1051. if(!isFunctionWithThis(func))
  1052. static_functions[x] = func;
  1053. }
  1054. }
  1055. }
  1056. out << " { NULL, NULL }\n"
  1057. << "};\n\n";
  1058. int num_derivations = obj->_itype.number_of_derivations();
  1059. int di;
  1060. for (di = 0; di < num_derivations; di++)
  1061. {
  1062. TypeIndex d_type_Index = obj->_itype.get_derivation(di);
  1063. if(!interrogate_type_is_unpublished(d_type_Index))
  1064. {
  1065. const InterrogateType &d_itype = idb->get_type(d_type_Index);
  1066. if(isCppTypeLegal(d_itype._cpptype))
  1067. {
  1068. if(!isExportThisRun(d_itype._cpptype))
  1069. {
  1070. _external_imports.insert(make_safe_name(d_itype.get_scoped_name().c_str()));
  1071. //out << "IMPORT_THIS struct Dtool_PyTypedObject Dtool_" << make_safe_name(d_itype.get_scoped_name().c_str()) <<";\n";
  1072. }
  1073. }
  1074. }
  1075. }
  1076. std::vector< std::string > bases;
  1077. for (di = 0; di < num_derivations; di++)
  1078. {
  1079. TypeIndex d_type_Index = obj->_itype.get_derivation(di);
  1080. if(!interrogate_type_is_unpublished(d_type_Index))
  1081. {
  1082. const InterrogateType &d_itype = idb->get_type(d_type_Index);
  1083. if(isCppTypeLegal(d_itype._cpptype))
  1084. {
  1085. bases.push_back(make_safe_name(d_itype.get_scoped_name().c_str()));
  1086. }
  1087. }
  1088. }
  1089. if(bases.empty())
  1090. bases.push_back("DTOOL_SUPPER_BASE");
  1091. {
  1092. std::map<Function *, std::pair< std::string , int> >::iterator rfi; // wraped_Operator_functions;
  1093. for(rfi = wraped_Operator_functions.begin(); rfi != wraped_Operator_functions.end(); rfi++)
  1094. {
  1095. if(rfi->second.second == 1)
  1096. {
  1097. Function *func = rfi->first;
  1098. out << "//////////////////\n";
  1099. out << "// Required TO Convert the calling Conventions.. \n";
  1100. out << "// " <<ClassName<< " ..." << rfi->second.first <<" = "<< methodNameFromCppName(func,export_calss_name) <<"\n";
  1101. out << "//////////////////\n";
  1102. out << "static PyObject * " << func->_name << methodNameFromCppName(func,export_calss_name) << "( PyObject * self, PyObject * args, PyObject *dict)\n";
  1103. out << "{\n";
  1104. out << " return "<< func->_name <<"(self,args);\n";
  1105. out << "}\n\n";
  1106. }
  1107. else if(rfi->second.second == 2)
  1108. {
  1109. Function *func = rfi->first;
  1110. out << "//////////////////\n";
  1111. out << "// Required TO Convert the calling Conventions.. \n";
  1112. out << "// " <<ClassName<< " ..." << rfi->second.first <<" = "<< methodNameFromCppName(func,export_calss_name) <<"\n";
  1113. out << "//////////////////\n";
  1114. out << "static PyObject * " << func->_name << methodNameFromCppName(func,export_calss_name) << "( PyObject * self)\n";
  1115. out << "{\n";
  1116. out << " return "<< func->_name <<"(self,Py_None,Py_None);\n";
  1117. out << "}\n\n";
  1118. }
  1119. if(rfi->second.second == 3)
  1120. {
  1121. Function *func = rfi->first;
  1122. out << "//////////////////\n";
  1123. out << "// Required TO Convert the calling Conventions.. \n";
  1124. out << "// " <<ClassName<< " ..." << rfi->second.first <<" = "<< methodNameFromCppName(func,export_calss_name) <<"\n";
  1125. out << "//////////////////\n";
  1126. out << "static PyObject * " << func->_name << methodNameFromCppName(func,export_calss_name) << "( PyObject * self, PyObject * args)\n";
  1127. out << "{\n";
  1128. out << " return "<< func->_name <<"(self,args,Py_None);\n";
  1129. out << "}\n\n";
  1130. }
  1131. }
  1132. if(HasAGetKeyFunction(obj->_itype))
  1133. {
  1134. out << "//////////////////\n";
  1135. out << "// A LocalHash(getKey) Function for this type";
  1136. out << "// " <<ClassName << "\n";
  1137. out << "//////////////////\n";
  1138. out << "static long DTool_HashKey_"<<ClassName << "(PyObject * self)\n";
  1139. out << "{\n";
  1140. out << " "<<cClassName << " * local_this = NULL;\n";
  1141. out << " DTOOL_Call_ExtractThisPointerForType(self,&Dtool_"<< ClassName<<",(void **)&local_this);\n";
  1142. out << " if(local_this == NULL)\n";
  1143. out << " {\n";
  1144. out << " return -1;\n";
  1145. out << " };\n";
  1146. out << " return local_this->get_key();\n";
  1147. out << "}\n\n";
  1148. has_local_hash = true;
  1149. }
  1150. else
  1151. {
  1152. if(bases.size() == 0)
  1153. {
  1154. out << "//////////////////\n";
  1155. out << "// A LocalHash(This Pointer) Function for this type";
  1156. out << "// " <<ClassName << "\n";
  1157. out << "//////////////////\n";
  1158. out << "static long DTool_HashKey_"<<ClassName << "(PyObject * self)\n";
  1159. out << "{\n";
  1160. out << " "<<cClassName << " * local_this = NULL;\n";
  1161. out << " DTOOL_Call_ExtractThisPointerForType(self,&Dtool_"<< ClassName<<",(void **)&local_this);\n";
  1162. out << " if(local_this == NULL)\n";
  1163. out << " {\n";
  1164. out << " return -1;\n";
  1165. out << " };\n";
  1166. out << " return (long)local_this;\n";
  1167. out << "}\n\n";
  1168. has_local_hash = true;
  1169. }
  1170. }
  1171. int need_repr = NeedsAReprFunction(obj->_itype);
  1172. if(need_repr > 0)
  1173. {
  1174. out << "//////////////////\n";
  1175. out << "// A __repr__ Function\n";
  1176. out << "// " <<ClassName << "\n";
  1177. out << "//////////////////\n";
  1178. out << "static PyObject * Dtool_Repr_"<<ClassName << "(PyObject * self)\n";
  1179. out << "{\n";
  1180. out << " "<<cClassName << " * local_this = NULL;\n";
  1181. out << " DTOOL_Call_ExtractThisPointerForType(self,&Dtool_"<< ClassName<<",(void **)&local_this);\n";
  1182. out << " if(local_this != NULL)\n";
  1183. out << " {\n";
  1184. out << " ostringstream os;\n";
  1185. if (need_repr == 2) {
  1186. out << " local_this->output(os);\n";
  1187. } else {
  1188. out << " local_this->python_repr(os, \""
  1189. << classNameFromCppName(ClassName) << "\");\n";
  1190. }
  1191. out << " std::string ss = os.str();\n";
  1192. out << " return PyString_FromStringAndSize(ss.data(),ss.length());\n";
  1193. out << " };\n";
  1194. out << " return Py_BuildValue(\"\");\n";
  1195. out << "}\n";
  1196. has_local_repr = true;
  1197. }
  1198. int need_str = NeedsAStrFunction(obj->_itype);
  1199. if(need_str > 0)
  1200. {
  1201. out << "//////////////////\n";
  1202. out << "// A __str__ Function\n";
  1203. out << "// " <<ClassName << "\n";
  1204. out << "//////////////////\n";
  1205. out << "static PyObject * Dtool_Str_"<<ClassName << "(PyObject * self)\n";
  1206. out << "{\n";
  1207. out << " "<<cClassName << " * local_this = NULL;\n";
  1208. out << " DTOOL_Call_ExtractThisPointerForType(self,&Dtool_"<< ClassName<<",(void **)&local_this);\n";
  1209. out << " if(local_this != NULL)\n";
  1210. out << " {\n";
  1211. out << " ostringstream os;\n";
  1212. if(need_str == 2)
  1213. out << " local_this->write(os,0);\n";
  1214. else
  1215. out << " local_this->write(os);\n";
  1216. out << " std::string ss = os.str();\n";
  1217. out << " return PyString_FromStringAndSize(ss.data(),ss.length());\n";
  1218. out << " };\n";
  1219. out << " return Py_BuildValue(\"\");\n";
  1220. out << "}\n";
  1221. has_local_str = true;
  1222. }
  1223. }
  1224. out << "void Dtool_PyModuleClassInit_" << ClassName << "(PyObject *module)\n";
  1225. out << "{\n";
  1226. out << " static bool initdone = false;\n";
  1227. out << " if(!initdone)\n";
  1228. out << " {\n";
  1229. out << " initdone = true;\n";
  1230. // out << " memset(Dtool_"<< ClassName << ".As_PyTypeObject().tp_as_number,0,sizeof(PyNumberMethods));\n";
  1231. // out << " memset(Dtool_"<< ClassName << ".As_PyTypeObject().tp_as_mapping,0,sizeof(PyMappingMethods));\n";
  1232. // out << " static Dtool_PyTypedObject *InheritsFrom[] = {";
  1233. // add doc string
  1234. if (obj->_itype.has_comment()) {
  1235. out << "#ifndef NDEBUG\n";
  1236. out << " // Class documentation string\n";
  1237. out << " Dtool_" << ClassName
  1238. << ".As_PyTypeObject().tp_doc =\n";
  1239. output_quoted(out, 10, obj->_itype.get_comment());
  1240. out << ";\n"
  1241. << "#endif\n";
  1242. }
  1243. // add bases///
  1244. if(bases.size() > 0)
  1245. {
  1246. out << " // Dependent Objects \n";
  1247. std::string format1= "";
  1248. std::string format2= "";
  1249. for(std::vector< std::string >::iterator bi = bases.begin(); bi != bases.end(); bi++)
  1250. {
  1251. format1 += "O";
  1252. format2 += ",&Dtool_" + *bi + ".As_PyTypeObject()";
  1253. out << " Dtool_"<< make_safe_name(*bi) << "._Dtool_ClassInit(NULL);\n";
  1254. }
  1255. out << " Dtool_"<<ClassName<<".As_PyTypeObject().tp_bases = Py_BuildValue(\"(" << format1 << ")\""<< format2 << ");\n";
  1256. }
  1257. // get dictionary
  1258. out << " Dtool_" << ClassName << ".As_PyTypeObject().tp_dict = PyDict_New();\n";
  1259. out << " PyDict_SetItemString(Dtool_"<<ClassName <<".As_PyTypeObject().tp_dict,\"DtoolClassDict\",Dtool_"<<ClassName <<".As_PyTypeObject().tp_dict);\n";
  1260. // the standard call functions
  1261. std::map<Function *, std::string >::iterator ofi;
  1262. for(ofi = normal_Operator_functions.begin(); ofi != normal_Operator_functions.end(); ofi++)
  1263. {
  1264. Function *func = ofi->first;
  1265. out << " // " << ofi->second <<" = "<< methodNameFromCppName(func,export_calss_name) <<"\n";
  1266. out << " Dtool_" << ClassName <<".As_PyTypeObject()." << ofi->second <<" = &" << func->_name <<";\n";
  1267. }
  1268. // wraped functions...
  1269. {
  1270. std::map<Function *, std::pair< std::string , int> >::iterator rfi; // wraped_Operator_functions;
  1271. for(rfi = wraped_Operator_functions.begin(); rfi != wraped_Operator_functions.end(); rfi++)
  1272. {
  1273. Function *func = rfi->first;
  1274. out << " // " << rfi->second.first <<" = "<< methodNameFromCppName(func,export_calss_name) <<"\n";
  1275. out << " Dtool_" << ClassName <<".As_PyTypeObject()." << rfi->second.first <<" = &" << func->_name << methodNameFromCppName(func,export_calss_name)<<";\n";
  1276. }
  1277. }
  1278. // compare and hash work together in PY inherit behavior hmm grrr
  1279. // __hash__
  1280. if(has_local_hash == true)
  1281. {
  1282. out << " // __hash__\n";
  1283. out << " Dtool_" << ClassName <<".As_PyTypeObject().tp_hash = &DTool_HashKey_"<<ClassName <<";\n";
  1284. out << " Dtool_" << ClassName <<".As_PyTypeObject().tp_compare = &DTOOL_PyObject_Compare;\n";
  1285. }
  1286. if(has_local_repr == true)
  1287. {
  1288. out << " // __repr__\n";
  1289. out << " Dtool_" << ClassName <<".As_PyTypeObject().tp_repr = & Dtool_Repr_"<<ClassName <<";\n";
  1290. }
  1291. if(has_local_str == true)
  1292. {
  1293. out << " // __str__\n";
  1294. out << " Dtool_" << ClassName <<".As_PyTypeObject().tp_str = & Dtool_Str_"<<ClassName <<";\n";
  1295. }
  1296. else if(has_local_repr == true)
  1297. {
  1298. out << " // __str__ Repr Proxy\n";
  1299. out << " Dtool_" << ClassName <<".As_PyTypeObject().tp_str = & Dtool_Repr_"<<ClassName <<";\n";
  1300. }
  1301. int num_nested = obj->_itype.number_of_nested_types();
  1302. for (int ni = 0; ni < num_nested; ni++)
  1303. {
  1304. TypeIndex nested_index = obj->_itype.get_nested_type(ni);
  1305. Object * nested_obj = _objects[nested_index];
  1306. if(nested_obj->_itype.is_class() ||nested_obj->_itype.is_struct())
  1307. {
  1308. std::string ClassName1 = make_safe_name(nested_obj->_itype.get_scoped_name());
  1309. std::string ClassName2 = make_safe_name(nested_obj->_itype.get_name());
  1310. out << " // Nested Object "<< ClassName1 << ";\n";
  1311. out << " Dtool_" << ClassName1 << "._Dtool_ClassInit(NULL);\n";
  1312. out << " PyDict_SetItemString(Dtool_" << ClassName << ".As_PyTypeObject().tp_dict,\"" << classNameFromCppName(ClassName2) <<"\",(PyObject *)&Dtool_" << ClassName1 << ".As_PyTypeObject());\n";
  1313. }
  1314. else
  1315. {
  1316. if(nested_obj->_itype.is_enum())
  1317. {
  1318. out << " // Enum "<< nested_obj->_itype.get_scoped_name() << ";\n";
  1319. int enum_count = nested_obj->_itype.number_of_enum_values();
  1320. for(int xx = 0; xx< enum_count; xx++)
  1321. 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";
  1322. }
  1323. }
  1324. }
  1325. out << " if(PyType_Ready(&Dtool_"<< ClassName << ".As_PyTypeObject()) < 0)\n";
  1326. out << " {\n";
  1327. out << " PyErr_SetString(PyExc_TypeError, \"PyType_Ready("<< ClassName << ")\");\n";
  1328. out << " printf(\" Error In PyType_Ready" << ClassName << "\");\n";
  1329. out << " return;\n";
  1330. out << " }\n";
  1331. out << " Py_INCREF(&Dtool_"<< ClassName << ".As_PyTypeObject());\n";
  1332. out << " PyDict_SetItemString(Dtool_"<<ClassName <<".As_PyTypeObject().tp_dict,\""<<export_calss_name<< "\",&Dtool_"<<ClassName <<".As_PyObject());\n";
  1333. // static function into dictionary with bogus self..
  1334. //
  1335. std::map<int , Function * >::iterator sfi;
  1336. for(sfi= static_functions.begin(); sfi != static_functions.end(); sfi++)
  1337. {
  1338. out << " // Static Method " << methodNameFromCppName(sfi->second,export_calss_name) << "\n";
  1339. out << " PyDict_SetItemString(Dtool_" << ClassName << ".As_PyTypeObject().tp_dict,\"" ;
  1340. out << methodNameFromCppName(sfi->second,export_calss_name) ;
  1341. out << "\",PyCFunction_New(&Dtool_Methods_"<< ClassName <<"[" << sfi->first << "],&Dtool_"<< ClassName<< ".As_PyObject()));\n";
  1342. }
  1343. bool is_runtime_typed = IsPandaTypedObject(obj->_itype._cpptype->as_struct_type());
  1344. if (HasAGetClassTypeFunction(obj->_itype)) {
  1345. is_runtime_typed = true;
  1346. }
  1347. if(is_runtime_typed)
  1348. out << " RegisterRuntimeClass(&Dtool_"<<ClassName<<","<< cClassName <<"::get_class_type().get_index());\n";
  1349. else
  1350. out << " RegisterRuntimeClass(&Dtool_"<<ClassName<<",-1);\n";
  1351. out << " }\n";
  1352. out << " if(module != NULL)\n";
  1353. out << " {\n";
  1354. out << " Py_INCREF(&Dtool_"<< ClassName << ".As_PyTypeObject());\n";
  1355. out << " PyModule_AddObject(module, \""<<export_calss_name<<"\",(PyObject *)&Dtool_"<< ClassName << ".As_PyTypeObject());\n";
  1356. out << " }\n";
  1357. out << "}\n";
  1358. }
  1359. ////////////////////////////////////////////////////////////////////
  1360. // Function: InterfaceMakerPythonNative::synthesize_this_parameter
  1361. // Access: Public, Virtual
  1362. // Description: This method should be overridden and redefined to
  1363. // return true for interfaces that require the implicit
  1364. // "this" parameter, if present, to be passed as the
  1365. // first parameter to any wrapper functions.
  1366. ////////////////////////////////////////////////////////////////////
  1367. bool InterfaceMakerPythonNative::
  1368. synthesize_this_parameter() {
  1369. return true;
  1370. }
  1371. ////////////////////////////////////////////////////////////////////
  1372. // Function: InterfaceMakerPythonNative::get_wrapper_prefix
  1373. // Access: Protected, Virtual
  1374. // Description: Returns the prefix string used to generate wrapper
  1375. // function names.
  1376. ////////////////////////////////////////////////////////////////////
  1377. string InterfaceMakerPythonNative::
  1378. get_wrapper_prefix() {
  1379. return "Dtool_";
  1380. }
  1381. ////////////////////////////////////////////////////////////////////
  1382. // Function: InterfaceMakerPythonNative::get_unique_prefix
  1383. // Access: Protected, Virtual
  1384. // Description: Returns the prefix string used to generate unique
  1385. // symbolic names, which are not necessarily C-callable
  1386. // function names.
  1387. ////////////////////////////////////////////////////////////////////
  1388. string InterfaceMakerPythonNative::get_unique_prefix()
  1389. {
  1390. return "Dtool_";
  1391. }
  1392. ////////////////////////////////////////////////////////////////////
  1393. // Function: InterfaceMakerPythonNative::record_function_wrapper
  1394. // Access: Protected, Virtual
  1395. // Description: Associates the function wrapper with its function in
  1396. // the appropriate structures in the database.
  1397. ////////////////////////////////////////////////////////////////////
  1398. void InterfaceMakerPythonNative::record_function_wrapper(InterrogateFunction &ifunc, FunctionWrapperIndex wrapper_index)
  1399. {
  1400. ifunc._python_wrappers.push_back(wrapper_index);
  1401. }
  1402. ////////////////////////////////////////////////////////////////////
  1403. // Function: InterfaceMakerPythonNative::write_prototype_for
  1404. // Access: Private
  1405. // Description: Writes the prototype for the indicated function.
  1406. ////////////////////////////////////////////////////////////////////
  1407. void InterfaceMakerPythonNative::write_prototype_for(ostream &out, InterfaceMaker::Function *func)
  1408. {
  1409. std::string fname = "PyObject *"+func->_name+"(PyObject *self, PyObject *args)";
  1410. write_prototype_for_name(out,func,fname);
  1411. }
  1412. ////////////////////////////////////////////////////////////////////
  1413. ////////////////////////////////////////////////////////////////////
  1414. ////////////////////////////////////////////////////////////////////
  1415. void InterfaceMakerPythonNative::write_prototype_for_name(ostream &out, InterfaceMaker::Function *func, const std::string &function_namename)
  1416. {
  1417. Function::Remaps::const_iterator ri;
  1418. // for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri) {
  1419. // FunctionRemap *remap = (*ri);
  1420. if (!output_function_names) {
  1421. // If we're not saving the function names, don't export it from
  1422. // the library.
  1423. out << "static ";
  1424. } else {
  1425. out << "extern \"C\" ";
  1426. }
  1427. out << function_namename <<";\n";
  1428. // }
  1429. }
  1430. ////////////////////////////////////////////////////////////////////
  1431. // Function: InterfaceMakerPythonNative::write_function_for
  1432. // Access: Private
  1433. // Description: Writes the definition for a function that will call
  1434. // the indicated C++ function or method.
  1435. ////////////////////////////////////////////////////////////////////
  1436. void InterfaceMakerPythonNative::write_function_for_top(ostream &out, InterfaceMaker::Function *func, const std::string &PreProcess)
  1437. {
  1438. std::string fname = "static PyObject *"+func->_name+"(PyObject *self, PyObject *args,PyObject *kwds)";
  1439. write_function_for_name(out,func,fname,PreProcess,"");
  1440. }
  1441. ////////////////////////////////////////////////////////////////////
  1442. /// Function : write_function_for_name
  1443. //
  1444. // Wrap a complete name override function for Py.....
  1445. ////////////////////////////////////////////////////////////////////
  1446. void InterfaceMakerPythonNative::
  1447. write_function_for_name(ostream &out1, InterfaceMaker::Function *func,
  1448. const std::string &function_name,
  1449. const std::string &PreProcess,
  1450. const std::string &ClassName) {
  1451. ostringstream forward_decl;
  1452. ostringstream out;
  1453. std::map<int , std::set<FunctionRemap *> > MapSets;
  1454. std::map<int , std::set<FunctionRemap *> >::iterator mii;
  1455. std::set<FunctionRemap *>::iterator sii;
  1456. Function::Remaps::const_iterator ri;
  1457. out1 << "/******************************************************************\n" << " * Python type method wrapper for\n";
  1458. for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri) {
  1459. FunctionRemap *remap = (*ri);
  1460. if (isRemapLegal(*remap)) {
  1461. int parameter_size = remap->_parameters.size();
  1462. if(remap->_has_this && remap->_type != FunctionRemap::T_constructor)
  1463. parameter_size --;
  1464. MapSets[parameter_size].insert(remap);
  1465. out1 << " * ";
  1466. remap->write_orig_prototype(out1, 0);
  1467. out1 << "\n";
  1468. } else {
  1469. out1 << " * Rejected Remap [";
  1470. remap->write_orig_prototype(out1, 0);
  1471. out1 << "]\n";
  1472. }
  1473. }
  1474. out1 << " *******************************************************************/\n";
  1475. out << function_name << " {\n";
  1476. if (isFunctionWithThis(func)) {
  1477. out << PreProcess;
  1478. }
  1479. bool is_inplace = isInplaceFunction(func);
  1480. if (MapSets.empty()) {
  1481. return;
  1482. }
  1483. std::string FunctionComment = func->_ifunc._comment;
  1484. std::string FunctionComment1;
  1485. if (FunctionComment.size() > 2) {
  1486. FunctionComment += "\n";
  1487. }
  1488. bool constructor = false;
  1489. if (MapSets.size() > 1) {
  1490. string expected_params;
  1491. indent(out,4) << "int parameter_count = 1;\n";
  1492. indent(out,4) << "if(PyTuple_Check(args))\n";
  1493. indent(out,4) << "{\n";
  1494. indent(out,4) << " parameter_count = PyTuple_Size(args);\n" ;
  1495. indent(out,4) << " if(kwds != NULL && PyDict_Check(kwds))\n";
  1496. indent(out,4) << " parameter_count += PyDict_Size(kwds);\n" ;
  1497. indent(out,4) << "}\n";
  1498. indent(out,4) << "switch(parameter_count)\n";
  1499. indent(out,4) << "{\n";
  1500. for (mii = MapSets.begin(); mii != MapSets.end(); mii ++) {
  1501. indent(out,4) << "case(" << mii->first << "):\n";
  1502. indent(out,8) << "{\n";
  1503. write_function_forset(out,func,mii->second,expected_params,8,forward_decl,ClassName + function_name, is_inplace);
  1504. if ((*mii->second.begin())->_type == FunctionRemap::T_constructor) {
  1505. constructor = true;
  1506. }
  1507. indent(out,8)<< "}\n";
  1508. indent(out,8)<< "break;\n";
  1509. }
  1510. indent(out,4)<< "default:\n";
  1511. indent(out,8)<< "{\n";
  1512. indent(out,12)
  1513. << "PyErr_Format(PyExc_TypeError, \""
  1514. << methodNameFromCppName(func, "")
  1515. << "() takes ";
  1516. // We add one to the parameter count for "self", following the
  1517. // Python convention.
  1518. int add_self = func->_has_this ? 1 : 0;
  1519. size_t mic;
  1520. for (mic = 0, mii = MapSets.begin();
  1521. mii != MapSets.end();
  1522. ++mii, ++mic) {
  1523. if (mic == MapSets.size() - 1) {
  1524. if (mic == 1) {
  1525. out << " or ";
  1526. } else {
  1527. out << ", or ";
  1528. }
  1529. } else if (mic != 0) {
  1530. out << ", ";
  1531. }
  1532. out << mii->first + add_self;
  1533. }
  1534. out << " arguments (%d given)\", parameter_count + " << add_self << ");\n";
  1535. if (constructor)
  1536. indent(out,12) << "return -1;\n";
  1537. else
  1538. indent(out,12) << "return (PyObject *) NULL; \n";
  1539. indent(out,8)<< "}\n";
  1540. indent(out,8)<< "break;\n";
  1541. indent(out,4)<< "}\n";
  1542. out << " if(!PyErr_Occurred()) // let error pass on \n";
  1543. out << " PyErr_SetString(PyExc_TypeError, \n";
  1544. out << " \"Arguments must match one of:\\n\"\n";
  1545. output_quoted(out, 10, expected_params);
  1546. out << ");\n";
  1547. if (constructor)
  1548. indent(out,4) << "return -1;\n";
  1549. else
  1550. indent(out,4) << "return (PyObject *) NULL; \n";
  1551. if(!expected_params.empty() && FunctionComment1.empty())
  1552. FunctionComment1 += "C++ Interface:\n";
  1553. FunctionComment1 += expected_params;
  1554. } else {
  1555. string expected_params = "";
  1556. for (mii = MapSets.begin(); mii != MapSets.end(); mii ++) {
  1557. write_function_forset(out,func,mii->second,expected_params,4,forward_decl,ClassName + function_name,is_inplace);
  1558. if((*mii->second.begin())->_type == FunctionRemap::T_constructor) {
  1559. constructor = true;
  1560. }
  1561. }
  1562. out << " if(!PyErr_Occurred())\n";
  1563. out << " PyErr_SetString(PyExc_TypeError,\n";
  1564. out << " \"Must Match :\\n\"\n";
  1565. output_quoted(out, 10, expected_params);
  1566. out << ");\n";
  1567. if (constructor)
  1568. indent(out,4) << "return -1;\n";
  1569. else
  1570. indent(out,4) << "return (PyObject *) NULL; \n";
  1571. if (!expected_params.empty() && FunctionComment1.empty()) {
  1572. FunctionComment1 += "C++ Interface:\n";
  1573. }
  1574. FunctionComment1 += expected_params;
  1575. }
  1576. out << "}\n\n";
  1577. if (!FunctionComment1.empty()) {
  1578. FunctionComment = FunctionComment1 + "\n" + FunctionComment;
  1579. }
  1580. if (!constructor) {
  1581. // Write out the function doc string. We only do this if it is
  1582. // not a constructor, since we don't have a place to put the
  1583. // constructor doc string.
  1584. out << "#ifndef NDEBUG\n";
  1585. out << "static char * " << func->_name << "_comment =\n";
  1586. output_quoted(out, 4, FunctionComment);
  1587. out << ";\n";
  1588. out << "#else\n";
  1589. out << "static char * " << func->_name << "_comment = NULL;\n";
  1590. out << "#endif\n";
  1591. }
  1592. out << "\n";
  1593. out1 << forward_decl.str();
  1594. out1 << out.str();
  1595. }
  1596. ////////////////////////////////////////////////////////
  1597. // Function : GetParnetDepth
  1598. //
  1599. // Support Function used to Sort the name based overrides.. For know must be complex to simple
  1600. ////////////////////////////////////////////////////////
  1601. int GetParnetDepth(CPPType *type)
  1602. {
  1603. int answer = 0;
  1604. // printf(" %s\n",type->get_local_name().c_str());
  1605. if (TypeManager::is_basic_string_char(type)) {
  1606. } else if (TypeManager::is_basic_string_wchar(type)) {
  1607. } else if (TypeManager::is_bool(type)) {
  1608. } else if (TypeManager::is_unsigned_longlong(type)) {
  1609. } else if (TypeManager::is_longlong(type)) {
  1610. } else if (TypeManager::is_integer(type)) {
  1611. } else if (TypeManager::is_float(type)) {
  1612. } else if (TypeManager::is_char_pointer(type)) {
  1613. } else if (TypeManager::is_pointer_to_PyObject(type)) {
  1614. } else if (TypeManager::is_pointer(type) ||TypeManager::is_reference(type) || TypeManager::is_struct(type) )
  1615. {
  1616. answer ++;
  1617. int deepest = 0;
  1618. TypeIndex type_index = builder.get_type(TypeManager::unwrap(TypeManager::resolve_type(type)),false);
  1619. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  1620. const InterrogateType &itype = idb->get_type(type_index);
  1621. if(itype.is_class() ||itype.is_struct())
  1622. {
  1623. int num_derivations = itype.number_of_derivations();
  1624. for (int di = 0; di < num_derivations; di++)
  1625. {
  1626. TypeIndex d_type_Index = itype.get_derivation(di);
  1627. const InterrogateType &d_itype = idb->get_type(d_type_Index);
  1628. int this_one = GetParnetDepth(d_itype._cpptype);
  1629. if(this_one > deepest)
  1630. deepest = this_one;
  1631. }
  1632. }
  1633. answer += deepest;
  1634. // printf(" Class Name %s %d\n",itype.get_name().c_str(),answer);
  1635. }
  1636. // printf(" Class Name %s %d\n",itype.get_name().c_str(),answer);
  1637. return answer;
  1638. }
  1639. ////////////////////////////////////////////////////////
  1640. // The Core sort function for remap calling orders..
  1641. //////////////////////////////////////////////////////////
  1642. int RemapCompareLesss(FunctionRemap * in1 , FunctionRemap * in2)
  1643. {
  1644. if(in1->_parameters.size() != in2->_parameters.size())
  1645. return (in1->_parameters.size() > in2->_parameters.size());
  1646. int pcount = in1->_parameters.size();
  1647. for(int x = 0; x< pcount; x++)
  1648. {
  1649. CPPType *orig_type1 = in1->_parameters[x]._remap->get_orig_type();
  1650. CPPType *orig_type2 = in2->_parameters[x]._remap->get_orig_type();
  1651. int pd1 = GetParnetDepth(orig_type1);
  1652. int pd2 = GetParnetDepth(orig_type2);
  1653. if(pd1 != pd2)
  1654. return pd1> pd2;
  1655. }
  1656. // ok maybe something to do with return strength..
  1657. return false;
  1658. }
  1659. //////////////////////////////////////////////////////////
  1660. // Convience for the sort behavior..
  1661. ///////////////////////////////////////////////////////////
  1662. std::vector< FunctionRemap * > SortFunctionSet(std::set< FunctionRemap *> &remaps)
  1663. {
  1664. std::vector< FunctionRemap * > out;
  1665. for(std::set< FunctionRemap *>::iterator ii = remaps.begin(); ii!= remaps.end(); ii++)
  1666. out.push_back(*ii);
  1667. std::sort(out.begin(), out.end(), RemapCompareLesss);
  1668. return out;
  1669. }
  1670. ///////////////////////////////////////////////////////////
  1671. // Function : write_function_forset
  1672. //
  1673. // A set is defined as all remaps that have the same number of paramaters..
  1674. ///////////////////////////////////////////////////////////
  1675. void InterfaceMakerPythonNative::write_function_forset(ostream &out, InterfaceMaker::Function *func,
  1676. std::set< FunctionRemap *> &remapsin, string &expected_params, int indent_level,ostream &forward_decl, const std::string &functionname, bool is_inplace)
  1677. {
  1678. if(remapsin.size() > 1)
  1679. {
  1680. // printf("---------------------------- Start Sort ----- %s , %s\n",func->_name.c_str(),functionname.c_str());
  1681. std::vector<FunctionRemap *> remaps = SortFunctionSet(remapsin);
  1682. std::vector<FunctionRemap *>::iterator sii;
  1683. for(sii = remaps.begin(); sii != remaps.end(); sii ++)
  1684. {
  1685. FunctionRemap *remap = (*sii);
  1686. if(isRemapLegal(*remap))
  1687. {
  1688. if (remap->_has_this && !remap->_const_method) {
  1689. // If it's a non-const method, we only allow a
  1690. // non-const this.
  1691. indent(out,indent_level)
  1692. << "if (!((Dtool_PyInstDef *)self)->_is_const) {\n";
  1693. } else {
  1694. indent(out, indent_level)
  1695. << "{\n";
  1696. }
  1697. indent(out,indent_level) << " // -2 " ;
  1698. remap->write_orig_prototype(out, 0); out << "\n" ;
  1699. write_function_instance(out, func, remap,expected_params,indent_level+4,false,forward_decl, func->_name, is_inplace);
  1700. indent(out,indent_level+4)<< "PyErr_Clear(); \n";
  1701. indent(out,indent_level)<< "}\n\n";
  1702. }
  1703. }
  1704. }
  1705. else
  1706. {
  1707. std::set<FunctionRemap *>::iterator sii;
  1708. for(sii = remapsin.begin(); sii != remapsin.end(); sii ++)
  1709. {
  1710. FunctionRemap *remap = (*sii);
  1711. if(isRemapLegal(*remap)) {
  1712. if (remap->_has_this && !remap->_const_method) {
  1713. // If it's a non-const method, we only allow a
  1714. // non-const this.
  1715. indent(out, indent_level)
  1716. << "if (!((Dtool_PyInstDef *)self)->_is_const) {\n";
  1717. } else {
  1718. indent(out, indent_level)
  1719. << "{\n";
  1720. }
  1721. indent(out,indent_level + 2)
  1722. << "// 1-" ;remap->write_orig_prototype(out, 0); out << "\n" ;
  1723. write_function_instance(out, func, remap,expected_params,indent_level+4,true,forward_decl, func->_name, is_inplace);
  1724. if (remap->_has_this && !remap->_const_method) {
  1725. indent(out, indent_level)
  1726. << "} else {\n";
  1727. indent(out, indent_level + 2)
  1728. << "PyErr_SetString(PyExc_TypeError,\n";
  1729. string class_name = remap->_cpptype->get_simple_name();
  1730. indent(out, indent_level + 2)
  1731. << " \"Cannot call "
  1732. << classNameFromCppName(class_name)
  1733. << "." << methodNameFromCppName(func, class_name)
  1734. << "() on a const object.\");\n";
  1735. indent(out, indent_level + 2)
  1736. << "return (PyObject *) NULL;\n";
  1737. indent(out,indent_level)
  1738. << "}\n\n";
  1739. } else {
  1740. indent(out,indent_level)
  1741. << "}\n\n";
  1742. }
  1743. }
  1744. }
  1745. }
  1746. }
  1747. ////////////////////////////////////////////////////////////////////
  1748. // Function: InterfaceMakerPythonNative::write_function_instance
  1749. // Access: Private
  1750. // Description: Writes out the particular function that handles a
  1751. // single instance of an overloaded function.
  1752. ////////////////////////////////////////////////////////////////////
  1753. void InterfaceMakerPythonNative::write_function_instance(ostream &out, InterfaceMaker::Function *func1,
  1754. FunctionRemap *remap, string &expected_params, int indent_level, bool errors_fatal, ostream &ForwardDeclrs, const std::string &functionnamestr, bool is_inplace)
  1755. {
  1756. string format_specifiers;
  1757. std::string keyword_list;
  1758. string parameter_list;
  1759. string container;
  1760. vector_string pexprs;
  1761. string extra_convert;
  1762. string extra_param_check;
  1763. string extra_cleanup;
  1764. string pname_for_pyobject;
  1765. bool is_constructor = false;
  1766. if (remap->_type == FunctionRemap::T_constructor) {
  1767. is_constructor = true;
  1768. }
  1769. // Make one pass through the parameter list. We will output a
  1770. // one-line temporary variable definition for each parameter, while
  1771. // simultaneously building the ParseTuple() function call and also
  1772. // the parameter expression list for call_function().
  1773. expected_params += methodNameFromCppName(func1, "");
  1774. expected_params += "(";
  1775. int pn;
  1776. for (pn = 0; pn < (int)remap->_parameters.size(); pn++) {
  1777. if(pn > 0) {
  1778. expected_params += ", ";
  1779. }
  1780. CPPType *orig_type = remap->_parameters[pn]._remap->get_orig_type();
  1781. CPPType *type = remap->_parameters[pn]._remap->get_new_type();
  1782. string param_name = remap->get_parameter_name(pn);
  1783. // This is the string to convert our local variable to the
  1784. // appropriate C++ type. Normally this is just a cast.
  1785. string pexpr_string =
  1786. "(" + type->get_local_name(&parser) + ")" + param_name;
  1787. if (!remap->_has_this || pn != 0) {
  1788. keyword_list += "\""+remap->_parameters[pn]._name + "\", ";
  1789. }
  1790. if (remap->_parameters[pn]._remap->new_type_is_atomic_string()) {
  1791. if (TypeManager::is_char_pointer(orig_type)) {
  1792. indent(out,indent_level)<< "char *" << param_name;
  1793. format_specifiers += "s";
  1794. parameter_list += ", &" + param_name;
  1795. } else if (TypeManager::is_wstring(orig_type)) {
  1796. indent(out,indent_level) << "PyUnicodeObject *" << param_name << "\n";
  1797. format_specifiers += "U";
  1798. parameter_list += ", &" + param_name;
  1799. extra_convert += " int " + param_name + "_len = PyUnicode_GetSize((PyObject *)" + param_name + "); wchar_t *" + param_name + "_str = new wchar_t[" + param_name + "_len]; PyUnicode_AsWideChar(" + param_name + ", " + param_name + "_str, " + param_name + "_len);";
  1800. pexpr_string = "basic_string<wchar_t>((wchar_t *)" +
  1801. param_name + "_str, " +
  1802. param_name + "_len)";
  1803. extra_cleanup += " delete[] " + param_name + "_str;";
  1804. } else {
  1805. indent(out,indent_level) << "char *" << param_name
  1806. << "_str; int " << param_name << "_len";
  1807. format_specifiers += "s#";
  1808. parameter_list += ", &" + param_name
  1809. + "_str, &" + param_name + "_len";
  1810. pexpr_string = "basic_string<char>(" +
  1811. param_name + "_str, " +
  1812. param_name + "_len)";
  1813. }
  1814. expected_params += "string";
  1815. } else if (TypeManager::is_bool(type)) {
  1816. indent(out,indent_level) << "PyObject *" << param_name;
  1817. format_specifiers += "O";
  1818. parameter_list += ", &" + param_name;
  1819. pexpr_string = "(PyObject_IsTrue(" + param_name + ")!=0)";
  1820. expected_params += "bool";
  1821. pname_for_pyobject += param_name;
  1822. } else if (TypeManager::is_unsigned_longlong(type)) {
  1823. indent(out,indent_level) << "PyObject *" << param_name;
  1824. format_specifiers += "O";
  1825. parameter_list += ", &" + param_name;
  1826. extra_convert += " PyObject *" + param_name + "_long = PyNumber_Long(" + param_name + ");";
  1827. extra_param_check += "|| (" + param_name + "_long == NULL)";
  1828. pexpr_string = "PyLong_AsUnsignedLongLong(" + param_name + "_long)";
  1829. extra_cleanup += " Py_XDECREF(" + param_name + "_long);";
  1830. expected_params += "unsigned long long";
  1831. pname_for_pyobject += param_name;
  1832. } else if (TypeManager::is_longlong(type)) {
  1833. indent(out,indent_level) << "PyObject *" << param_name;
  1834. format_specifiers += "O";
  1835. parameter_list += ", &" + param_name;
  1836. extra_convert += " PyObject *" + param_name + "_long = PyNumber_Long(" + param_name + ");";
  1837. extra_param_check += "|| (" + param_name + "_long == NULL)";
  1838. pexpr_string = "PyLong_AsLongLong(" + param_name + "_long)";
  1839. extra_cleanup += " Py_XDECREF(" + param_name + "_long);";
  1840. expected_params += "long long";
  1841. pname_for_pyobject += param_name;
  1842. } else if (TypeManager::is_unsigned_integer(type)) {
  1843. indent(out,indent_level) << "PyObject *" << param_name;
  1844. format_specifiers += "O";
  1845. parameter_list += ", &" + param_name;
  1846. extra_convert += " PyObject *" + param_name + "_uint = PyNumber_Long(" + param_name + ");";
  1847. extra_param_check += "|| (" + param_name + "_uint == NULL)";
  1848. pexpr_string = "PyLong_AsUnsignedLong(" + param_name + "_uint)";
  1849. extra_cleanup += " Py_XDECREF(" + param_name + "_uint);";
  1850. expected_params += "unsigned int";
  1851. pname_for_pyobject += param_name;
  1852. } else if (TypeManager::is_integer(type)) {
  1853. indent(out,indent_level) << "int " << param_name;
  1854. format_specifiers += "i";
  1855. parameter_list += ", &" + param_name;
  1856. expected_params += "int";
  1857. } else if (TypeManager::is_float(type)) {
  1858. indent(out,indent_level) << "double " << param_name;
  1859. format_specifiers += "d";
  1860. parameter_list += ", &" + param_name;
  1861. expected_params += "float";
  1862. } else if (TypeManager::is_char_pointer(type)) {
  1863. indent(out,indent_level) << "char *" << param_name;
  1864. format_specifiers += "s";
  1865. parameter_list += ", &" + param_name;
  1866. expected_params += "string";
  1867. } else if (TypeManager::is_pointer_to_PyObject(type)) {
  1868. indent(out,indent_level) << "PyObject *" << param_name;
  1869. format_specifiers += "O";
  1870. parameter_list += ", &" + param_name;
  1871. pexpr_string = param_name;
  1872. pname_for_pyobject += param_name;
  1873. expected_params += "any";
  1874. } else if (TypeManager::is_pointer(type)) {
  1875. CPPType *obj_type = TypeManager::unwrap(TypeManager::resolve_type(type));
  1876. bool const_ok = !TypeManager::is_non_const_pointer_or_ref(orig_type);
  1877. if (const_ok) {
  1878. expected_params += "const ";
  1879. } else {
  1880. expected_params += "non-const ";
  1881. }
  1882. expected_params += classNameFromCppName(obj_type->get_simple_name());
  1883. if (!remap->_has_this || pn != 0) {
  1884. indent(out, indent_level)
  1885. << "PyObject *" << param_name;
  1886. format_specifiers += "O";
  1887. parameter_list += ", &" + param_name;
  1888. pname_for_pyobject += param_name;
  1889. TypeIndex p_type_index = builder.get_type(obj_type,false);
  1890. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  1891. const InterrogateType &p_itype = idb->get_type(p_type_index);
  1892. //make_safe_name(itype.get_scoped_name())
  1893. extra_convert += p_itype.get_scoped_name()+" *" + param_name + "_this = ("+p_itype.get_scoped_name()+" *)";
  1894. // need to a forward scope for this class..
  1895. if(!isExportThisRun(p_itype._cpptype)) {
  1896. _external_imports.insert(make_safe_name(p_itype.get_scoped_name()));
  1897. //ForwardDeclrs << "IMPORT_THIS struct Dtool_PyTypedObject Dtool_" << make_safe_name(p_itype.get_scoped_name()) << ";\n";
  1898. }
  1899. string class_name;
  1900. string method_prefix;
  1901. if (remap->_cpptype) {
  1902. class_name = remap->_cpptype->get_simple_name();
  1903. method_prefix = classNameFromCppName(class_name) + string(".");
  1904. }
  1905. ostringstream str;
  1906. str << "DTOOL_Call_GetPointerThisClass(" << param_name
  1907. << ", &Dtool_" << make_safe_name(p_itype.get_scoped_name())
  1908. << ", " << pn << ", \""
  1909. << method_prefix << methodNameFromCppName(func1, class_name)
  1910. << "\", " << const_ok << ");\n";
  1911. extra_convert += str.str();
  1912. extra_param_check += "|| (" + param_name + "_this == NULL)";
  1913. pexpr_string = param_name + "_this";
  1914. }
  1915. } else {
  1916. // Ignore a parameter.
  1917. indent(out,indent_level) << "PyObject *" << param_name;
  1918. format_specifiers += "O";
  1919. parameter_list += ", &" + param_name;
  1920. expected_params += "any";
  1921. pname_for_pyobject += param_name;
  1922. }
  1923. if (remap->_parameters[pn]._has_name) {
  1924. expected_params += " " + remap->_parameters[pn]._name;
  1925. }
  1926. if (remap->_has_this && pn == 0) {
  1927. container = "local_this";
  1928. } else {
  1929. out << ";\n";
  1930. }
  1931. pexprs.push_back(pexpr_string);
  1932. }
  1933. expected_params += ")\n";
  1934. // If we got what claimed to be a unary operator, don't check for
  1935. // parameters, since we won't be getting any anyway.
  1936. if (!func1->_ifunc.is_unary_op()) {
  1937. std::string format_specifiers1 = format_specifiers + ":" +
  1938. methodNameFromCppName(func1, "");
  1939. indent(out,indent_level)
  1940. << "static char * key_word_list[] = {" << keyword_list << "NULL};\n";
  1941. if (remap->_parameters.size() == 1 ||
  1942. (remap->_has_this && remap->_parameters.size() == 2)) {
  1943. indent(out,indent_level)
  1944. << "// Special Case to Make operator work \n";
  1945. indent(out,indent_level)
  1946. << "if(PyTuple_Check(args) || (kwds != NULL && PyDict_Check(kwds)))\n";
  1947. indent(out,indent_level)
  1948. << " (PyArg_ParseTupleAndKeywords(args,kwds, \""
  1949. << format_specifiers1 << "\", key_word_list" << parameter_list
  1950. << "));\n";
  1951. indent(out,indent_level)
  1952. << "else\n";
  1953. indent(out,indent_level)
  1954. << " (PyArg_Parse(args, \"" << format_specifiers1 << "\""
  1955. << parameter_list << "));\n";
  1956. indent(out,indent_level)
  1957. << "if(!PyErr_Occurred())\n";
  1958. } else {
  1959. indent(out,indent_level)
  1960. << "if (PyArg_ParseTupleAndKeywords(args,kwds, \""
  1961. << format_specifiers1 << "\", key_word_list"
  1962. << parameter_list << "))\n";
  1963. }
  1964. }
  1965. indent(out,indent_level) << "{\n";
  1966. if (!extra_convert.empty()) {
  1967. indent(out,indent_level+4)
  1968. << extra_convert << "\n";
  1969. }
  1970. int extra_indent_level = indent_level+4;
  1971. if (!extra_param_check.empty()) {
  1972. indent(out,extra_indent_level)
  1973. << "if (!(" << extra_param_check.substr(3) << "))\n";
  1974. indent(out,extra_indent_level)
  1975. <<"{\n";
  1976. extra_indent_level+=4;
  1977. }
  1978. if (!remap->_void_return &&
  1979. remap->_return_type->new_type_is_atomic_string()) {
  1980. // Treat strings as a special case. We don't want to format the
  1981. // return expression.
  1982. if (remap->_blocking) {
  1983. // With SIMPLE_THREADS, it's important that we never release the
  1984. // interpreter lock.
  1985. out << "#if defined(HAVE_THREADS) && !defined(SIMPLE_THREADS)\n";
  1986. indent(out, extra_indent_level)
  1987. << "PyThreadState *_save;\n";
  1988. indent(out, extra_indent_level)
  1989. << "Py_UNBLOCK_THREADS\n";
  1990. out << "#endif // HAVE_THREADS && !SIMPLE_THREADS\n";
  1991. }
  1992. if (track_interpreter) {
  1993. indent(out,extra_indent_level) << "in_interpreter = 0;\n";
  1994. }
  1995. string tt;
  1996. string return_expr = remap->call_function(out, extra_indent_level, false, container, pexprs);
  1997. CPPType *type = remap->_return_type->get_orig_type();
  1998. indent(out,extra_indent_level);
  1999. type->output_instance(out, "return_value", &parser);
  2000. // type->output_instance(tt, "return_value", &parser);
  2001. out << " = " << return_expr << ";\n";
  2002. if (track_interpreter) {
  2003. indent(out,extra_indent_level) << "in_interpreter = 1;\n";
  2004. }
  2005. if (remap->_blocking) {
  2006. out << "#if defined(HAVE_THREADS) && !defined(SIMPLE_THREADS)\n";
  2007. indent(out, extra_indent_level)
  2008. << "Py_BLOCK_THREADS\n";
  2009. out << "#endif // HAVE_THREADS && !SIMPLE_THREADS\n";
  2010. }
  2011. if (!extra_cleanup.empty()) {
  2012. indent(out,extra_indent_level) << extra_cleanup << "\n";
  2013. }
  2014. return_expr = manage_return_value(out, 4, remap, "return_value");
  2015. do_assert_init(out, extra_indent_level,is_constructor);
  2016. pack_return_value(out, extra_indent_level, remap, return_expr,ForwardDeclrs,is_inplace);
  2017. } else {
  2018. if (remap->_blocking) {
  2019. out << "#if defined(HAVE_THREADS) && !defined(SIMPLE_THREADS)\n";
  2020. indent(out, extra_indent_level)
  2021. << "PyThreadState *_save;\n";
  2022. indent(out, extra_indent_level)
  2023. << "Py_UNBLOCK_THREADS\n";
  2024. out << "#endif // HAVE_THREADS && !SIMPLE_THREADS\n";
  2025. }
  2026. if (track_interpreter) {
  2027. indent(out,extra_indent_level) << "in_interpreter = 0;\n";
  2028. }
  2029. string return_expr = remap->call_function(out, extra_indent_level, true, container, pexprs);
  2030. if (return_expr.empty()) {
  2031. if (track_interpreter) {
  2032. indent(out,extra_indent_level) << "in_interpreter = 1;\n";
  2033. }
  2034. if (remap->_blocking) {
  2035. out << "#if defined(HAVE_THREADS) && !defined(SIMPLE_THREADS)\n";
  2036. indent(out, extra_indent_level)
  2037. << "Py_BLOCK_THREADS\n";
  2038. out << "#endif // HAVE_THREADS && !SIMPLE_THREADS\n";
  2039. }
  2040. if (!extra_cleanup.empty()) {
  2041. indent(out,extra_indent_level) << extra_cleanup << "\n";
  2042. }
  2043. do_assert_init(out, extra_indent_level,is_constructor);
  2044. indent(out,extra_indent_level) << "return Py_BuildValue(\"\");\n";
  2045. } else {
  2046. CPPType *type = remap->_return_type->get_temporary_type();
  2047. if(!is_inplace) {
  2048. indent(out,extra_indent_level);
  2049. type->output_instance(out, "return_value", &parser);
  2050. out << " = " << return_expr << ";\n";
  2051. }
  2052. if (track_interpreter) {
  2053. indent(out,extra_indent_level) << "in_interpreter = 1;\n";
  2054. }
  2055. if (remap->_blocking) {
  2056. out << "#if defined(HAVE_THREADS) && !defined(SIMPLE_THREADS)\n";
  2057. indent(out, extra_indent_level)
  2058. << "Py_BLOCK_THREADS\n";
  2059. out << "#endif // HAVE_THREADS && !SIMPLE_THREADS\n";
  2060. }
  2061. if (!extra_cleanup.empty()) {
  2062. indent(out,extra_indent_level) << extra_cleanup << "\n";
  2063. }
  2064. return_expr = manage_return_value(out, extra_indent_level, remap, "return_value");
  2065. do_assert_init(out, extra_indent_level,is_constructor);
  2066. pack_return_value(out, extra_indent_level, remap, remap->_return_type->temporary_to_return(return_expr),ForwardDeclrs,is_inplace);
  2067. }
  2068. }
  2069. if (!extra_param_check.empty()) {
  2070. extra_indent_level-=4;
  2071. indent(out,extra_indent_level)<< "}\n";
  2072. }
  2073. indent(out,indent_level) << "}\n";
  2074. }
  2075. ////////////////////////////////////////////////////////////////////
  2076. // Function: InterfaceMakerPythonNative::pack_return_value
  2077. // Access: Private
  2078. // Description: Outputs a command to pack the indicated expression,
  2079. // of the return_type type, as a Python return value.
  2080. ////////////////////////////////////////////////////////////////////
  2081. void InterfaceMakerPythonNative::pack_return_value(ostream &out, int indent_level,
  2082. FunctionRemap *remap, string return_expr, ostream &ForwardDeclrs, bool is_inplace)
  2083. {
  2084. CPPType *orig_type = remap->_return_type->get_orig_type();
  2085. CPPType *type = remap->_return_type->get_new_type();
  2086. if (remap->_return_type->new_type_is_atomic_string()) {
  2087. if (TypeManager::is_char_pointer(orig_type)) {
  2088. indent(out, indent_level)
  2089. << "return PyString_FromString(" << return_expr << ");\n";
  2090. } else if (TypeManager::is_wstring(orig_type)) {
  2091. indent(out, indent_level)
  2092. << "return PyUnicode_FromWideChar("
  2093. << return_expr << ".data(), (int)" << return_expr << ".length());\n";
  2094. } else {
  2095. indent(out, indent_level)
  2096. << "return PyString_FromStringAndSize("
  2097. << return_expr << ".data(), (int)" << return_expr << ".length());\n";
  2098. }
  2099. } else if (TypeManager::is_unsigned_longlong(type)) {
  2100. indent(out, indent_level)
  2101. << "return PyLong_FromUnsignedLongLong(" << return_expr << ");\n";
  2102. } else if (TypeManager::is_longlong(type)) {
  2103. indent(out, indent_level)
  2104. << "return PyLong_FromLongLong(" << return_expr << ");\n";
  2105. } else if(TypeManager::is_unsigned_integer(type)){
  2106. indent(out, indent_level)
  2107. << "return PyLong_FromUnsignedLong(" << return_expr << ");\n";
  2108. }else if (TypeManager::is_integer(type)) {
  2109. indent(out, indent_level)
  2110. << "return PyInt_FromLong(" << return_expr << ");\n";
  2111. } else if (TypeManager::is_float(type)) {
  2112. indent(out, indent_level)
  2113. << "return PyFloat_FromDouble(" << return_expr << ");\n";
  2114. } else if (TypeManager::is_char_pointer(type)) {
  2115. indent(out, indent_level)
  2116. << "return PyString_FromString(" << return_expr << ");\n";
  2117. }
  2118. else if (TypeManager::is_pointer_to_PyObject(type))
  2119. {
  2120. indent(out, indent_level)
  2121. << "return "<< return_expr << ";\n";
  2122. }
  2123. else if (TypeManager::is_pointer(type))
  2124. {
  2125. string const_flag;
  2126. if (TypeManager::is_const_pointer_to_anything(type)) {
  2127. const_flag = "true";
  2128. } else {
  2129. const_flag = "false";
  2130. }
  2131. if (TypeManager::is_struct(orig_type) || TypeManager::is_ref_to_anything(orig_type))
  2132. {
  2133. if( TypeManager::is_ref_to_anything(orig_type))
  2134. {
  2135. TypeIndex type_index = builder.get_type(TypeManager::unwrap(TypeManager::resolve_type(type)),false);
  2136. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2137. const InterrogateType &itype = idb->get_type(type_index);
  2138. std::string ows_memory_flag("true");
  2139. if(remap->_return_value_needs_management)
  2140. ows_memory_flag = "true";
  2141. else
  2142. ows_memory_flag = "false";
  2143. if(!isExportThisRun(itype._cpptype))
  2144. {
  2145. _external_imports.insert(make_safe_name(itype.get_scoped_name()));
  2146. //ForwardDeclrs << "IMPORT_THIS struct Dtool_PyTypedObject Dtool_" << make_safe_name(itype.get_scoped_name()) << ";\n";
  2147. }
  2148. WriteReturnInstance(out,indent_level,return_expr,ows_memory_flag,itype.get_scoped_name(),itype._cpptype,is_inplace, const_flag);
  2149. }
  2150. else
  2151. {
  2152. if (remap->_type == FunctionRemap::T_constructor )
  2153. {
  2154. // should only reach this in the INIT function a a Class .. IE the PY exists before the CPP object
  2155. // this is were we type to returned a class/struct.. ie CPP TYpe
  2156. TypeIndex type_index = builder.get_type(TypeManager::unwrap(TypeManager::resolve_type(orig_type)),false);
  2157. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2158. const InterrogateType &itype = idb->get_type(type_index);
  2159. indent(out, indent_level)
  2160. <<"return DTool_PyInit_Finalize(self, " << return_expr <<",&"<<CLASS_PREFEX << make_safe_name(itype.get_scoped_name()) << ",true,false);\n";
  2161. }
  2162. else
  2163. {
  2164. std::string ows_memory_flag("true");
  2165. if(remap->_return_value_needs_management)
  2166. ows_memory_flag = "true";
  2167. else
  2168. ows_memory_flag = "false";
  2169. if(remap->_manage_reference_count)
  2170. {
  2171. TypeIndex type_index = builder.get_type(TypeManager::unwrap(TypeManager::resolve_type(type)),false);
  2172. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2173. const InterrogateType &itype = idb->get_type(type_index);
  2174. if(!isExportThisRun(itype._cpptype))
  2175. {
  2176. _external_imports.insert(make_safe_name(itype.get_scoped_name()));
  2177. //ForwardDeclrs << "IMPORT_THIS struct Dtool_PyTypedObject Dtool_" << make_safe_name(itype.get_scoped_name()) << ";\n";
  2178. }
  2179. // ForwardDeclrs << "extern \"C\" struct Dtool_PyTypedObject Dtool_" << make_safe_name(itype.get_scoped_name()) << ";\n";
  2180. WriteReturnInstance(out,indent_level,return_expr,ows_memory_flag,itype.get_scoped_name(),itype._cpptype,is_inplace, const_flag);
  2181. }
  2182. else
  2183. {
  2184. TypeIndex type_index = builder.get_type(TypeManager::unwrap(TypeManager::resolve_type(orig_type)),false);
  2185. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2186. const InterrogateType &itype = idb->get_type(type_index);
  2187. if(!isExportThisRun(itype._cpptype))
  2188. {
  2189. _external_imports.insert(make_safe_name(itype.get_scoped_name()));
  2190. //ForwardDeclrs << "IMPORT_THIS struct Dtool_PyTypedObject Dtool_" << make_safe_name(itype.get_scoped_name()) << ";\n";
  2191. }
  2192. // ForwardDeclrs << "extern \"C\" struct Dtool_PyTypedObject Dtool_" << make_safe_name(itype.get_scoped_name()) << ";\n";
  2193. WriteReturnInstance(out,indent_level,return_expr,ows_memory_flag,itype.get_scoped_name(),itype._cpptype,is_inplace, const_flag);
  2194. }
  2195. }
  2196. }
  2197. }
  2198. else if( TypeManager::is_struct(orig_type->as_pointer_type()->_pointing_at) )
  2199. {
  2200. TypeIndex type_index = builder.get_type(TypeManager::unwrap(TypeManager::resolve_type(orig_type)),false);
  2201. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2202. const InterrogateType &itype = idb->get_type(type_index);
  2203. std::string ows_memory_flag("true");
  2204. if(remap->_return_value_needs_management)
  2205. ows_memory_flag ="true";
  2206. else
  2207. ows_memory_flag = "false";
  2208. if(!isExportThisRun(itype._cpptype))
  2209. {
  2210. _external_imports.insert(make_safe_name(itype.get_scoped_name()));
  2211. //ForwardDeclrs << "IMPORT_THIS struct Dtool_PyTypedObject Dtool_" << make_safe_name(itype.get_scoped_name()) << ";\n";
  2212. }
  2213. // ForwardDeclrs << "extern \"C\" struct Dtool_PyTypedObject Dtool_" << make_safe_name(itype.get_scoped_name()) << ";\n";
  2214. WriteReturnInstance(out,indent_level,return_expr,ows_memory_flag,itype.get_scoped_name(),itype._cpptype,is_inplace, const_flag);
  2215. }
  2216. else
  2217. {
  2218. indent(out, indent_level)<<" Shouln Never Reach This InterfaceMakerPythonNative::pack_return_value";
  2219. //<< "return PyInt_FromLong((int)" << return_expr << ");\n";
  2220. }
  2221. } else {
  2222. // Return None.
  2223. indent(out, indent_level)
  2224. << "return Py_BuildValue(\"\");\n";
  2225. }
  2226. }
  2227. ////////////////////////////////////////////////////////////////////
  2228. ////////////////////////////////////////////////////////////////////
  2229. // Function: InterfaceMakerPythonNative::record_object
  2230. // Access: Protected
  2231. // Description: Records the indicated type, which may be a struct
  2232. // type, along with all of its associated methods, if
  2233. // any.
  2234. ////////////////////////////////////////////////////////////////////
  2235. InterfaceMaker::Object *InterfaceMakerPythonNative::record_object(TypeIndex type_index)
  2236. {
  2237. if (type_index == 0) {
  2238. return (Object *)NULL;
  2239. }
  2240. Objects::iterator oi = _objects.find(type_index);
  2241. if (oi != _objects.end()) {
  2242. return (*oi).second;
  2243. }
  2244. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2245. const InterrogateType &itype = idb->get_type(type_index);
  2246. if(!isCppTypeLegal(itype._cpptype))
  2247. {
  2248. return (Object *)NULL;
  2249. }
  2250. Object *object = new Object(itype);
  2251. bool inserted = _objects.insert(Objects::value_type(type_index, object)).second;
  2252. assert(inserted);
  2253. Function *function;
  2254. int num_constructors = itype.number_of_constructors();
  2255. for (int ci = 0; ci < num_constructors; ci++)
  2256. {
  2257. function = record_function(itype, itype.get_constructor(ci));
  2258. if(isFunctionLegal(function))
  2259. object->_constructors.push_back(function);
  2260. }
  2261. int num_methods = itype.number_of_methods();
  2262. int mi;
  2263. for (mi = 0; mi < num_methods; mi++)
  2264. {
  2265. function = record_function(itype, itype.get_method(mi));
  2266. if(isFunctionLegal(function))
  2267. object->_methods.push_back(function);
  2268. }
  2269. int num_casts = itype.number_of_casts();
  2270. for (mi = 0; mi < num_casts; mi++)
  2271. {
  2272. function = record_function(itype, itype.get_cast(mi));
  2273. if(isFunctionLegal(function))
  2274. object->_methods.push_back(function);
  2275. }
  2276. int num_derivations = itype.number_of_derivations();
  2277. for (int di = 0; di < num_derivations; di++)
  2278. {
  2279. TypeIndex d_type_Index = itype.get_derivation(di);
  2280. idb->get_type(d_type_Index);
  2281. if(!interrogate_type_is_unpublished(d_type_Index))
  2282. {
  2283. if (itype.derivation_has_upcast(di))
  2284. {
  2285. function = record_function(itype, itype.derivation_get_upcast(di));
  2286. if(isFunctionLegal(function))
  2287. object->_methods.push_back(function);
  2288. }
  2289. if (itype.derivation_has_downcast(di))
  2290. {
  2291. // Downcasts are methods of the base class, not the child class.
  2292. TypeIndex base_type_index = itype.get_derivation(di);
  2293. const InterrogateType &base_type = idb->get_type(base_type_index);
  2294. function = record_function(base_type, itype.derivation_get_downcast(di));
  2295. if(isFunctionLegal(function))
  2296. {
  2297. Object * pobject = record_object(base_type_index);
  2298. if(pobject != NULL)
  2299. pobject->_methods.push_back(function);
  2300. }
  2301. }
  2302. }
  2303. }
  2304. int num_elements = itype.number_of_elements();
  2305. for (int ei = 0; ei < num_elements; ei++)
  2306. {
  2307. ElementIndex element_index = itype.get_element(ei);
  2308. const InterrogateElement &ielement = idb->get_element(element_index);
  2309. if (ielement.has_getter())
  2310. {
  2311. FunctionIndex func_index = ielement.get_getter();
  2312. record_function(itype, func_index);
  2313. }
  2314. if (ielement.has_setter())
  2315. {
  2316. FunctionIndex func_index = ielement.get_setter();
  2317. record_function(itype, func_index);
  2318. }
  2319. }
  2320. int num_nested = itype.number_of_nested_types();
  2321. for (int ni = 0; ni < num_nested; ni++)
  2322. {
  2323. TypeIndex nested_index = itype.get_nested_type(ni);
  2324. record_object(nested_index);
  2325. }
  2326. return object;
  2327. }
  2328. ////////////////////////////////////////////////////////////////////
  2329. // Function: InterfaceMaker::generate_wrappers
  2330. // Access: Public, Virtual
  2331. // Description: Walks through the set of functions in the database
  2332. // and generates wrappers for each function, storing
  2333. // these in the database. No actual code should be
  2334. // output yet; this just updates the database with the
  2335. // wrapper information.
  2336. ////////////////////////////////////////////////////////////////////
  2337. void InterfaceMakerPythonNative::generate_wrappers()
  2338. {
  2339. inside_python_native = true;
  2340. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2341. // We use a while loop rather than a simple for loop, because we
  2342. // might increase the number of types recursively during the
  2343. // traversal.
  2344. int ti = 0;
  2345. while (ti < idb->get_num_all_types())
  2346. {
  2347. TypeIndex type_index = idb->get_all_type(ti);
  2348. record_object(type_index);
  2349. ++ti;
  2350. }
  2351. int num_global_elements = idb->get_num_global_elements();
  2352. for (int gi = 0; gi < num_global_elements; ++gi) {
  2353. printf(" Global Type = %d",gi);
  2354. TypeIndex type_index = idb->get_global_element(gi);
  2355. record_object(type_index);
  2356. }
  2357. int num_functions = idb->get_num_global_functions();
  2358. for (int fi = 0; fi < num_functions; fi++)
  2359. {
  2360. FunctionIndex func_index = idb->get_global_function(fi);
  2361. record_function(dummy_type, func_index);
  2362. }
  2363. int num_manifests = idb->get_num_global_manifests();
  2364. for (int mi = 0; mi < num_manifests; mi++)
  2365. {
  2366. ManifestIndex manifest_index = idb->get_global_manifest(mi);
  2367. const InterrogateManifest &iman = idb->get_manifest(manifest_index);
  2368. if (iman.has_getter())
  2369. {
  2370. FunctionIndex func_index = iman.get_getter();
  2371. record_function(dummy_type, func_index);
  2372. }
  2373. }
  2374. int num_elements = idb->get_num_global_elements();
  2375. for (int ei = 0; ei < num_elements; ei++)
  2376. {
  2377. printf(" Element %d\n",ei);
  2378. ElementIndex element_index = idb->get_global_element(ei);
  2379. const InterrogateElement &ielement = idb->get_element(element_index);
  2380. if (ielement.has_getter())
  2381. {
  2382. FunctionIndex func_index = ielement.get_getter();
  2383. record_function(dummy_type, func_index);
  2384. }
  2385. if (ielement.has_setter())
  2386. {
  2387. FunctionIndex func_index = ielement.get_setter();
  2388. record_function(dummy_type, func_index);
  2389. }
  2390. }
  2391. inside_python_native = false;
  2392. }
  2393. //////////////////////////////////////////////
  2394. // Function :isCppTypeLegal
  2395. //
  2396. // is the cpp object supported by by the dtool_py interface..
  2397. //////////////////////////////////////////////
  2398. bool InterfaceMakerPythonNative::isCppTypeLegal(CPPType *in_ctype)
  2399. {
  2400. if(in_ctype == NULL)
  2401. return false;
  2402. if(builder.in_ignoretype(in_ctype->get_local_name(&parser)))
  2403. {
  2404. return false;
  2405. }
  2406. //bool answer = false;
  2407. CPPType *type = TypeManager::unwrap(TypeManager::resolve_type(in_ctype));
  2408. type = TypeManager::unwrap(type);
  2409. //CPPType *type = ctype;
  2410. if(TypeManager::is_basic_string_char(type))
  2411. {
  2412. return true;
  2413. }
  2414. else if(TypeManager::is_basic_string_wchar(type))
  2415. {
  2416. return true;
  2417. }
  2418. else if(TypeManager::is_simple(type))
  2419. {
  2420. return true;
  2421. }
  2422. else if(builder.in_forcetype(in_ctype->get_local_name(&parser)))
  2423. {
  2424. return true;
  2425. }
  2426. else if(TypeManager::IsExported(type) == true)
  2427. {
  2428. return true;
  2429. }
  2430. else if(TypeManager::is_pointer_to_PyObject(in_ctype) == true)
  2431. {
  2432. return true;
  2433. }
  2434. //if(answer == false)
  2435. // printf(" -------------------- Bad Type ?? %s \n",type->get_local_name().c_str());
  2436. return false;
  2437. }
  2438. //////////////////////////////////////////////
  2439. // Function :isExportThisRun
  2440. //
  2441. //////////////////////////////////////////////
  2442. bool InterfaceMakerPythonNative::isExportThisRun(CPPType *ctype)
  2443. {
  2444. CPPType *type = TypeManager::unwrap(ctype);
  2445. if(TypeManager::IsLocal(type))
  2446. return true;
  2447. if(builder.in_forcetype(type->get_local_name(&parser)))
  2448. return true;
  2449. return false;
  2450. }
  2451. //////////////////////////////////////////////
  2452. // Function : isExportThisRun
  2453. /////////////////////////////////////////////
  2454. bool InterfaceMakerPythonNative::isExportThisRun(Function *func)
  2455. {
  2456. if(func == NULL || !isFunctionLegal(func))
  2457. return false;
  2458. Function::Remaps::const_iterator ri;
  2459. for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri)
  2460. {
  2461. FunctionRemap *remap = (*ri);
  2462. return isExportThisRun(remap->_cpptype);
  2463. }
  2464. return false;
  2465. }
  2466. //////////////////////////////////////////////
  2467. // Function : isRemapLegal
  2468. //////////////////////////////////////////////
  2469. bool InterfaceMakerPythonNative::isRemapLegal( FunctionRemap &remap)
  2470. {
  2471. // return must be legal and managable..
  2472. if(!isCppTypeLegal(remap._return_type->get_orig_type()))
  2473. {
  2474. // printf(" isRemapLegal Return Is Bad %s\n",remap._return_type->get_orig_type()->get_fully_scoped_name().c_str());
  2475. return false;
  2476. }
  2477. // ouch .. bad things will happen here .. do not even try..
  2478. if(remap._ForcedVoidReturn)
  2479. return false;
  2480. // all params must be legal
  2481. for (int pn = 0; pn < (int)remap._parameters.size(); pn++)
  2482. {
  2483. CPPType *orig_type = remap._parameters[pn]._remap->get_orig_type();
  2484. if(!isCppTypeLegal(orig_type))
  2485. return false;
  2486. }
  2487. // ok all looks ok.
  2488. return true;
  2489. }
  2490. ////////////////////////////////////////////////////////////////////////
  2491. // Function : isFunctionLegal
  2492. ////////////////////////////////////////////////////////////////////////
  2493. bool InterfaceMakerPythonNative::isFunctionLegal( Function *func)
  2494. {
  2495. Function::Remaps::const_iterator ri;
  2496. for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri)
  2497. {
  2498. FunctionRemap *remap = (*ri);
  2499. if(isRemapLegal(*remap))
  2500. {
  2501. // printf(" Function Is Marked Legal %s\n",func->_name.c_str());
  2502. return true;
  2503. }
  2504. }
  2505. // printf(" Function Is Marked Illegal %s\n",func->_name.c_str());
  2506. return false;
  2507. }
  2508. ////////////////////////////////////////////////////////////////////////
  2509. // Function : isFunctionWithThis
  2510. //
  2511. // If any rempas have a this .. this function has a this..( of self) to python..
  2512. ////////////////////////////////////////////////////////////////////////
  2513. bool InterfaceMakerPythonNative::isFunctionWithThis( Function *func)
  2514. {
  2515. Function::Remaps::const_iterator ri;
  2516. for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri)
  2517. {
  2518. FunctionRemap *remap = (*ri);
  2519. if(remap->_has_this)
  2520. return true;
  2521. }
  2522. return false;
  2523. }
  2524. ////////////////////////////////////////////////////////////////////
  2525. // Function: InterfaceMakerPython::test_assert
  2526. // Access: Protected
  2527. // Description: Outputs code to check to see if an assertion has
  2528. // failed while the C++ code was executing, and report
  2529. // this failure back to Python.
  2530. ////////////////////////////////////////////////////////////////////
  2531. void InterfaceMakerPythonNative::do_assert_init(ostream &out, int indent_level, bool constructor) const {
  2532. if (watch_asserts) {
  2533. out << "#ifndef NDEBUG\n";
  2534. indent(out, indent_level)
  2535. << "Notify *notify = Notify::ptr();\n";
  2536. indent(out, indent_level)
  2537. << "if (notify->has_assert_failed()) {\n";
  2538. indent(out, indent_level + 2)
  2539. << "PyErr_SetString(PyExc_AssertionError, notify->get_assert_error_message().c_str());\n";
  2540. indent(out, indent_level + 2)
  2541. << "notify->clear_assert_failed();\n";
  2542. if(constructor)
  2543. indent(out, indent_level + 2) << "return -1;\n";
  2544. else
  2545. indent(out, indent_level + 2) << "return (PyObject *)NULL;\n";
  2546. indent(out, indent_level)
  2547. << "}\n";
  2548. indent(out, indent_level)
  2549. << "if (PyErr_Occurred()) {\n";
  2550. if(constructor)
  2551. indent(out, indent_level + 2) << "return -1;\n";
  2552. else
  2553. indent(out, indent_level + 2) << "return (PyObject *)NULL;\n";
  2554. indent(out, indent_level)
  2555. << "}\n";
  2556. out << "#endif\n";
  2557. }
  2558. }
  2559. ////////////////////////////////////////////////////////
  2560. // Function : IsRunTimeTyped
  2561. ///////////////////////////////////////////////////////
  2562. bool InterfaceMakerPythonNative::IsRunTimeTyped(const InterrogateType &itype)
  2563. {
  2564. TypeIndex ptype_id = itype.get_outer_class();
  2565. if(ptype_id > 0)
  2566. {
  2567. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2568. InterrogateType ptype = idb->get_type(ptype_id);
  2569. return IsRunTimeTyped(ptype);
  2570. }
  2571. if(itype.get_name() == "TypedObject")
  2572. return true;
  2573. return false;
  2574. };
  2575. //////////////////////////////////////////////////////////
  2576. // Function : DoesInheritFromIsClass
  2577. //
  2578. // Helper function to check cpp class inharatience..
  2579. ///////////////////////////////////////////////////////////
  2580. bool InterfaceMakerPythonNative::DoesInheritFromIsClass( const CPPStructType * inclass, const std::string &name)
  2581. {
  2582. if(inclass == NULL)
  2583. return false;
  2584. std::string scoped_name = inclass->get_fully_scoped_name();
  2585. if(scoped_name == name)
  2586. return true;
  2587. CPPStructType::Derivation::const_iterator bi;
  2588. for (bi = inclass->_derivation.begin();
  2589. bi != inclass->_derivation.end();
  2590. ++bi)
  2591. {
  2592. const CPPStructType::Base &base = (*bi);
  2593. CPPStructType *base_type = TypeManager::resolve_type(base._base)->as_struct_type();
  2594. if(base_type != NULL)
  2595. {
  2596. if(DoesInheritFromIsClass(base_type,name) == true)
  2597. return true;
  2598. }
  2599. }
  2600. return false;
  2601. }
  2602. ////////////////////////////////////////////////////////////////////////////////////////////
  2603. // Function : HasAGetKeyFunction
  2604. //
  2605. // does the class have a supportable GetKey for hash usage..
  2606. //////////////////////////////////////////////////////////////////////////////////////////
  2607. bool InterfaceMakerPythonNative::HasAGetKeyFunction(const InterrogateType &itype_class)
  2608. {
  2609. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2610. int num_methods = itype_class.number_of_methods();
  2611. int mi;
  2612. for (mi = 0; mi < num_methods; mi++)
  2613. {
  2614. FunctionIndex func_index = itype_class.get_method(mi);
  2615. const InterrogateFunction &ifunc = idb->get_function(func_index);
  2616. if(ifunc.get_name() == "get_key")
  2617. {
  2618. if (ifunc._instances != (InterrogateFunction::Instances *)NULL)
  2619. {
  2620. InterrogateFunction::Instances::const_iterator ii;
  2621. for (ii = ifunc._instances->begin();ii != ifunc._instances->end();++ii)
  2622. {
  2623. CPPInstance *cppinst = (*ii).second;
  2624. CPPFunctionType *cppfunc = cppinst->_type->as_function_type();
  2625. if(cppfunc != NULL)
  2626. {
  2627. if(cppfunc->_parameters != NULL && cppfunc->_return_type != NULL && TypeManager::is_integer(cppfunc->_return_type))
  2628. {
  2629. if(cppfunc->_parameters->_parameters.size() == 0)
  2630. {
  2631. return true;
  2632. }
  2633. }
  2634. }
  2635. }
  2636. }
  2637. }
  2638. }
  2639. return false;
  2640. };
  2641. ////////////////////////////////////////////////////////////////////////////////////////////
  2642. // Function : HasAGetClassTypeFunction
  2643. //
  2644. // does the class have a supportable GetClassType which returns a TypeHandle.
  2645. //////////////////////////////////////////////////////////////////////////////////////////
  2646. bool InterfaceMakerPythonNative::
  2647. HasAGetClassTypeFunction(const InterrogateType &itype_class) {
  2648. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2649. int num_methods = itype_class.number_of_methods();
  2650. int mi;
  2651. for (mi = 0; mi < num_methods; mi++) {
  2652. FunctionIndex func_index = itype_class.get_method(mi);
  2653. const InterrogateFunction &ifunc = idb->get_function(func_index);
  2654. if (ifunc.get_name() == "get_class_type") {
  2655. if (ifunc._instances != (InterrogateFunction::Instances *)NULL) {
  2656. InterrogateFunction::Instances::const_iterator ii;
  2657. for (ii = ifunc._instances->begin();ii != ifunc._instances->end();++ii) {
  2658. CPPInstance *cppinst = (*ii).second;
  2659. CPPFunctionType *cppfunc = cppinst->_type->as_function_type();
  2660. if (cppfunc != NULL && cppfunc->_return_type != NULL &&
  2661. cppfunc->_parameters != NULL) {
  2662. CPPType *ret_type = TypeManager::unwrap(cppfunc->_return_type);
  2663. if (TypeManager::is_struct(ret_type) &&
  2664. ret_type->get_simple_name() == "TypeHandle") {
  2665. if(cppfunc->_parameters->_parameters.size() == 0) {
  2666. return true;
  2667. }
  2668. }
  2669. }
  2670. }
  2671. }
  2672. }
  2673. }
  2674. return false;
  2675. }
  2676. ////////////////////////////////////////////////////////////////////
  2677. // Function: InterfaceMakerPythonNative::NeedsAStrFunction
  2678. // Access: Private
  2679. // Description: Returns -1 if the class does not define write() (and
  2680. // therefore cannot support a __str__ function).
  2681. //
  2682. // Returns 1 if the class defines write(ostream).
  2683. //
  2684. // Returns 2 if the class defines write(ostream, int).
  2685. ////////////////////////////////////////////////////////////////////
  2686. int InterfaceMakerPythonNative::
  2687. NeedsAStrFunction(const InterrogateType &itype_class) {
  2688. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2689. int num_methods = itype_class.number_of_methods();
  2690. int mi;
  2691. for (mi = 0; mi < num_methods; ++mi) {
  2692. FunctionIndex func_index = itype_class.get_method(mi);
  2693. const InterrogateFunction &ifunc = idb->get_function(func_index);
  2694. if (ifunc.get_name() == "write") {
  2695. if (ifunc._instances != (InterrogateFunction::Instances *)NULL) {
  2696. InterrogateFunction::Instances::const_iterator ii;
  2697. for (ii = ifunc._instances->begin();
  2698. ii != ifunc._instances->end();
  2699. ++ii) {
  2700. CPPInstance *cppinst = (*ii).second;
  2701. CPPFunctionType *cppfunc = cppinst->_type->as_function_type();
  2702. if (cppfunc != NULL) {
  2703. if (cppfunc->_parameters != NULL &&
  2704. cppfunc->_return_type != NULL &&
  2705. TypeManager::is_void(cppfunc->_return_type)) {
  2706. if (cppfunc->_parameters->_parameters.size() == 1) {
  2707. CPPInstance *inst1 = cppfunc->_parameters->_parameters[0];
  2708. if (TypeManager::is_pointer_to_ostream(inst1->_type)) {
  2709. // write(ostream)
  2710. return 1;
  2711. }
  2712. }
  2713. if (cppfunc->_parameters->_parameters.size() == 2) {
  2714. CPPInstance *inst1 = cppfunc->_parameters->_parameters[0];
  2715. if (TypeManager::is_pointer_to_ostream(inst1->_type)) {
  2716. inst1 = cppfunc->_parameters->_parameters[1];
  2717. if (inst1->_initializer != NULL) {
  2718. // write(ostream, int = 0)
  2719. return 1;
  2720. }
  2721. if (TypeManager::is_integer(inst1->_type)) {
  2722. // write(ostream, int)
  2723. return 2;
  2724. }
  2725. }
  2726. }
  2727. }
  2728. }
  2729. }
  2730. }
  2731. }
  2732. }
  2733. return -1;
  2734. }
  2735. ////////////////////////////////////////////////////////////////////
  2736. // Function: InterfaceMakerPythonNative::NeedsAReprFunction
  2737. // Access: Private
  2738. // Description: Returns -1 if the class does not define output() or
  2739. // python_repr() (and therefore cannot support a
  2740. // __repr__ function).
  2741. //
  2742. // Returns 1 if the class defines python_repr(ostream, string).
  2743. //
  2744. // Returns 2 if the class defines output(ostream).
  2745. ////////////////////////////////////////////////////////////////////
  2746. int InterfaceMakerPythonNative::
  2747. NeedsAReprFunction(const InterrogateType &itype_class) {
  2748. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  2749. int num_methods = itype_class.number_of_methods();
  2750. int mi;
  2751. for (mi = 0; mi < num_methods; ++mi) {
  2752. FunctionIndex func_index = itype_class.get_method(mi);
  2753. const InterrogateFunction &ifunc = idb->get_function(func_index);
  2754. if (ifunc.get_name() == "python_repr") {
  2755. if (ifunc._instances != (InterrogateFunction::Instances *)NULL) {
  2756. InterrogateFunction::Instances::const_iterator ii;
  2757. for (ii = ifunc._instances->begin();
  2758. ii != ifunc._instances->end();
  2759. ++ii) {
  2760. CPPInstance *cppinst = (*ii).second;
  2761. CPPFunctionType *cppfunc = cppinst->_type->as_function_type();
  2762. if (cppfunc != NULL) {
  2763. if (cppfunc->_parameters != NULL &&
  2764. cppfunc->_return_type != NULL &&
  2765. TypeManager::is_void(cppfunc->_return_type)) {
  2766. if (cppfunc->_parameters->_parameters.size() == 2) {
  2767. CPPInstance *inst1 = cppfunc->_parameters->_parameters[0];
  2768. if (TypeManager::is_pointer_to_ostream(inst1->_type)) {
  2769. inst1 = cppfunc->_parameters->_parameters[1];
  2770. if (TypeManager::is_string(inst1->_type) ||
  2771. TypeManager::is_char_pointer(inst1->_type)) {
  2772. // python_repr(ostream, string)
  2773. return 1;
  2774. }
  2775. }
  2776. }
  2777. }
  2778. }
  2779. }
  2780. }
  2781. }
  2782. }
  2783. for (mi = 0; mi < num_methods; ++mi) {
  2784. FunctionIndex func_index = itype_class.get_method(mi);
  2785. const InterrogateFunction &ifunc = idb->get_function(func_index);
  2786. if (ifunc.get_name() == "output") {
  2787. if (ifunc._instances != (InterrogateFunction::Instances *)NULL) {
  2788. InterrogateFunction::Instances::const_iterator ii;
  2789. for (ii = ifunc._instances->begin();
  2790. ii != ifunc._instances->end();
  2791. ++ii) {
  2792. CPPInstance *cppinst = (*ii).second;
  2793. CPPFunctionType *cppfunc = cppinst->_type->as_function_type();
  2794. if (cppfunc != NULL) {
  2795. if (cppfunc->_parameters != NULL &&
  2796. cppfunc->_return_type != NULL &&
  2797. TypeManager::is_void(cppfunc->_return_type)) {
  2798. if (cppfunc->_parameters->_parameters.size() == 1) {
  2799. CPPInstance *inst1 = cppfunc->_parameters->_parameters[0];
  2800. if (TypeManager::is_pointer_to_ostream(inst1->_type)) {
  2801. // output(ostream)
  2802. return 2;
  2803. }
  2804. }
  2805. if (cppfunc->_parameters->_parameters.size() >= 2) {
  2806. CPPInstance *inst1 = cppfunc->_parameters->_parameters[0];
  2807. if (TypeManager::is_pointer_to_ostream(inst1->_type)) {
  2808. inst1 = cppfunc->_parameters->_parameters[1];
  2809. if (inst1->_initializer != NULL) {
  2810. // output(ostream, foo = bar, ...)
  2811. return 2;
  2812. }
  2813. }
  2814. }
  2815. }
  2816. }
  2817. }
  2818. }
  2819. }
  2820. }
  2821. return -1;
  2822. }
  2823. ////////////////////////////////////////////////////////////////////
  2824. // Function: InterfaceMakerPythonNative::output_quoted
  2825. // Access: Private
  2826. // Description: Outputs the indicated string as a single quoted,
  2827. // multi-line string to the generated C++ source code.
  2828. // The output point is left on the last line of the
  2829. // string, following the trailing quotation mark.
  2830. ////////////////////////////////////////////////////////////////////
  2831. void InterfaceMakerPythonNative::
  2832. output_quoted(ostream &out, int indent_level, const std::string &str) {
  2833. indent(out, indent_level)
  2834. << '"';
  2835. std::string::const_iterator si;
  2836. for (si = str.begin(); si != str.end(); ++si) {
  2837. switch (*si) {
  2838. case '"':
  2839. case '\\':
  2840. out << '\\' << *si;
  2841. break;
  2842. case '\n':
  2843. out << "\\n\"\n";
  2844. indent(out, indent_level)
  2845. << '"';
  2846. break;
  2847. default:
  2848. if (!isprint(*si)) {
  2849. out << "\\" << oct << setw(3) << setfill('0') << (unsigned int)(*si)
  2850. << dec;
  2851. } else {
  2852. out << *si;
  2853. }
  2854. }
  2855. }
  2856. out << '"';
  2857. }