interfaceMakerPythonNative.cxx 134 KB

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