interfaceMakerPythonNative.cxx 141 KB

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