interfaceMakerPythonNative.cxx 166 KB

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