interfaceMakerPythonNative.cxx 171 KB

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