interfaceMakerPythonNative.cxx 137 KB

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