interfaceMakerPythonNative.cxx 152 KB

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