interfaceMakerPythonNative.cxx 257 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948
  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 "pnotify.h" // For nout
  19. #include "interrogateDatabase.h"
  20. #include "interrogateType.h"
  21. #include "interrogateFunction.h"
  22. #include "cppArrayType.h"
  23. #include "cppConstType.h"
  24. #include "cppEnumType.h"
  25. #include "cppFunctionType.h"
  26. #include "cppFunctionGroup.h"
  27. #include "cppPointerType.h"
  28. #include "cppTypeDeclaration.h"
  29. #include "cppTypedefType.h"
  30. #include "cppSimpleType.h"
  31. #include "cppStructType.h"
  32. #include "cppExpression.h"
  33. #include "vector"
  34. #include "cppParameterList.h"
  35. #include "algorithm"
  36. #include "lineStream.h"
  37. #include <set>
  38. #include <map>
  39. extern bool inside_python_native;
  40. extern InterrogateType dummy_type;
  41. extern std::string EXPORT_IMPORT_PREFIX;
  42. #define CLASS_PREFIX "Dtool_"
  43. /////////////////////////////////////////////////////////
  44. // Name Remapper...
  45. // Snagged from ffi py code....
  46. /////////////////////////////////////////////////////////
  47. struct RenameSet {
  48. const char *_from;
  49. const char *_to;
  50. int function_type;
  51. };
  52. ///////////////////////////////////////////////////////////////////////////////////////
  53. RenameSet methodRenameDictionary[] = {
  54. { "operator ==" , "__eq__", 0 },
  55. { "operator !=" , "__ne__", 0 },
  56. { "operator << " , "__lshift__", 0 },
  57. { "operator >>" , "__rshift__", 0 },
  58. { "operator <" , "__lt__", 0 },
  59. { "operator >" , "__gt__", 0 },
  60. { "operator <=" , "__le__", 0 },
  61. { "operator >=" , "__ge__", 0 },
  62. { "operator =" , "assign", 0 },
  63. { "operator ()" , "__call__", 0 },
  64. { "operator []" , "__getitem__", 0 },
  65. { "operator ++unary", "increment", 0 },
  66. { "operator ++" , "increment", 0 },
  67. { "operator --unary", "decrement", 0 },
  68. { "operator --" , "decrement", 0 },
  69. { "operator ^" , "__xor__", 0 },
  70. { "operator %" , "__mod__", 0 },
  71. { "operator !" , "logicalNot", 0 },
  72. { "operator ~unary", "__invert__", 0 },
  73. { "operator &" , "__and__", 0 },
  74. { "operator &&" , "logicalAnd", 0 },
  75. { "operator |" , "__or__", 0 },
  76. { "operator ||" , "logicalOr", 0 },
  77. { "operator +" , "__add__", 0 },
  78. { "operator -" , "__sub__", 0 },
  79. { "operator -unary", "__neg__", 0 },
  80. { "operator *" , "__mul__", 0 },
  81. { "operator /" , "__div__", 0 },
  82. { "operator +=" , "__iadd__", 1 },
  83. { "operator -=" , "__isub__", 1 },
  84. { "operator *=" , "__imul__", 1 },
  85. { "operator /=" , "__idiv__", 1 },
  86. { "operator ," , "concatenate", 0 },
  87. { "operator |=" , "__ior__", 1 },
  88. { "operator &=" , "__iand__", 1 },
  89. { "operator ^=" , "__ixor__", 1 },
  90. { "operator ~=" , "bitwiseNotEqual", 0 },
  91. { "operator ->" , "dereference", 0 },
  92. { "operator <<=" , "__ilshift__", 1 },
  93. { "operator >>=" , "__irshift__", 1 },
  94. { "operator typecast bool", "__nonzero__", 0 },
  95. { "__nonzero__" , "__nonzero__", 0 },
  96. { "__reduce__" , "__reduce__", 0 },
  97. { "__reduce_persist__", "__reduce_persist__", 0 },
  98. { "__copy__" , "__copy__", 0 },
  99. { "__deepcopy__" , "__deepcopy__", 0 },
  100. { "print" , "Cprint", 0 },
  101. { "CInterval.set_t", "_priv__cSetT", 0 },
  102. { NULL, NULL, -1 }
  103. };
  104. ///////////////////////////////////////////////////////////////////////////////////////
  105. RenameSet classRenameDictionary[] = {
  106. // No longer used, now empty.
  107. { NULL, NULL, -1 }
  108. };
  109. ///////////////////////////////////////////////////////////////////////////////////////
  110. ///////////////////////////////////////////////////////////////////////////////////////
  111. const char *pythonKeywords[] = {
  112. "and",
  113. "as",
  114. "assert",
  115. "break",
  116. "class",
  117. "continue",
  118. "def",
  119. "del",
  120. "elif",
  121. "else",
  122. "except",
  123. "exec",
  124. "finally",
  125. "for",
  126. "from",
  127. "global",
  128. "if",
  129. "import",
  130. "in",
  131. "is",
  132. "lambda",
  133. "nonlocal",
  134. "not",
  135. "or",
  136. "pass",
  137. "print",
  138. "raise",
  139. "return",
  140. "try",
  141. "while",
  142. "with",
  143. "yield",
  144. NULL
  145. };
  146. ///////////////////////////////////////////////////////////////////////////////////////
  147. std::string
  148. checkKeyword(std::string &cppName) {
  149. for (int x = 0; pythonKeywords[x] != NULL; x++) {
  150. if (cppName == pythonKeywords[x]) {
  151. return std::string("_") + cppName;
  152. }
  153. }
  154. return cppName;
  155. }
  156. ///////////////////////////////////////////////////////////////////////////////////////
  157. ///////////////////////////////////////////////////////////////////////////////////////
  158. std::string
  159. classNameFromCppName(const std::string &cppName, bool mangle) {
  160. if (!mangle_names) {
  161. mangle = false;
  162. }
  163. //# initialize to empty string
  164. std::string className = "";
  165. //# These are the characters we want to strip out of the name
  166. const std::string badChars("!@#$%^&*()<>,.-=+~{}? ");
  167. bool nextCap = false;
  168. bool nextUscore = false;
  169. bool firstChar = true && mangle;
  170. for (std::string::const_iterator chr = cppName.begin();
  171. chr != cppName.end(); ++chr) {
  172. if ((*chr == '_' || *chr == ' ') && mangle) {
  173. nextCap = true;
  174. } else if (badChars.find(*chr) != std::string::npos) {
  175. nextUscore = !mangle;
  176. } else if (nextCap || firstChar) {
  177. className += toupper(*chr);
  178. nextCap = false;
  179. firstChar = false;
  180. } else if (nextUscore) {
  181. className += '_';
  182. nextUscore = false;
  183. className += *chr;
  184. } else {
  185. className += *chr;
  186. }
  187. }
  188. for (int x = 0; classRenameDictionary[x]._from != NULL; x++) {
  189. if (cppName == classRenameDictionary[x]._from) {
  190. className = classRenameDictionary[x]._to;
  191. }
  192. }
  193. if (className.empty()) {
  194. std::string text = "** ERROR ** Renaming class: " + cppName + " to empty string";
  195. printf("%s", text.c_str());
  196. }
  197. className = checkKeyword(className);
  198. //# FFIConstants.notify.debug('Renaming class: ' + cppName + ' to: ' + className)
  199. return className;
  200. }
  201. ///////////////////////////////////////////////////////////////////////////////////////
  202. ///////////////////////////////////////////////////////////////////////////////////////
  203. std::string
  204. methodNameFromCppName(const std::string &cppName, const std::string &className, bool mangle) {
  205. if (!mangle_names) {
  206. mangle = false;
  207. }
  208. std::string origName = cppName;
  209. if (origName.substr(0, 6) == "__py__") {
  210. // By convention, a leading prefix of "__py__" is stripped. This
  211. // indicates a Python-specific variant of a particular method.
  212. origName = origName.substr(6);
  213. }
  214. std::string methodName;
  215. const std::string badChars("!@#$%^&*()<>,.-=+~{}? ");
  216. bool nextCap = false;
  217. for (std::string::const_iterator chr = origName.begin();
  218. chr != origName.end();
  219. chr++) {
  220. if ((*chr == '_' || *chr == ' ') && mangle) {
  221. nextCap = true;
  222. } else if (badChars.find(*chr) != std::string::npos) {
  223. if (!mangle) {
  224. methodName += '_';
  225. }
  226. } else if (nextCap) {
  227. methodName += toupper(*chr);
  228. nextCap = false;
  229. } else {
  230. methodName += *chr;
  231. }
  232. }
  233. for (int x = 0; methodRenameDictionary[x]._from != NULL; x++) {
  234. if (origName == methodRenameDictionary[x]._from) {
  235. methodName = methodRenameDictionary[x]._to;
  236. }
  237. }
  238. if (className.size() > 0) {
  239. string lookup_name = className + '.' + cppName;
  240. for (int x = 0; classRenameDictionary[x]._from != NULL; x++) {
  241. if (lookup_name == methodRenameDictionary[x]._from) {
  242. methodName = methodRenameDictionary[x]._to;
  243. }
  244. }
  245. }
  246. // # Mangle names that happen to be python keywords so they are not anymore
  247. methodName = checkKeyword(methodName);
  248. return methodName;
  249. }
  250. std::string methodNameFromCppName(InterfaceMaker::Function *func, const std::string &className, bool mangle) {
  251. std::string cppName = func->_ifunc.get_name();
  252. if (func->_ifunc.is_unary_op()) {
  253. cppName += "unary";
  254. }
  255. return methodNameFromCppName(cppName, className, mangle);
  256. }
  257. std::string methodNameFromCppName(FunctionRemap *remap, const std::string &className, bool mangle) {
  258. std::string cppName = remap->_cppfunc->get_local_name();
  259. if (remap->_ftype->_flags & CPPFunctionType::F_unary_op) {
  260. cppName += "unary";
  261. }
  262. return methodNameFromCppName(cppName, className, mangle);
  263. }
  264. ////////////////////////////////////////////////////////////////////
  265. // Function: InterfaceMakerPythonNative::get_slotted_function_def
  266. // Access: Private, Static
  267. // Description: Determines whether this method should be mapped to
  268. // one of Python's special slotted functions, those
  269. // hard-coded functions that are assigned to particular
  270. // function pointers within the object structure, for
  271. // special functions like __getitem__ and __len__.
  272. //
  273. // Returns true if it has such a mapping, false if it is
  274. // just a normal method. If it returns true, the
  275. // SlottedFunctionDef structure is filled in with the
  276. // important details.
  277. ////////////////////////////////////////////////////////////////////
  278. bool InterfaceMakerPythonNative::
  279. get_slotted_function_def(Object *obj, Function *func, FunctionRemap *remap,
  280. SlottedFunctionDef &def) {
  281. if (obj == NULL) {
  282. // Only methods may be slotted.
  283. return false;
  284. }
  285. def._answer_location = string();
  286. def._wrapper_type = WT_none;
  287. def._min_version = 0;
  288. string method_name = func->_ifunc.get_name();
  289. bool is_unary_op = func->_ifunc.is_unary_op();
  290. if (method_name == "operator +") {
  291. def._answer_location = "nb_add";
  292. def._wrapper_type = WT_binary_operator;
  293. return true;
  294. }
  295. if (method_name == "operator -" && is_unary_op) {
  296. def._answer_location = "nb_negative";
  297. def._wrapper_type = WT_no_params;
  298. return true;
  299. }
  300. if (method_name == "operator -") {
  301. def._answer_location = "nb_subtract";
  302. def._wrapper_type = WT_binary_operator;
  303. return true;
  304. }
  305. if (method_name == "operator *") {
  306. def._answer_location = "nb_multiply";
  307. def._wrapper_type = WT_binary_operator;
  308. return true;
  309. }
  310. if (method_name == "operator /") {
  311. def._answer_location = "nb_divide";
  312. def._wrapper_type = WT_binary_operator;
  313. return true;
  314. }
  315. if (method_name == "operator %") {
  316. def._answer_location = "nb_remainder";
  317. def._wrapper_type = WT_binary_operator;
  318. return true;
  319. }
  320. if (method_name == "operator <<") {
  321. def._answer_location = "nb_lshift";
  322. def._wrapper_type = WT_binary_operator;
  323. return true;
  324. }
  325. if (method_name == "operator >>") {
  326. def._answer_location = "nb_rshift";
  327. def._wrapper_type = WT_binary_operator;
  328. return true;
  329. }
  330. if (method_name == "operator ^") {
  331. def._answer_location = "nb_xor";
  332. def._wrapper_type = WT_binary_operator;
  333. return true;
  334. }
  335. if (method_name == "operator ~" && is_unary_op) {
  336. def._answer_location = "nb_invert";
  337. def._wrapper_type = WT_no_params;
  338. return true;
  339. }
  340. if (method_name == "operator &") {
  341. def._answer_location = "nb_and";
  342. def._wrapper_type = WT_binary_operator;
  343. return true;
  344. }
  345. if (method_name == "operator |") {
  346. def._answer_location = "nb_or";
  347. def._wrapper_type = WT_binary_operator;
  348. return true;
  349. }
  350. if (method_name == "__pow__") {
  351. def._answer_location = "nb_power";
  352. def._wrapper_type = WT_ternary_operator;
  353. return true;
  354. }
  355. if (method_name == "operator +=") {
  356. def._answer_location = "nb_inplace_add";
  357. def._wrapper_type = WT_inplace_binary_operator;
  358. return true;
  359. }
  360. if (method_name == "operator -=") {
  361. def._answer_location = "nb_inplace_subtract";
  362. def._wrapper_type = WT_inplace_binary_operator;
  363. return true;
  364. }
  365. if (method_name == "operator *=") {
  366. def._answer_location = "nb_inplace_multiply";
  367. def._wrapper_type = WT_inplace_binary_operator;
  368. return true;
  369. }
  370. if (method_name == "operator /=") {
  371. def._answer_location = "nb_inplace_divide";
  372. def._wrapper_type = WT_inplace_binary_operator;
  373. return true;
  374. }
  375. if (method_name == "operator %=") {
  376. def._answer_location = "nb_inplace_remainder";
  377. def._wrapper_type = WT_inplace_binary_operator;
  378. return true;
  379. }
  380. if (method_name == "operator <<=") {
  381. def._answer_location = "nb_inplace_lshift";
  382. def._wrapper_type = WT_inplace_binary_operator;
  383. return true;
  384. }
  385. if (method_name == "operator >>=") {
  386. def._answer_location = "nb_inplace_rshift";
  387. def._wrapper_type = WT_inplace_binary_operator;
  388. return true;
  389. }
  390. if (method_name == "operator &=") {
  391. def._answer_location = "nb_inplace_and";
  392. def._wrapper_type = WT_inplace_binary_operator;
  393. return true;
  394. }
  395. if (method_name == "operator ^=") {
  396. def._answer_location = "nb_inplace_xor";
  397. def._wrapper_type = WT_inplace_binary_operator;
  398. return true;
  399. }
  400. if (method_name == "__ipow__") {
  401. def._answer_location = "nb_inplace_power";
  402. def._wrapper_type = WT_inplace_ternary_operator;
  403. return true;
  404. }
  405. if (obj->_protocol_types & Object::PT_sequence) {
  406. if (remap->_flags & FunctionRemap::F_getitem_int) {
  407. def._answer_location = "sq_item";
  408. def._wrapper_type = WT_sequence_getitem;
  409. return true;
  410. }
  411. if (remap->_flags & FunctionRemap::F_setitem_int ||
  412. remap->_flags & FunctionRemap::F_delitem_int) {
  413. def._answer_location = "sq_ass_item";
  414. def._wrapper_type = WT_sequence_setitem;
  415. return true;
  416. }
  417. if (remap->_flags & FunctionRemap::F_size) {
  418. def._answer_location = "sq_length";
  419. def._wrapper_type = WT_sequence_size;
  420. return true;
  421. }
  422. }
  423. if (obj->_protocol_types & Object::PT_mapping) {
  424. if (remap->_flags & FunctionRemap::F_getitem) {
  425. def._answer_location = "mp_subscript";
  426. def._wrapper_type = WT_one_param;
  427. return true;
  428. }
  429. if (remap->_flags & FunctionRemap::F_setitem ||
  430. remap->_flags & FunctionRemap::F_delitem) {
  431. def._answer_location = "mp_ass_subscript";
  432. def._wrapper_type = WT_mapping_setitem;
  433. return true;
  434. }
  435. }
  436. if (obj->_protocol_types & Object::PT_iter) {
  437. if (method_name == "__iter__") {
  438. def._answer_location = "tp_iter";
  439. def._wrapper_type = WT_no_params;
  440. return true;
  441. }
  442. if (method_name == "next" || method_name == "__next__") {
  443. def._answer_location = "tp_iternext";
  444. def._wrapper_type = WT_iter_next;
  445. return true;
  446. }
  447. }
  448. if (method_name == "operator ()") {
  449. def._answer_location = "tp_call";
  450. def._wrapper_type = WT_none;
  451. return true;
  452. }
  453. if (method_name == "__getattribute__") {
  454. // Like __getattr__, but is called unconditionally, ie.
  455. // does not try PyObject_GenericGetAttr first.
  456. def._answer_location = "tp_getattro";
  457. def._wrapper_type = WT_one_param;
  458. return true;
  459. }
  460. if (method_name == "__getattr__") {
  461. def._answer_location = "tp_getattro";
  462. def._wrapper_type = WT_getattr;
  463. return true;
  464. }
  465. if (method_name == "__setattr__") {
  466. def._answer_location = "tp_setattro";
  467. def._wrapper_type = WT_setattr;
  468. return true;
  469. }
  470. if (method_name == "__delattr__") {
  471. // __delattr__ shares the slot with __setattr__, except
  472. // that it takes only one argument.
  473. def._answer_location = "tp_setattro";
  474. def._wrapper_type = WT_setattr;
  475. return true;
  476. }
  477. if (method_name == "__nonzero__" || method_name == "__bool__") {
  478. // Python 2 named it nb_nonzero, Python 3 nb_bool. We refer to it just
  479. // as nb_bool.
  480. def._answer_location = "nb_bool";
  481. def._wrapper_type = WT_inquiry;
  482. return true;
  483. }
  484. if (method_name == "__getbuffer__") {
  485. def._answer_location = "bf_getbuffer";
  486. def._wrapper_type = WT_getbuffer;
  487. return true;
  488. }
  489. if (method_name == "__releasebuffer__") {
  490. def._answer_location = "bf_releasebuffer";
  491. def._wrapper_type = WT_releasebuffer;
  492. return true;
  493. }
  494. if (method_name == "__traverse__") {
  495. def._answer_location = "tp_traverse";
  496. def._wrapper_type = WT_traverse;
  497. return true;
  498. }
  499. if (method_name == "__clear__") {
  500. def._answer_location = "tp_clear";
  501. def._wrapper_type = WT_inquiry;
  502. return true;
  503. }
  504. if (method_name == "__repr__") {
  505. def._answer_location = "tp_repr";
  506. def._wrapper_type = WT_no_params;
  507. return true;
  508. }
  509. if (method_name == "__str__") {
  510. def._answer_location = "tp_str";
  511. def._wrapper_type = WT_no_params;
  512. return true;
  513. }
  514. if (method_name == "__cmp__" || (remap->_flags & FunctionRemap::F_compare_to) != 0) {
  515. def._answer_location = "tp_compare";
  516. def._wrapper_type = WT_compare;
  517. return true;
  518. }
  519. if (remap->_type == FunctionRemap::T_typecast_method) {
  520. // A typecast operator. Check for a supported low-level typecast type.
  521. if (TypeManager::is_bool(remap->_return_type->get_orig_type())) {
  522. // If it's a bool type, then we wrap it with the __nonzero__
  523. // slot method.
  524. def._answer_location = "nb_bool";
  525. def._wrapper_type = WT_inquiry;
  526. return true;
  527. } else if (TypeManager::is_integer(remap->_return_type->get_orig_type())) {
  528. // An integer type.
  529. def._answer_location = "nb_int";
  530. def._wrapper_type = WT_no_params;
  531. return true;
  532. } else if (TypeManager::is_float(remap->_return_type->get_orig_type())) {
  533. // A floating-point (or double) type.
  534. def._answer_location = "nb_float";
  535. def._wrapper_type = WT_no_params;
  536. return true;
  537. } else if (remap->_return_type->new_type_is_atomic_string()) {
  538. // A string type.
  539. def._answer_location = "tp_str";
  540. def._wrapper_type = WT_no_params;
  541. return true;
  542. }
  543. }
  544. return false;
  545. }
  546. ////////////////////////////////////////////////////////////////////
  547. // Function: InterfaceMakerPythonNative::write_function_slot
  548. // Access: Private, Static
  549. // Description: Determines whether the slot occurs in the map of
  550. // slotted functions, and if so, writes out a pointer
  551. // to its wrapper. If not, writes out def (usually 0).
  552. ////////////////////////////////////////////////////////////////////
  553. void InterfaceMakerPythonNative::
  554. write_function_slot(ostream &out, int indent_level, const SlottedFunctions &slots,
  555. const string &slot, const string &default_) {
  556. SlottedFunctions::const_iterator rfi = slots.find(slot);
  557. if (rfi == slots.end()) {
  558. indent(out, indent_level) << default_ << ",";
  559. if (default_ == "0") {
  560. out << " // " << slot;
  561. }
  562. out << "\n";
  563. return;
  564. }
  565. const SlottedFunctionDef &def = rfi->second;
  566. // Add an #ifdef if there is a specific version requirement on this function.
  567. if (def._min_version > 0) {
  568. out << "#if PY_VERSION_HEX >= 0x" << hex << def._min_version << dec << "\n";
  569. }
  570. indent(out, indent_level) << "&" << def._wrapper_name << ",\n";
  571. if (def._min_version > 0) {
  572. out << "#else\n";
  573. indent(out, indent_level) << default_ << ",\n";
  574. out << "#endif\n";
  575. }
  576. }
  577. ///////////////////////////////////////////////////////////////////////////////
  578. ///////////////////////////////////////////////////////////////////////////////
  579. void InterfaceMakerPythonNative::
  580. get_valid_child_classes(std::map<std::string, CastDetails> &answer, CPPStructType *inclass, const std::string &upcast_seed, bool can_downcast) {
  581. if (inclass == NULL) {
  582. return;
  583. }
  584. CPPStructType::Derivation::const_iterator bi;
  585. for (bi = inclass->_derivation.begin();
  586. bi != inclass->_derivation.end();
  587. ++bi) {
  588. const CPPStructType::Base &base = (*bi);
  589. // if (base._vis <= V_public)
  590. // can_downcast = false;
  591. CPPStructType *base_type = TypeManager::resolve_type(base._base)->as_struct_type();
  592. if (base_type != NULL) {
  593. std::string scoped_name = base_type->get_local_name(&parser);
  594. if (answer.find(scoped_name) == answer.end()) {
  595. answer[scoped_name]._can_downcast = can_downcast;
  596. answer[scoped_name]._to_class_name = scoped_name;
  597. answer[scoped_name]._structType = base_type;
  598. if (base._is_virtual) {
  599. answer[scoped_name]._can_downcast = false;
  600. }
  601. std::string local_upcast("(");
  602. local_upcast += scoped_name + " *)"+ upcast_seed +"";
  603. answer[scoped_name]._up_cast_string = local_upcast;
  604. answer[scoped_name]._is_legal_py_class = is_cpp_type_legal(base_type);
  605. } else {
  606. answer[scoped_name]._can_downcast = false;
  607. }
  608. get_valid_child_classes(answer, base_type, answer[scoped_name]._up_cast_string, answer[scoped_name]._can_downcast);
  609. }
  610. }
  611. }
  612. ///////////////////////////////////////////////////////////////////////////////
  613. // Function : write_python_instance
  614. //
  615. ///////////////////////////////////////////////////////////////////////////////
  616. void InterfaceMakerPythonNative::
  617. write_python_instance(ostream &out, int indent_level, const string &return_expr,
  618. bool owns_memory, const string &class_name,
  619. CPPType *ctype, bool is_const) {
  620. out << boolalpha;
  621. if (IsPandaTypedObject(ctype->as_struct_type())) {
  622. // We can't let DTool_CreatePyInstanceTyped do the NULL check since we
  623. // will be grabbing the type index (which would obviously crash when called
  624. // on a NULL pointer), so we do it here.
  625. indent(out, indent_level)
  626. << "if (" << return_expr << " == NULL) {\n";
  627. indent(out, indent_level)
  628. << " Py_INCREF(Py_None);\n";
  629. indent(out, indent_level)
  630. << " return Py_None;\n";
  631. indent(out, indent_level)
  632. << "} else {\n";
  633. indent(out, indent_level)
  634. << " return DTool_CreatePyInstanceTyped((void *)" << return_expr
  635. << ", " << CLASS_PREFIX << make_safe_name(class_name) << ", "
  636. << owns_memory << ", " << is_const << ", "
  637. << return_expr << "->as_typed_object()->get_type_index());\n";
  638. indent(out, indent_level)
  639. << "}\n";
  640. } else {
  641. // DTool_CreatePyInstance will do the NULL check.
  642. indent(out, indent_level)
  643. << "return "
  644. << "DTool_CreatePyInstance((void *)" << return_expr << ", "
  645. << CLASS_PREFIX << make_safe_name(class_name) << ", "
  646. << owns_memory << ", " << is_const << ");\n";
  647. }
  648. }
  649. ////////////////////////////////////////////////////////////////////
  650. // Function: InterfaceMakerPythonNative::Constructor
  651. // Access: Public
  652. // Description:
  653. ////////////////////////////////////////////////////////////////////
  654. InterfaceMakerPythonNative::
  655. InterfaceMakerPythonNative(InterrogateModuleDef *def) :
  656. InterfaceMakerPython(def)
  657. {
  658. }
  659. ////////////////////////////////////////////////////////////////////
  660. // Function: InterfaceMakerPythonNative::Destructor
  661. // Access: Public, Virtual
  662. // Description:
  663. ////////////////////////////////////////////////////////////////////
  664. InterfaceMakerPythonNative::
  665. ~InterfaceMakerPythonNative() {
  666. }
  667. ////////////////////////////////////////////////////////////////////
  668. // Function: InterfaceMakerPythonNative::write_prototypes
  669. // Access: Public, Virtual
  670. // Description: Generates the list of function prototypes
  671. // corresponding to the functions that will be output in
  672. // write_functions().
  673. ////////////////////////////////////////////////////////////////////
  674. void InterfaceMakerPythonNative::
  675. write_prototypes(ostream &out_code, ostream *out_h) {
  676. inside_python_native = true;
  677. Functions::iterator fi;
  678. if (out_h != NULL) {
  679. *out_h << "#include \"py_panda.h\"\n\n";
  680. }
  681. out_code << "//********************************************************************\n";
  682. out_code << "//*** prototypes for .. Global\n";
  683. out_code << "//********************************************************************\n";
  684. /*
  685. for (fi = _functions.begin(); fi != _functions.end(); ++fi)
  686. {
  687. Function *func = (*fi);
  688. if (!func->_itype.is_global() && is_function_legal(func))
  689. write_prototype_for (out_code, func);
  690. }
  691. */
  692. Objects::iterator oi;
  693. for (oi = _objects.begin(); oi != _objects.end(); ++oi) {
  694. Object *object = (*oi).second;
  695. if (object->_itype.is_class() || object->_itype.is_struct()) {
  696. if (is_cpp_type_legal(object->_itype._cpptype)) {
  697. if (isExportThisRun(object->_itype._cpptype)) {
  698. write_prototypes_class(out_code, out_h, object);
  699. } else {
  700. //write_prototypes_class_external(out_code, object);
  701. _external_imports.insert(object->_itype._cpptype);
  702. }
  703. }
  704. }
  705. }
  706. out_code << "//********************************************************************\n";
  707. out_code << "//*** prototypes for .. External Objects\n";
  708. out_code << "//********************************************************************\n";
  709. for (std::set<CPPType *>::iterator ii = _external_imports.begin(); ii != _external_imports.end(); ii++) {
  710. CPPType *type = (*ii);
  711. string class_name = type->get_local_name(&parser);
  712. string safe_name = make_safe_name(class_name);
  713. out_code << "IMPORT_THIS struct Dtool_PyTypedObject Dtool_" << safe_name << ";\n";
  714. out_code << "IMPORT_THIS void Dtool_PyModuleClassInit_" << safe_name << "(PyObject *module);\n";
  715. int has_coerce = has_coerce_constructor(type->as_struct_type());
  716. if (TypeManager::is_reference_count(type)) {
  717. if (has_coerce > 0) {
  718. out_code << "IMPORT_THIS bool Dtool_Coerce_" << safe_name << "(PyObject *args, CPT(" << class_name << ") &coerced);\n";
  719. if (has_coerce > 1) {
  720. out_code << "IMPORT_THIS bool Dtool_Coerce_" << safe_name << "(PyObject *args, PT(" << class_name << ") &coerced);\n";
  721. }
  722. }
  723. } else {
  724. if (has_coerce > 0) {
  725. out_code << "IMPORT_THIS bool Dtool_Coerce_" << safe_name << "(PyObject *args, " << class_name << " const *&coerced, bool &manage);\n";
  726. if (has_coerce > 1) {
  727. out_code << "IMPORT_THIS bool Dtool_Coerce_" << safe_name << "(PyObject *args, " << class_name << " *&coerced, bool &manage);\n";
  728. }
  729. }
  730. }
  731. }
  732. inside_python_native = false;
  733. }
  734. /////////////////////////////////////////////////////////////////////////////////////////////
  735. // Function : write_prototypes_class_external
  736. //
  737. // Description : Output enough enformation to a declartion of a externally
  738. // generated dtool type object
  739. /////////////////////////////////////////////////////////////////////////////////////////////
  740. void InterfaceMakerPythonNative::
  741. write_prototypes_class_external(ostream &out, Object *obj) {
  742. std::string class_name = make_safe_name(obj->_itype.get_scoped_name());
  743. std::string c_class_name = obj->_itype.get_true_name();
  744. std::string preferred_name = obj->_itype.get_name();
  745. out << "//********************************************************************\n";
  746. out << "//*** prototypes for external.. " << class_name << "\n";
  747. out << "//********************************************************************\n";
  748. // This typedef is necessary for class templates since we can't pass
  749. // a comma to a macro function.
  750. out << "typedef " << c_class_name << " " << class_name << "_localtype;\n";
  751. out << "Define_Module_Class_Forward(" << _def->module_name << ", " << class_name << ", " << class_name << "_localtype, " << classNameFromCppName(preferred_name, false) << ");\n";
  752. }
  753. ///////////////////////////////////////// ////////////////////////////////////////////////////
  754. // Function : write_prototypes_class
  755. //
  756. /////////////////////////////////////////////////////////////////////////////////////////////
  757. void InterfaceMakerPythonNative::
  758. write_prototypes_class(ostream &out_code, ostream *out_h, Object *obj) {
  759. std::string ClassName = make_safe_name(obj->_itype.get_scoped_name());
  760. Functions::iterator fi;
  761. out_code << "//********************************************************************\n";
  762. out_code << "//*** prototypes for .. " << ClassName << "\n";
  763. out_code << "//********************************************************************\n";
  764. /*
  765. for (fi = obj->_methods.begin(); fi != obj->_methods.end(); ++fi) {
  766. Function *func = (*fi);
  767. write_prototype_for(out_code, func);
  768. }
  769. */
  770. /*
  771. for (fi = obj->_constructors.begin(); fi != obj->_constructors.end(); ++fi) {
  772. Function *func = (*fi);
  773. std::string fname = "int Dtool_Init_" + ClassName + "(PyObject *self, PyObject *args, PyObject *kwds)";
  774. write_prototype_for_name(out_code, obj, func, fname);
  775. }
  776. */
  777. write_class_declarations(out_code, out_h, obj);
  778. }
  779. ////////////////////////////////////////////////////////////////////
  780. // Function: InterfaceMakerPythonNative::write_functions
  781. // Access: Public, Virtual
  782. // Description: Generates the list of functions that are appropriate
  783. // for this interface. This function is called *before*
  784. // write_prototypes(), above.
  785. ////////////////////////////////////////////////////////////////////
  786. void InterfaceMakerPythonNative::
  787. write_functions(ostream &out) {
  788. inside_python_native = true;
  789. out << "//********************************************************************\n";
  790. out << "//*** Functions for .. Global\n" ;
  791. out << "//********************************************************************\n";
  792. FunctionsByIndex::iterator fi;
  793. for (fi = _functions.begin(); fi != _functions.end(); ++fi) {
  794. Function *func = (*fi).second;
  795. if (!func->_itype.is_global() && is_function_legal(func)) {
  796. write_function_for_top(out, NULL, func);
  797. }
  798. }
  799. Objects::iterator oi;
  800. for (oi = _objects.begin(); oi != _objects.end(); ++oi) {
  801. Object *object = (*oi).second;
  802. if (object->_itype.is_class() || object->_itype.is_struct()) {
  803. if (is_cpp_type_legal(object->_itype._cpptype)) {
  804. if (isExportThisRun(object->_itype._cpptype)) {
  805. write_class_details(out, object);
  806. }
  807. }
  808. }
  809. }
  810. //Objects::iterator oi;
  811. for (oi = _objects.begin(); oi != _objects.end(); ++oi) {
  812. Object *object = (*oi).second;
  813. if (!object->_itype.get_outer_class()) {
  814. if (object->_itype.is_class() || object->_itype.is_struct()) {
  815. if (is_cpp_type_legal(object->_itype._cpptype)) {
  816. if (isExportThisRun(object->_itype._cpptype)) {
  817. write_module_class(out, object);
  818. }
  819. }
  820. }
  821. }
  822. }
  823. inside_python_native = true;
  824. }
  825. ////////////////////////////////////////////////////////////////////
  826. // Function: InterfaceMakerPythonNative::write_class_details
  827. // Access: Private
  828. // Description: Writes out all of the wrapper methods necessary to
  829. // export the given object. This is called by
  830. // write_functions.
  831. ////////////////////////////////////////////////////////////////////
  832. void InterfaceMakerPythonNative::
  833. write_class_details(ostream &out, Object *obj) {
  834. Functions::iterator fi;
  835. Function::Remaps::const_iterator ri;
  836. //std::string cClassName = obj->_itype.get_scoped_name();
  837. std::string ClassName = make_safe_name(obj->_itype.get_scoped_name());
  838. std::string cClassName = obj->_itype.get_true_name();
  839. out << "//********************************************************************\n";
  840. out << "//*** Functions for .. " << cClassName << "\n" ;
  841. out << "//********************************************************************\n";
  842. // First write out all the wrapper functions for the methods.
  843. for (fi = obj->_methods.begin(); fi != obj->_methods.end(); ++fi) {
  844. Function *func = (*fi);
  845. if (func) {
  846. // Write the definition of the generic wrapper function for this function.
  847. write_function_for_top(out, obj, func);
  848. }
  849. }
  850. // Now write out generated getters and setters for the properties.
  851. Properties::const_iterator pit;
  852. for (pit = obj->_properties.begin(); pit != obj->_properties.end(); ++pit) {
  853. Property *property = (*pit);
  854. const InterrogateElement &ielem = property->_ielement;
  855. string expected_params;
  856. if (property->_getter != NULL) {
  857. std::string fname = "PyObject *Dtool_" + ClassName + "_" + ielem.get_name() + "_Getter(PyObject *self, void *)";
  858. write_function_for_name(out, obj, property->_getter->_remaps,
  859. fname, expected_params, true,
  860. AT_no_args, RF_pyobject | RF_err_null);
  861. }
  862. if (property->_setter != NULL) {
  863. std::string fname = "int Dtool_" + ClassName + "_" + ielem.get_name() + "_Setter(PyObject *self, PyObject *arg, void *)";
  864. write_function_for_name(out, obj, property->_setter->_remaps,
  865. fname, expected_params, true,
  866. AT_single_arg, RF_int);
  867. }
  868. }
  869. // Write the constructors.
  870. if (obj->_constructors.size() == 0) {
  871. // There is no constructor - write one that simply outputs an error.
  872. out << "int Dtool_Init_" + ClassName + "(PyObject *, PyObject *, PyObject *) {\n"
  873. << "#ifdef NDEBUG\n"
  874. << " Dtool_Raise_TypeError(\"cannot init constant class\");\n"
  875. << "#else\n"
  876. << " Dtool_Raise_TypeError(\"cannot init constant class " << cClassName << "\");\n"
  877. << "#endif\n"
  878. << " return -1;\n"
  879. << "}\n\n";
  880. } else {
  881. for (fi = obj->_constructors.begin(); fi != obj->_constructors.end(); ++fi) {
  882. Function *func = (*fi);
  883. std::string fname = "int Dtool_Init_" + ClassName + "(PyObject *self, PyObject *args, PyObject *kwds)";
  884. string expected_params;
  885. write_function_for_name(out, obj, func->_remaps, fname, expected_params, true, AT_keyword_args, RF_int);
  886. }
  887. }
  888. CPPType *cpptype = TypeManager::resolve_type(obj->_itype._cpptype);
  889. // If we have "coercion constructors", write a single wrapper to consolidate those.
  890. int has_coerce = has_coerce_constructor(cpptype->as_struct_type());
  891. if (has_coerce > 0) {
  892. write_coerce_constructor(out, obj, true);
  893. if (has_coerce > 1) {
  894. write_coerce_constructor(out, obj, false);
  895. }
  896. }
  897. // Write make seqs: generated methods that return a sequence of items.
  898. MakeSeqs::iterator msi;
  899. for (msi = obj->_make_seqs.begin(); msi != obj->_make_seqs.end(); ++msi) {
  900. write_make_seq(out, obj, ClassName, cClassName, *msi);
  901. }
  902. // Determine which external imports we will need.
  903. std::map<string, CastDetails> details;
  904. std::map<string, CastDetails>::iterator di;
  905. builder.get_type(TypeManager::unwrap(cpptype), false);
  906. get_valid_child_classes(details, cpptype->as_struct_type());
  907. for (di = details.begin(); di != details.end(); di++) {
  908. //InterrogateType ptype =idb->get_type(di->first);
  909. if (di->second._is_legal_py_class && !isExportThisRun(di->second._structType)) {
  910. _external_imports.insert(di->second._structType);
  911. }
  912. //out << "IMPORT_THIS struct Dtool_PyTypedObject Dtool_" << make_safe_name(di->second._to_class_name) << ";\n";
  913. }
  914. // Write support methods to cast from and to pointers of this type.
  915. {
  916. out << "inline void *Dtool_UpcastInterface_" << ClassName << "(PyObject *self, Dtool_PyTypedObject *requested_type) {\n";
  917. out << " Dtool_PyTypedObject *SelfType = ((Dtool_PyInstDef *)self)->_My_Type;\n";
  918. out << " if (SelfType != &Dtool_" << ClassName << ") {\n";
  919. out << " printf(\"" << ClassName << " ** Bad Source Type-- Requesting Conversion from %s to %s\\n\", Py_TYPE(self)->tp_name, requested_type->_PyType.tp_name); fflush(NULL);\n";;
  920. out << " return NULL;\n";
  921. out << " }\n";
  922. out << "\n";
  923. out << " " << cClassName << " *local_this = (" << cClassName << " *)((Dtool_PyInstDef *)self)->_ptr_to_object;\n";
  924. out << " if (requested_type == &Dtool_" << ClassName << ") {\n";
  925. out << " return local_this;\n";
  926. out << " }\n";
  927. for (di = details.begin(); di != details.end(); di++) {
  928. if (di->second._is_legal_py_class) {
  929. out << " if (requested_type == &Dtool_" << make_safe_name(di->second._to_class_name) << ") {\n";
  930. out << " return " << di->second._up_cast_string << " local_this;\n";
  931. out << " }\n";
  932. }
  933. }
  934. out << " return NULL;\n";
  935. out << "}\n\n";
  936. out << "inline void *Dtool_DowncastInterface_" << ClassName << "(void *from_this, Dtool_PyTypedObject *from_type) {\n";
  937. out << " if (from_this == NULL || from_type == NULL) {\n";
  938. out << " return NULL;\n";
  939. out << " }\n";
  940. out << " if (from_type == &Dtool_" << ClassName << ") {\n";
  941. out << " return from_this;\n";
  942. out << " }\n";
  943. for (di = details.begin(); di != details.end(); di++) {
  944. if (di->second._can_downcast && di->second._is_legal_py_class) {
  945. out << " if (from_type == &Dtool_" << make_safe_name(di->second._to_class_name) << ") {\n";
  946. out << " " << di->second._to_class_name << "* other_this = (" << di->second._to_class_name << "*)from_this;\n" ;
  947. out << " return (" << cClassName << "*)other_this;\n";
  948. out << " }\n";
  949. }
  950. }
  951. out << " return (void *) NULL;\n";
  952. out << "}\n\n";
  953. }
  954. }
  955. ////////////////////////////////////////////////////////////
  956. /// Function : write_class_declarations
  957. //
  958. //
  959. ////////////////////////////////////////////////////////////
  960. void InterfaceMakerPythonNative::
  961. write_class_declarations(ostream &out, ostream *out_h, Object *obj) {
  962. const InterrogateType &itype = obj->_itype;
  963. std::string class_name = make_safe_name(obj->_itype.get_scoped_name());
  964. std::string c_class_name = obj->_itype.get_true_name();
  965. std::string preferred_name = itype.get_name();
  966. std::string class_struct_name = std::string(CLASS_PREFIX) + class_name;
  967. CPPType *type = obj->_itype._cpptype;
  968. // This typedef is necessary for class templates since we can't pass
  969. // a comma to a macro function.
  970. out << "typedef " << c_class_name << " " << class_name << "_localtype;\n";
  971. if (obj->_itype.has_destructor() ||
  972. obj->_itype.destructor_is_inherited()) {
  973. if (TypeManager::is_reference_count(type)) {
  974. out << "Define_Module_ClassRef";
  975. } else {
  976. out << "Define_Module_Class";
  977. }
  978. } else {
  979. if (TypeManager::is_reference_count(type)) {
  980. out << "Define_Module_ClassRef_Private";
  981. } else {
  982. out << "Define_Module_Class_Private";
  983. }
  984. }
  985. out << "(" << _def->module_name << ", " << class_name << ", " << class_name << "_localtype, " << classNameFromCppName(preferred_name, false) << ");\n";
  986. out << "EXPORT_THIS void Dtool_PyModuleClassInit_" << class_name << "(PyObject *module);\n";
  987. int has_coerce = has_coerce_constructor(type->as_struct_type());
  988. if (TypeManager::is_reference_count(type)) {
  989. if (has_coerce > 0) {
  990. out << "EXPORT_THIS bool Dtool_Coerce_" << class_name << "(PyObject *args, CPT(" << c_class_name << ") &coerced);\n";
  991. if (has_coerce > 1) {
  992. out << "EXPORT_THIS bool Dtool_Coerce_" << class_name << "(PyObject *args, PT(" << c_class_name << ") &coerced);\n";
  993. }
  994. }
  995. } else {
  996. if (has_coerce > 0) {
  997. out << "EXPORT_THIS bool Dtool_Coerce_" << class_name << "(PyObject *args, " << c_class_name << " const *&coerced, bool &manage);\n";
  998. if (has_coerce > 1) {
  999. out << "EXPORT_THIS bool Dtool_Coerce_" << class_name << "(PyObject *args, " << c_class_name << " *&coerced, bool &manage);\n";
  1000. }
  1001. }
  1002. }
  1003. out << "\n";
  1004. if (out_h != NULL) {
  1005. *out_h << "extern \"C\" " << EXPORT_IMPORT_PREFIX << " struct Dtool_PyTypedObject Dtool_" << class_name << ";\n";
  1006. }
  1007. }
  1008. ////////////////////////////////////////////////////////////////////
  1009. // Function: InterfaceMakerPythonNative::write_sub_module
  1010. // Access: Public, Virtual
  1011. // Description: Generates whatever additional code is required to
  1012. // support a module file.
  1013. ////////////////////////////////////////////////////////////////////
  1014. void InterfaceMakerPythonNative::
  1015. write_sub_module(ostream &out, Object *obj) {
  1016. //Object * obj = _objects[_embeded_index] ;
  1017. string class_name = make_safe_name(obj->_itype.get_scoped_name());
  1018. out << " // Module init upcall for " << obj->_itype.get_scoped_name() << "\n";
  1019. if (!obj->_itype.is_typedef()) {
  1020. out << " // " << *(obj->_itype._cpptype) << "\n";
  1021. out << " Dtool_PyModuleClassInit_" << class_name << "(module);\n";
  1022. } else {
  1023. // Unwrap typedefs.
  1024. TypeIndex wrapped = obj->_itype._wrapped_type;
  1025. while (interrogate_type_is_typedef(wrapped)) {
  1026. wrapped = interrogate_type_wrapped_type(wrapped);
  1027. }
  1028. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  1029. const InterrogateType &wrapped_itype = idb->get_type(wrapped);
  1030. class_name = make_safe_name(wrapped_itype.get_scoped_name());
  1031. out << " // typedef " << wrapped_itype.get_scoped_name()
  1032. << " " << *(obj->_itype._cpptype) << "\n";
  1033. if (!isExportThisRun(wrapped_itype._cpptype)) {
  1034. _external_imports.insert(wrapped_itype._cpptype);
  1035. }
  1036. }
  1037. std::string export_class_name = classNameFromCppName(obj->_itype.get_name(), false);
  1038. std::string export_class_name2 = classNameFromCppName(obj->_itype.get_name(), true);
  1039. // out << " Py_INCREF(&Dtool_" << class_name << ".As_PyTypeObject());\n";
  1040. out << " PyModule_AddObject(module, \"" << export_class_name << "\", (PyObject *)&Dtool_" << class_name << ".As_PyTypeObject());\n";
  1041. if (export_class_name != export_class_name2) {
  1042. out << " PyModule_AddObject(module, \"" << export_class_name2 << "\", (PyObject *)&Dtool_" << class_name << ".As_PyTypeObject());\n";
  1043. }
  1044. }
  1045. /////////////////////////////////////////////////////////////////////////////
  1046. // Function : write_module_support
  1047. /////////////////////////////////////////////////////////////////////////////
  1048. void InterfaceMakerPythonNative::
  1049. write_module_support(ostream &out, ostream *out_h, InterrogateModuleDef *def) {
  1050. out << "//********************************************************************\n";
  1051. out << "//*** Module Object Linker ..\n";
  1052. out << "//********************************************************************\n";
  1053. out << "static void BuildInstants(PyObject *module) {\n";
  1054. out << " (void) module; // Unused\n";
  1055. Objects::iterator oi;
  1056. for (oi = _objects.begin(); oi != _objects.end(); ++oi) {
  1057. Object *object = (*oi).second;
  1058. if (object->_itype.is_enum() && !object->_itype.is_nested()) {
  1059. int enum_count = object->_itype.number_of_enum_values();
  1060. if (enum_count > 0) {
  1061. out << "//********************************************************************\n";
  1062. out << "//*** Module Enums .." << object->_itype.get_scoped_name() << "\n";
  1063. out << "//********************************************************************\n";
  1064. }
  1065. for (int xx = 0; xx < enum_count; xx++) {
  1066. string name1 = classNameFromCppName(object->_itype.get_enum_value_name(xx), false);
  1067. string name2 = classNameFromCppName(object->_itype.get_enum_value_name(xx), true);
  1068. string enum_value = "::" + object->_itype.get_enum_value_name(xx);
  1069. out << " PyModule_AddIntConstant(module, \"" << name1 << "\", " << enum_value << ");\n";
  1070. if (name1 != name2) {
  1071. // Also write the mangled name, for historical purposes.
  1072. out << " PyModule_AddIntConstant(module, \"" << name2 << "\", " << enum_value << ");\n";
  1073. }
  1074. }
  1075. }
  1076. }
  1077. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  1078. int num_manifests = idb->get_num_global_manifests();
  1079. for (int mi = 0; mi < num_manifests; mi++) {
  1080. ManifestIndex manifest_index = idb->get_global_manifest(mi);
  1081. const InterrogateManifest &iman = idb->get_manifest(manifest_index);
  1082. if (iman.has_getter()) {
  1083. FunctionIndex func_index = iman.get_getter();
  1084. record_function(dummy_type, func_index);
  1085. }
  1086. string name1 = classNameFromCppName(iman.get_name(), false);
  1087. string name2 = classNameFromCppName(iman.get_name(), true);
  1088. if (iman.has_int_value()) {
  1089. int value = iman.get_int_value();
  1090. out << " PyModule_AddIntConstant(module, \"" << name1 << "\", " << value << ");\n";
  1091. if (name1 != name2) {
  1092. // Also write the mangled name, for historical purposes.
  1093. out << " PyModule_AddIntConstant(module, \"" << name2 << "\", " << value << ");\n";
  1094. }
  1095. } else {
  1096. string value = iman.get_definition();
  1097. out << " PyModule_AddStringConstant(module, \"" << name1 << "\", \"" << value << "\");\n";
  1098. if (name1 != name2) {
  1099. out << " PyModule_AddStringConstant(module, \"" << name2 << "\", \"" << value << "\");\n";
  1100. }
  1101. }
  1102. }
  1103. for (oi = _objects.begin(); oi != _objects.end(); ++oi) {
  1104. Object *object = (*oi).second;
  1105. if (!object->_itype.get_outer_class()) {
  1106. if (object->_itype.is_class() ||
  1107. object->_itype.is_struct() ||
  1108. object->_itype.is_typedef()) {
  1109. if (is_cpp_type_legal(object->_itype._cpptype)) {
  1110. if (isExportThisRun(object->_itype._cpptype)) {
  1111. write_sub_module(out, object);
  1112. }
  1113. }
  1114. }
  1115. }
  1116. }
  1117. out << "//********************************************************************\n";
  1118. out << "//*** Module Init Upcall .. Externally Defined Class\n";
  1119. out << "//********************************************************************\n";
  1120. // for (std::set< std::string >::iterator ii = _external_imports.begin(); ii != _external_imports.end(); ii++)
  1121. // out << "Dtool_" <<*ii << "._Dtool_ClassInit(NULL);\n";
  1122. out << "}\n\n";
  1123. bool force_base_functions = true;
  1124. out << "static PyMethodDef python_simple_funcs[] = {\n";
  1125. FunctionsByIndex::iterator fi;
  1126. for (fi = _functions.begin(); fi != _functions.end(); ++fi) {
  1127. Function *func = (*fi).second;
  1128. if (!func->_itype.is_global() && is_function_legal(func)) {
  1129. string name1 = methodNameFromCppName(func, "", false);
  1130. string name2 = methodNameFromCppName(func, "", true);
  1131. string flags;
  1132. switch (func->_args_type) {
  1133. case AT_keyword_args:
  1134. flags = "METH_VARARGS | METH_KEYWORDS";
  1135. break;
  1136. case AT_varargs:
  1137. flags = "METH_VARARGS";
  1138. break;
  1139. case AT_single_arg:
  1140. flags = "METH_O";
  1141. break;
  1142. default:
  1143. flags = "METH_NOARGS";
  1144. break;
  1145. }
  1146. // Note: we shouldn't add METH_STATIC here, since both METH_STATIC
  1147. // and METH_CLASS are illegal for module-level functions.
  1148. out << " { \"" << name1 << "\", (PyCFunction) &"
  1149. << func->_name << ", " << flags << ", (const char *)" << func->_name << "_comment},\n";
  1150. if (name1 != name2) {
  1151. out << " { \"" << name2 << "\", (PyCFunction) &"
  1152. << func->_name << ", " << flags << ", (const char *)" << func->_name << "_comment},\n";
  1153. }
  1154. }
  1155. }
  1156. if (force_base_functions) {
  1157. out << " // Support Function For Dtool_types ... for now in each module ??\n";
  1158. out << " {\"Dtool_BorrowThisReference\", &Dtool_BorrowThisReference, METH_VARARGS, \"Used to borrow 'this' pointer (to, from)\\nAssumes no ownership.\"},\n";
  1159. out << " {\"Dtool_AddToDictionary\", &Dtool_AddToDictionary, METH_VARARGS, \"Used to add items into a tp_dict\"},\n";
  1160. }
  1161. out << " {NULL, NULL, 0, NULL}\n" << "};\n\n";
  1162. out << "EXPORT_THIS struct LibraryDef " << def->library_name << "_moddef = {python_simple_funcs, BuildInstants};\n";
  1163. if (out_h != NULL) {
  1164. *out_h << "extern struct LibraryDef " << def->library_name << "_moddef;\n";
  1165. }
  1166. }
  1167. /////////////////////////////////////////////////////////////////////////////
  1168. ///// Function : write_module
  1169. /////////////////////////////////////////////////////////////////////////////
  1170. void InterfaceMakerPythonNative::
  1171. write_module(ostream &out, ostream *out_h, InterrogateModuleDef *def) {
  1172. InterfaceMakerPython::write_module(out, out_h, def);
  1173. Objects::iterator oi;
  1174. out << "//********************************************************************\n";
  1175. out << "//*** Py Init Code For .. GlobalScope\n" ;
  1176. out << "//********************************************************************\n";
  1177. out << "#if PY_MAJOR_VERSION >= 3\n"
  1178. << "static struct PyModuleDef python_native_module = {\n"
  1179. << " PyModuleDef_HEAD_INIT,\n"
  1180. << " \"" << def->module_name << "\",\n"
  1181. << " NULL,\n"
  1182. << " -1,\n"
  1183. << " NULL,\n"
  1184. << " NULL, NULL, NULL, NULL\n"
  1185. << "};\n"
  1186. << "\n"
  1187. << "#ifdef _WIN32\n"
  1188. << "extern \"C\" __declspec(dllexport) PyObject *PyInit_" << def->module_name << "();\n"
  1189. << "#else\n"
  1190. << "extern \"C\" PyObject *PyInit_" << def->module_name << "();\n"
  1191. << "#endif\n"
  1192. << "\n"
  1193. << "PyObject *PyInit_" << def->module_name << "() {\n"
  1194. << " LibraryDef *refs[] = {&" << def->library_name << "_moddef, NULL};\n"
  1195. << " return Dtool_PyModuleInitHelper(refs, &python_native_module);\n"
  1196. << "}\n"
  1197. << "\n"
  1198. << "#else // Python 2 case\n"
  1199. << "\n"
  1200. << "#ifdef _WIN32\n"
  1201. << "extern \"C\" __declspec(dllexport) void init" << def->module_name << "();\n"
  1202. << "#else\n"
  1203. << "extern \"C\" void init" << def->module_name << "();\n"
  1204. << "#endif\n"
  1205. << "\n"
  1206. << "void init" << def->module_name << "() {\n"
  1207. << " LibraryDef *refs[] = {&" << def->library_name << "_moddef, NULL};\n"
  1208. << " Dtool_PyModuleInitHelper(refs, \"" << def->module_name << "\");\n"
  1209. << "}\n"
  1210. << "\n"
  1211. << "#endif\n"
  1212. << "\n";
  1213. }
  1214. /////////////////////////////////////////////////////////////////////////////////////////////
  1215. // Function :write_module_class
  1216. /////////////////////////////////////////////////////////////////////////////////////////////
  1217. void InterfaceMakerPythonNative::
  1218. write_module_class(ostream &out, Object *obj) {
  1219. bool has_local_hash = false;
  1220. bool has_local_repr = false;
  1221. bool has_local_str = false;
  1222. bool has_local_richcompare = false;
  1223. bool has_local_getbuffer = false;
  1224. {
  1225. int num_nested = obj->_itype.number_of_nested_types();
  1226. for (int ni = 0; ni < num_nested; ni++) {
  1227. TypeIndex nested_index = obj->_itype.get_nested_type(ni);
  1228. if (_objects.count(nested_index) == 0) {
  1229. // Illegal type.
  1230. continue;
  1231. }
  1232. Object *nested_obj = _objects[nested_index];
  1233. assert(nested_obj != (Object *)NULL);
  1234. if (nested_obj->_itype.is_class() || nested_obj->_itype.is_struct()) {
  1235. write_module_class(out, nested_obj);
  1236. }
  1237. }
  1238. }
  1239. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  1240. std::string ClassName = make_safe_name(obj->_itype.get_scoped_name());
  1241. std::string cClassName = obj->_itype.get_true_name();
  1242. std::string export_class_name = classNameFromCppName(obj->_itype.get_name(), false);
  1243. Functions::iterator fi;
  1244. out << "//********************************************************************\n";
  1245. out << "//*** Py Init Code For .. " << ClassName << " | " << export_class_name << "\n" ;
  1246. out << "//********************************************************************\n";
  1247. out << "static PyMethodDef Dtool_Methods_" << ClassName << "[] = {\n";
  1248. SlottedFunctions slots;
  1249. // function Table
  1250. bool got_copy = false;
  1251. bool got_deepcopy = false;
  1252. for (fi = obj->_methods.begin(); fi != obj->_methods.end(); ++fi) {
  1253. Function *func = (*fi);
  1254. if (func->_name == "__copy__") {
  1255. got_copy = true;
  1256. } else if (func->_name == "__deepcopy__") {
  1257. got_deepcopy = true;
  1258. }
  1259. string name1 = methodNameFromCppName(func, export_class_name, false);
  1260. string name2 = methodNameFromCppName(func, export_class_name, true);
  1261. string flags;
  1262. switch (func->_args_type) {
  1263. case AT_keyword_args:
  1264. flags = "METH_VARARGS | METH_KEYWORDS";
  1265. break;
  1266. case AT_varargs:
  1267. flags = "METH_VARARGS";
  1268. break;
  1269. case AT_single_arg:
  1270. flags = "METH_O";
  1271. break;
  1272. default:
  1273. flags = "METH_NOARGS";
  1274. break;
  1275. }
  1276. if (!func->_has_this) {
  1277. flags += " | METH_STATIC";
  1278. }
  1279. bool has_nonslotted = false;
  1280. Function::Remaps::const_iterator ri;
  1281. for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri) {
  1282. FunctionRemap *remap = (*ri);
  1283. if (!is_remap_legal(remap)) {
  1284. continue;
  1285. }
  1286. SlottedFunctionDef slotted_def;
  1287. if (get_slotted_function_def(obj, func, remap, slotted_def)) {
  1288. const string &key = slotted_def._answer_location;
  1289. if (slotted_def._wrapper_type == WT_none) {
  1290. slotted_def._wrapper_name = func->_name;
  1291. } else {
  1292. slotted_def._wrapper_name = func->_name + "_" + key;
  1293. }
  1294. if (slots.count(key)) {
  1295. slots[key]._remaps.insert(remap);
  1296. } else {
  1297. slots[key] = slotted_def;
  1298. slots[key]._remaps.insert(remap);
  1299. }
  1300. // Python 3 doesn't support nb_divide. It has nb_true_divide and also
  1301. // nb_floor_divide, but they have different semantics than in C++. Ugh.
  1302. // Make special slots to store the nb_divide members that take a float.
  1303. // We'll use this to build up nb_true_divide, so that we can still properly
  1304. // divide float vector types.
  1305. if (remap->_flags & FunctionRemap::F_divide_float) {
  1306. string true_key;
  1307. if (key == "nb_inplace_divide") {
  1308. true_key = "nb_inplace_true_divide";
  1309. } else {
  1310. true_key = "nb_true_divide";
  1311. }
  1312. if (slots.count(true_key) == 0) {
  1313. SlottedFunctionDef def;
  1314. def._answer_location = true_key;
  1315. def._wrapper_type = slotted_def._wrapper_type;
  1316. def._min_version = 0x03000000;
  1317. def._wrapper_name = func->_name + "_" + true_key;
  1318. slots[true_key] = def;
  1319. }
  1320. slots[true_key]._remaps.insert(remap);
  1321. }
  1322. } else {
  1323. has_nonslotted = true;
  1324. }
  1325. }
  1326. if (has_nonslotted) {
  1327. // This is a bit of a hack, as these methods should probably be
  1328. // going through the slotted function system. But it's kind of
  1329. // pointless to write these out, and a waste of space.
  1330. string fname = func->_ifunc.get_name();
  1331. if (fname == "operator <" ||
  1332. fname == "operator <=" ||
  1333. fname == "operator ==" ||
  1334. fname == "operator !=" ||
  1335. fname == "operator >" ||
  1336. fname == "operator >=") {
  1337. continue;
  1338. }
  1339. // This method has non-slotted remaps, so write it out into the function table.
  1340. out << " { \"" << name1 << "\", (PyCFunction) &"
  1341. << func->_name << ", " << flags << ", (char *) " << func->_name << "_comment},\n";
  1342. if (name1 != name2) {
  1343. out << " { \"" << name2 << "\", (PyCFunction) &"
  1344. << func->_name << ", " << flags << ", (char *) " << func->_name << "_comment},\n";
  1345. }
  1346. }
  1347. }
  1348. if (obj->_protocol_types & Object::PT_make_copy) {
  1349. if (!got_copy) {
  1350. out << " { \"__copy__\", (PyCFunction) &copy_from_make_copy, METH_NOARGS, NULL},\n";
  1351. got_copy = true;
  1352. }
  1353. } else if (obj->_protocol_types & Object::PT_copy_constructor) {
  1354. if (!got_copy) {
  1355. out << " { \"__copy__\", (PyCFunction) &copy_from_copy_constructor, METH_NOARGS, NULL},\n";
  1356. got_copy = true;
  1357. }
  1358. }
  1359. if (got_copy && !got_deepcopy) {
  1360. out << " { \"__deepcopy__\", (PyCFunction) &map_deepcopy_to_copy, METH_VARARGS, NULL},\n";
  1361. }
  1362. MakeSeqs::iterator msi;
  1363. for (msi = obj->_make_seqs.begin(); msi != obj->_make_seqs.end(); ++msi) {
  1364. string flags = "METH_NOARGS";
  1365. if (obj->is_static_method((*msi)->_element_name)) {
  1366. flags += " | METH_CLASS";
  1367. }
  1368. string name1 = methodNameFromCppName((*msi)->_seq_name, export_class_name, false);
  1369. string name2 = methodNameFromCppName((*msi)->_seq_name, export_class_name, true);
  1370. out << " { \"" << name1
  1371. << "\", (PyCFunction) &" << (*msi)->_name << ", " << flags << ", NULL},\n";
  1372. if (name1 != name2) {
  1373. out << " { \"" << name2
  1374. << "\", (PyCFunction) &" << (*msi)->_name << ", " << flags << ", NULL},\n";
  1375. }
  1376. }
  1377. out << " { NULL, NULL, 0, NULL }\n"
  1378. << "};\n\n";
  1379. int num_derivations = obj->_itype.number_of_derivations();
  1380. int di;
  1381. for (di = 0; di < num_derivations; di++) {
  1382. TypeIndex d_type_Index = obj->_itype.get_derivation(di);
  1383. if (!interrogate_type_is_unpublished(d_type_Index)) {
  1384. const InterrogateType &d_itype = idb->get_type(d_type_Index);
  1385. if (is_cpp_type_legal(d_itype._cpptype)) {
  1386. if (!isExportThisRun(d_itype._cpptype)) {
  1387. _external_imports.insert(d_itype._cpptype);
  1388. //out << "IMPORT_THIS struct Dtool_PyTypedObject Dtool_" << make_safe_name(d_itype.get_scoped_name().c_str()) << ";\n";
  1389. }
  1390. }
  1391. }
  1392. }
  1393. std::vector<std::string> bases;
  1394. for (di = 0; di < num_derivations; di++) {
  1395. TypeIndex d_type_Index = obj->_itype.get_derivation(di);
  1396. if (!interrogate_type_is_unpublished(d_type_Index)) {
  1397. const InterrogateType &d_itype = idb->get_type(d_type_Index);
  1398. if (is_cpp_type_legal(d_itype._cpptype)) {
  1399. bases.push_back(make_safe_name(d_itype.get_scoped_name().c_str()));
  1400. }
  1401. }
  1402. }
  1403. if (bases.empty()) {
  1404. bases.push_back("DTOOL_SUPER_BASE");
  1405. }
  1406. {
  1407. SlottedFunctions::iterator rfi;
  1408. for (rfi = slots.begin(); rfi != slots.end(); rfi++) {
  1409. const SlottedFunctionDef &def = rfi->second;
  1410. // This is just for reporting. There might be remaps from multiple
  1411. // functions with different names mapped to the same slot.
  1412. string fname;
  1413. if (def._remaps.size() > 0) {
  1414. const FunctionRemap *first_remap = *def._remaps.begin();
  1415. fname = first_remap->_cppfunc->get_simple_name();
  1416. }
  1417. if (def._min_version > 0) {
  1418. out << "#if PY_VERSION_HEX >= 0x" << hex << def._min_version << dec << "\n";
  1419. }
  1420. switch (rfi->second._wrapper_type) {
  1421. case WT_no_params:
  1422. case WT_iter_next: // TODO: fix iter_next to return NULL instead of None
  1423. // PyObject *func(PyObject *self)
  1424. {
  1425. out << "//////////////////\n";
  1426. out << "// A wrapper function to satisfy Python's internal calling conventions.\n";
  1427. out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n";
  1428. out << "//////////////////\n";
  1429. out << "static PyObject *" << def._wrapper_name << "(PyObject *self) {\n";
  1430. out << " " << cClassName << " *local_this = NULL;\n";
  1431. out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n";
  1432. out << " return NULL;\n";
  1433. out << " }\n\n";
  1434. string expected_params;
  1435. write_function_forset(out, def._remaps, 0, 0, expected_params, 2, true, true,
  1436. AT_no_args, RF_pyobject | RF_err_null, false);
  1437. out << " if (!_PyErr_OCCURRED()) {\n";
  1438. out << " return Dtool_Raise_BadArgumentsError(\n";
  1439. output_quoted(out, 6, expected_params);
  1440. out << ");\n";
  1441. out << " }\n";
  1442. out << " return NULL;\n";
  1443. out << "}\n\n";
  1444. }
  1445. break;
  1446. case WT_one_param:
  1447. case WT_binary_operator:
  1448. case WT_inplace_binary_operator:
  1449. // PyObject *func(PyObject *self, PyObject *one)
  1450. {
  1451. int return_flags = RF_err_null;
  1452. if (rfi->second._wrapper_type == WT_inplace_binary_operator) {
  1453. return_flags |= RF_self;
  1454. } else {
  1455. return_flags |= RF_pyobject;
  1456. }
  1457. out << "//////////////////\n";
  1458. out << "// A wrapper function to satisfy Python's internal calling conventions.\n";
  1459. out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n";
  1460. out << "//////////////////\n";
  1461. out << "static PyObject *" << def._wrapper_name << "(PyObject *self, PyObject *arg) {\n";
  1462. out << " " << cClassName << " *local_this = NULL;\n";
  1463. if (rfi->second._wrapper_type != WT_one_param) {
  1464. // WT_binary_operator means we must return NotImplemented, instead
  1465. // of raising an exception, if the this pointer doesn't
  1466. // match. This is for things like __sub__, which Python
  1467. // likes to call on the wrong-type objects.
  1468. out << " DTOOL_Call_ExtractThisPointerForType(self, &Dtool_" << ClassName << ", (void **)&local_this);\n";
  1469. out << " if (local_this == NULL) {\n";
  1470. out << " Py_INCREF(Py_NotImplemented);\n";
  1471. out << " return Py_NotImplemented;\n";
  1472. } else {
  1473. out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n";
  1474. out << " return NULL;\n";
  1475. }
  1476. out << " }\n";
  1477. string expected_params;
  1478. write_function_forset(out, def._remaps, 1, 1, expected_params, 2, true, true,
  1479. AT_single_arg, return_flags, false);
  1480. if (rfi->second._wrapper_type != WT_one_param) {
  1481. out << " Py_INCREF(Py_NotImplemented);\n";
  1482. out << " return Py_NotImplemented;\n";
  1483. } else {
  1484. out << " if (!_PyErr_OCCURRED()) {\n";
  1485. out << " return Dtool_Raise_BadArgumentsError(\n";
  1486. output_quoted(out, 6, expected_params);
  1487. out << ");\n";
  1488. out << " }\n";
  1489. out << " return NULL;\n";
  1490. }
  1491. out << "}\n\n";
  1492. }
  1493. break;
  1494. case WT_setattr:
  1495. // int func(PyObject *self, PyObject *one, PyObject *two = NULL)
  1496. {
  1497. out << "//////////////////\n";
  1498. out << "// A wrapper function to satisfy Python's internal calling conventions.\n";
  1499. out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n";
  1500. out << "//////////////////\n";
  1501. out << "static int " << def._wrapper_name << "(PyObject *self, PyObject *arg, PyObject *arg2) {\n";
  1502. out << " " << cClassName << " *local_this = NULL;\n";
  1503. out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n";
  1504. out << " return -1;\n";
  1505. out << " }\n\n";
  1506. set<FunctionRemap*> setattr_remaps;
  1507. set<FunctionRemap*> delattr_remaps;
  1508. // This function handles both delattr and setattr. Fish out
  1509. // the remaps for both types.
  1510. set<FunctionRemap*>::const_iterator ri;
  1511. for (ri = def._remaps.begin(); ri != def._remaps.end(); ++ri) {
  1512. FunctionRemap *remap = (*ri);
  1513. if (remap->_cppfunc->get_simple_name() == "__delattr__" && remap->_parameters.size() == 2) {
  1514. delattr_remaps.insert(remap);
  1515. } else if (remap->_cppfunc->get_simple_name() == "__setattr__" && remap->_parameters.size() == 3) {
  1516. setattr_remaps.insert(remap);
  1517. }
  1518. }
  1519. out << " // Determine whether to call __setattr__ or __delattr__.\n";
  1520. out << " if (arg2 != (PyObject *)NULL) { // __setattr__\n";
  1521. if (!setattr_remaps.empty()) {
  1522. out << " PyObject *args = PyTuple_Pack(2, arg, arg2);\n";
  1523. string expected_params;
  1524. write_function_forset(out, setattr_remaps, 2, 2, expected_params, 4,
  1525. true, true, AT_varargs, RF_int | RF_decref_args, true);
  1526. out << " Py_DECREF(args);\n";
  1527. out << " if (!_PyErr_OCCURRED()) {\n";
  1528. out << " Dtool_Raise_BadArgumentsError(\n";
  1529. output_quoted(out, 8, expected_params);
  1530. out << ");\n";
  1531. out << " }\n";
  1532. } else {
  1533. out << " PyErr_Format(PyExc_TypeError,\n";
  1534. out << " \"can't set attributes of built-in/extension type '%s'\",\n";
  1535. out << " Py_TYPE(self)->tp_name);\n";
  1536. }
  1537. out << " return -1;\n\n";
  1538. out << " } else { // __delattr__\n";
  1539. if (!delattr_remaps.empty()) {
  1540. string expected_params;
  1541. write_function_forset(out, delattr_remaps, 1, 1, expected_params, 4,
  1542. true, true, AT_single_arg, RF_int, true);
  1543. out << " if (!_PyErr_OCCURRED()) {\n";
  1544. out << " Dtool_Raise_BadArgumentsError(\n";
  1545. output_quoted(out, 8, expected_params);
  1546. out << ");\n";
  1547. out << " }\n";
  1548. } else {
  1549. out << " PyErr_Format(PyExc_TypeError,\n";
  1550. out << " \"can't delete attributes of built-in/extension type '%s'\",\n";
  1551. out << " Py_TYPE(self)->tp_name);\n";
  1552. }
  1553. out << " return -1;\n";
  1554. out << " }\n";
  1555. out << "}\n\n";
  1556. }
  1557. break;
  1558. case WT_getattr:
  1559. // PyObject *func(PyObject *self, PyObject *one)
  1560. // Specifically to implement __getattr__.
  1561. // First calls PyObject_GenericGetAttr(), and only calls the wrapper if it returns NULL.
  1562. // If one wants to override this completely, one should define __getattribute__ instead.
  1563. {
  1564. out << "//////////////////\n";
  1565. out << "// A wrapper function to satisfy Python's internal calling conventions.\n";
  1566. out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n";
  1567. out << "//////////////////\n";
  1568. out << "static PyObject *" << def._wrapper_name << "(PyObject *self, PyObject *arg) {\n";
  1569. out << " PyObject *res = PyObject_GenericGetAttr(self, arg);\n";
  1570. out << " if (res != NULL) {\n";
  1571. out << " return res;\n";
  1572. out << " }\n";
  1573. out << " if (!PyErr_ExceptionMatches(PyExc_AttributeError)) {\n";
  1574. out << " return NULL;\n";
  1575. out << " }\n";
  1576. out << " PyErr_Clear();\n\n";
  1577. out << " " << cClassName << " *local_this = NULL;\n";
  1578. out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n";
  1579. out << " return NULL;\n";
  1580. out << " }\n\n";
  1581. string expected_params;
  1582. write_function_forset(out, def._remaps, 1, 1, expected_params, 2,
  1583. true, true, AT_single_arg,
  1584. RF_pyobject | RF_err_null, true);
  1585. //out << " PyErr_Clear();\n";
  1586. out << " return NULL;\n";
  1587. out << "}\n\n";
  1588. }
  1589. break;
  1590. case WT_sequence_getitem:
  1591. // PyObject *func(PyObject *self, Py_ssize_t index)
  1592. {
  1593. out << "//////////////////\n";
  1594. out << "// A wrapper function to satisfy Python's internal calling conventions.\n";
  1595. out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n";
  1596. out << "//////////////////\n";
  1597. out << "static PyObject *" << def._wrapper_name << "(PyObject *self, Py_ssize_t index) {\n";
  1598. out << " " << cClassName << " *local_this = NULL;\n";
  1599. out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n";
  1600. out << " return NULL;\n";
  1601. out << " }\n\n";
  1602. // This is a getitem or setitem of a sequence type. This means we
  1603. // *need* to raise IndexError if we're out of bounds. We have to
  1604. // assume the bounds are 0 .. this->size() (this is the same
  1605. // assumption that Python makes).
  1606. out << " if (index < 0 || index >= (Py_ssize_t) local_this->size()) {\n";
  1607. out << " PyErr_SetString(PyExc_IndexError, \"" << ClassName << " index out of range\");\n";
  1608. out << " return NULL;\n";
  1609. out << " }\n";
  1610. string expected_params;
  1611. write_function_forset(out, def._remaps, 1, 1, expected_params, 2, true, true,
  1612. AT_no_args, RF_pyobject | RF_err_null, false, true, "index");
  1613. out << " if (!_PyErr_OCCURRED()) {\n";
  1614. out << " return Dtool_Raise_BadArgumentsError(\n";
  1615. output_quoted(out, 6, expected_params);
  1616. out << ");\n";
  1617. out << " }\n";
  1618. out << " return NULL;\n";
  1619. out << "}\n\n";
  1620. }
  1621. break;
  1622. case WT_sequence_setitem:
  1623. // int_t func(PyObject *self, Py_ssize_t index, PyObject *value)
  1624. {
  1625. out << "//////////////////\n";
  1626. out << "// A wrapper function to satisfy Python's internal calling conventions.\n";
  1627. out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n";
  1628. out << "//////////////////\n";
  1629. out << "static int " << def._wrapper_name << "(PyObject *self, Py_ssize_t index, PyObject *arg) {\n";
  1630. out << " " << cClassName << " *local_this = NULL;\n";
  1631. out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n";
  1632. out << " return -1;\n";
  1633. out << " }\n\n";
  1634. out << " if (index < 0 || index >= (Py_ssize_t) local_this->size()) {\n";
  1635. out << " PyErr_SetString(PyExc_IndexError, \"" << ClassName << " index out of range\");\n";
  1636. out << " return -1;\n";
  1637. out << " }\n";
  1638. set<FunctionRemap*> setitem_remaps;
  1639. set<FunctionRemap*> delitem_remaps;
  1640. // This function handles both delitem and setitem. Fish out
  1641. // the remaps for either one.
  1642. set<FunctionRemap*>::const_iterator ri;
  1643. for (ri = def._remaps.begin(); ri != def._remaps.end(); ++ri) {
  1644. FunctionRemap *remap = (*ri);
  1645. if (remap->_flags & FunctionRemap::F_setitem_int) {
  1646. setitem_remaps.insert(remap);
  1647. } else if (remap->_flags & FunctionRemap::F_delitem_int) {
  1648. delitem_remaps.insert(remap);
  1649. }
  1650. }
  1651. string expected_params;
  1652. out << " if (arg != (PyObject *)NULL) { // __setitem__\n";
  1653. write_function_forset(out, setitem_remaps, 2, 2, expected_params, 4,
  1654. true, true, AT_single_arg, RF_int, false, true, "index");
  1655. out << " } else { // __delitem__\n";
  1656. write_function_forset(out, delitem_remaps, 1, 1, expected_params, 4,
  1657. true, true, AT_single_arg, RF_int, false, true, "index");
  1658. out << " }\n\n";
  1659. out << " if (!_PyErr_OCCURRED()) {\n";
  1660. out << " Dtool_Raise_BadArgumentsError(\n";
  1661. output_quoted(out, 6, expected_params);
  1662. out << ");\n";
  1663. out << " }\n";
  1664. out << " return -1;\n";
  1665. out << "}\n\n";
  1666. }
  1667. break;
  1668. case WT_sequence_size:
  1669. // Py_ssize_t func(PyObject *self)
  1670. {
  1671. out << "//////////////////\n";
  1672. out << "// A wrapper function to satisfy Python's internal calling conventions.\n";
  1673. out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n";
  1674. out << "//////////////////\n";
  1675. out << "static Py_ssize_t " << def._wrapper_name << "(PyObject *self) {\n";
  1676. out << " " << cClassName << " *local_this = NULL;\n";
  1677. out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n";
  1678. out << " return -1;\n";
  1679. out << " }\n\n";
  1680. // This is a cheap cheat around all of the overhead of calling the wrapper function.
  1681. out << " return (Py_ssize_t) local_this->" << fname << "();\n";
  1682. out << "}\n\n";
  1683. }
  1684. break;
  1685. case WT_mapping_setitem:
  1686. // int func(PyObject *self, PyObject *one, PyObject *two)
  1687. {
  1688. out << "//////////////////\n";
  1689. out << "// A wrapper function to satisfy Python's internal calling conventions.\n";
  1690. out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n";
  1691. out << "//////////////////\n";
  1692. out << "static int " << def._wrapper_name << "(PyObject *self, PyObject *arg, PyObject *arg2) {\n";
  1693. out << " " << cClassName << " *local_this = NULL;\n";
  1694. out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n";
  1695. out << " return -1;\n";
  1696. out << " }\n\n";
  1697. set<FunctionRemap*> setitem_remaps;
  1698. set<FunctionRemap*> delitem_remaps;
  1699. // This function handles both delitem and setitem. Fish out
  1700. // the remaps for either one.
  1701. set<FunctionRemap*>::const_iterator ri;
  1702. for (ri = def._remaps.begin(); ri != def._remaps.end(); ++ri) {
  1703. FunctionRemap *remap = (*ri);
  1704. if (remap->_flags & FunctionRemap::F_setitem_int) {
  1705. setitem_remaps.insert(remap);
  1706. } else if (remap->_flags & FunctionRemap::F_delitem_int) {
  1707. delitem_remaps.insert(remap);
  1708. }
  1709. }
  1710. string expected_params;
  1711. out << " if (arg2 != (PyObject *)NULL) { // __setitem__\n";
  1712. out << " PyObject *args = PyTuple_Pack(2, arg, arg2);\n";
  1713. write_function_forset(out, setitem_remaps, 2, 2, expected_params, 4,
  1714. true, true, AT_varargs, RF_int | RF_decref_args, false);
  1715. out << " Py_DECREF(args);\n";
  1716. out << " } else { // __delitem__\n";
  1717. write_function_forset(out, delitem_remaps, 1, 1, expected_params, 4,
  1718. true, true, AT_single_arg, RF_int, false);
  1719. out << " }\n\n";
  1720. out << " if (!_PyErr_OCCURRED()) {\n";
  1721. out << " Dtool_Raise_BadArgumentsError(\n";
  1722. output_quoted(out, 6, expected_params);
  1723. out << ");\n";
  1724. out << " }\n";
  1725. out << " return -1;\n";
  1726. out << "}\n\n";
  1727. }
  1728. break;
  1729. case WT_inquiry:
  1730. // int func(PyObject *self)
  1731. {
  1732. out << "//////////////////\n";
  1733. out << "// A wrapper function to satisfy Python's internal calling conventions.\n";
  1734. out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n";
  1735. out << "//////////////////\n";
  1736. out << "static int " << def._wrapper_name << "(PyObject *self) {\n";
  1737. out << " " << cClassName << " *local_this = NULL;\n";
  1738. out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n";
  1739. out << " return -1;\n";
  1740. out << " }\n\n";
  1741. FunctionRemap *remap = *def._remaps.begin();
  1742. vector_string params;
  1743. out << " return (int) " << remap->call_function(out, 4, false, "local_this", params) << ";\n";
  1744. out << "}\n\n";
  1745. }
  1746. break;
  1747. case WT_getbuffer:
  1748. // int __getbuffer__(PyObject *self, Py_buffer *buffer, int flags)
  1749. // We map this directly, and assume that the arguments match. The whole point
  1750. // of this is to be fast, and we don't want to negate that by first wrapping
  1751. // and then unwrapping the arguments again. We also want to guarantee const
  1752. // correctness, since that will determine whether a read-only buffer is given.
  1753. {
  1754. has_local_getbuffer = true;
  1755. out << "//////////////////\n";
  1756. out << "// A wrapper function to satisfy Python's internal calling conventions.\n";
  1757. out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n";
  1758. out << "//////////////////\n";
  1759. out << "static int " << def._wrapper_name << "(PyObject *self, Py_buffer *buffer, int flags) {\n";
  1760. out << " " << cClassName << " *local_this = NULL;\n";
  1761. out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n";
  1762. out << " return -1;\n";
  1763. out << " }\n\n";
  1764. vector_string params_const(1);
  1765. vector_string params_nonconst(1);
  1766. FunctionRemap *remap_const = NULL;
  1767. FunctionRemap *remap_nonconst = NULL;
  1768. // Iterate through the remaps to find the one that matches our parameters.
  1769. set<FunctionRemap*>::const_iterator ri;
  1770. for (ri = def._remaps.begin(); ri != def._remaps.end(); ++ri) {
  1771. FunctionRemap *remap = (*ri);
  1772. if (remap->_const_method) {
  1773. if ((remap->_flags & FunctionRemap::F_explicit_self) == 0) {
  1774. params_const.push_back("self");
  1775. }
  1776. remap_const = remap;
  1777. } else {
  1778. if ((remap->_flags & FunctionRemap::F_explicit_self) == 0) {
  1779. params_nonconst.push_back("self");
  1780. }
  1781. remap_nonconst = remap;
  1782. }
  1783. }
  1784. params_const.push_back("buffer");
  1785. params_const.push_back("flags");
  1786. params_nonconst.push_back("buffer");
  1787. params_nonconst.push_back("flags");
  1788. // We have to distinguish properly between const and nonconst, because the function
  1789. // may depend on it to decide whether to provide a writable buffer or a readonly buffer.
  1790. const string const_this = "(const " + cClassName + " *)local_this";
  1791. if (remap_const != NULL && remap_nonconst != NULL) {
  1792. out << " if (!((Dtool_PyInstDef *)self)->_is_const) {\n";
  1793. out << " return " << remap_nonconst->call_function(out, 4, false, "local_this", params_nonconst) << ";\n";
  1794. out << " } else {\n";
  1795. out << " return " << remap_const->call_function(out, 4, false, const_this, params_const) << ";\n";
  1796. out << " }\n";
  1797. } else if (remap_nonconst != NULL) {
  1798. out << " if (!((Dtool_PyInstDef *)self)->_is_const) {\n";
  1799. out << " return " << remap_nonconst->call_function(out, 4, false, "local_this", params_nonconst) << ";\n";
  1800. out << " } else {\n";
  1801. out << " Dtool_Raise_TypeError(\"Cannot call " << ClassName << ".__getbuffer__() on a const object.\");\n";
  1802. out << " return -1;\n";
  1803. out << " }\n";
  1804. } else if (remap_const != NULL) {
  1805. out << " return " << remap_const->call_function(out, 4, false, const_this, params_const) << ";\n";
  1806. } else {
  1807. nout << ClassName << "::__getbuffer__ does not match the required signature.\n";
  1808. out << " return -1;\n";
  1809. }
  1810. out << "}\n\n";
  1811. }
  1812. break;
  1813. case WT_releasebuffer:
  1814. // void __releasebuffer__(PyObject *self, Py_buffer *buffer)
  1815. // Same story as __getbuffer__ above.
  1816. {
  1817. out << "//////////////////\n";
  1818. out << "// A wrapper function to satisfy Python's internal calling conventions.\n";
  1819. out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n";
  1820. out << "//////////////////\n";
  1821. out << "static void " << def._wrapper_name << "(PyObject *self, Py_buffer *buffer) {\n";
  1822. out << " " << cClassName << " *local_this = NULL;\n";
  1823. out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n";
  1824. out << " return;\n";
  1825. out << " }\n\n";
  1826. vector_string params_const(1);
  1827. vector_string params_nonconst(1);
  1828. FunctionRemap *remap_const = NULL;
  1829. FunctionRemap *remap_nonconst = NULL;
  1830. // Iterate through the remaps to find the one that matches our parameters.
  1831. set<FunctionRemap*>::const_iterator ri;
  1832. for (ri = def._remaps.begin(); ri != def._remaps.end(); ++ri) {
  1833. FunctionRemap *remap = (*ri);
  1834. if (remap->_const_method) {
  1835. if ((remap->_flags & FunctionRemap::F_explicit_self) == 0) {
  1836. params_const.push_back("self");
  1837. }
  1838. remap_const = remap;
  1839. } else {
  1840. if ((remap->_flags & FunctionRemap::F_explicit_self) == 0) {
  1841. params_nonconst.push_back("self");
  1842. }
  1843. remap_nonconst = remap;
  1844. }
  1845. }
  1846. params_const.push_back("buffer");
  1847. params_nonconst.push_back("buffer");
  1848. string return_expr;
  1849. const string const_this = "(const " + cClassName + " *)local_this";
  1850. if (remap_const != NULL && remap_nonconst != NULL) {
  1851. out << " if (!((Dtool_PyInstDef *)self)->_is_const) {\n";
  1852. return_expr = remap_nonconst->call_function(out, 4, false, "local_this", params_nonconst);
  1853. if (!return_expr.empty()) {
  1854. out << " " << return_expr << ";\n";
  1855. }
  1856. out << " } else {\n";
  1857. return_expr = remap_const->call_function(out, 4, false, const_this, params_const);
  1858. if (!return_expr.empty()) {
  1859. out << " " << return_expr << ";\n";
  1860. }
  1861. out << " }\n";
  1862. } else if (remap_nonconst != NULL) {
  1863. // Doesn't matter if there's no const version. We *have* to call it or else we could leak memory.
  1864. return_expr = remap_nonconst->call_function(out, 2, false, "local_this", params_nonconst);
  1865. if (!return_expr.empty()) {
  1866. out << " " << return_expr << ";\n";
  1867. }
  1868. } else if (remap_const != NULL) {
  1869. return_expr = remap_const->call_function(out, 2, false, const_this, params_const);
  1870. if (!return_expr.empty()) {
  1871. out << " " << return_expr << ";\n";
  1872. }
  1873. } else {
  1874. nout << ClassName << "::__releasebuffer__ does not match the required signature.\n";
  1875. out << " return;\n";
  1876. }
  1877. out << "}\n\n";
  1878. }
  1879. break;
  1880. case WT_ternary_operator:
  1881. case WT_inplace_ternary_operator:
  1882. // PyObject *func(PyObject *self, PyObject *one, PyObject *two)
  1883. {
  1884. int return_flags = RF_err_null;
  1885. if (rfi->second._wrapper_type == WT_inplace_ternary_operator) {
  1886. return_flags |= RF_self;
  1887. } else {
  1888. return_flags |= RF_pyobject;
  1889. }
  1890. out << "//////////////////\n";
  1891. out << "// A wrapper function to satisfy Python's internal calling conventions.\n";
  1892. out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n";
  1893. out << "//////////////////\n";
  1894. out << "static PyObject *" << def._wrapper_name << "(PyObject *self, PyObject *arg, PyObject *arg2) {\n";
  1895. out << " " << cClassName << " *local_this = NULL;\n";
  1896. out << " DTOOL_Call_ExtractThisPointerForType(self, &Dtool_" << ClassName << ", (void **)&local_this);\n";
  1897. out << " if (local_this == NULL) {\n";
  1898. // WT_ternary_operator means we must return NotImplemented, instead
  1899. // of raising an exception, if the this pointer doesn't
  1900. // match. This is for things like __pow__, which Python
  1901. // likes to call on the wrong-type objects.
  1902. out << " Py_INCREF(Py_NotImplemented);\n";
  1903. out << " return Py_NotImplemented;\n";
  1904. out << " }\n";
  1905. set<FunctionRemap*> one_param_remaps;
  1906. set<FunctionRemap*> two_param_remaps;
  1907. set<FunctionRemap*>::const_iterator ri;
  1908. for (ri = def._remaps.begin(); ri != def._remaps.end(); ++ri) {
  1909. FunctionRemap *remap = (*ri);
  1910. if (remap->_parameters.size() == 2) {
  1911. one_param_remaps.insert(remap);
  1912. } else if (remap->_parameters.size() == 3) {
  1913. two_param_remaps.insert(remap);
  1914. }
  1915. }
  1916. string expected_params;
  1917. out << " if (arg2 != (PyObject *)NULL) {\n";
  1918. out << " PyObject *args = PyTuple_Pack(2, arg, arg2);\n";
  1919. write_function_forset(out, two_param_remaps, 2, 2, expected_params, 4,
  1920. true, true, AT_varargs, RF_pyobject | RF_err_null | RF_decref_args, true);
  1921. out << " Py_DECREF(args);\n";
  1922. out << " } else {\n";
  1923. write_function_forset(out, one_param_remaps, 1, 1, expected_params, 4,
  1924. true, true, AT_single_arg, RF_pyobject | RF_err_null, true);
  1925. out << " }\n\n";
  1926. out << " if (!_PyErr_OCCURRED()) {\n";
  1927. out << " return Dtool_Raise_BadArgumentsError(\n";
  1928. output_quoted(out, 6, expected_params);
  1929. out << ");\n";
  1930. out << " }\n";
  1931. out << " return NULL;\n";
  1932. out << "}\n\n";
  1933. }
  1934. break;
  1935. case WT_traverse:
  1936. // int __traverse__(PyObject *self, visitproc visit, void *arg)
  1937. // This is a low-level function. Overloads are not supported.
  1938. {
  1939. out << "//////////////////\n";
  1940. out << "// A wrapper function to satisfy Python's internal calling conventions.\n";
  1941. out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n";
  1942. out << "//////////////////\n";
  1943. out << "static int " << def._wrapper_name << "(PyObject *self, visitproc visit, void *arg) {\n";
  1944. out << " " << cClassName << " *local_this = NULL;\n";
  1945. out << " DTOOL_Call_ExtractThisPointerForType(self, &Dtool_" << ClassName << ", (void **) &local_this);\n";
  1946. out << " if (local_this == NULL) {\n";
  1947. out << " PyErr_SetString(PyExc_AttributeError, \"C++ object is not yet constructed, or already destructed.\");\n";
  1948. out << " return -1;\n";
  1949. out << " }\n\n";
  1950. // Find the remap. There should be only one.
  1951. FunctionRemap *remap = *def._remaps.begin();
  1952. vector_string params(1);
  1953. if (remap->_flags & FunctionRemap::F_explicit_self) {
  1954. params.push_back("self");
  1955. }
  1956. params.push_back("visit");
  1957. params.push_back("arg");
  1958. out << " return " << remap->call_function(out, 2, false, "local_this", params) << ";\n";
  1959. out << "}\n\n";
  1960. }
  1961. break;
  1962. case WT_compare:
  1963. // int func(PyObject *self, Py_ssize_t index)
  1964. {
  1965. out << "//////////////////\n";
  1966. out << "// A wrapper function to satisfy Python's internal calling conventions.\n";
  1967. out << "// " << ClassName << " slot " << rfi->second._answer_location << " -> " << fname << "\n";
  1968. out << "//////////////////\n";
  1969. out << "static int " << def._wrapper_name << "(PyObject *self, PyObject *arg) {\n";
  1970. out << " " << cClassName << " *local_this = NULL;\n";
  1971. out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n";
  1972. out << " return -1;\n";
  1973. out << " }\n\n";
  1974. string expected_params;
  1975. write_function_forset(out, def._remaps, 1, 1, expected_params, 2, true, true,
  1976. AT_single_arg, RF_compare, false, true);
  1977. out << " if (!_PyErr_OCCURRED()) {\n";
  1978. out << " Dtool_Raise_BadArgumentsError(\n";
  1979. output_quoted(out, 6, expected_params);
  1980. out << ");\n";
  1981. out << " }\n";
  1982. out << " return -1;\n";
  1983. out << "}\n\n";
  1984. }
  1985. break;
  1986. case WT_none:
  1987. // Nothing special about the wrapper function: just write it normally.
  1988. string fname = "static PyObject *" + def._wrapper_name + "(PyObject *self, PyObject *args, PyObject *kwds)\n";
  1989. vector<FunctionRemap *> remaps;
  1990. remaps.insert(remaps.end(), def._remaps.begin(), def._remaps.end());
  1991. string expected_params;
  1992. write_function_for_name(out, obj, remaps, fname, expected_params, true, AT_keyword_args, RF_pyobject | RF_err_null);
  1993. break;
  1994. }
  1995. if (def._min_version > 0) {
  1996. out << "#endif // PY_VERSION_HEX >= 0x" << hex << def._min_version << dec << "\n";
  1997. }
  1998. }
  1999. string get_key = HasAGetKeyFunction(obj->_itype);
  2000. if (!get_key.empty()) {
  2001. out << "//////////////////\n";
  2002. out << "// A LocalHash(getKey) Function for this type\n";
  2003. out << "// " << ClassName << "\n";
  2004. out << "//////////////////\n";
  2005. out << "static Py_hash_t Dtool_HashKey_" << ClassName << "(PyObject *self) {\n";
  2006. out << " " << cClassName << " *local_this = NULL;\n";
  2007. out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n";
  2008. out << " return -1;\n";
  2009. out << " }\n\n";
  2010. out << " return local_this->" << get_key << "();\n";
  2011. out << "}\n\n";
  2012. has_local_hash = true;
  2013. } else {
  2014. if (bases.size() == 0) {
  2015. out << "//////////////////\n";
  2016. out << "// A LocalHash(This Pointer) Function for this type\n";
  2017. out << "// " << ClassName << "\n";
  2018. out << "//////////////////\n";
  2019. out << "static Py_hash_t Dtool_HashKey_" << ClassName << "(PyObject *self) {\n";
  2020. out << " " << cClassName << " *local_this = NULL;\n";
  2021. out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n";
  2022. out << " return -1;\n";
  2023. out << " }\n\n";
  2024. out << " return (Py_hash_t) local_this;\n";
  2025. out << "}\n\n";
  2026. has_local_hash = true;
  2027. }
  2028. }
  2029. int need_repr = 0;
  2030. if (slots.count("tp_repr") == 0) {
  2031. need_repr = NeedsAReprFunction(obj->_itype);
  2032. }
  2033. if (need_repr > 0) {
  2034. out << "//////////////////\n";
  2035. out << "// A __repr__ function\n";
  2036. out << "// " << ClassName << "\n";
  2037. out << "//////////////////\n";
  2038. out << "static PyObject *Dtool_Repr_" << ClassName << "(PyObject *self) {\n";
  2039. out << " " << cClassName << " *local_this = NULL;\n";
  2040. out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n";
  2041. out << " return NULL;\n";
  2042. out << " }\n\n";
  2043. out << " ostringstream os;\n";
  2044. if (need_repr == 3) {
  2045. out << " invoke_extension(local_this).python_repr(os, \""
  2046. << classNameFromCppName(ClassName, false) << "\");\n";
  2047. } else if (need_repr == 2) {
  2048. out << " local_this->output(os);\n";
  2049. } else {
  2050. out << " local_this->python_repr(os, \""
  2051. << classNameFromCppName(ClassName, false) << "\");\n";
  2052. }
  2053. out << " std::string ss = os.str();\n";
  2054. out << "#if PY_MAJOR_VERSION >= 3\n";
  2055. out << " return PyUnicode_FromStringAndSize(ss.data(), ss.length());\n";
  2056. out << "#else\n";
  2057. out << " return PyString_FromStringAndSize(ss.data(), ss.length());\n";
  2058. out << "#endif\n";
  2059. out << "}\n\n";
  2060. has_local_repr = true;
  2061. }
  2062. int need_str = 0;
  2063. if (slots.count("tp_str") == 0) {
  2064. need_str = NeedsAStrFunction(obj->_itype);
  2065. }
  2066. if (need_str > 0) {
  2067. out << "//////////////////\n";
  2068. out << "// A __str__ function\n";
  2069. out << "// " << ClassName << "\n";
  2070. out << "//////////////////\n";
  2071. out << "static PyObject *Dtool_Str_" << ClassName << "(PyObject *self) {\n";
  2072. out << " " << cClassName << " *local_this = NULL;\n";
  2073. out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n";
  2074. out << " return NULL;\n";
  2075. out << " }\n\n";
  2076. out << " ostringstream os;\n";
  2077. if (need_str == 2) {
  2078. out << " local_this->write(os, 0);\n";
  2079. } else {
  2080. out << " local_this->write(os);\n";
  2081. }
  2082. out << " std::string ss = os.str();\n";
  2083. out << "#if PY_MAJOR_VERSION >= 3\n";
  2084. out << " return PyUnicode_FromStringAndSize(ss.data(), ss.length());\n";
  2085. out << "#else\n";
  2086. out << " return PyString_FromStringAndSize(ss.data(), ss.length());\n";
  2087. out << "#endif\n";
  2088. out << "}\n\n";
  2089. has_local_str = true;
  2090. }
  2091. }
  2092. if (NeedsARichCompareFunction(obj->_itype)) {
  2093. out << "//////////////////\n";
  2094. out << "// A rich comparison function\n";
  2095. out << "// " << ClassName << "\n";
  2096. out << "//////////////////\n";
  2097. out << "static PyObject *Dtool_RichCompare_" << ClassName << "(PyObject *self, PyObject *arg, int op) {\n";
  2098. out << " " << cClassName << " *local_this = NULL;\n";
  2099. out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n";
  2100. out << " return NULL;\n";
  2101. out << " }\n\n";
  2102. out << " switch (op) {\n";
  2103. for (fi = obj->_methods.begin(); fi != obj->_methods.end(); ++fi) {
  2104. std::set<FunctionRemap*> remaps;
  2105. Function *func = (*fi);
  2106. if (!func) {
  2107. continue;
  2108. }
  2109. // We only accept comparison operators that take one parameter (besides 'this').
  2110. Function::Remaps::const_iterator ri;
  2111. for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri) {
  2112. FunctionRemap *remap = (*ri);
  2113. if (is_remap_legal(remap) && remap->_has_this && (remap->_args_type == AT_single_arg)) {
  2114. remaps.insert(remap);
  2115. }
  2116. }
  2117. const string &fname = func->_ifunc.get_name();
  2118. if (fname == "operator <") {
  2119. out << " case Py_LT:\n";
  2120. } else if (fname == "operator <=") {
  2121. out << " case Py_LE:\n";
  2122. } else if (fname == "operator ==") {
  2123. out << " case Py_EQ:\n";
  2124. } else if (fname == "operator !=") {
  2125. out << " case Py_NE:\n";
  2126. } else if (fname == "operator >") {
  2127. out << " case Py_GT:\n";
  2128. } else if (fname == "operator >=") {
  2129. out << " case Py_GE:\n";
  2130. } else {
  2131. continue;
  2132. }
  2133. out << " {\n";
  2134. string expected_params;
  2135. write_function_forset(out, remaps, 1, 1, expected_params, 6, true, false,
  2136. AT_single_arg, RF_pyobject | RF_err_null, false);
  2137. out << " break;\n";
  2138. out << " }\n";
  2139. has_local_richcompare = true;
  2140. }
  2141. out << " }\n\n";
  2142. out << " if (_PyErr_OCCURRED()) {\n";
  2143. out << " PyErr_Clear();\n";
  2144. out << " }\n\n";
  2145. if (slots.count("tp_compare")) {
  2146. // A lot of Panda code depends on comparisons being done via the
  2147. // compare_to function, which is mapped to the tp_compare slot, which
  2148. // Python 3 no longer has. So, we'll write code to fall back to that if
  2149. // no matching comparison operator was found.
  2150. out << "#if PY_MAJOR_VERSION >= 3\n";
  2151. out << " // All is not lost; we still have the compare_to function to fall back onto.\n";
  2152. out << " int cmpval = " << slots["tp_compare"]._wrapper_name << "(self, arg);\n";
  2153. out << " if (cmpval == -1 && _PyErr_OCCURRED()) {\n";
  2154. out << " if (PyErr_ExceptionMatches(PyExc_TypeError)) {\n";
  2155. out << " PyErr_Clear();\n";
  2156. out << " } else {\n";
  2157. out << " return (PyObject *)NULL;\n";
  2158. out << " }\n";
  2159. out << " }\n";
  2160. out << " switch (op) {\n";
  2161. out << " case Py_LT:\n";
  2162. out << " return PyBool_FromLong(cmpval < 0);\n";
  2163. out << " case Py_LE:\n";
  2164. out << " return PyBool_FromLong(cmpval <= 0);\n";
  2165. out << " case Py_EQ:\n";
  2166. out << " return PyBool_FromLong(cmpval == 0);\n";
  2167. out << " case Py_NE:\n";
  2168. out << " return PyBool_FromLong(cmpval != 0);\n";
  2169. out << " case Py_GT:\n";
  2170. out << " return PyBool_FromLong(cmpval > 0);\n";
  2171. out << " case Py_GE:\n";
  2172. out << " return PyBool_FromLong(cmpval >= 0);\n";
  2173. out << " }\n";
  2174. out << "#endif\n\n";
  2175. }
  2176. out << " Py_INCREF(Py_NotImplemented);\n";
  2177. out << " return Py_NotImplemented;\n";
  2178. out << "}\n\n";
  2179. }
  2180. int num_getset = 0;
  2181. if (obj->_properties.size() > 0) {
  2182. // Write out the array of properties, telling Python which getter and setter
  2183. // to call when they are assigned or queried in Python code.
  2184. out << "static PyGetSetDef Dtool_Properties_" << ClassName << "[] = {\n";
  2185. Properties::const_iterator pit;
  2186. for (pit = obj->_properties.begin(); pit != obj->_properties.end(); ++pit) {
  2187. Property *property = (*pit);
  2188. const InterrogateElement &ielem = property->_ielement;
  2189. if (property->_getter == NULL || !is_function_legal(property->_getter)) {
  2190. continue;
  2191. }
  2192. ++num_getset;
  2193. string name1 = methodNameFromCppName(ielem.get_name(), "", false);
  2194. string name2 = methodNameFromCppName(ielem.get_name(), "", true);
  2195. string getter = "&Dtool_" + ClassName + "_" + ielem.get_name() + "_Getter";
  2196. string setter = "NULL";
  2197. if (property->_setter != NULL && is_function_legal(property->_setter)) {
  2198. setter = "&Dtool_" + ClassName + "_" + ielem.get_name() + "_Setter";
  2199. }
  2200. out << " {(char *)\"" << name1 << "\", " << getter << ", " << setter;
  2201. if (ielem.has_comment()) {
  2202. out << ", (char *)\n";
  2203. output_quoted(out, 4, ielem.get_comment());
  2204. out << ",\n ";
  2205. } else {
  2206. out << ", NULL, ";
  2207. }
  2208. // Extra void* argument; we don't make use of it.
  2209. out << "NULL},\n";
  2210. if (name1 != name2 && name1 != "__dict__") {
  2211. // Add alternative spelling.
  2212. out << " {(char *)\"" << name2 << "\", " << getter << ", " << setter
  2213. << ", (char *)\n"
  2214. << " \"Alias of " << name1 << ", for consistency with old naming conventions.\",\n"
  2215. << " NULL},\n";
  2216. }
  2217. }
  2218. out << " {NULL},\n";
  2219. out << "};\n\n";
  2220. }
  2221. bool has_parent_class = (obj->_itype.number_of_derivations() != 0);
  2222. // Output the type slot tables.
  2223. out << "static PyNumberMethods Dtool_NumberMethods_" << ClassName << " = {\n";
  2224. write_function_slot(out, 2, slots, "nb_add");
  2225. write_function_slot(out, 2, slots, "nb_subtract");
  2226. write_function_slot(out, 2, slots, "nb_multiply");
  2227. out << "#if PY_MAJOR_VERSION < 3\n";
  2228. // Note: nb_divide does not exist in Python 3. We will probably need some
  2229. // smart mechanism for dispatching to either floor_divide or true_divide.
  2230. write_function_slot(out, 2, slots, "nb_divide");
  2231. out << "#endif\n";
  2232. write_function_slot(out, 2, slots, "nb_remainder");
  2233. write_function_slot(out, 2, slots, "nb_divmod");
  2234. write_function_slot(out, 2, slots, "nb_power");
  2235. write_function_slot(out, 2, slots, "nb_negative");
  2236. write_function_slot(out, 2, slots, "nb_positive");
  2237. write_function_slot(out, 2, slots, "nb_absolute");
  2238. write_function_slot(out, 2, slots, "nb_bool");
  2239. write_function_slot(out, 2, slots, "nb_invert");
  2240. write_function_slot(out, 2, slots, "nb_lshift");
  2241. write_function_slot(out, 2, slots, "nb_rshift");
  2242. write_function_slot(out, 2, slots, "nb_and");
  2243. write_function_slot(out, 2, slots, "nb_xor");
  2244. write_function_slot(out, 2, slots, "nb_or");
  2245. out << "#if PY_MAJOR_VERSION < 3\n";
  2246. write_function_slot(out, 2, slots, "nb_coerce");
  2247. out << "#endif\n";
  2248. write_function_slot(out, 2, slots, "nb_int");
  2249. out << " 0, // nb_long\n"; // removed in Python 3
  2250. write_function_slot(out, 2, slots, "nb_float");
  2251. out << "#if PY_MAJOR_VERSION < 3\n";
  2252. write_function_slot(out, 2, slots, "nb_oct");
  2253. write_function_slot(out, 2, slots, "nb_hex");
  2254. out << "#endif\n";
  2255. write_function_slot(out, 2, slots, "nb_inplace_add");
  2256. write_function_slot(out, 2, slots, "nb_inplace_subtract");
  2257. write_function_slot(out, 2, slots, "nb_inplace_multiply");
  2258. out << "#if PY_MAJOR_VERSION < 3\n";
  2259. write_function_slot(out, 2, slots, "nb_inplace_divide");
  2260. out << "#endif\n";
  2261. write_function_slot(out, 2, slots, "nb_inplace_remainder");
  2262. write_function_slot(out, 2, slots, "nb_inplace_power");
  2263. write_function_slot(out, 2, slots, "nb_inplace_lshift");
  2264. write_function_slot(out, 2, slots, "nb_inplace_rshift");
  2265. write_function_slot(out, 2, slots, "nb_inplace_and");
  2266. write_function_slot(out, 2, slots, "nb_inplace_xor");
  2267. write_function_slot(out, 2, slots, "nb_inplace_or");
  2268. write_function_slot(out, 2, slots, "nb_floor_divide");
  2269. write_function_slot(out, 2, slots, "nb_true_divide");
  2270. write_function_slot(out, 2, slots, "nb_inplace_floor_divide");
  2271. write_function_slot(out, 2, slots, "nb_inplace_true_divide");
  2272. out << "#if PY_VERSION_HEX >= 0x02050000\n";
  2273. write_function_slot(out, 2, slots, "nb_index");
  2274. out << "#endif\n";
  2275. out << "};\n\n";
  2276. // NB: it's tempting not to write this table when a class doesn't have them.
  2277. // But then Python won't inherit them from base classes either! So we always
  2278. // write this table for now even if it will be full of 0's, unless this type
  2279. // has no base classes at all.
  2280. if (has_parent_class || (obj->_protocol_types & Object::PT_sequence) != 0) {
  2281. out << "static PySequenceMethods Dtool_SequenceMethods_" << ClassName << " = {\n";
  2282. write_function_slot(out, 2, slots, "sq_length");
  2283. write_function_slot(out, 2, slots, "sq_concat");
  2284. write_function_slot(out, 2, slots, "sq_repeat");
  2285. write_function_slot(out, 2, slots, "sq_item");
  2286. out << " 0, // sq_slice\n"; // removed in Python 3
  2287. write_function_slot(out, 2, slots, "sq_ass_item");
  2288. out << " 0, // sq_ass_slice\n"; // removed in Python 3
  2289. write_function_slot(out, 2, slots, "sq_contains");
  2290. write_function_slot(out, 2, slots, "sq_inplace_concat");
  2291. write_function_slot(out, 2, slots, "sq_inplace_repeat");
  2292. out << "};\n\n";
  2293. }
  2294. // Same note applies as for the SequenceMethods.
  2295. if (has_parent_class || (obj->_protocol_types & Object::PT_mapping) != 0) {
  2296. out << "static PyMappingMethods Dtool_MappingMethods_" << ClassName << " = {\n";
  2297. write_function_slot(out, 2, slots, "mp_length");
  2298. write_function_slot(out, 2, slots, "mp_subscript");
  2299. write_function_slot(out, 2, slots, "mp_ass_subscript");
  2300. out << "};\n\n";
  2301. }
  2302. // Same note applies as above.
  2303. if (has_parent_class || has_local_getbuffer) {
  2304. out << "static PyBufferProcs Dtool_BufferProcs_" << ClassName << " = {\n";
  2305. out << "#if PY_MAJOR_VERSION < 3\n";
  2306. write_function_slot(out, 2, slots, "bf_getreadbuffer");
  2307. write_function_slot(out, 2, slots, "bf_getwritebuffer");
  2308. write_function_slot(out, 2, slots, "bf_getsegcount");
  2309. write_function_slot(out, 2, slots, "bf_getcharbuffer");
  2310. out << "#endif\n";
  2311. out << "#if PY_MAJOR_VERSION >= 0x02060000\n";
  2312. write_function_slot(out, 2, slots, "bf_getbuffer");
  2313. write_function_slot(out, 2, slots, "bf_releasebuffer");
  2314. out << "#endif\n";
  2315. out << "};\n\n";
  2316. }
  2317. // Output the actual PyTypeObject definition.
  2318. out << "EXPORT_THIS Dtool_PyTypedObject Dtool_" << ClassName << " = {\n";
  2319. out << " {\n";
  2320. out << " PyVarObject_HEAD_INIT(NULL, 0)\n";
  2321. // const char *tp_name;
  2322. out << " \"" << _def->module_name << "." << export_class_name << "\",\n";
  2323. // Py_ssize_t tp_basicsize;
  2324. out << " sizeof(Dtool_PyInstDef),\n";
  2325. // Py_ssize_t tp_itemsize;
  2326. out << " 0, // tp_itemsize\n";
  2327. // destructor tp_dealloc;
  2328. out << " &Dtool_FreeInstance_" << ClassName << ",\n";
  2329. // printfunc tp_print;
  2330. write_function_slot(out, 4, slots, "tp_print");
  2331. // getattrfunc tp_getattr;
  2332. write_function_slot(out, 4, slots, "tp_getattr");
  2333. // setattrfunc tp_setattr;
  2334. write_function_slot(out, 4, slots, "tp_setattr");
  2335. // cmpfunc tp_compare; (reserved in Python 3)
  2336. out << "#if PY_MAJOR_VERSION >= 3\n";
  2337. out << " 0, // tp_reserved\n";
  2338. out << "#else\n";
  2339. if (slots.count("tp_compare") != 0) {
  2340. write_function_slot(out, 4, slots, "tp_compare");
  2341. } else {
  2342. // We can/should still define a comparison in Python 2 that is more
  2343. // meaningful that comparing id(x) with id(y).
  2344. out << " &DTOOL_PyObject_ComparePointers,\n";
  2345. }
  2346. out << "#endif\n";
  2347. // reprfunc tp_repr;
  2348. if (has_local_repr) {
  2349. out << " &Dtool_Repr_" << ClassName << ",\n";
  2350. } else {
  2351. write_function_slot(out, 4, slots, "tp_repr");
  2352. }
  2353. // PyNumberMethods *tp_as_number;
  2354. out << " &Dtool_NumberMethods_" << ClassName << ",\n";
  2355. // PySequenceMethods *tp_as_sequence;
  2356. if (has_parent_class || (obj->_protocol_types & Object::PT_sequence) != 0) {
  2357. out << " &Dtool_SequenceMethods_" << ClassName << ",\n";
  2358. } else {
  2359. out << " 0, // tp_as_sequence\n";
  2360. }
  2361. // PyMappingMethods *tp_as_mapping;
  2362. if (has_parent_class || (obj->_protocol_types & Object::PT_mapping) != 0) {
  2363. out << " &Dtool_MappingMethods_" << ClassName << ",\n";
  2364. } else {
  2365. out << " 0, // tp_as_mapping\n";
  2366. }
  2367. // hashfunc tp_hash;
  2368. if (has_local_hash) {
  2369. out << " &Dtool_HashKey_" << ClassName << ",\n";
  2370. } else {
  2371. write_function_slot(out, 4, slots, "tp_hash");
  2372. }
  2373. // ternaryfunc tp_call;
  2374. write_function_slot(out, 4, slots, "tp_call");
  2375. // reprfunc tp_str;
  2376. if (has_local_str) {
  2377. out << " &Dtool_Str_" << ClassName << ",\n";
  2378. } else if (has_local_repr) {
  2379. out << " &Dtool_Repr_" << ClassName << ",\n";
  2380. } else {
  2381. write_function_slot(out, 4, slots, "tp_str");
  2382. }
  2383. // getattrofunc tp_getattro;
  2384. write_function_slot(out, 4, slots, "tp_getattro",
  2385. "PyObject_GenericGetAttr");
  2386. // setattrofunc tp_setattro;
  2387. write_function_slot(out, 4, slots, "tp_setattro",
  2388. "PyObject_GenericSetAttr");
  2389. // PyBufferProcs *tp_as_buffer;
  2390. if (has_parent_class || has_local_getbuffer) {
  2391. out << " &Dtool_BufferProcs_" << ClassName << ",\n";
  2392. } else {
  2393. out << " 0, // tp_as_buffer\n";
  2394. }
  2395. string gcflag;
  2396. if (obj->_protocol_types & Object::PT_python_gc) {
  2397. gcflag = " | Py_TPFLAGS_HAVE_GC";
  2398. }
  2399. // long tp_flags;
  2400. if (has_local_getbuffer) {
  2401. out << "#if PY_VERSION_HEX >= 0x02060000 && PY_VERSION_HEX < 0x03000000\n";
  2402. out << " Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_CHECKTYPES | Py_TPFLAGS_HAVE_NEWBUFFER" << gcflag << ",\n";
  2403. out << "#else\n";
  2404. out << " Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_CHECKTYPES" << gcflag << ",\n";
  2405. out << "#endif\n";
  2406. } else {
  2407. out << " Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_CHECKTYPES" << gcflag << ",\n";
  2408. }
  2409. // const char *tp_doc;
  2410. if (obj->_itype.has_comment()) {
  2411. out << "#ifdef NDEBUG\n";
  2412. out << " 0,\n";
  2413. out << "#else\n";
  2414. output_quoted(out, 4, obj->_itype.get_comment());
  2415. out << ",\n";
  2416. out << "#endif\n";
  2417. } else {
  2418. out << " 0, // tp_doc\n";
  2419. }
  2420. // traverseproc tp_traverse;
  2421. write_function_slot(out, 4, slots, "tp_traverse");
  2422. // inquiry tp_clear;
  2423. write_function_slot(out, 4, slots, "tp_clear");
  2424. // richcmpfunc tp_richcompare;
  2425. if (has_local_richcompare) {
  2426. out << " &Dtool_RichCompare_" << ClassName << ",\n";
  2427. } else if (has_local_hash) {
  2428. out << "#if PY_MAJOR_VERSION >= 3\n";
  2429. out << " &DTOOL_PyObject_RichCompare,\n";
  2430. out << "#else\n";
  2431. out << " 0,\n";
  2432. out << "#endif\n";
  2433. } else {
  2434. write_function_slot(out, 4, slots, "tp_richcompare");
  2435. }
  2436. // Py_ssize_t tp_weaklistoffset;
  2437. out << " 0, // tp_weaklistoffset\n";
  2438. // getiterfunc tp_iter;
  2439. write_function_slot(out, 4, slots, "tp_iter");
  2440. // iternextfunc tp_iternext;
  2441. write_function_slot(out, 4, slots, "tp_iternext");
  2442. // struct PyMethodDef *tp_methods;
  2443. out << " Dtool_Methods_" << ClassName << ",\n";
  2444. // struct PyMemberDef *tp_members;
  2445. out << " standard_type_members,\n";
  2446. // struct PyGetSetDef *tp_getset;
  2447. if (num_getset > 0) {
  2448. out << " Dtool_Properties_" << ClassName << ",\n";
  2449. } else {
  2450. out << " 0, // tp_getset\n";
  2451. }
  2452. // struct _typeobject *tp_base;
  2453. out << " 0, // tp_base\n";
  2454. // PyObject *tp_dict;
  2455. out << " 0, // tp_dict\n";
  2456. // descrgetfunc tp_descr_get;
  2457. write_function_slot(out, 4, slots, "tp_descr_get");
  2458. // descrsetfunc tp_descr_set;
  2459. write_function_slot(out, 4, slots, "tp_descr_set");
  2460. // Py_ssize_t tp_dictoffset;
  2461. out << " 0, // tp_dictoffset\n";
  2462. // initproc tp_init;
  2463. if (obj->_constructors.size() > 0) {
  2464. out << " Dtool_Init_" << ClassName << ",\n";
  2465. } else {
  2466. out << " 0,\n";
  2467. }
  2468. // allocfunc tp_alloc;
  2469. out << " PyType_GenericAlloc,\n";
  2470. // newfunc tp_new;
  2471. out << " Dtool_new_" << ClassName << ",\n";
  2472. // freefunc tp_free;
  2473. if (obj->_protocol_types & Object::PT_python_gc) {
  2474. out << " PyObject_GC_Del,\n";
  2475. } else {
  2476. out << " PyObject_Del,\n";
  2477. }
  2478. // inquiry tp_is_gc;
  2479. out << " 0, // tp_is_gc\n";
  2480. // PyObject *tp_bases;
  2481. out << " 0, // tp_bases\n";
  2482. // PyObject *tp_mro;
  2483. out << " 0, // tp_mro\n";
  2484. // PyObject *tp_cache;
  2485. out << " 0, // tp_cache\n";
  2486. // PyObject *tp_subclasses;
  2487. out << " 0, // tp_subclasses\n";
  2488. // PyObject *tp_weaklist;
  2489. out << " 0, // tp_weaklist\n";
  2490. // destructor tp_del;
  2491. out << " 0, // tp_del\n";
  2492. // unsigned int tp_version_tag
  2493. out << "#if PY_VERSION_HEX >= 0x02060000\n";
  2494. out << " 0, // tp_version_tag\n";
  2495. out << "#endif\n";
  2496. out << " },\n";
  2497. out << " Dtool_UpcastInterface_" << ClassName << ",\n";
  2498. out << " Dtool_DowncastInterface_" << ClassName << ",\n";
  2499. out << " TypeHandle::none(),\n";
  2500. out << "};\n\n";
  2501. out << "void Dtool_PyModuleClassInit_" << ClassName << "(PyObject *module) {\n";
  2502. out << " (void) module; // Unused\n";
  2503. out << " static bool initdone = false;\n";
  2504. out << " if (!initdone) {\n";
  2505. out << " initdone = true;\n";
  2506. // Add bases.
  2507. if (bases.size() > 0) {
  2508. out << " // Dependent objects\n";
  2509. string baseargs;
  2510. for (vector<string>::iterator bi = bases.begin(); bi != bases.end(); ++bi) {
  2511. baseargs += ", &Dtool_" + *bi + ".As_PyTypeObject()";
  2512. out << " Dtool_PyModuleClassInit_" << make_safe_name(*bi) << "(NULL);\n";
  2513. }
  2514. out << " Dtool_" << ClassName << ".As_PyTypeObject().tp_bases = PyTuple_Pack(" << bases.size() << baseargs << ");\n";
  2515. }
  2516. int num_nested = obj->_itype.number_of_nested_types();
  2517. int num_dict_items = 1;
  2518. // Go through once to estimate the number of elements the dict will hold.
  2519. for (int ni = 0; ni < num_nested; ni++) {
  2520. TypeIndex nested_index = obj->_itype.get_nested_type(ni);
  2521. if (_objects.count(nested_index) == 0) {
  2522. continue;
  2523. }
  2524. Object *nested_obj = _objects[nested_index];
  2525. assert(nested_obj != (Object *)NULL);
  2526. if (nested_obj->_itype.is_class() || nested_obj->_itype.is_struct()) {
  2527. num_dict_items += 2;
  2528. } else if (nested_obj->_itype.is_typedef()) {
  2529. ++num_dict_items;
  2530. } else if (nested_obj->_itype.is_enum()) {
  2531. CPPEnumType *enum_type = nested_obj->_itype._cpptype->as_enum_type();
  2532. num_dict_items += 2 * enum_type->_elements.size();
  2533. }
  2534. }
  2535. // Build type dictionary. The size is just an estimation.
  2536. if (num_dict_items > 5) {
  2537. out << " PyObject *dict = _PyDict_NewPresized(" << num_dict_items << ");\n";
  2538. } else {
  2539. out << " PyObject *dict = PyDict_New();\n";
  2540. }
  2541. out << " Dtool_" << ClassName << ".As_PyTypeObject().tp_dict = dict;\n";
  2542. out << " PyDict_SetItemString(dict, \"DtoolClassDict\", dict);\n";
  2543. // Now go through the nested types again to actually add the dict items.
  2544. for (int ni = 0; ni < num_nested; ni++) {
  2545. TypeIndex nested_index = obj->_itype.get_nested_type(ni);
  2546. if (_objects.count(nested_index) == 0) {
  2547. // Illegal type.
  2548. continue;
  2549. }
  2550. Object *nested_obj = _objects[nested_index];
  2551. assert(nested_obj != (Object *)NULL);
  2552. if (nested_obj->_itype.is_class() || nested_obj->_itype.is_struct()) {
  2553. std::string ClassName1 = make_safe_name(nested_obj->_itype.get_scoped_name());
  2554. std::string ClassName2 = make_safe_name(nested_obj->_itype.get_name());
  2555. out << " // Nested Object " << ClassName1 << ";\n";
  2556. out << " Dtool_PyModuleClassInit_" << ClassName1 << "(NULL);\n";
  2557. string name1 = classNameFromCppName(ClassName2, false);
  2558. string name2 = classNameFromCppName(ClassName2, true);
  2559. out << " PyDict_SetItemString(dict, \"" << name1 << "\", (PyObject *)&Dtool_" << ClassName1 << ".As_PyTypeObject());\n";
  2560. if (name1 != name2) {
  2561. out << " PyDict_SetItemString(dict, \"" << name2 << "\", (PyObject *)&Dtool_" << ClassName1 << ".As_PyTypeObject());\n";
  2562. }
  2563. } else if (nested_obj->_itype.is_typedef()) {
  2564. // Unwrap typedefs.
  2565. TypeIndex wrapped = nested_obj->_itype._wrapped_type;
  2566. while (interrogate_type_is_typedef(wrapped)) {
  2567. wrapped = interrogate_type_wrapped_type(wrapped);
  2568. }
  2569. // Er, we can only export typedefs to structs.
  2570. if (!interrogate_type_is_struct(wrapped)) {
  2571. continue;
  2572. }
  2573. string ClassName1 = make_safe_name(interrogate_type_scoped_name(wrapped));
  2574. string ClassName2 = make_safe_name(interrogate_type_name(wrapped));
  2575. string name1 = classNameFromCppName(ClassName2, false);
  2576. out << " PyDict_SetItemString(dict, \"" << name1 << "\", (PyObject *)&Dtool_" << ClassName1 << ".As_PyTypeObject());\n";
  2577. // No need to support mangled names for nested typedefs; we only added support recently.
  2578. } else if (nested_obj->_itype.is_enum()) {
  2579. out << " // Enum " << nested_obj->_itype.get_scoped_name() << ";\n";
  2580. CPPEnumType *enum_type = nested_obj->_itype._cpptype->as_enum_type();
  2581. CPPEnumType::Elements::const_iterator ei;
  2582. for (ei = enum_type->_elements.begin(); ei != enum_type->_elements.end(); ++ei) {
  2583. string name1 = classNameFromCppName((*ei)->get_simple_name(), false);
  2584. string name2;
  2585. if (nested_obj->_itype.has_true_name()) {
  2586. name2 = classNameFromCppName((*ei)->get_simple_name(), true);
  2587. } else {
  2588. // Don't generate the alternative syntax for anonymous enums, since we added support
  2589. // for those after we started deprecating the alternative syntax.
  2590. name2 = name1;
  2591. }
  2592. string enum_value = obj->_itype.get_scoped_name() + "::" + (*ei)->get_simple_name();
  2593. out << " PyDict_SetItemString(dict, \"" << name1 << "\", PyLongOrInt_FromLong(" << enum_value << "));\n";
  2594. if (name1 != name2) {
  2595. out << " PyDict_SetItemString(dict, \"" << name2 << "\", PyLongOrInt_FromLong(" << enum_value << "));\n";
  2596. }
  2597. }
  2598. }
  2599. }
  2600. out << " if (PyType_Ready(&Dtool_" << ClassName << ".As_PyTypeObject()) < 0) {\n";
  2601. out << " Dtool_Raise_TypeError(\"PyType_Ready(" << ClassName << ")\");\n";
  2602. out << " return;\n";
  2603. out << " }\n";
  2604. out << " Py_INCREF(&Dtool_" << ClassName << ".As_PyTypeObject());\n";
  2605. // Why make the class a member of itself?
  2606. //out << " PyDict_SetItemString(Dtool_" <<ClassName << ".As_PyTypeObject().tp_dict,\"" <<export_class_name<< "\",&Dtool_" <<ClassName << ".As_PyObject());\n";
  2607. bool is_runtime_typed = IsPandaTypedObject(obj->_itype._cpptype->as_struct_type());
  2608. if (HasAGetClassTypeFunction(obj->_itype)) {
  2609. is_runtime_typed = true;
  2610. }
  2611. if (is_runtime_typed) {
  2612. out << " RegisterRuntimeClass(&Dtool_" << ClassName << ", " << cClassName << "::get_class_type().get_index());\n";
  2613. } else {
  2614. out << " RegisterRuntimeClass(&Dtool_" << ClassName << ", -1);\n";
  2615. }
  2616. out << " }\n";
  2617. // Also write out the explicit alternate names.
  2618. //int num_alt_names = obj->_itype.get_num_alt_names();
  2619. //for (int i = 0; i < num_alt_names; ++i) {
  2620. // string alt_name = make_safe_name(obj->_itype.get_alt_name(i));
  2621. // if (export_class_name != alt_name) {
  2622. // out << " PyModule_AddObject(module, \"" << alt_name << "\", (PyObject *)&Dtool_" << ClassName << ".As_PyTypeObject());\n";
  2623. // }
  2624. //}
  2625. //out << " }\n";
  2626. out << "}\n\n";
  2627. }
  2628. ////////////////////////////////////////////////////////////////////
  2629. // Function: InterfaceMakerPythonNative::synthesize_this_parameter
  2630. // Access: Public, Virtual
  2631. // Description: This method should be overridden and redefined to
  2632. // return true for interfaces that require the implicit
  2633. // "this" parameter, if present, to be passed as the
  2634. // first parameter to any wrapper functions.
  2635. ////////////////////////////////////////////////////////////////////
  2636. bool InterfaceMakerPythonNative::
  2637. synthesize_this_parameter() {
  2638. return true;
  2639. }
  2640. ////////////////////////////////////////////////////////////////////
  2641. // Function: InterfaceMakerPythonNative::separate_overloading
  2642. // Access: Public, Virtual
  2643. // Description: This method should be overridden and redefined to
  2644. // return true for interfaces that require overloaded
  2645. // instances of a function to be defined as separate
  2646. // functions (each with its own hashed name), or false
  2647. // for interfaces that can support overloading natively,
  2648. // and thus only require one wrapper function per each
  2649. // overloaded input function.
  2650. ////////////////////////////////////////////////////////////////////
  2651. bool InterfaceMakerPythonNative::
  2652. separate_overloading() {
  2653. // We used to return true here. Nowadays, some of the default
  2654. // arguments are handled in the PyArg_ParseTuple code, and some
  2655. // are still being considered as separate overloads (this depends
  2656. // on a bunch of factors, see collapse_default_remaps).
  2657. // This is all handled elsewhere.
  2658. return false;
  2659. }
  2660. ////////////////////////////////////////////////////////////////////
  2661. // Function: InterfaceMakerPythonNative::get_wrapper_prefix
  2662. // Access: Protected, Virtual
  2663. // Description: Returns the prefix string used to generate wrapper
  2664. // function names.
  2665. ////////////////////////////////////////////////////////////////////
  2666. string InterfaceMakerPythonNative::
  2667. get_wrapper_prefix() {
  2668. return "Dtool_";
  2669. }
  2670. ////////////////////////////////////////////////////////////////////
  2671. // Function: InterfaceMakerPythonNative::get_unique_prefix
  2672. // Access: Protected, Virtual
  2673. // Description: Returns the prefix string used to generate unique
  2674. // symbolic names, which are not necessarily C-callable
  2675. // function names.
  2676. ////////////////////////////////////////////////////////////////////
  2677. string InterfaceMakerPythonNative::
  2678. get_unique_prefix() {
  2679. return "Dtool_";
  2680. }
  2681. ////////////////////////////////////////////////////////////////////
  2682. // Function: InterfaceMakerPythonNative::record_function_wrapper
  2683. // Access: Protected, Virtual
  2684. // Description: Associates the function wrapper with its function in
  2685. // the appropriate structures in the database.
  2686. ////////////////////////////////////////////////////////////////////
  2687. void InterfaceMakerPythonNative::
  2688. record_function_wrapper(InterrogateFunction &ifunc, FunctionWrapperIndex wrapper_index) {
  2689. ifunc._python_wrappers.push_back(wrapper_index);
  2690. }
  2691. ////////////////////////////////////////////////////////////////////
  2692. // Function: InterfaceMakerPythonNative::write_prototype_for
  2693. // Access: Private
  2694. // Description: Writes the prototype for the indicated function.
  2695. ////////////////////////////////////////////////////////////////////
  2696. void InterfaceMakerPythonNative::
  2697. write_prototype_for(ostream &out, InterfaceMaker::Function *func) {
  2698. std::string fname = "PyObject *" + func->_name + "(PyObject *self, PyObject *args)";
  2699. write_prototype_for_name(out, func, fname);
  2700. }
  2701. ////////////////////////////////////////////////////////////////////
  2702. ////////////////////////////////////////////////////////////////////
  2703. ////////////////////////////////////////////////////////////////////
  2704. void InterfaceMakerPythonNative::
  2705. write_prototype_for_name(ostream &out, InterfaceMaker::Function *func, const std::string &function_namename) {
  2706. Function::Remaps::const_iterator ri;
  2707. // for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri) {
  2708. // FunctionRemap *remap = (*ri);
  2709. if (!output_function_names) {
  2710. // If we're not saving the function names, don't export it from
  2711. // the library.
  2712. out << "static ";
  2713. } else {
  2714. out << "extern \"C\" ";
  2715. }
  2716. out << function_namename << ";\n";
  2717. // }
  2718. }
  2719. ////////////////////////////////////////////////////////////////////
  2720. // Function: InterfaceMakerPythonNative::write_function_for_top
  2721. // Access: Private
  2722. // Description: Writes the definition for a function that will call
  2723. // the indicated C++ function or method.
  2724. ////////////////////////////////////////////////////////////////////
  2725. void InterfaceMakerPythonNative::
  2726. write_function_for_top(ostream &out, InterfaceMaker::Object *obj, InterfaceMaker::Function *func) {
  2727. // First check if this function has non-slotted and legal remaps,
  2728. // ie. if we should even write it.
  2729. bool has_remaps = false;
  2730. Function::Remaps::const_iterator ri;
  2731. for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri) {
  2732. FunctionRemap *remap = (*ri);
  2733. if (!is_remap_legal(remap)) {
  2734. continue;
  2735. }
  2736. SlottedFunctionDef slotted_def;
  2737. if (!get_slotted_function_def(obj, func, remap, slotted_def)) {
  2738. // It has a non-slotted remap, so we should write it.
  2739. has_remaps = true;
  2740. break;
  2741. }
  2742. }
  2743. if (!has_remaps) {
  2744. // Nope.
  2745. return;
  2746. }
  2747. // This is a bit of a hack, as these methods should probably be
  2748. // going through the slotted function system. But it's kind of
  2749. // pointless to write these out, and a waste of space.
  2750. string fname = func->_ifunc.get_name();
  2751. if (fname == "operator <" ||
  2752. fname == "operator <=" ||
  2753. fname == "operator ==" ||
  2754. fname == "operator !=" ||
  2755. fname == "operator >" ||
  2756. fname == "operator >=") {
  2757. return;
  2758. }
  2759. if (func->_ifunc.is_unary_op()) {
  2760. assert(func->_args_type == AT_no_args);
  2761. }
  2762. string prototype = "static PyObject *" + func->_name + "(PyObject *";
  2763. // This will be NULL for static funcs, so prevent code from using it.
  2764. if (func->_has_this) {
  2765. prototype += "self";
  2766. }
  2767. switch (func->_args_type) {
  2768. case AT_keyword_args:
  2769. prototype += ", PyObject *args, PyObject *kwds";
  2770. break;
  2771. case AT_varargs:
  2772. prototype += ", PyObject *args";
  2773. break;
  2774. case AT_single_arg:
  2775. prototype += ", PyObject *arg";
  2776. break;
  2777. default:
  2778. break;
  2779. }
  2780. prototype += ")";
  2781. string expected_params;
  2782. write_function_for_name(out, obj, func->_remaps, prototype, expected_params, true, func->_args_type, RF_pyobject | RF_err_null);
  2783. // Now synthesize a variable for the docstring.
  2784. ostringstream comment;
  2785. if (!expected_params.empty()) {
  2786. comment << "C++ Interface:\n"
  2787. << expected_params;
  2788. }
  2789. if (func->_ifunc._comment.size() > 2) {
  2790. if (!expected_params.empty()) {
  2791. comment << "\n";
  2792. }
  2793. comment << func->_ifunc._comment;
  2794. }
  2795. out << "#ifndef NDEBUG\n";
  2796. out << "static const char *" << func->_name << "_comment =\n";
  2797. output_quoted(out, 2, comment.str());
  2798. out << ";\n";
  2799. out << "#else\n";
  2800. out << "static const char *" << func->_name << "_comment = NULL;\n";
  2801. out << "#endif\n\n";
  2802. }
  2803. ////////////////////////////////////////////////////////////////////
  2804. // Function: InterfaceMakerPythonNative::write_function_for_name
  2805. // Access: Private
  2806. // Description: Writes the definition for a function that will call
  2807. // the indicated C++ function or method.
  2808. ////////////////////////////////////////////////////////////////////
  2809. void InterfaceMakerPythonNative::
  2810. write_function_for_name(ostream &out, Object *obj,
  2811. const Function::Remaps &remaps,
  2812. const string &function_name,
  2813. string &expected_params,
  2814. bool coercion_allowed,
  2815. ArgsType args_type, int return_flags) {
  2816. std::map<int, std::set<FunctionRemap *> > map_sets;
  2817. std::map<int, std::set<FunctionRemap *> >::iterator mii;
  2818. std::set<FunctionRemap *>::iterator sii;
  2819. bool has_this = false;
  2820. Function::Remaps::const_iterator ri;
  2821. FunctionRemap *remap = NULL;
  2822. int max_required_args = 0;
  2823. bool all_nonconst = true;
  2824. out << "/******************************************************************\n" << " * Python type method wrapper for\n";
  2825. for (ri = remaps.begin(); ri != remaps.end(); ++ri) {
  2826. remap = (*ri);
  2827. if (is_remap_legal(remap)) {
  2828. int max_num_args = remap->_parameters.size();
  2829. if (remap->_has_this) {
  2830. has_this = true;
  2831. if (remap->_type != FunctionRemap::T_constructor) {
  2832. max_num_args--;
  2833. }
  2834. }
  2835. if (!remap->_has_this || remap->_const_method) {
  2836. all_nonconst = false;
  2837. }
  2838. int min_num_args = 0;
  2839. FunctionRemap::Parameters::const_iterator pi;
  2840. pi = remap->_parameters.begin();
  2841. if (remap->_has_this && pi != remap->_parameters.end()) {
  2842. ++pi;
  2843. }
  2844. for (; pi != remap->_parameters.end(); ++pi) {
  2845. ParameterRemap *param = (*pi)._remap;
  2846. if (param->get_default_value() != (CPPExpression *)NULL) {
  2847. // We've reached the first parameter that takes a default value.
  2848. break;
  2849. } else {
  2850. ++min_num_args;
  2851. }
  2852. }
  2853. max_required_args = max(max_num_args, max_required_args);
  2854. for (int i = min_num_args; i <= max_num_args; ++i) {
  2855. map_sets[i].insert(remap);
  2856. }
  2857. out << " * ";
  2858. remap->write_orig_prototype(out, 0, false, (max_num_args - min_num_args));
  2859. out << "\n";
  2860. } else {
  2861. out << " * Rejected Remap [";
  2862. remap->write_orig_prototype(out, 0);
  2863. out << "]\n";
  2864. }
  2865. }
  2866. out << " *******************************************************************/\n";
  2867. out << function_name << " {\n";
  2868. if (has_this) {
  2869. std::string ClassName = make_safe_name(obj->_itype.get_scoped_name());
  2870. std::string cClassName = obj->_itype.get_true_name();
  2871. //string class_name = remap->_cpptype->get_simple_name();
  2872. // Extract pointer from 'self' parameter.
  2873. out << " " << cClassName << " *local_this = NULL;\n";
  2874. if (all_nonconst) {
  2875. // All remaps are non-const. Also check that this object isn't const.
  2876. out << " if (!Dtool_Call_ExtractThisPointer_NonConst(self, Dtool_" << ClassName << ", "
  2877. << "(void **)&local_this, \"" << classNameFromCppName(cClassName, false)
  2878. << "." << methodNameFromCppName(remap, cClassName, false) << "\")) {\n";
  2879. } else {
  2880. out << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n";
  2881. }
  2882. error_return(out, 4, return_flags);
  2883. out << " }\n";
  2884. }
  2885. if (map_sets.empty()) {
  2886. error_return(out, 2, return_flags);
  2887. out << "}\n\n";
  2888. return;
  2889. }
  2890. if (args_type == AT_keyword_args || args_type == AT_varargs) {
  2891. max_required_args = collapse_default_remaps(map_sets, max_required_args);
  2892. }
  2893. if (map_sets.size() > 1) {
  2894. switch (args_type) {
  2895. case AT_keyword_args:
  2896. indent(out, 2) << "int parameter_count = PyTuple_Size(args);\n";
  2897. indent(out, 2) << "if (kwds != NULL) {\n";
  2898. indent(out, 2) << " parameter_count += PyDict_Size(kwds);\n";
  2899. indent(out, 2) << "}\n";
  2900. break;
  2901. case AT_varargs:
  2902. indent(out, 2) << "int parameter_count = PyTuple_Size(args);\n";
  2903. break;
  2904. case AT_single_arg:
  2905. // It shouldn't get here, but we'll handle these cases nonetheless.
  2906. indent(out, 2) << "const int parameter_count = 1;\n";
  2907. break;
  2908. default:
  2909. indent(out, 2) << "const int parameter_count = 0;\n";
  2910. break;
  2911. }
  2912. // Keep track of how many args this function actually takes for
  2913. // the error message. We add one to the parameter count for "self",
  2914. // following the Python convention.
  2915. int add_self = has_this ? 1 : 0;
  2916. set<int> num_args;
  2917. indent(out, 2) << "switch (parameter_count) {\n";
  2918. for (mii = map_sets.begin(); mii != map_sets.end(); ++mii) {
  2919. int max_args = mii->first;
  2920. int min_args = min(max_required_args, max_args);
  2921. for (int i = min_args; i <= max_args; ++i) {
  2922. indent(out, 2) << "case " << i << ":\n";
  2923. num_args.insert(i + add_self);
  2924. }
  2925. indent(out, 4) << "{\n";
  2926. num_args.insert(max_args + add_self);
  2927. if (min_args == 1 && max_args == 1 && args_type == AT_varargs) {
  2928. // Might as well, since we already checked the number of args.
  2929. indent(out, 6) << " PyObject *arg = PyTuple_GET_ITEM(args, 0);\n";
  2930. write_function_forset(out, mii->second, min_args, max_args, expected_params, 6,
  2931. coercion_allowed, true, AT_single_arg, return_flags, true, !all_nonconst);
  2932. } else {
  2933. write_function_forset(out, mii->second, min_args, max_args, expected_params, 6,
  2934. coercion_allowed, true, args_type, return_flags, true, !all_nonconst);
  2935. }
  2936. indent(out, 4) << "}\n";
  2937. indent(out, 4) << "break;\n";
  2938. }
  2939. // In NDEBUG case, fall through to the error at end of function.
  2940. out << "#ifndef NDEBUG\n";
  2941. indent(out, 2) << "default:\n";
  2942. // Format an error saying how many arguments we actually take. So much
  2943. // logic for such a silly matter. Sheesh.
  2944. ostringstream msg;
  2945. msg << methodNameFromCppName(remap, "", false) << "() takes ";
  2946. set<int>::iterator si = num_args.begin();
  2947. msg << *si;
  2948. if (num_args.size() == 2) {
  2949. msg << " or " << *(++si);
  2950. } else if (num_args.size() > 2) {
  2951. ++si;
  2952. while (si != num_args.end()) {
  2953. int num = *si;
  2954. if ((++si) == num_args.end()) {
  2955. msg << " or " << num;
  2956. } else {
  2957. msg << ", " << num;
  2958. }
  2959. }
  2960. }
  2961. msg << " arguments (%d given)";
  2962. string count_var = "parameter_count";
  2963. if (add_self) {
  2964. count_var += " + 1";
  2965. }
  2966. error_raise_return(out, 4, return_flags, "TypeError",
  2967. msg.str(), count_var);
  2968. out << "#endif\n";
  2969. indent(out, 2) << "}\n";
  2970. out << " if (!_PyErr_OCCURRED()) {\n"
  2971. << " ";
  2972. if ((return_flags & ~RF_pyobject) == RF_err_null) {
  2973. out << "return ";
  2974. }
  2975. out << "Dtool_Raise_BadArgumentsError(\n";
  2976. output_quoted(out, 6, expected_params);
  2977. out << ");\n"
  2978. << " }\n";
  2979. error_return(out, 2, return_flags);
  2980. } else {
  2981. mii = map_sets.begin();
  2982. // If no parameters are accepted, we do need to check that the argument
  2983. // count is indeed 0, since we won't check that in write_function_instance.
  2984. if (mii->first == 0 && args_type != AT_no_args) {
  2985. switch (args_type) {
  2986. case AT_keyword_args:
  2987. out << " if (PyTuple_Size(args) > 0 || (kwds != NULL && PyDict_Size(kwds) > 0)) {\n";
  2988. out << " int parameter_count = PyTuple_Size(args);\n";
  2989. out << " if (kwds != NULL) {\n";
  2990. out << " parameter_count += PyDict_Size(kwds);\n";
  2991. out << " }\n";
  2992. break;
  2993. case AT_varargs:
  2994. out << " if (PyTuple_Size(args) > 0) {\n";
  2995. out << " const int parameter_count = PyTuple_GET_SIZE(args);\n";
  2996. break;
  2997. case AT_single_arg:
  2998. // Shouldn't happen, but let's handle this case nonetheless.
  2999. out << " {\n";
  3000. out << " const int parameter_count = 1;\n";
  3001. break;
  3002. case AT_no_args:
  3003. break;
  3004. case AT_unknown:
  3005. break;
  3006. }
  3007. out << "#ifdef NDEBUG\n";
  3008. error_raise_return(out, 4, return_flags, "TypeError", "function takes no arguments");
  3009. out << "#else\n";
  3010. error_raise_return(out, 4, return_flags, "TypeError",
  3011. methodNameFromCppName(remap, "", false) + "() takes no arguments (%d given)",
  3012. "parameter_count");
  3013. out << "#endif\n";
  3014. out << " }\n";
  3015. } else if (args_type == AT_keyword_args && max_required_args == 1 && mii->first == 1) {
  3016. // Check this to be sure, as we handle the case of only 1 keyword arg
  3017. // in write_function_forset (not using ParseTupleAndKeywords).
  3018. out << " int parameter_count = PyTuple_Size(args);\n"
  3019. " if (kwds != NULL) {\n"
  3020. " parameter_count += PyDict_Size(kwds);\n"
  3021. " }\n"
  3022. " if (parameter_count != 1) {\n"
  3023. "#ifdef NDEBUG\n";
  3024. error_raise_return(out, 4, return_flags, "TypeError",
  3025. "function takes exactly 1 argument");
  3026. out << "#else\n";
  3027. error_raise_return(out, 4, return_flags, "TypeError",
  3028. methodNameFromCppName(remap, "", false) + "() takes exactly 1 argument (%d given)",
  3029. "parameter_count");
  3030. out << "#endif\n";
  3031. out << " }\n";
  3032. }
  3033. int min_args = min(max_required_args, mii->first);
  3034. write_function_forset(out, mii->second, min_args, mii->first, expected_params, 2,
  3035. coercion_allowed, true, args_type, return_flags, true, !all_nonconst);
  3036. // This block is often unreachable for many functions... maybe we can
  3037. // figure out a way in the future to better determine when it will be
  3038. // and won't be necessary to write this out.
  3039. if (args_type != AT_no_args) {
  3040. out << " if (!_PyErr_OCCURRED()) {\n"
  3041. << " ";
  3042. if ((return_flags & ~RF_pyobject) == RF_err_null) {
  3043. out << "return ";
  3044. }
  3045. out << "Dtool_Raise_BadArgumentsError(\n";
  3046. output_quoted(out, 6, expected_params);
  3047. out << ");\n"
  3048. << " }\n";
  3049. error_return(out, 2, return_flags);
  3050. }
  3051. }
  3052. out << "}\n\n";
  3053. }
  3054. ////////////////////////////////////////////////////////////////////
  3055. // Function: InterfaceMakerPythonNative::write_coerce_constructor
  3056. // Access: Private
  3057. // Description: Writes the definition for a coerce constructor: a
  3058. // special constructor that is called to implicitly
  3059. // cast a tuple or other type to a desired type. This
  3060. // is done by calling the appropriate constructor or
  3061. // static make() function. Constructors marked with
  3062. // the "explicit" keyword aren't considered, just like
  3063. // in C++.
  3064. //
  3065. // There are usually two coerce constructors: one for
  3066. // const pointers, one for non-const pointers. This
  3067. // is due to the possibility that a static make()
  3068. // function may return a const pointer.
  3069. //
  3070. // There are two variants of this: if the class in
  3071. // question is a ReferenceCount, the coerce constructor
  3072. // takes a reference to a PointerTo or ConstPointerTo
  3073. // to store the converted pointer in. Otherwise, it
  3074. // is a regular pointer, and an additional boolean
  3075. // indicates whether the caller is supposed to call
  3076. // "delete" on the coerced pointer or not.
  3077. //
  3078. // In all cases, the coerce constructor returns a bool
  3079. // indicating whether the conversion was possible.
  3080. // It does not raise exceptions when none of the
  3081. // constructors matched, but just returns false.
  3082. ////////////////////////////////////////////////////////////////////
  3083. void InterfaceMakerPythonNative::
  3084. write_coerce_constructor(ostream &out, Object *obj, bool is_const) {
  3085. std::map<int, std::set<FunctionRemap *> > map_sets;
  3086. std::map<int, std::set<FunctionRemap *> >::iterator mii;
  3087. std::set<FunctionRemap *>::iterator sii;
  3088. int max_required_args = 0;
  3089. Functions::iterator fi;
  3090. Function::Remaps::const_iterator ri;
  3091. // Go through the methods and find appropriate static make() functions.
  3092. for (fi = obj->_methods.begin(); fi != obj->_methods.end(); ++fi) {
  3093. Function *func = (*fi);
  3094. for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri) {
  3095. FunctionRemap *remap = (*ri);
  3096. if (is_remap_legal(remap) && remap->_flags & FunctionRemap::F_coerce_constructor) {
  3097. nassertd(!remap->_has_this) continue;
  3098. // It's a static make() function.
  3099. CPPType *return_type = remap->_return_type->get_new_type();
  3100. if (!is_const && TypeManager::is_const_pointer_or_ref(return_type)) {
  3101. // If we're making the non-const coerce constructor, reject
  3102. // this remap if it returns a const pointer.
  3103. continue;
  3104. }
  3105. int max_num_args = remap->_parameters.size();
  3106. int min_num_args = 0;
  3107. FunctionRemap::Parameters::const_iterator pi;
  3108. for (pi = remap->_parameters.begin(); pi != remap->_parameters.end(); ++pi) {
  3109. ParameterRemap *param = (*pi)._remap;
  3110. if (param->get_default_value() != (CPPExpression *)NULL) {
  3111. // We've reached the first parameter that takes a default value.
  3112. break;
  3113. } else {
  3114. ++min_num_args;
  3115. }
  3116. }
  3117. // Coerce constructor should take at least one argument.
  3118. nassertd(max_num_args > 0) continue;
  3119. min_num_args = max(min_num_args, 1);
  3120. max_required_args = max(max_num_args, max_required_args);
  3121. for (int i = min_num_args; i <= max_num_args; ++i) {
  3122. map_sets[i].insert(remap);
  3123. }
  3124. int parameter_size = remap->_parameters.size();
  3125. map_sets[parameter_size].insert(remap);
  3126. }
  3127. }
  3128. }
  3129. // Now go through the constructors that are suitable for coercion.
  3130. // This excludes copy constructors and ones marked "explicit".
  3131. for (fi = obj->_constructors.begin(); fi != obj->_constructors.end(); ++fi) {
  3132. Function *func = (*fi);
  3133. for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri) {
  3134. FunctionRemap *remap = (*ri);
  3135. if (is_remap_legal(remap) && remap->_flags & FunctionRemap::F_coerce_constructor) {
  3136. nassertd(!remap->_has_this) continue;
  3137. int max_num_args = remap->_parameters.size();
  3138. int min_num_args = 0;
  3139. FunctionRemap::Parameters::const_iterator pi;
  3140. for (pi = remap->_parameters.begin(); pi != remap->_parameters.end(); ++pi) {
  3141. ParameterRemap *param = (*pi)._remap;
  3142. if (param->get_default_value() != (CPPExpression *)NULL) {
  3143. // We've reached the first parameter that takes a default value.
  3144. break;
  3145. } else {
  3146. ++min_num_args;
  3147. }
  3148. }
  3149. // Coerce constructor should take at least one argument.
  3150. nassertd(max_num_args > 0) continue;
  3151. min_num_args = max(min_num_args, 1);
  3152. max_required_args = max(max_num_args, max_required_args);
  3153. for (int i = min_num_args; i <= max_num_args; ++i) {
  3154. map_sets[i].insert(remap);
  3155. }
  3156. int parameter_size = remap->_parameters.size();
  3157. map_sets[parameter_size].insert(remap);
  3158. }
  3159. }
  3160. }
  3161. std::string ClassName = make_safe_name(obj->_itype.get_scoped_name());
  3162. std::string cClassName = obj->_itype.get_true_name();
  3163. if (TypeManager::is_reference_count(obj->_itype._cpptype)) {
  3164. // The coercion works slightly different for reference counted types, since
  3165. // we can handle those a bit more nicely by taking advantage of the refcount
  3166. // instead of having to use a boolean to indicate that it should be managed.
  3167. if (is_const) {
  3168. out << "bool Dtool_Coerce_" << ClassName << "(PyObject *args, CPT(" << cClassName << ") &coerced) {\n";
  3169. } else {
  3170. out << "bool Dtool_Coerce_" << ClassName << "(PyObject *args, PT(" << cClassName << ") &coerced) {\n";
  3171. }
  3172. // Note: this relies on the PT() being initialized to NULL. This is currently
  3173. // the case in all invocations, but this may not be true in the future.
  3174. out << " DTOOL_Call_ExtractThisPointerForType(args, &Dtool_" << ClassName << ", (void**)&coerced.cheat());\n";
  3175. out << " if (coerced != NULL) {\n";
  3176. out << " // The argument is already of matching type, no need to coerce.\n";
  3177. if (!is_const) {
  3178. out << " if (!((Dtool_PyInstDef *)args)->_is_const) {\n";
  3179. out << " // A non-const instance is required, which this is.\n";
  3180. out << " coerced->ref();\n";
  3181. out << " return true;\n";
  3182. out << " }\n";
  3183. } else {
  3184. out << " coerced->ref();\n";
  3185. out << " return true;\n";
  3186. }
  3187. } else {
  3188. if (is_const) {
  3189. out << "bool Dtool_Coerce_" << ClassName << "(PyObject *args, " << cClassName << " const *&coerced, bool &manage) {\n";
  3190. } else {
  3191. out << "bool Dtool_Coerce_" << ClassName << "(PyObject *args, " << cClassName << " *&coerced, bool &manage) {\n";
  3192. }
  3193. out << " DTOOL_Call_ExtractThisPointerForType(args, &Dtool_" << ClassName << ", (void**)&coerced);\n";
  3194. out << " if (coerced != NULL) {\n";
  3195. if (!is_const) {
  3196. out << " if (!((Dtool_PyInstDef *)args)->_is_const) {\n";
  3197. out << " // A non-const instance is required, which this is.\n";
  3198. out << " return true;\n";
  3199. out << " }\n";
  3200. } else {
  3201. out << " return true;\n";
  3202. }
  3203. }
  3204. out << " }\n\n";
  3205. if (map_sets.empty()) {
  3206. error_return(out, 2, RF_coerced | RF_err_false);
  3207. out << "}\n\n";
  3208. return;
  3209. }
  3210. // Coercion constructors are special cases in that they can take either
  3211. // a single value or a tuple. (They never, however, take a tuple
  3212. // containing a single value.)
  3213. string expected_params;
  3214. mii = map_sets.find(1);
  3215. if (mii != map_sets.end()) {
  3216. out << " if (!PyTuple_Check(args)) {\n";
  3217. out << " PyObject *arg = args;\n";
  3218. write_function_forset(out, mii->second, mii->first, mii->first, expected_params, 4, false, false,
  3219. AT_single_arg, RF_coerced | RF_err_false, true, false);
  3220. if (map_sets.size() == 1) {
  3221. out << " }\n";
  3222. //out << " PyErr_Clear();\n";
  3223. error_return(out, 2, RF_coerced | RF_err_false);
  3224. out << "}\n\n";
  3225. return;
  3226. }
  3227. // We take this one out of the map sets. There's not much value in
  3228. // coercing tuples containing just one value.
  3229. map_sets.erase(mii);
  3230. out << " } else {\n";
  3231. } else {
  3232. out << " if (PyTuple_Check(args)) {\n";
  3233. }
  3234. max_required_args = collapse_default_remaps(map_sets, max_required_args);
  3235. if (map_sets.size() > 1) {
  3236. indent(out, 4) << "switch (PyTuple_GET_SIZE(args)) {\n";
  3237. for (mii = map_sets.begin(); mii != map_sets.end(); ++mii) {
  3238. int max_args = mii->first;
  3239. int min_args = min(max_required_args, max_args);
  3240. // This is not called for tuples containing just one value or no
  3241. // values at all, so we should never have to consider that case.
  3242. if (min_args < 2) {
  3243. min_args = 2;
  3244. }
  3245. nassertd(max_args >= min_args) continue;
  3246. for (int i = min_args; i < max_args; ++i) {
  3247. if (i != 1) {
  3248. indent(out, 6) << "case " << i << ":\n";
  3249. }
  3250. }
  3251. indent(out, 6) << "case " << max_args << ": {\n";
  3252. write_function_forset(out, mii->second, min_args, max_args, expected_params, 8, false, false,
  3253. AT_varargs, RF_coerced | RF_err_false, true, false);
  3254. indent(out, 8) << "break;\n";
  3255. indent(out, 6) << "}\n";
  3256. }
  3257. indent(out, 4) << "}\n";
  3258. } else {
  3259. mii = map_sets.begin();
  3260. int max_args = mii->first;
  3261. int min_args = min(max_required_args, max_args);
  3262. // This is not called for tuples containing just one value or no
  3263. // values at all, so we should never have to consider that case.
  3264. if (min_args < 2) {
  3265. min_args = 2;
  3266. }
  3267. nassertv(max_args >= min_args);
  3268. if (min_args == max_args) {
  3269. indent(out, 4) << "if (PyTuple_GET_SIZE(args) == " << mii->first << ") {\n";
  3270. } else {
  3271. indent(out, 4) << "Py_ssize_t size = PyTuple_GET_SIZE(args);\n";
  3272. // Not sure if this check really does any good. I guess it's a
  3273. // useful early-fail test.
  3274. indent(out, 4) << "if (size >= " << min_args << " && size <= " << max_args << ") {\n";
  3275. }
  3276. write_function_forset(out, mii->second, min_args, max_args, expected_params, 6, false, false,
  3277. AT_varargs, RF_coerced | RF_err_false, true, false);
  3278. indent(out, 4) << "}\n";
  3279. }
  3280. out << " }\n\n";
  3281. //out << " PyErr_Clear();\n";
  3282. error_return(out, 2, RF_coerced | RF_err_false);
  3283. out << "}\n\n";
  3284. }
  3285. ////////////////////////////////////////////////////////////////////
  3286. // Function: InterfaceMakerPythonNative::collapse_default_remaps
  3287. // Access: Private
  3288. // Description: Special case optimization: if the last map is a subset
  3289. // of the map before it, and the last parameter is only a
  3290. // simple parameter type (that we have special default
  3291. // argument handling for), we can merge the cases.
  3292. // When this happens, we can make use of a special
  3293. // feature of PyArg_ParseTuple for handling of these
  3294. // last few default arguments. This doesn't work well
  3295. // for all types of default expressions, though, hence the
  3296. // need for this elaborate checking mechanism down here,
  3297. // which goes in parallel with the actual optional arg
  3298. // handling logic in write_function_instance.
  3299. //
  3300. // This isn't just to help reduce the amount of generated
  3301. // code; it also enables arbitrary selection of keyword
  3302. // arguments for many functions, ie. for this function:
  3303. //
  3304. // int func(int a=0, int b=0, bool c=false, string d="");
  3305. //
  3306. // Thanks to this mechanism, we can call it like so:
  3307. //
  3308. // func(c=True, d=".")
  3309. //
  3310. // The return value is the minimum of the number
  3311. // of maximum arguments.
  3312. //
  3313. // Sorry, let me try that again: it returns the
  3314. // largest number of arguments for which the overloads
  3315. // will be separated out rather than handled via the
  3316. // special default handling mechanism. Or something.
  3317. //
  3318. // Please don't hate me.
  3319. /////////////////////////////////////////////////////////////////
  3320. int InterfaceMakerPythonNative::
  3321. collapse_default_remaps(std::map<int, std::set<FunctionRemap *> > &map_sets,
  3322. int max_required_args) {
  3323. if (map_sets.size() < 1) {
  3324. return max_required_args;
  3325. }
  3326. std::map<int, std::set<FunctionRemap *> >::reverse_iterator rmi, rmi_next;
  3327. rmi = map_sets.rbegin();
  3328. rmi_next = rmi;
  3329. for (++rmi_next; rmi_next != map_sets.rend();) {
  3330. if (std::includes(rmi_next->second.begin(), rmi_next->second.end(),
  3331. rmi->second.begin(), rmi->second.end())) {
  3332. // Check if the nth argument is something we can easily create a default for.
  3333. std::set<FunctionRemap *>::iterator sii;
  3334. for (sii = rmi->second.begin(); sii != rmi->second.end(); ++sii) {
  3335. FunctionRemap *remap = (*sii);
  3336. int pn = rmi->first - 1;
  3337. if (remap->_has_this && remap->_type != FunctionRemap::T_constructor) {
  3338. ++pn;
  3339. }
  3340. nassertd(pn < remap->_parameters.size()) goto abort_iteration;
  3341. ParameterRemap *param = remap->_parameters[pn]._remap;
  3342. CPPType *type = param->get_new_type();
  3343. if (param->new_type_is_atomic_string()) {
  3344. CPPType *orig_type = param->get_orig_type();
  3345. if (TypeManager::is_char_pointer(orig_type)) {
  3346. } else if (TypeManager::is_wchar_pointer(orig_type)) {
  3347. goto abort_iteration;
  3348. } else if (TypeManager::is_wstring(orig_type)) {
  3349. goto abort_iteration;
  3350. } else if (TypeManager::is_const_ptr_to_basic_string_wchar(orig_type)) {
  3351. goto abort_iteration;
  3352. } else {
  3353. // Regular strings are OK if the default argument is a string literal
  3354. // or the default string constructor, since those are trivial to handle.
  3355. // This actually covers almost all of the cases of default string args.
  3356. CPPExpression::Type expr_type = param->get_default_value()->_type;
  3357. if (expr_type != CPPExpression::T_default_construct &&
  3358. expr_type != CPPExpression::T_string) {
  3359. goto abort_iteration;
  3360. }
  3361. }
  3362. } else if (TypeManager::is_bool(type)) {
  3363. } else if (TypeManager::is_char(type)) {
  3364. } else if (TypeManager::is_wchar(type)) {
  3365. goto abort_iteration;
  3366. } else if (TypeManager::is_longlong(type)) {
  3367. } else if (TypeManager::is_integer(type)) {
  3368. } else if (TypeManager::is_double(type)) {
  3369. } else if (TypeManager::is_float(type)) {
  3370. } else if (TypeManager::is_const_char_pointer(type)) {
  3371. } else if (TypeManager::is_pointer_to_PyTypeObject(type)) {
  3372. } else if (TypeManager::is_pointer_to_PyStringObject(type)) {
  3373. } else if (TypeManager::is_pointer_to_PyUnicodeObject(type)) {
  3374. } else if (TypeManager::is_pointer_to_PyObject(type)) {
  3375. } else if (TypeManager::is_pointer_to_Py_buffer(type)) {
  3376. goto abort_iteration;
  3377. } else if (TypeManager::is_pointer_to_simple(type)) {
  3378. goto abort_iteration;
  3379. } else if (TypeManager::is_pointer(type)) {
  3380. // I'm allowing other pointer types, but only if the expression happens
  3381. // to evaluate to a numeric constant (which will likely only be NULL).
  3382. // There are too many issues to resolve right now with allowing more
  3383. // complex default expressions, including issues in the C++ parser
  3384. // (but the reader is welcome to give it a try!)
  3385. CPPExpression::Result res = param->get_default_value()->evaluate();
  3386. if (res._type != CPPExpression::RT_integer &&
  3387. res._type != CPPExpression::RT_pointer) {
  3388. goto abort_iteration;
  3389. }
  3390. } else {
  3391. goto abort_iteration;
  3392. }
  3393. }
  3394. // rmi_next has a superset of the remaps in rmi, and we are going to
  3395. // erase rmi_next, so put all the remaps in rmi.
  3396. //rmi->second = rmi_next->second;
  3397. max_required_args = rmi_next->first;
  3398. rmi = rmi_next;
  3399. ++rmi_next;
  3400. } else {
  3401. break;
  3402. }
  3403. }
  3404. abort_iteration:
  3405. // Now erase the other remap sets. Reverse iterators are weird, we
  3406. // first need to get forward iterators and decrement them by one.
  3407. std::map<int, std::set<FunctionRemap *> >::iterator erase_begin, erase_end;
  3408. erase_begin = rmi.base();
  3409. erase_end = map_sets.rbegin().base();
  3410. --erase_begin;
  3411. --erase_end;
  3412. if (erase_begin == erase_end) {
  3413. return max_required_args;
  3414. }
  3415. // We're never erasing the map set with the highest number of args.
  3416. nassertr(erase_end != map_sets.end(), max_required_args);
  3417. // We know erase_begin is a superset of erase_end, but we want all
  3418. // the remaps in erase_end (which we aren't erasing).
  3419. //if (rmi == map_sets.rbegin()) {
  3420. erase_end->second = erase_begin->second;
  3421. //}
  3422. map_sets.erase(erase_begin, erase_end);
  3423. assert(map_sets.size() >= 1);
  3424. return max_required_args;
  3425. }
  3426. ////////////////////////////////////////////////////////
  3427. // Function : GetParnetDepth
  3428. //
  3429. // Support Function used to Sort the name based overrides.. For know must be complex to simple
  3430. ////////////////////////////////////////////////////////
  3431. int get_type_sort(CPPType *type) {
  3432. int answer = 0;
  3433. // printf(" %s\n",type->get_local_name().c_str());
  3434. // The highest numbered one will be checked first.
  3435. if (TypeManager::is_pointer_to_Py_buffer(type)) {
  3436. return 14;
  3437. } else if (TypeManager::is_pointer_to_PyTypeObject(type)) {
  3438. return 13;
  3439. } else if (TypeManager::is_pointer_to_PyObject(type)) {
  3440. return 12;
  3441. } else if (TypeManager::is_wstring(type)) {
  3442. return 11;
  3443. } else if (TypeManager::is_wchar_pointer(type)) {
  3444. return 10;
  3445. } else if (TypeManager::is_string(type)) {
  3446. return 9;
  3447. } else if (TypeManager::is_char_pointer(type)) {
  3448. return 8;
  3449. } else if (TypeManager::is_unsigned_longlong(type)) {
  3450. return 7;
  3451. } else if (TypeManager::is_longlong(type)) {
  3452. return 6;
  3453. } else if (TypeManager::is_integer(type)) {
  3454. return 5;
  3455. } else if (TypeManager::is_double(type)) {
  3456. return 4;
  3457. } else if (TypeManager::is_float(type)) {
  3458. return 3;
  3459. } else if (TypeManager::is_pointer_to_simple(type)) {
  3460. return 2;
  3461. } else if (TypeManager::is_bool(type)) {
  3462. return 1;
  3463. } else if (TypeManager::is_pointer(type) ||
  3464. TypeManager::is_reference(type) ||
  3465. TypeManager::is_struct(type)) {
  3466. answer = 20;
  3467. int deepest = 0;
  3468. TypeIndex type_index = builder.get_type(TypeManager::unwrap(TypeManager::resolve_type(type)), false);
  3469. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  3470. const InterrogateType &itype = idb->get_type(type_index);
  3471. if (itype.is_class() || itype.is_struct()) {
  3472. int num_derivations = itype.number_of_derivations();
  3473. for (int di = 0; di < num_derivations; di++) {
  3474. TypeIndex d_type_Index = itype.get_derivation(di);
  3475. const InterrogateType &d_itype = idb->get_type(d_type_Index);
  3476. int this_one = get_type_sort(d_itype._cpptype);
  3477. if (this_one > deepest) {
  3478. deepest = this_one;
  3479. }
  3480. }
  3481. }
  3482. answer += deepest;
  3483. // printf(" Class Name %s %d\n",itype.get_name().c_str(),answer);
  3484. }
  3485. // printf(" Class Name %s %d\n",itype.get_name().c_str(),answer);
  3486. return answer;
  3487. }
  3488. ////////////////////////////////////////////////////////
  3489. // The Core sort function for remap calling orders..
  3490. //////////////////////////////////////////////////////////
  3491. bool RemapCompareLess(FunctionRemap *in1, FunctionRemap *in2) {
  3492. assert(in1 != NULL);
  3493. assert(in2 != NULL);
  3494. if (in1->_parameters.size() != in2->_parameters.size()) {
  3495. return (in1->_parameters.size() > in2->_parameters.size());
  3496. }
  3497. int pcount = in1->_parameters.size();
  3498. for (int x = 0; x < pcount; x++) {
  3499. CPPType *orig_type1 = in1->_parameters[x]._remap->get_orig_type();
  3500. CPPType *orig_type2 = in2->_parameters[x]._remap->get_orig_type();
  3501. int pd1 = get_type_sort(orig_type1);
  3502. int pd2 = get_type_sort(orig_type2);
  3503. if (pd1 != pd2) {
  3504. return (pd1 > pd2);
  3505. }
  3506. }
  3507. // ok maybe something to do with return strength..
  3508. return false;
  3509. }
  3510. ////////////////////////////////////////////////////////////////////
  3511. // Function: InterfaceMakerPythonNative::write_function_forset
  3512. // Access: Private
  3513. // Description: Writes out a set of function wrappers that handle
  3514. // all instances of a particular function with the
  3515. // same number of parameters.
  3516. // (Actually, in some cases relating to default
  3517. // argument handling, this may be called with remaps
  3518. // taking a range of parameters.)
  3519. //
  3520. // min_num_args and max_num_args are the range of
  3521. // parameter counts to respect for these functions.
  3522. // This is important for default argument handling.
  3523. //
  3524. // expected_params is a reference to a string that
  3525. // will be filled in with a list of overloads that
  3526. // this function takes, for displaying in the doc
  3527. // string and error messages.
  3528. //
  3529. // If coercion_allowed is true, it will attempt
  3530. // to convert arguments to the appropriate parameter
  3531. // type using the appropriate Dtool_Coerce function.
  3532. // This means it may write some remaps twice: once
  3533. // without coercion, and then it may go back and
  3534. // write it a second time to try parameter coercion.
  3535. //
  3536. // If report_errors is true, it will print an error
  3537. // and exit when one has occurred, instead of falling
  3538. // back to the next overload. This is automatically
  3539. // disabled when more than one function is passed.
  3540. //
  3541. // args_type indicates whether this function takes
  3542. // no args, a single PyObject* arg, an args tuple,
  3543. // or an args tuple and kwargs dictionary.
  3544. //
  3545. // return_flags indicates which value should be
  3546. // returned from the wrapper function and what should
  3547. // be returned on error.
  3548. //
  3549. // If check_exceptions is false, it will not check
  3550. // if the function raised an exception, except if
  3551. // it took PyObject* arguments. This should NEVER
  3552. // be false for C++ functions that call Python code,
  3553. // since that would block a meaningful exception
  3554. // like SystemExit or KeyboardInterrupt.
  3555. //
  3556. // If verify_const is set, it will write out a check
  3557. // to make sure that non-const functions aren't called
  3558. // for a const "this". This is usually only false when
  3559. // write_function_for_name has already done this check
  3560. // (which it does when *all* remaps are non-const).
  3561. //
  3562. // If first_pexpr is not empty, it represents the
  3563. // preconverted value of the first parameter. This
  3564. // is a special-case hack for one of the slot functions.
  3565. ////////////////////////////////////////////////////////////////////
  3566. void InterfaceMakerPythonNative::
  3567. write_function_forset(ostream &out,
  3568. const std::set<FunctionRemap *> &remapsin,
  3569. int min_num_args, int max_num_args,
  3570. string &expected_params, int indent_level,
  3571. bool coercion_allowed, bool report_errors,
  3572. ArgsType args_type, int return_flags,
  3573. bool check_exceptions, bool verify_const,
  3574. const string &first_pexpr) {
  3575. if (remapsin.empty()) {
  3576. return;
  3577. }
  3578. FunctionRemap *remap;
  3579. std::set<FunctionRemap *>::iterator sii;
  3580. bool all_nonconst = false;
  3581. if (verify_const) {
  3582. // Check if all of the remaps are non-const. If so, we only have to
  3583. // check the constness of the self pointer once, rather than per remap.
  3584. all_nonconst = true;
  3585. for (sii = remapsin.begin(); sii != remapsin.end(); ++sii) {
  3586. remap = (*sii);
  3587. if (!remap->_has_this || remap->_const_method) {
  3588. all_nonconst = false;
  3589. break;
  3590. }
  3591. }
  3592. if (all_nonconst) {
  3593. // Yes, they do. Check that the parameter has the required constness.
  3594. indent(out, indent_level)
  3595. << "if (!((Dtool_PyInstDef *)self)->_is_const) {\n";
  3596. indent_level += 2;
  3597. verify_const = false;
  3598. }
  3599. }
  3600. string first_param_name;
  3601. bool same_first_param = false;
  3602. // If there's only one arg and all remaps have the same parameter name, we
  3603. // extract it from the dictionary, so we don't have to call ParseTupleAndKeywords.
  3604. if (first_pexpr.empty() && min_num_args == 1 && max_num_args == 1 &&
  3605. args_type == AT_keyword_args) {
  3606. sii = remapsin.begin();
  3607. remap = (*sii);
  3608. first_param_name = remap->_parameters[(int)remap->_has_this]._name;
  3609. same_first_param = true;
  3610. for (++sii; sii != remapsin.end(); ++sii) {
  3611. remap = (*sii);
  3612. if (remap->_parameters[(int)remap->_has_this]._name != first_param_name) {
  3613. same_first_param = false;
  3614. break;
  3615. }
  3616. }
  3617. }
  3618. if (same_first_param) {
  3619. // Yes, they all have the same argument name (or there is only one remap).
  3620. // Extract it from the dict so we don't have to call ParseTupleAndKeywords.
  3621. indent(out, indent_level) << "PyObject *arg = NULL;\n";
  3622. indent(out, indent_level) << "if (PyTuple_GET_SIZE(args) == 1) {\n";
  3623. indent(out, indent_level) << " arg = PyTuple_GET_ITEM(args, 0);\n";
  3624. indent(out, indent_level) << "} else if (kwds != NULL) {\n";
  3625. indent(out, indent_level) << " arg = PyDict_GetItemString(kwds, \"" << first_param_name << "\");\n";
  3626. indent(out, indent_level) << "}\n";
  3627. if (report_errors) {
  3628. indent(out, indent_level) << "if (arg == (PyObject *)NULL) {\n";
  3629. error_raise_return(out, indent_level + 2, return_flags, "TypeError",
  3630. "Required argument '" + first_param_name + "' (pos 1) not found");
  3631. indent(out, indent_level) << "}\n";
  3632. } else {
  3633. indent(out, indent_level) << "if (arg != (PyObject *)NULL) {\n";
  3634. indent_level += 2;
  3635. }
  3636. args_type = AT_single_arg;
  3637. }
  3638. if (remapsin.size() > 1) {
  3639. // There are multiple different overloads for this number of
  3640. // parameters. Sort them all into order from most-specific to
  3641. // least-specific, then try them one at a time.
  3642. std::vector<FunctionRemap *> remaps (remapsin.begin(), remapsin.end());
  3643. std::sort(remaps.begin(), remaps.end(), RemapCompareLess);
  3644. std::vector<FunctionRemap *>::const_iterator sii;
  3645. // Check if all of them have an InternalName pointer as first
  3646. // parameter. This is a dirty hack, of course, to work around an
  3647. // awkward overload resolution problem in NodePath::set_shader_input()
  3648. // (while perhaps also improving its performance). If I had more time
  3649. // I'd create a better solution.
  3650. bool first_internalname = false;
  3651. string first_pexpr2(first_pexpr);
  3652. if (first_pexpr.empty() && args_type != AT_no_args) {
  3653. first_internalname = true;
  3654. for (sii = remaps.begin(); sii != remaps.end(); ++sii) {
  3655. remap = (*sii);
  3656. if (remap->_parameters.size() > (int)remap->_has_this) {
  3657. ParameterRemap *param = remap->_parameters[(int)remap->_has_this]._remap;
  3658. string param_name = param->get_orig_type()->get_local_name(&parser);
  3659. if (param_name != "CPT_InternalName" &&
  3660. param_name != "InternalName const *" &&
  3661. param_name != "InternalName *") {
  3662. // Aw.
  3663. first_internalname = false;
  3664. break;
  3665. }
  3666. } else {
  3667. first_internalname = false;
  3668. break;
  3669. }
  3670. }
  3671. if (first_internalname) {
  3672. // Yeah, all remaps have a first InternalName parameter, so process
  3673. // that and remove it from the args tuple.
  3674. if (args_type == AT_single_arg) {
  3675. // Bit of a weird case, but whatever.
  3676. indent(out, indent_level) << "PyObject *name_obj = arg;\n";
  3677. args_type = AT_no_args;
  3678. } else if (min_num_args == 2 && max_num_args == 2) {
  3679. indent(out, indent_level) << "PyObject *name_obj = PyTuple_GET_ITEM(args, 0);\n";
  3680. indent(out, indent_level) << "PyObject *arg = PyTuple_GET_ITEM(args, 1);\n";
  3681. args_type = AT_single_arg;
  3682. } else {
  3683. indent(out, indent_level) << "PyObject *name_obj = PyTuple_GET_ITEM(args, 0);\n";
  3684. indent(out, indent_level) << "args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));\n";
  3685. return_flags |= RF_decref_args;
  3686. }
  3687. indent(out, indent_level) << "PT(InternalName) name;\n";
  3688. indent(out, indent_level) << "if (Dtool_Coerce_InternalName(name_obj, name)) {\n";
  3689. indent_level += 2;
  3690. first_pexpr2 = "name";
  3691. }
  3692. }
  3693. int num_coercion_possible = 0;
  3694. sii = remaps.begin();
  3695. while (sii != remaps.end()) {
  3696. remap = *(sii++);
  3697. if (coercion_allowed && is_remap_coercion_possible(remap)) {
  3698. if (++num_coercion_possible == 1 && sii == remaps.end()) {
  3699. // This is the last remap, and it happens to be the only one
  3700. // with coercion possible. So we might as well just break off
  3701. // now, and let this case be handled by the coercion loop, below.
  3702. // BUG: this remap doesn't get listed in expected_params.
  3703. break;
  3704. }
  3705. }
  3706. if (verify_const && (remap->_has_this && !remap->_const_method)) {
  3707. // If it's a non-const method, we only allow a
  3708. // non-const this.
  3709. indent(out, indent_level)
  3710. << "if (!((Dtool_PyInstDef *)self)->_is_const) {\n";
  3711. } else {
  3712. indent(out, indent_level)
  3713. << "{\n";
  3714. }
  3715. indent(out, indent_level) << " // -2 ";
  3716. remap->write_orig_prototype(out, 0, false, (max_num_args - min_num_args));
  3717. out << "\n";
  3718. // NB. We don't pass on report_errors here because we want
  3719. // it to silently drop down to the next overload.
  3720. write_function_instance(out, remap, min_num_args, max_num_args,
  3721. expected_params, indent_level + 2,
  3722. false, false, args_type, return_flags,
  3723. check_exceptions, first_pexpr2);
  3724. indent(out, indent_level) << "}\n\n";
  3725. }
  3726. // Go through one more time, but allow coercion this time.
  3727. if (coercion_allowed) {
  3728. for (sii = remaps.begin(); sii != remaps.end(); sii ++) {
  3729. remap = (*sii);
  3730. if (!is_remap_coercion_possible(remap)) {
  3731. indent(out, indent_level)
  3732. << "// No coercion possible: ";
  3733. remap->write_orig_prototype(out, 0, false, (max_num_args - min_num_args));
  3734. out << "\n";
  3735. continue;
  3736. }
  3737. if (verify_const && (remap->_has_this && !remap->_const_method)) {
  3738. indent(out, indent_level)
  3739. << "if (!((Dtool_PyInstDef *)self)->_is_const) {\n";
  3740. } else {
  3741. indent(out, indent_level)
  3742. << "{\n";
  3743. }
  3744. indent(out, indent_level) << " // -2 ";
  3745. remap->write_orig_prototype(out, 0, false, (max_num_args - min_num_args));
  3746. out << "\n";
  3747. string ignore_expected_params;
  3748. write_function_instance(out, remap, min_num_args, max_num_args,
  3749. ignore_expected_params, indent_level + 2,
  3750. true, false, args_type, return_flags,
  3751. check_exceptions, first_pexpr2);
  3752. indent(out, indent_level) << "}\n\n";
  3753. }
  3754. }
  3755. if (first_internalname) {
  3756. indent_level -= 2;
  3757. if (report_errors) {
  3758. indent(out, indent_level) << "} else {\n";
  3759. string class_name = remap->_cpptype->get_simple_name();
  3760. ostringstream msg;
  3761. msg << classNameFromCppName(class_name, false) << "."
  3762. << methodNameFromCppName(remap, class_name, false)
  3763. << "() first argument must be str or InternalName";
  3764. error_raise_return(out, indent_level + 2, return_flags,
  3765. "TypeError", msg.str());
  3766. }
  3767. indent(out, indent_level) << "}\n";
  3768. }
  3769. } else {
  3770. // There is only one possible overload with this number of
  3771. // parameters. Just call it.
  3772. sii = remapsin.begin();
  3773. remap = (*sii);
  3774. indent(out, indent_level)
  3775. << "// 1-" ;
  3776. remap->write_orig_prototype(out, 0, false, (max_num_args - min_num_args));
  3777. out << "\n";
  3778. write_function_instance(out, remap, min_num_args, max_num_args,
  3779. expected_params, indent_level,
  3780. coercion_allowed, report_errors,
  3781. args_type, return_flags,
  3782. check_exceptions, first_pexpr);
  3783. }
  3784. // Close the brace we opened earlier.
  3785. if (same_first_param && !report_errors) {
  3786. indent_level -= 2;
  3787. indent(out, indent_level) << "}\n";
  3788. }
  3789. // If we did a const check earlier, and we were asked to report errors,
  3790. // write out an else case raising an exception.
  3791. if (all_nonconst) {
  3792. if (report_errors) {
  3793. indent(out, indent_level - 2)
  3794. << "} else {\n";
  3795. string class_name = remap->_cpptype->get_simple_name();
  3796. ostringstream msg;
  3797. msg << "Cannot call "
  3798. << classNameFromCppName(class_name, false)
  3799. << "." << methodNameFromCppName(remap, class_name, false)
  3800. << "() on a const object.";
  3801. out << "#ifdef NDEBUG\n";
  3802. error_raise_return(out, indent_level, return_flags, "TypeError",
  3803. "non-const method called on const object");
  3804. out << "#else\n";
  3805. error_raise_return(out, indent_level, return_flags, "TypeError", msg.str());
  3806. out << "#endif\n";
  3807. }
  3808. indent_level -= 2;
  3809. indent(out, indent_level) << "}\n";
  3810. }
  3811. }
  3812. ////////////////////////////////////////////////////////////////////
  3813. // Function: InterfaceMakerPythonNative::write_function_instance
  3814. // Access: Private
  3815. // Description: Writes out the code to handle a a single instance
  3816. // of an overloaded function. This will convert all
  3817. // of the arguments from PyObject* to the appropriate
  3818. // C++ type, call the C++ function, possibly check
  3819. // for errors, and construct a Python wrapper for the
  3820. // return value.
  3821. //
  3822. // return_flags indicates which value should be
  3823. // returned from the wrapper function and what should
  3824. // be returned on error.
  3825. //
  3826. // If coercion_possible is true, it will attempt
  3827. // to convert arguments to the appropriate parameter
  3828. // type using the appropriate Dtool_Coerce function.
  3829. //
  3830. // If report_errors is true, it will print an error
  3831. // and exit when one has occurred, instead of falling
  3832. // back to the next overload. This should be done
  3833. // if it is the only overload.
  3834. //
  3835. // If check_exceptions is false, it will not check
  3836. // if the function raised an exception, except if
  3837. // it took PyObject* arguments. This should NEVER
  3838. // be false for C++ functions that call Python code,
  3839. // since that would block a meaningful exception
  3840. // like SystemExit or KeyboardInterrupt.
  3841. //
  3842. // If first_pexpr is not empty, it represents the
  3843. // preconverted value of the first parameter. This
  3844. // is a special-case hack for one of the slot functions.
  3845. ////////////////////////////////////////////////////////////////////
  3846. void InterfaceMakerPythonNative::
  3847. write_function_instance(ostream &out, FunctionRemap *remap,
  3848. int min_num_args, int max_num_args,
  3849. string &expected_params, int indent_level,
  3850. bool coercion_possible, bool report_errors,
  3851. ArgsType args_type, int return_flags,
  3852. bool check_exceptions,
  3853. const string &first_pexpr) {
  3854. string format_specifiers;
  3855. string keyword_list;
  3856. string parameter_list;
  3857. string container;
  3858. string type_check;
  3859. vector_string pexprs;
  3860. LineStream extra_convert;
  3861. ostringstream extra_param_check;
  3862. LineStream extra_cleanup;
  3863. int min_version = 0;
  3864. // This will be set if the function itself is suspected of possibly
  3865. // raising a TypeError.
  3866. bool may_raise_typeerror = false;
  3867. // This will be set to true if one of the things we're about to do
  3868. // *might* raise a TypeError that we may have to clear.
  3869. bool clear_error = false;
  3870. bool is_constructor = (remap->_type == FunctionRemap::T_constructor);
  3871. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  3872. // Make one pass through the parameter list. We will output a
  3873. // one-line temporary variable definition for each parameter, while
  3874. // simultaneously building the ParseTuple() function call and also
  3875. // the parameter expression list for call_function().
  3876. expected_params += methodNameFromCppName(remap, "", false);
  3877. expected_params += "(";
  3878. int num_params = max_num_args;
  3879. if (remap->_has_this) {
  3880. num_params += 1;
  3881. }
  3882. if (num_params > remap->_parameters.size()) {
  3883. // Limit to how many parameters this remap actually has.
  3884. num_params = remap->_parameters.size();
  3885. max_num_args = num_params;
  3886. if (remap->_has_this) {
  3887. --max_num_args;
  3888. }
  3889. }
  3890. nassertv(num_params <= remap->_parameters.size());
  3891. bool only_pyobjects = true;
  3892. int pn = 0;
  3893. if (remap->_has_this) {
  3894. // The first parameter is the 'this' parameter.
  3895. string expected_class_name = classNameFromCppName(remap->_cpptype->get_simple_name(), false);
  3896. if (remap->_const_method) {
  3897. expected_params += expected_class_name + " self";
  3898. string class_name = remap->_cpptype->get_local_name(&parser);
  3899. container = "(const " + class_name + "*)local_this";
  3900. } else {
  3901. expected_params += "const " + expected_class_name + " self";
  3902. container = "local_this";
  3903. }
  3904. pexprs.push_back(container);
  3905. ++pn;
  3906. }
  3907. if (!first_pexpr.empty()) {
  3908. if (pn >= num_params) {
  3909. // first_pexpr was passed even though the function takes no arguments.
  3910. nassert_raise("pn < num_params");
  3911. } else {
  3912. // The first actual argument was already converted.
  3913. if (pn > 0) {
  3914. expected_params += ", ";
  3915. }
  3916. expected_params += first_pexpr;
  3917. pexprs.push_back(first_pexpr);
  3918. ++pn;
  3919. }
  3920. }
  3921. // Now convert (the rest of the) actual arguments, one by one.
  3922. for (; pn < num_params; ++pn) {
  3923. if (pn > 0) {
  3924. expected_params += ", ";
  3925. }
  3926. bool is_optional = false;
  3927. // Has this remap been selected to consider optional arguments for
  3928. // this parameter? We can do that by adding a vertical bar to the
  3929. // PyArg_ParseTuple format string, coupled with some extra logic
  3930. // in the argument handling, below.
  3931. if (remap->_has_this && !is_constructor) {
  3932. if (pn > min_num_args) {
  3933. is_optional = true;
  3934. if ((pn - 1) == min_num_args) {
  3935. format_specifiers += "|";
  3936. }
  3937. }
  3938. } else {
  3939. if (pn >= min_num_args) {
  3940. is_optional = true;
  3941. if (pn == min_num_args) {
  3942. format_specifiers += "|";
  3943. }
  3944. }
  3945. }
  3946. ParameterRemap *param = remap->_parameters[pn]._remap;
  3947. CPPType *orig_type = param->get_orig_type();
  3948. CPPType *type = param->get_new_type();
  3949. CPPExpression *default_value = param->get_default_value();
  3950. string param_name = remap->get_parameter_name(pn);
  3951. // This is the string to convert our local variable to the
  3952. // appropriate C++ type. Normally this is just a cast.
  3953. string pexpr_string =
  3954. "(" + orig_type->get_local_name(&parser) + ")" + param_name;
  3955. string default_expr;
  3956. if (is_optional) {
  3957. // If this is an optional argument, PyArg_ParseTuple will leave
  3958. // the variable unchanged if it has been omitted, so we have to
  3959. // initialize it to the desired default expression. Format it.
  3960. ostringstream default_expr_str;
  3961. default_expr_str << " = ";
  3962. default_value->output(default_expr_str, 0, &parser, false);
  3963. default_expr = default_expr_str.str();
  3964. // We should only ever have to consider optional arguments for
  3965. // functions taking a variable number of arguments.
  3966. nassertv(args_type == AT_varargs || args_type == AT_keyword_args);
  3967. }
  3968. string reported_name = remap->_parameters[pn]._name;
  3969. keyword_list += "\"" + reported_name + "\", ";
  3970. if (param->new_type_is_atomic_string()) {
  3971. if (TypeManager::is_char_pointer(orig_type)) {
  3972. indent(out, indent_level) << "char ";
  3973. if (TypeManager::is_const_char_pointer(orig_type)) {
  3974. out << "const ";
  3975. }
  3976. out << "*" << param_name << default_expr << ";\n";
  3977. format_specifiers += "z";
  3978. parameter_list += ", &" + param_name;
  3979. expected_params += "str";
  3980. } else if (TypeManager::is_wchar_pointer(orig_type)) {
  3981. indent(out, indent_level) << "PyUnicodeObject *" << param_name << ";\n";
  3982. format_specifiers += "U";
  3983. parameter_list += ", &" + param_name;
  3984. extra_convert
  3985. << "#if PY_VERSION_HEX >= 0x03030000\n"
  3986. << "wchar_t *" << param_name << "_str = PyUnicode_AsWideCharString((PyObject *)" << param_name << ", NULL);\n"
  3987. << "#else"
  3988. << "Py_ssize_t " << param_name << "_len = PyUnicode_GET_SIZE(" << param_name << ");\n"
  3989. << "wchar_t *" << param_name << "_str = (wchar_t *)alloca(sizeof(wchar_t) * (" + param_name + "_len + 1));\n"
  3990. << "PyUnicode_AsWideChar(" << param_name << ", " << param_name << "_str, " << param_name << "_len);\n"
  3991. << param_name << "_str[" << param_name << "_len] = 0;\n"
  3992. << "#endif\n";
  3993. pexpr_string = param_name + "_str";
  3994. extra_cleanup
  3995. << "#if PY_VERSION_HEX >= 0x03030000\n"
  3996. << "PyMem_Free(" << param_name << "_str);\n"
  3997. << "#endif\n";
  3998. expected_params += "unicode";
  3999. } else if (TypeManager::is_wstring(orig_type)) {
  4000. indent(out, indent_level) << "PyUnicodeObject *" << param_name << ";\n";
  4001. format_specifiers += "U";
  4002. parameter_list += ", &" + param_name;
  4003. extra_convert
  4004. << "#if PY_VERSION_HEX >= 0x03030000\n"
  4005. << "Py_ssize_t " << param_name << "_len;\n"
  4006. << "wchar_t *" << param_name << "_str = PyUnicode_AsWideCharString((PyObject *)"
  4007. << param_name << ", &" << param_name << "_len);\n"
  4008. << "#else\n"
  4009. << "Py_ssize_t " << param_name << "_len = PyUnicode_GET_SIZE(" << param_name << ");\n"
  4010. << "wchar_t *" << param_name << "_str = (wchar_t *)alloca(sizeof(wchar_t) * (" + param_name + "_len + 1));\n"
  4011. << "PyUnicode_AsWideChar(" << param_name << ", " << param_name << "_str, " << param_name << "_len);\n"
  4012. << "#endif\n";
  4013. pexpr_string = "std::wstring(" +
  4014. param_name + "_str, " + param_name + "_len)";
  4015. extra_cleanup
  4016. << "#if PY_VERSION_HEX >= 0x03030000\n"
  4017. << "PyMem_Free(" << param_name << "_str);\n"
  4018. << "#endif\n";
  4019. expected_params += "unicode";
  4020. } else if (TypeManager::is_const_ptr_to_basic_string_wchar(orig_type)) {
  4021. indent(out, indent_level) << "PyUnicodeObject *" << param_name << ";\n";
  4022. format_specifiers += "U";
  4023. parameter_list += ", &" + param_name;
  4024. extra_convert
  4025. << "#if PY_VERSION_HEX >= 0x03030000\n"
  4026. << "Py_ssize_t " << param_name << "_len;\n"
  4027. << "wchar_t *" << param_name << "_str = PyUnicode_AsWideCharString((PyObject *)"
  4028. << param_name << ", &" << param_name << "_len);\n"
  4029. << "#else\n"
  4030. << "Py_ssize_t " << param_name << "_len = PyUnicode_GET_SIZE(" << param_name << ");\n"
  4031. << "wchar_t *" << param_name << "_str = (wchar_t *)alloca(sizeof(wchar_t) * (" + param_name + "_len + 1));\n"
  4032. << "PyUnicode_AsWideChar(" << param_name << ", " << param_name << "_str, " << param_name << "_len);\n"
  4033. << "#endif\n";
  4034. pexpr_string = "&std::wstring(" +
  4035. param_name + "_str, " + param_name + "_len)";
  4036. extra_cleanup
  4037. << "#if PY_VERSION_HEX >= 0x03030000\n"
  4038. << "PyMem_Free(" << param_name << "_str);\n"
  4039. << "#endif\n";
  4040. expected_params += "unicode";
  4041. } else { // A regular string.
  4042. if (is_optional) {
  4043. CPPExpression::Type expr_type = default_value->_type;
  4044. if (expr_type == CPPExpression::T_default_construct) {
  4045. // The default string constructor yields an empty string.
  4046. indent(out, indent_level) << "const char *" << param_name << "_str = \"\";\n";
  4047. indent(out, indent_level) << "Py_ssize_t " << param_name << "_len = 0;\n";
  4048. } else {
  4049. // We only get here for string literals, so this should be fine
  4050. indent(out, indent_level) << "const char *" << param_name << "_str"
  4051. << default_expr << ";\n";
  4052. indent(out, indent_level) << "Py_ssize_t " << param_name << "_len = "
  4053. << default_value->_str.size() << ";\n";
  4054. }
  4055. } else {
  4056. indent(out, indent_level) << "char *" << param_name << "_str = NULL;\n";
  4057. indent(out, indent_level) << "Py_ssize_t " << param_name << "_len;\n";
  4058. }
  4059. if (args_type == AT_single_arg) {
  4060. out << "#if PY_MAJOR_VERSION >= 3\n";
  4061. indent(out, indent_level)
  4062. << param_name << "_str = PyUnicode_AsUTF8AndSize(arg, &"
  4063. << param_name << "_len);\n";
  4064. out << "#else\n"; // NB. PyString_AsStringAndSize also accepts a PyUnicode.
  4065. indent(out, indent_level) << "if (PyString_AsStringAndSize(arg, &"
  4066. << param_name << "_str, &" << param_name << "_len) == -1) {\n";
  4067. indent(out, indent_level + 2) << param_name << "_str = NULL;\n";
  4068. indent(out, indent_level) << "}\n";
  4069. out << "#endif\n";
  4070. extra_param_check << " && " << param_name << "_str != NULL";
  4071. } else {
  4072. format_specifiers += "s#";
  4073. parameter_list += ", &" + param_name
  4074. + "_str, &" + param_name + "_len";
  4075. }
  4076. if (TypeManager::is_const_ptr_to_basic_string_char(orig_type)) {
  4077. pexpr_string = "&std::string(" +
  4078. param_name + "_str, " + param_name + "_len)";
  4079. } else {
  4080. pexpr_string = "std::string(" +
  4081. param_name + "_str, " + param_name + "_len)";
  4082. }
  4083. expected_params += "str";
  4084. }
  4085. only_pyobjects = false;
  4086. } else if (TypeManager::is_bool(type)) {
  4087. if (args_type == AT_single_arg) {
  4088. param_name = "arg";
  4089. } else {
  4090. indent(out, indent_level) << "PyObject *" << param_name;
  4091. if (is_optional) {
  4092. CPPExpression::Result res = default_value->evaluate();
  4093. if (res._type != CPPExpression::RT_error) {
  4094. // It's a compile-time constant. Write Py_True or Py_False.
  4095. out << " = " << (res.as_boolean() ? "Py_True" : "Py_False");
  4096. } else {
  4097. // Select Py_True or Py_False at runtime.
  4098. out << " = (";
  4099. default_value->output(out, 0, &parser, false);
  4100. out << ") ? Py_True : Py_False";
  4101. }
  4102. }
  4103. out << ";\n";
  4104. format_specifiers += "O";
  4105. parameter_list += ", &" + param_name;
  4106. }
  4107. pexpr_string = "(PyObject_IsTrue(" + param_name + ") != 0)";
  4108. expected_params += "bool";
  4109. } else if (TypeManager::is_char(type)) {
  4110. indent(out, indent_level) << "char " << param_name << default_expr << ";\n";
  4111. format_specifiers += "c";
  4112. parameter_list += ", &" + param_name;
  4113. //extra_param_check << " && isascii(" << param_name << ")";
  4114. pexpr_string = "(char) " + param_name;
  4115. expected_params += "char";
  4116. only_pyobjects = false;
  4117. } else if (TypeManager::is_wchar(type)) {
  4118. indent(out, indent_level) << "#if PY_VERSION_HEX >= 0x03020000\n";
  4119. indent(out, indent_level) << "PyObject *" << param_name << ";\n";
  4120. indent(out, indent_level) << "#else\n";
  4121. indent(out, indent_level) << "PyUnicodeObject *" << param_name << ";\n";
  4122. indent(out, indent_level) << "#endif\n";
  4123. format_specifiers += "U";
  4124. parameter_list += ", &" + param_name;
  4125. // We tell it to copy 2 characters, but make sure it only
  4126. // copied one, as a trick to check for the proper length in one go.
  4127. extra_convert << "wchar_t " << param_name << "_chars[2];\n";
  4128. extra_param_check << " && PyUnicode_AsWideChar(" << param_name << ", " << param_name << "_chars, 2) == 1";
  4129. pexpr_string = param_name + "_chars[0]";
  4130. expected_params += "unicode char";
  4131. only_pyobjects = false;
  4132. clear_error = true;
  4133. } else if (TypeManager::is_ssize(type)) {
  4134. indent(out, indent_level) << "Py_ssize_t " << param_name << default_expr << ";\n";
  4135. format_specifiers += "n";
  4136. parameter_list += ", &" + param_name;
  4137. expected_params += "int";
  4138. only_pyobjects = false;
  4139. } else if (TypeManager::is_size(type)) {
  4140. // It certainly isn't the exact same thing as size_t, but Py_ssize_t
  4141. // should at least be the same size. The problem with mapping this
  4142. // to unsigned int is that that doesn't work well on 64-bit systems,
  4143. // on which size_t is a 64-bit integer.
  4144. indent(out, indent_level) << "Py_ssize_t " << param_name << default_expr << ";\n";
  4145. format_specifiers += "n";
  4146. parameter_list += ", &" + param_name;
  4147. expected_params += "int";
  4148. only_pyobjects = false;
  4149. extra_convert
  4150. << "#ifndef NDEBUG\n"
  4151. << "if (" << param_name << " < 0) {\n";
  4152. error_raise_return(extra_convert, 2, return_flags, "OverflowError",
  4153. "can't convert negative value %zd to size_t",
  4154. param_name);
  4155. extra_convert
  4156. << "}\n"
  4157. << "#endif\n";
  4158. } else if (TypeManager::is_longlong(type)) {
  4159. // It's not trivial to do overflow checking for a long long, so we
  4160. // simply don't do it.
  4161. if (TypeManager::is_unsigned_longlong(type)) {
  4162. indent(out, indent_level) << "unsigned PY_LONG_LONG " << param_name << default_expr << ";\n";
  4163. format_specifiers += "K";
  4164. } else {
  4165. indent(out, indent_level) << "PY_LONG_LONG " << param_name << default_expr << ";\n";
  4166. format_specifiers += "L";
  4167. }
  4168. parameter_list += ", &" + param_name;
  4169. expected_params += "long";
  4170. only_pyobjects = false;
  4171. } else if (TypeManager::is_unsigned_short(type)) {
  4172. if (args_type == AT_single_arg) {
  4173. // This is defined to PyLong_Check for Python 3 by py_panda.h.
  4174. type_check = "PyInt_Check(arg)";
  4175. extra_convert
  4176. << "long " << param_name << " = PyInt_AS_LONG(arg);\n";
  4177. pexpr_string = "(" + type->get_local_name(&parser) + ")" + param_name;
  4178. } else {
  4179. indent(out, indent_level) << "long " << param_name << default_expr << ";\n";
  4180. format_specifiers += "l";
  4181. parameter_list += ", &" + param_name;
  4182. }
  4183. // The "H" format code, unlike "h", does not do overflow checking, so
  4184. // we have to do it ourselves (except in release builds).
  4185. extra_convert
  4186. << "#ifndef NDEBUG\n"
  4187. << "if (" << param_name << " < 0 || " << param_name << " > USHRT_MAX) {\n";
  4188. error_raise_return(extra_convert, 2, return_flags, "OverflowError",
  4189. "value %ld out of range for unsigned short integer",
  4190. param_name);
  4191. extra_convert
  4192. << "}\n"
  4193. << "#endif\n";
  4194. expected_params += "int";
  4195. only_pyobjects = false;
  4196. } else if (TypeManager::is_short(type)) {
  4197. if (args_type == AT_single_arg) {
  4198. // This is defined to PyLong_Check for Python 3 by py_panda.h.
  4199. type_check = "PyInt_Check(arg)";
  4200. // Perform overflow checking in debug builds.
  4201. extra_convert
  4202. << "long arg_val = PyInt_AS_LONG(arg);\n"
  4203. << "#ifndef NDEBUG\n"
  4204. << "if (arg_val < SHRT_MIN || arg_val > SHRT_MAX) {\n";
  4205. error_raise_return(extra_convert, 2, return_flags, "OverflowError",
  4206. "value %ld out of range for signed short integer",
  4207. "arg_val");
  4208. extra_convert
  4209. << "}\n"
  4210. << "#endif\n";
  4211. pexpr_string = "(" + type->get_local_name(&parser) + ")arg_val";
  4212. } else {
  4213. indent(out, indent_level) << "short " << param_name << default_expr << ";\n";
  4214. format_specifiers += "h";
  4215. parameter_list += ", &" + param_name;
  4216. }
  4217. expected_params += "int";
  4218. only_pyobjects = false;
  4219. } else if (TypeManager::is_unsigned_integer(type)) {
  4220. if (args_type == AT_single_arg) {
  4221. // Windows has 32-bit longs, and Python 2 stores a C long for PyInt
  4222. // internally, so a PyInt wouldn't cover the whole range; that's why
  4223. // we have to accept PyLong as well here.
  4224. type_check = "PyLongOrInt_Check(arg)";
  4225. extra_convert
  4226. << "unsigned long " << param_name << " = PyLong_AsUnsignedLong(arg);\n";
  4227. pexpr_string = "(" + type->get_local_name(&parser) + ")" + param_name;
  4228. } else {
  4229. indent(out, indent_level) << "unsigned long " << param_name << default_expr << ";\n";
  4230. format_specifiers += "k";
  4231. parameter_list += ", &" + param_name;
  4232. }
  4233. // The "I" format code, unlike "i", does not do overflow checking, so
  4234. // we have to do it ourselves (in debug builds). Note that Python 2
  4235. // stores longs internally, for ints, so we don't do it for Python 2 on
  4236. // Windows, where longs are the same size as ints.
  4237. // BUG: does not catch negative values on Windows when going through
  4238. // the PyArg_ParseTuple case.
  4239. extra_convert
  4240. << "#if (SIZEOF_LONG > SIZEOF_INT) && !defined(NDEBUG)\n"
  4241. << "if (" << param_name << " > UINT_MAX) {\n";
  4242. error_raise_return(extra_convert, 2, return_flags, "OverflowError",
  4243. "value %lu out of range for unsigned integer",
  4244. param_name);
  4245. extra_convert
  4246. << "}\n"
  4247. << "#endif\n";
  4248. expected_params += "int";
  4249. only_pyobjects = false;
  4250. } else if (TypeManager::is_integer(type)) {
  4251. if (args_type == AT_single_arg) {
  4252. // This is defined to PyLong_Check for Python 3 by py_panda.h.
  4253. type_check = "PyInt_Check(arg)";
  4254. // Perform overflow checking in debug builds. Note that Python 2
  4255. // stores longs internally, for ints, so we don't do it on Windows,
  4256. // where longs are the same size as ints.
  4257. extra_convert
  4258. << "long arg_val = PyInt_AS_LONG(arg);\n"
  4259. << "#if (SIZEOF_LONG > SIZEOF_INT) && !defined(NDEBUG)\n"
  4260. << "if (arg_val < INT_MIN || arg_val > INT_MAX) {\n";
  4261. error_raise_return(extra_convert, 2, return_flags, "OverflowError",
  4262. "value %ld out of range for signed integer",
  4263. "arg_val");
  4264. extra_convert
  4265. << "}\n"
  4266. << "#endif\n";
  4267. pexpr_string = "(" + type->get_local_name(&parser) + ")arg_val";
  4268. } else {
  4269. indent(out, indent_level) << "int " << param_name << default_expr << ";\n";
  4270. format_specifiers += "i";
  4271. parameter_list += ", &" + param_name;
  4272. }
  4273. expected_params += "int";
  4274. only_pyobjects = false;
  4275. } else if (TypeManager::is_double(type)) {
  4276. if (args_type == AT_single_arg) {
  4277. pexpr_string = "PyFloat_AsDouble(arg)";
  4278. type_check = "PyNumber_Check(arg)";
  4279. } else {
  4280. indent(out, indent_level) << "double " << param_name << default_expr << ";\n";
  4281. format_specifiers += "d";
  4282. parameter_list += ", &" + param_name;
  4283. }
  4284. expected_params += "double";
  4285. only_pyobjects = false;
  4286. } else if (TypeManager::is_float(type)) {
  4287. if (args_type == AT_single_arg) {
  4288. pexpr_string = "(" + type->get_local_name(&parser) + ")PyFloat_AsDouble(arg)";
  4289. type_check = "PyNumber_Check(arg)";
  4290. } else {
  4291. indent(out, indent_level) << "float " << param_name << default_expr << ";\n";
  4292. format_specifiers += "f";
  4293. parameter_list += ", &" + param_name;
  4294. }
  4295. expected_params += "float";
  4296. only_pyobjects = false;
  4297. } else if (TypeManager::is_const_char_pointer(type)) {
  4298. indent(out, indent_level) << "const char *" << param_name << default_expr << ";\n";
  4299. format_specifiers += "z";
  4300. parameter_list += ", &" + param_name;
  4301. expected_params += "buffer";
  4302. only_pyobjects = false;
  4303. } else if (TypeManager::is_pointer_to_PyTypeObject(type)) {
  4304. if (args_type == AT_single_arg) {
  4305. param_name = "arg";
  4306. } else {
  4307. indent(out, indent_level) << "PyObject *" << param_name << default_expr << ";\n";
  4308. format_specifiers += "O";
  4309. parameter_list += ", &" + param_name;
  4310. pexpr_string = param_name;
  4311. }
  4312. extra_param_check << " && PyType_Check(" << param_name << ")";
  4313. pexpr_string = "(PyTypeObject *)" + param_name;
  4314. expected_params += "type";
  4315. // It's reasonable to assume that a function taking a PyTypeObject
  4316. // might also throw a TypeError if the type is incorrect.
  4317. may_raise_typeerror = true;
  4318. } else if (TypeManager::is_pointer_to_PyStringObject(type)) {
  4319. if (args_type == AT_single_arg) {
  4320. // This is a single-arg function, so there's no need
  4321. // to convert anything.
  4322. param_name = "arg";
  4323. type_check = "PyString_Check(arg)";
  4324. pexpr_string = "(PyStringObject *)" + param_name;
  4325. } else {
  4326. indent(out, indent_level) << "PyStringObject *" << param_name << default_expr << ";\n";
  4327. format_specifiers += "S";
  4328. parameter_list += ", &" + param_name;
  4329. pexpr_string = param_name;
  4330. }
  4331. expected_params += "string";
  4332. } else if (TypeManager::is_pointer_to_PyUnicodeObject(type)) {
  4333. if (args_type == AT_single_arg) {
  4334. // This is a single-arg function, so there's no need
  4335. // to convert anything.
  4336. param_name = "arg";
  4337. type_check = "PyUnicode_Check(arg)";
  4338. pexpr_string = "(PyUnicodeObject *)" + param_name;
  4339. } else {
  4340. indent(out, indent_level) << "PyUnicodeObject *" << param_name << default_expr << ";\n";
  4341. format_specifiers += "U";
  4342. parameter_list += ", &" + param_name;
  4343. pexpr_string = param_name;
  4344. }
  4345. expected_params += "unicode";
  4346. } else if (TypeManager::is_pointer_to_PyObject(type)) {
  4347. if (args_type == AT_single_arg) {
  4348. // This is a single-arg function, so there's no need
  4349. // to convert anything.
  4350. param_name = "arg";
  4351. } else {
  4352. indent(out, indent_level) << "PyObject *" << param_name << default_expr << ";\n";
  4353. format_specifiers += "O";
  4354. parameter_list += ", &" + param_name;
  4355. }
  4356. pexpr_string = param_name;
  4357. expected_params += "object";
  4358. // It's reasonable to assume that a function taking a PyObject
  4359. // might also throw a TypeError if the type is incorrect.
  4360. may_raise_typeerror = true;
  4361. } else if (TypeManager::is_pointer_to_Py_buffer(type)) {
  4362. min_version = 0x02060000; // Only support this remap in version 2.6+.
  4363. if (args_type == AT_single_arg) {
  4364. param_name = "arg";
  4365. } else {
  4366. indent(out, indent_level) << "PyObject *" << param_name << ";\n";
  4367. format_specifiers += "O";
  4368. parameter_list += ", &" + param_name;
  4369. }
  4370. indent(out, indent_level) << "Py_buffer " << param_name << "_view;\n";
  4371. extra_param_check << " && PyObject_GetBuffer("
  4372. << param_name << ", &"
  4373. << param_name << "_view, PyBUF_FULL) == 0";
  4374. pexpr_string = "&" + param_name + "_view";
  4375. extra_cleanup << "PyBuffer_Release(&" << param_name << "_view);\n";
  4376. expected_params += "buffer";
  4377. may_raise_typeerror = true;
  4378. clear_error = true;
  4379. } else if (TypeManager::is_pointer_to_simple(type)) {
  4380. if (args_type == AT_single_arg) {
  4381. param_name = "arg";
  4382. } else {
  4383. indent(out, indent_level) << "PyObject *" << param_name << ";\n";
  4384. format_specifiers += "O";
  4385. parameter_list += ", &" + param_name;
  4386. }
  4387. indent(out, indent_level) << "Py_buffer " << param_name << "_view;\n";
  4388. // Unravel the type to determine its properties.
  4389. int array_len = -1;
  4390. bool is_const = true;
  4391. CPPSimpleType *simple = NULL;
  4392. CPPType *unwrap = TypeManager::unwrap_const_reference(type);
  4393. if (unwrap != NULL) {
  4394. CPPArrayType *array_type = unwrap->as_array_type();
  4395. CPPPointerType *pointer_type = unwrap->as_pointer_type();
  4396. if (array_type != NULL) {
  4397. if (array_type->_bounds != NULL) {
  4398. array_len = array_type->_bounds->evaluate().as_integer();
  4399. }
  4400. unwrap = array_type->_element_type;
  4401. } else if (pointer_type != NULL) {
  4402. unwrap = pointer_type->_pointing_at;
  4403. }
  4404. CPPConstType *const_type = unwrap->as_const_type();
  4405. if (const_type != NULL) {
  4406. unwrap = const_type->_wrapped_around;
  4407. } else {
  4408. is_const = false;
  4409. }
  4410. while (unwrap->get_subtype() == CPPDeclaration::ST_typedef) {
  4411. unwrap = unwrap->as_typedef_type()->_type;
  4412. }
  4413. simple = unwrap->as_simple_type();
  4414. }
  4415. // Determine the format, so we can check the type of the buffer we get.
  4416. char format_chr = 'B';
  4417. switch (simple->_type) {
  4418. case CPPSimpleType::T_char:
  4419. if (simple->_flags & CPPSimpleType::F_unsigned) {
  4420. format_chr = 'B';
  4421. } else if (simple->_flags & CPPSimpleType::F_signed) {
  4422. format_chr = 'b';
  4423. } else {
  4424. format_chr = 'c';
  4425. }
  4426. break;
  4427. case CPPSimpleType::T_int:
  4428. if (simple->_flags & CPPSimpleType::F_longlong) {
  4429. format_chr = 'q';
  4430. } else if (simple->_flags & CPPSimpleType::F_long) {
  4431. format_chr = 'l';
  4432. } else if (simple->_flags & CPPSimpleType::F_short) {
  4433. format_chr = 'h';
  4434. } else {
  4435. format_chr = 'i';
  4436. }
  4437. if (simple->_flags & CPPSimpleType::F_unsigned) {
  4438. format_chr &= 0x5f; // Uppercase
  4439. }
  4440. break;
  4441. case CPPSimpleType::T_float:
  4442. format_chr = 'f';
  4443. break;
  4444. case CPPSimpleType::T_double:
  4445. format_chr = 'd';
  4446. break;
  4447. default:
  4448. nout << "Warning: cannot determine buffer format string for type "
  4449. << type->get_local_name(&parser)
  4450. << " (simple type " << *simple << ")\n";
  4451. extra_param_check << " && false";
  4452. }
  4453. const char *flags;
  4454. if (format_chr == 'B') {
  4455. if (is_const) {
  4456. flags = "PyBUF_SIMPLE";
  4457. } else {
  4458. flags = "PyBUF_WRITABLE";
  4459. }
  4460. } else if (is_const) {
  4461. flags = "PyBUF_FORMAT";
  4462. } else {
  4463. flags = "PyBUF_FORMAT | PyBUF_WRITABLE";
  4464. }
  4465. extra_param_check << " && PyObject_GetBuffer(" << param_name << ", &"
  4466. << param_name << "_view, " << flags << ") == 0";
  4467. if (format_chr != 'B') {
  4468. extra_param_check
  4469. << " && " << param_name << "_view.format[0] == '" << format_chr << "'"
  4470. << " && " << param_name << "_view.format[1] == 0";
  4471. }
  4472. if (array_len != -1) {
  4473. extra_param_check
  4474. << " && " << param_name << "_view.len == " << array_len;
  4475. }
  4476. pexpr_string = "(" + simple->get_local_name(&parser) + " *)" +
  4477. param_name + "_view.buf";
  4478. extra_cleanup << "PyBuffer_Release(&" << param_name << "_view);\n";
  4479. expected_params += "buffer";
  4480. clear_error = true;
  4481. } else if (TypeManager::is_pointer(type)) {
  4482. CPPType *obj_type = TypeManager::unwrap(TypeManager::resolve_type(type));
  4483. bool const_ok = !TypeManager::is_non_const_pointer_or_ref(orig_type);
  4484. if (TypeManager::is_const_pointer_or_ref(orig_type)) {
  4485. expected_params += "const ";
  4486. //} else {
  4487. // expected_params += "non-const ";
  4488. }
  4489. string expected_class_name = classNameFromCppName(obj_type->get_simple_name(), false);
  4490. expected_params += expected_class_name;
  4491. if (args_type == AT_single_arg) {
  4492. param_name = "arg";
  4493. } else {
  4494. indent(out, indent_level) << "PyObject *" << param_name;
  4495. if (is_optional) {
  4496. out << " = NULL";
  4497. }
  4498. out << ";\n";
  4499. format_specifiers += "O";
  4500. parameter_list += ", &" + param_name;
  4501. }
  4502. string class_name = obj_type->get_local_name(&parser);
  4503. // need to a forward scope for this class..
  4504. if (!isExportThisRun(obj_type)) {
  4505. _external_imports.insert(obj_type);
  4506. }
  4507. string this_class_name;
  4508. string method_prefix;
  4509. if (remap->_cpptype) {
  4510. this_class_name = remap->_cpptype->get_simple_name();
  4511. method_prefix = classNameFromCppName(this_class_name, false) + string(".");
  4512. }
  4513. if (coercion_possible &&
  4514. has_coerce_constructor(obj_type->as_struct_type())) {
  4515. // Call the coercion function directly, which will try to
  4516. // extract the pointer directly before trying coercion.
  4517. string coerce_call;
  4518. if (TypeManager::is_reference_count(obj_type)) {
  4519. // We use a PointerTo to handle the management here. It's cleaner
  4520. // that way.
  4521. if (TypeManager::is_const_pointer_to_anything(type)) {
  4522. extra_convert << 'C';
  4523. }
  4524. extra_convert
  4525. << "PT(" << class_name << ") " << param_name << "_this"
  4526. << default_expr << ";\n";
  4527. coerce_call = "Dtool_Coerce_" + make_safe_name(class_name) +
  4528. "(" + param_name + ", " + param_name + "_this)";
  4529. // Use move constructor when available for functions that take
  4530. // an actual PointerTo. This eliminates an unref()/ref() pair.
  4531. pexpr_string = "MOVE(" + param_name + "_this)";
  4532. } else {
  4533. // This is a bit less elegant: we use a bool to store whether
  4534. // we're supposed to clean up the reference afterward.
  4535. type->output_instance(extra_convert, param_name + "_this", &parser);
  4536. extra_convert
  4537. << default_expr << ";\n"
  4538. << "bool " << param_name << "_manage = false;\n";
  4539. coerce_call = "Dtool_Coerce_" + make_safe_name(class_name) +
  4540. "(" + param_name + ", " + param_name + "_this, " + param_name + "_manage)";
  4541. extra_cleanup
  4542. << "if (" << param_name << "_manage) {\n"
  4543. << " delete " << param_name << "_this;\n"
  4544. << "}\n";
  4545. pexpr_string = param_name + "_this";
  4546. }
  4547. if (report_errors) {
  4548. // We were asked to report any errors. Let's do it.
  4549. if (is_optional) {
  4550. extra_convert << "if (" << param_name << " != NULL && !" << coerce_call << ") {\n";
  4551. } else {
  4552. extra_convert << "if (!" << coerce_call << ") {\n";
  4553. }
  4554. // Display error like: Class.func() argument 0 must be A, not B
  4555. if ((return_flags & ~RF_pyobject) == RF_err_null) {
  4556. // Dtool_Raise_ArgTypeError returns NULL already
  4557. extra_convert << " return ";
  4558. } else {
  4559. extra_convert << " ";
  4560. }
  4561. extra_convert
  4562. << "Dtool_Raise_ArgTypeError(" << param_name << ", "
  4563. << pn << ", \"" << method_prefix
  4564. << methodNameFromCppName(remap, this_class_name, false)
  4565. << "\", \"" << expected_class_name << "\");\n";
  4566. if ((return_flags & ~RF_pyobject) != RF_err_null) {
  4567. error_return(extra_convert, 2, return_flags);
  4568. }
  4569. extra_convert << "}\n";
  4570. } else if (is_optional) {
  4571. extra_param_check << " && (" << param_name << " == NULL || " << coerce_call << ")";
  4572. } else {
  4573. extra_param_check << " && " << coerce_call;
  4574. }
  4575. } else {
  4576. type->output_instance(extra_convert, param_name + "_this", &parser);
  4577. if (is_optional) {
  4578. extra_convert
  4579. << default_expr << ";\n"
  4580. << "if (" << param_name << " != (PyObject *)NULL) {\n"
  4581. << " " << param_name << "_this";
  4582. }
  4583. if (const_ok && !report_errors) {
  4584. // This function does the same thing in this case and is slightly
  4585. // simpler. But maybe we should just reorganize these functions
  4586. // entirely?
  4587. extra_convert << ";\n";
  4588. if (is_optional) {
  4589. extra_convert << " ";
  4590. }
  4591. extra_convert
  4592. << "DTOOL_Call_ExtractThisPointerForType(" << param_name
  4593. << ", &Dtool_" << make_safe_name(class_name)
  4594. << ", (void **)&" << param_name << "_this);\n";
  4595. } else {
  4596. extra_convert << boolalpha
  4597. << " = (" << class_name << " *)"
  4598. << "DTOOL_Call_GetPointerThisClass(" << param_name
  4599. << ", &Dtool_" << make_safe_name(class_name)
  4600. << ", " << pn << ", \""
  4601. << method_prefix << methodNameFromCppName(remap, this_class_name, false)
  4602. << "\", " << const_ok << ", " << report_errors << ");\n";
  4603. }
  4604. if (is_optional) {
  4605. extra_convert << "}\n";
  4606. extra_param_check << " && (" << param_name << " == NULL || " << param_name << "_this != NULL)";
  4607. } else {
  4608. extra_param_check << " && " << param_name << "_this != NULL";
  4609. }
  4610. pexpr_string = param_name + "_this";
  4611. }
  4612. } else {
  4613. // Ignore a parameter.
  4614. if (args_type == AT_single_arg) {
  4615. param_name = "arg";
  4616. } else {
  4617. indent(out, indent_level) << "PyObject *" << param_name << ";\n";
  4618. format_specifiers += "O";
  4619. parameter_list += ", &" + param_name;
  4620. }
  4621. expected_params += "any";
  4622. }
  4623. if (!reported_name.empty()) {
  4624. expected_params += " " + reported_name;
  4625. }
  4626. pexprs.push_back(pexpr_string);
  4627. }
  4628. expected_params += ")\n";
  4629. if (min_version > 0) {
  4630. out << "#if PY_VERSION_HEX >= 0x" << hex << min_version << dec << "\n";
  4631. }
  4632. // Track how many curly braces we've opened.
  4633. short open_scopes = 0;
  4634. if (!type_check.empty() && args_type == AT_single_arg) {
  4635. indent(out, indent_level)
  4636. << "if (" << type_check << ") {\n";
  4637. ++open_scopes;
  4638. indent_level += 2;
  4639. } else if (!format_specifiers.empty()) {
  4640. string method_name = methodNameFromCppName(remap, "", false);
  4641. switch (args_type) {
  4642. case AT_keyword_args:
  4643. // Wrapper takes a varargs tuple and a keyword args dict.
  4644. indent(out, indent_level)
  4645. << "static const char *keyword_list[] = {" << keyword_list << "NULL};\n";
  4646. indent(out, indent_level)
  4647. << "if (PyArg_ParseTupleAndKeywords(args, kwds, \""
  4648. << format_specifiers << ":" << method_name
  4649. << "\", (char **)keyword_list" << parameter_list << ")) {\n";
  4650. ++open_scopes;
  4651. clear_error = true;
  4652. indent_level += 2;
  4653. break;
  4654. case AT_varargs:
  4655. // Wrapper takes a varargs tuple.
  4656. if (only_pyobjects) {
  4657. // All parameters are PyObject*, so we can use the slightly
  4658. // more efficient PyArg_UnpackTuple function instead.
  4659. indent(out, indent_level)
  4660. << "if (PyArg_UnpackTuple(args, \""
  4661. << methodNameFromCppName(remap, "", false)
  4662. << "\", " << min_num_args << ", " << max_num_args
  4663. << parameter_list << ")) {\n";
  4664. } else {
  4665. indent(out, indent_level)
  4666. << "if (PyArg_ParseTuple(args, \""
  4667. << format_specifiers << ":" << method_name
  4668. << "\"" << parameter_list << ")) {\n";
  4669. }
  4670. ++open_scopes;
  4671. clear_error = true;
  4672. indent_level += 2;
  4673. break;
  4674. case AT_single_arg:
  4675. // Single argument. If not a PyObject*, use PyArg_Parse.
  4676. if (!only_pyobjects && format_specifiers != "O") {
  4677. indent(out, indent_level)
  4678. << "if (PyArg_Parse(arg, \"" << format_specifiers << ":"
  4679. << method_name << "\"" << parameter_list << ")) {\n";
  4680. ++open_scopes;
  4681. clear_error = true;
  4682. indent_level += 2;
  4683. }
  4684. default:
  4685. break;
  4686. }
  4687. }
  4688. while (extra_convert.is_text_available()) {
  4689. string line = extra_convert.get_line();
  4690. if (line.size() == 0 || line[0] == '#') {
  4691. out << line << "\n";
  4692. } else {
  4693. indent(out, indent_level) << line << "\n";
  4694. }
  4695. }
  4696. string extra_param_check_str = extra_param_check.str();
  4697. if (!extra_param_check_str.empty()) {
  4698. indent(out, indent_level)
  4699. << "if (" << extra_param_check_str.substr(4) << ") {\n";
  4700. ++open_scopes;
  4701. indent_level += 2;
  4702. }
  4703. if (!remap->_has_this && (remap->_flags & FunctionRemap::F_explicit_self) != 0) {
  4704. // If we'll be passing "self" to the constructor, we need to
  4705. // pre-initialize it here. Unfortunately, we can't pre-load the
  4706. // "this" pointer, but the constructor itself can do this.
  4707. CPPType *orig_type = remap->_return_type->get_orig_type();
  4708. TypeIndex type_index = builder.get_type(TypeManager::unwrap(TypeManager::resolve_type(orig_type)), false);
  4709. const InterrogateType &itype = idb->get_type(type_index);
  4710. indent(out, indent_level)
  4711. << "// Pre-initialize self for the constructor\n";
  4712. if (!is_constructor || (return_flags & RF_int) == 0) {
  4713. // This is not a constructor, but somehow we landed up here at a
  4714. // static method requiring a 'self' pointer. This happens in
  4715. // coercion constructors in particular. We'll have to create
  4716. // a temporary PyObject instance to pass to it.
  4717. indent(out, indent_level)
  4718. << "PyObject *self = Dtool_new_"
  4719. << make_safe_name(itype.get_scoped_name()) << "(&"
  4720. << CLASS_PREFIX << make_safe_name(itype.get_scoped_name())
  4721. << "._PyType, NULL, NULL);\n";
  4722. extra_cleanup << "PyObject_Del(self);\n";
  4723. } else {
  4724. //XXX rdb: this isn't needed, is it, because tp_new already
  4725. // initializes the instance?
  4726. indent(out, indent_level)
  4727. << "DTool_PyInit_Finalize(self, NULL, &"
  4728. << CLASS_PREFIX << make_safe_name(itype.get_scoped_name())
  4729. << ", false, false);\n";
  4730. }
  4731. }
  4732. string return_expr;
  4733. if (remap->_blocking) {
  4734. // With SIMPLE_THREADS, it's important that we never release the
  4735. // interpreter lock.
  4736. out << "#if defined(HAVE_THREADS) && !defined(SIMPLE_THREADS)\n";
  4737. indent(out, indent_level)
  4738. << "PyThreadState *_save;\n";
  4739. indent(out, indent_level)
  4740. << "Py_UNBLOCK_THREADS\n";
  4741. out << "#endif // HAVE_THREADS && !SIMPLE_THREADS\n";
  4742. }
  4743. if (track_interpreter) {
  4744. indent(out, indent_level) << "in_interpreter = 0;\n";
  4745. }
  4746. // If the function returns a pointer that we may need to manage, we store
  4747. // it in a temporary return_value variable and set this to true.
  4748. bool manage_return = false;
  4749. if (remap->_return_type->new_type_is_atomic_string()) {
  4750. // Treat strings as a special case. We don't want to format the
  4751. // return expression.
  4752. return_expr = remap->call_function(out, indent_level, false, container, pexprs);
  4753. CPPType *type = remap->_return_type->get_orig_type();
  4754. indent(out, indent_level);
  4755. type->output_instance(out, "return_value", &parser);
  4756. out << " = " << return_expr << ";\n";
  4757. manage_return = remap->_return_value_needs_management;
  4758. return_expr = "return_value";
  4759. } else {
  4760. // The general case; an ordinary constructor or function.
  4761. return_expr = remap->call_function(out, indent_level, true, container, pexprs);
  4762. if (return_flags & RF_self) {
  4763. // We won't be using the return value, anyway.
  4764. return_expr.clear();
  4765. }
  4766. if (!return_expr.empty()) {
  4767. manage_return = remap->_return_value_needs_management;
  4768. CPPType *type = remap->_return_type->get_temporary_type();
  4769. indent(out, indent_level);
  4770. type->output_instance(out, "return_value", &parser);
  4771. out << " = " << return_expr << ";\n";
  4772. return_expr = "return_value";
  4773. }
  4774. }
  4775. // Clean up any memory we might have allocate for parsing the parameters.
  4776. while (extra_cleanup.is_text_available()) {
  4777. string line = extra_cleanup.get_line();
  4778. if (line.size() == 0 || line[0] == '#') {
  4779. out << line << "\n";
  4780. } else {
  4781. indent(out, indent_level) << line << "\n";
  4782. }
  4783. }
  4784. if (track_interpreter) {
  4785. indent(out, indent_level) << "in_interpreter = 1;\n";
  4786. }
  4787. if (remap->_blocking) {
  4788. out << "#if defined(HAVE_THREADS) && !defined(SIMPLE_THREADS)\n";
  4789. indent(out, indent_level)
  4790. << "Py_BLOCK_THREADS\n";
  4791. out << "#endif // HAVE_THREADS && !SIMPLE_THREADS\n";
  4792. }
  4793. if (manage_return) {
  4794. // If a constructor returns NULL, that means allocation failed.
  4795. if (remap->_return_type->return_value_needs_management()) {
  4796. indent(out, indent_level) << "if (return_value == NULL) {\n";
  4797. if ((return_flags & ~RF_pyobject) == RF_err_null) {
  4798. // PyErr_NoMemory returns NULL, so allow tail call elimination.
  4799. indent(out, indent_level) << " return PyErr_NoMemory();\n";
  4800. } else {
  4801. indent(out, indent_level) << " PyErr_NoMemory();\n";
  4802. error_return(out, indent_level + 2, return_flags);
  4803. }
  4804. indent(out, indent_level) << "}\n";
  4805. }
  4806. return_expr = manage_return_value(out, indent_level, remap, "return_value");
  4807. return_expr = remap->_return_type->temporary_to_return(return_expr);
  4808. }
  4809. // How could we raise a TypeError if we don't take any args?
  4810. if (args_type == AT_no_args || max_num_args == 0) {
  4811. may_raise_typeerror = false;
  4812. }
  4813. // If a function takes a PyObject* argument, it would be a good idea to
  4814. // always check for exceptions.
  4815. if (may_raise_typeerror) {
  4816. check_exceptions = true;
  4817. }
  4818. // Generated getters and setters don't raise exceptions or asserts
  4819. // since they don't contain any code.
  4820. if (remap->_type == FunctionRemap::T_getter ||
  4821. remap->_type == FunctionRemap::T_setter) {
  4822. check_exceptions = false;
  4823. }
  4824. // The most common case of the below logic is consolidated in a single
  4825. // function, as another way to reduce code bloat. Sigh.
  4826. if (check_exceptions && (!may_raise_typeerror || report_errors) &&
  4827. watch_asserts && (return_flags & RF_coerced) == 0) {
  4828. if (return_flags & RF_decref_args) {
  4829. indent(out, indent_level) << "Py_DECREF(args);\n";
  4830. return_flags &= ~RF_decref_args;
  4831. }
  4832. // An even specialer special case for functions with void return or
  4833. // bool return. We have our own functions that do all this in a
  4834. // single function call, so it should reduce the amount of code output
  4835. // while not being any slower.
  4836. bool return_null = (return_flags & RF_pyobject) != 0 &&
  4837. (return_flags & RF_err_null) != 0;
  4838. if (return_null && return_expr.empty()) {
  4839. indent(out, indent_level)
  4840. << "return Dtool_Return_None();\n";
  4841. // Reset the return value bit so that the code below doesn't generate
  4842. // the return statement a second time.
  4843. return_flags &= ~RF_pyobject;
  4844. } else if (return_null && TypeManager::is_bool(remap->_return_type->get_new_type())) {
  4845. indent(out, indent_level)
  4846. << "return Dtool_Return_Bool(" << return_expr << ");\n";
  4847. return_flags &= ~RF_pyobject;
  4848. } else {
  4849. indent(out, indent_level)
  4850. << "if (Dtool_CheckErrorOccurred()) {\n";
  4851. if (manage_return) {
  4852. delete_return_value(out, indent_level + 2, remap, return_expr);
  4853. }
  4854. error_return(out, indent_level + 2, return_flags);
  4855. indent(out, indent_level) << "}\n";
  4856. }
  4857. } else {
  4858. if (check_exceptions) {
  4859. // Check if a Python exception has occurred. We only do this when
  4860. // check_exception is set. If report_errors is set, this method
  4861. // must terminate on error.
  4862. if (!may_raise_typeerror || report_errors) {
  4863. indent(out, indent_level)
  4864. << "if (_PyErr_OCCURRED()) {\n";
  4865. } else {
  4866. // If a method is some extension method that takes a PyObject*,
  4867. // and it raised a TypeError, continue.
  4868. // The documentation tells us not to compare the result of
  4869. // PyErr_Occurred against a specific exception type. However, in our
  4870. // case, this seems okay because we know that the TypeError we want
  4871. // to catch here is going to be generated by a PyErr_SetString call,
  4872. // not by user code.
  4873. indent(out, indent_level)
  4874. << "PyObject *exception = _PyErr_OCCURRED();\n";
  4875. indent(out, indent_level)
  4876. << "if (exception == PyExc_TypeError) {\n";
  4877. indent(out, indent_level)
  4878. << " // TypeError raised; continue to next overload type.\n";
  4879. indent(out, indent_level)
  4880. << "} else if (exception != (PyObject *)NULL) {\n";
  4881. }
  4882. if (manage_return) {
  4883. delete_return_value(out, indent_level + 2, remap, return_expr);
  4884. }
  4885. error_return(out, indent_level + 2, return_flags);
  4886. indent(out, indent_level)
  4887. << "} else {\n";
  4888. ++open_scopes;
  4889. indent_level += 2;
  4890. }
  4891. if (return_flags & RF_decref_args) {
  4892. indent(out, indent_level) << "Py_DECREF(args);\n";
  4893. return_flags &= ~RF_decref_args;
  4894. }
  4895. // Outputs code to check to see if an assertion has failed while
  4896. // the C++ code was executing, and report this failure back to Python.
  4897. // Don't do this for coercion constructors since they are called by
  4898. // other wrapper functions which already check this on their own.
  4899. if (watch_asserts && (return_flags & RF_coerced) == 0) {
  4900. out << "#ifndef NDEBUG\n";
  4901. indent(out, indent_level)
  4902. << "Notify *notify = Notify::ptr();\n";
  4903. indent(out, indent_level)
  4904. << "if (notify->has_assert_failed()) {\n";
  4905. if (manage_return) {
  4906. // Output code to delete any temporary object we may have allocated.
  4907. delete_return_value(out, indent_level + 2, remap, return_expr);
  4908. }
  4909. if (return_flags & RF_err_null) {
  4910. // This function returns NULL, so we can pass it on.
  4911. indent(out, indent_level + 2)
  4912. << "return Dtool_Raise_AssertionError();\n";
  4913. } else {
  4914. indent(out, indent_level + 2)
  4915. << "Dtool_Raise_AssertionError();\n";
  4916. error_return(out, indent_level + 2, return_flags);
  4917. }
  4918. indent(out, indent_level)
  4919. << "}\n";
  4920. out << "#endif\n";
  4921. }
  4922. }
  4923. // Okay, we're past all the error conditions and special cases. Now
  4924. // return the return type in the way that was requested.
  4925. if (return_flags & RF_int) {
  4926. CPPType *orig_type = remap->_return_type->get_orig_type();
  4927. if (is_constructor) {
  4928. // Special case for constructor.
  4929. TypeIndex type_index = builder.get_type(TypeManager::unwrap(TypeManager::resolve_type(orig_type)), false);
  4930. const InterrogateType &itype = idb->get_type(type_index);
  4931. indent(out, indent_level)
  4932. << "return DTool_PyInit_Finalize(self, " << return_expr << ", &" << CLASS_PREFIX << make_safe_name(itype.get_scoped_name()) << ", true, false);\n";
  4933. } else if (TypeManager::is_integer(orig_type)) {
  4934. if (return_flags & RF_compare) {
  4935. // Make sure it returns -1, 0, or 1, or Python complains with:
  4936. // RuntimeWarning: tp_compare didn't return -1, 0 or 1
  4937. indent(out, indent_level) << "return (int)(" << return_expr << " > 0) - (int)(" << return_expr << " < 0);\n";
  4938. } else {
  4939. indent(out, indent_level) << "return " << return_expr << ";\n";
  4940. }
  4941. } else if (TypeManager::is_void(orig_type)) {
  4942. indent(out, indent_level) << "return 0;\n";
  4943. } else {
  4944. cerr << "Warning: function has return type " << *orig_type
  4945. << ", expected int or void:\n" << expected_params << "\n";
  4946. indent(out, indent_level) << "// Don't know what to do with return type "
  4947. << *orig_type << ".\n";
  4948. indent(out, indent_level) << "return 0;\n";
  4949. }
  4950. } else if (return_flags & RF_self) {
  4951. indent(out, indent_level) << "Py_INCREF(self);\n";
  4952. indent(out, indent_level) << "return self;\n";
  4953. } else if (return_flags & RF_pyobject) {
  4954. if (return_expr.empty()) {
  4955. indent(out, indent_level) << "Py_INCREF(Py_None);\n";
  4956. indent(out, indent_level) << "return Py_None;\n";
  4957. } else {
  4958. pack_return_value(out, indent_level, remap, return_expr);
  4959. }
  4960. } else if (return_flags & RF_coerced) {
  4961. // We were asked to assign the result to a "coerced" reference.
  4962. CPPType *return_type = remap->_cpptype;
  4963. CPPType *orig_type = remap->_return_type->get_orig_type();
  4964. // Special case for static make function that returns a pointer:
  4965. // cast the pointer to the right pointer type.
  4966. if (!is_constructor && (remap->_flags & FunctionRemap::F_coerce_constructor) != 0 &&
  4967. (TypeManager::is_pointer(orig_type) || TypeManager::is_pointer_to_base(orig_type))) {
  4968. CPPType *new_type = remap->_return_type->get_new_type();
  4969. if (TypeManager::is_const_pointer_to_anything(new_type)) {
  4970. return_type = CPPType::new_type(new CPPConstType(return_type));
  4971. }
  4972. if (IsPandaTypedObject(return_type->as_struct_type())) {
  4973. return_expr = "DCAST("
  4974. + return_type->get_local_name(&parser)
  4975. + ", " + return_expr + ")";
  4976. } else {
  4977. return_type = CPPType::new_type(new CPPPointerType(return_type));
  4978. return_expr = "(" + return_type->get_local_name(&parser) +
  4979. ") " + return_expr;
  4980. }
  4981. }
  4982. if (return_expr == "coerced") {
  4983. // We already did this earlier...
  4984. } else if (TypeManager::is_reference_count(remap->_cpptype)) {
  4985. indent(out, indent_level) << "coerced = MOVE(" << return_expr << ");\n";
  4986. } else {
  4987. indent(out, indent_level) << "coerced = " << return_expr << ";\n";
  4988. indent(out, indent_level) << "manage = true;\n";
  4989. }
  4990. indent(out, indent_level) << "return true;\n";
  4991. }
  4992. // Close the extra braces opened earlier.
  4993. while (open_scopes > 0) {
  4994. indent_level -= 2;
  4995. indent(out, indent_level) << "}\n";
  4996. --open_scopes;
  4997. }
  4998. if (clear_error && !report_errors) {
  4999. // We were asked not to report errors, so clear the active exception
  5000. // if this overload might have raised a TypeError.
  5001. indent(out, indent_level) << "PyErr_Clear();\n";
  5002. }
  5003. if (min_version > 0) {
  5004. // Close the #if PY_VERSION_HEX check.
  5005. out << "#endif\n";
  5006. }
  5007. }
  5008. ////////////////////////////////////////////////////////////////////
  5009. // Function: InterfaceMakerPythonNative::error_return
  5010. // Access: Private
  5011. // Description: Outputs the correct return statement that should be
  5012. // used in case of error based on the ReturnFlags.
  5013. ////////////////////////////////////////////////////////////////////
  5014. void InterfaceMakerPythonNative::
  5015. error_return(ostream &out, int indent_level, int return_flags) {
  5016. //if (return_flags & RF_coerced) {
  5017. // indent(out, indent_level) << "coerced = NULL;\n";
  5018. //}
  5019. if (return_flags & RF_decref_args) {
  5020. indent(out, indent_level) << "Py_DECREF(args);\n";
  5021. }
  5022. if (return_flags & RF_int) {
  5023. indent(out, indent_level) << "return -1;\n";
  5024. } else if (return_flags & RF_err_notimplemented) {
  5025. indent(out, indent_level) << "Py_INCREF(Py_NotImplemented);\n";
  5026. indent(out, indent_level) << "return Py_NotImplemented;\n";
  5027. } else if (return_flags & RF_err_null) {
  5028. indent(out, indent_level) << "return NULL;\n";
  5029. } else if (return_flags & RF_err_false) {
  5030. indent(out, indent_level) << "return false;\n";
  5031. }
  5032. }
  5033. ////////////////////////////////////////////////////////////////////
  5034. // Function: InterfaceMakerPythonNative::error_raise_return
  5035. // Access: Private
  5036. // Description: Similar to error_return, except raises an exception
  5037. // before returning. If format_args are not the empty
  5038. // string, uses PyErr_Format instead of PyErr_SetString.
  5039. ////////////////////////////////////////////////////////////////////
  5040. void InterfaceMakerPythonNative::
  5041. error_raise_return(ostream &out, int indent_level, int return_flags,
  5042. const string &exc_type, const string &message,
  5043. const string &format_args) {
  5044. if (return_flags & RF_decref_args) {
  5045. indent(out, indent_level) << "Py_DECREF(args);\n";
  5046. return_flags &= ~RF_decref_args;
  5047. }
  5048. if (format_args.empty()) {
  5049. if (exc_type == "TypeError") {
  5050. if ((return_flags & RF_err_null) != 0) {
  5051. // This is probably an over-optimization, but why the heck not.
  5052. indent(out, indent_level) << "return Dtool_Raise_TypeError(";
  5053. output_quoted(out, indent_level + 29, message, false);
  5054. out << ");\n";
  5055. return;
  5056. } else {
  5057. indent(out, indent_level) << "Dtool_Raise_TypeError(";
  5058. output_quoted(out, indent_level + 22, message, false);
  5059. out << ");\n";
  5060. }
  5061. } else {
  5062. indent(out, indent_level) << "PyErr_SetString(PyExc_" << exc_type << ",\n";
  5063. output_quoted(out, indent_level + 16, message);
  5064. out << ");\n";
  5065. }
  5066. } else if ((return_flags & RF_err_null) != 0) {
  5067. // PyErr_Format always returns NULL. Passing it on directly allows
  5068. // the compiler to make a tiny optimization, so why not.
  5069. indent(out, indent_level) << "return PyErr_Format(PyExc_" << exc_type << ",\n";
  5070. output_quoted(out, indent_level + 20, message);
  5071. out << ",\n";
  5072. indent(out, indent_level + 20) << format_args << ");\n";
  5073. return;
  5074. } else {
  5075. indent(out, indent_level) << "PyErr_Format(PyExc_" << exc_type << ",\n";
  5076. output_quoted(out, indent_level + 13, message);
  5077. out << ",\n";
  5078. indent(out, indent_level + 13) << format_args << ");\n";
  5079. }
  5080. error_return(out, indent_level, return_flags);
  5081. }
  5082. ////////////////////////////////////////////////////////////////////
  5083. // Function: InterfaceMakerPythonNative::pack_return_value
  5084. // Access: Private
  5085. // Description: Outputs a command to pack the indicated expression,
  5086. // of the return_type type, as a Python return value.
  5087. ////////////////////////////////////////////////////////////////////
  5088. void InterfaceMakerPythonNative::
  5089. pack_return_value(ostream &out, int indent_level, FunctionRemap *remap,
  5090. string return_expr) {
  5091. ParameterRemap *return_type = remap->_return_type;
  5092. CPPType *orig_type = return_type->get_orig_type();
  5093. CPPType *type = return_type->get_new_type();
  5094. if (return_type->new_type_is_atomic_string()) {
  5095. if (TypeManager::is_char_pointer(orig_type)) {
  5096. indent(out, indent_level) << "if (" << return_expr << " == NULL) {\n";
  5097. indent(out, indent_level) << " Py_INCREF(Py_None);\n";
  5098. indent(out, indent_level) << " return Py_None;\n";
  5099. indent(out, indent_level) << "} else {\n";
  5100. out << "#if PY_MAJOR_VERSION >= 3\n";
  5101. indent(out, indent_level) << " return "
  5102. << "PyUnicode_FromString(" << return_expr << ");\n";
  5103. out << "#else\n";
  5104. indent(out, indent_level) << " return "
  5105. << "PyString_FromString(" << return_expr << ");\n";
  5106. out << "#endif\n";
  5107. indent(out, indent_level) << "}\n";
  5108. } else if (TypeManager::is_wchar_pointer(orig_type)) {
  5109. indent(out, indent_level) << "if (" << return_expr << " == NULL) {\n";
  5110. indent(out, indent_level) << " Py_INCREF(Py_None);\n";
  5111. indent(out, indent_level) << " return Py_None;\n";
  5112. indent(out, indent_level) << "} else {\n";
  5113. indent(out, indent_level+2)
  5114. << "return PyUnicode_FromWideChar("
  5115. << return_expr << ", wcslen(" << return_expr << "));\n";
  5116. indent(out, indent_level) << "}\n";
  5117. } else if (TypeManager::is_wstring(orig_type)) {
  5118. indent(out, indent_level)
  5119. << "return PyUnicode_FromWideChar("
  5120. << return_expr << ".data(), (int) " << return_expr << ".length());\n";
  5121. } else if (TypeManager::is_const_ptr_to_basic_string_wchar(orig_type)) {
  5122. indent(out, indent_level) << "if (" << return_expr << " == NULL) {\n";
  5123. indent(out, indent_level) << " Py_INCREF(Py_None);\n";
  5124. indent(out, indent_level) << " return Py_None;\n";
  5125. indent(out, indent_level) << "} else {\n";
  5126. indent(out, indent_level) << " return "
  5127. << "PyUnicode_FromWideChar("
  5128. << return_expr << "->data(), (int) " << return_expr << "->length());\n";
  5129. indent(out, indent_level) << "}\n";
  5130. } else if (TypeManager::is_const_ptr_to_basic_string_char(orig_type)) {
  5131. indent(out, indent_level) << "if (" << return_expr<< " == NULL) {\n";
  5132. indent(out, indent_level) << " Py_INCREF(Py_None);\n";
  5133. indent(out, indent_level) << " return Py_None;\n";
  5134. indent(out, indent_level) << "} else {\n";
  5135. out << "#if PY_MAJOR_VERSION >= 3\n";
  5136. indent(out, indent_level) << " return "
  5137. << "PyUnicode_FromStringAndSize("
  5138. << return_expr << "->data(), (Py_ssize_t)" << return_expr << "->length());\n";
  5139. out << "#else\n";
  5140. indent(out, indent_level) << " return "
  5141. << "PyString_FromStringAndSize("
  5142. << return_expr << "->data(), (Py_ssize_t)" << return_expr << "->length());\n";
  5143. out << "#endif\n";
  5144. indent(out, indent_level) << "}\n";
  5145. } else {
  5146. out << "#if PY_MAJOR_VERSION >= 3\n";
  5147. indent(out, indent_level)
  5148. << "return PyUnicode_FromStringAndSize("
  5149. << return_expr << ".data(), (Py_ssize_t)" << return_expr << ".length());\n";
  5150. out << "#else\n";
  5151. indent(out, indent_level)
  5152. << "return PyString_FromStringAndSize("
  5153. << return_expr << ".data(), (Py_ssize_t)" << return_expr << ".length());\n";
  5154. out << "#endif\n";
  5155. }
  5156. } else if (TypeManager::is_bool(type)) {
  5157. indent(out, indent_level)
  5158. << "return PyBool_FromLong(" << return_expr << ");\n";
  5159. } else if (TypeManager::is_size(type)) {
  5160. indent(out, indent_level)
  5161. << "return PyLongOrInt_FromSize_t(" << return_expr << ");\n";
  5162. } else if (TypeManager::is_char(type)) {
  5163. out << "#if PY_MAJOR_VERSION >= 3\n";
  5164. indent(out, indent_level)
  5165. << "return PyUnicode_FromStringAndSize(&" << return_expr << ", 1);\n";
  5166. out << "#else\n";
  5167. indent(out, indent_level)
  5168. << "return PyString_FromStringAndSize(&" << return_expr << ", 1);\n";
  5169. out << "#endif\n";
  5170. } else if (TypeManager::is_wchar(type)) {
  5171. indent(out, indent_level)
  5172. << "return PyUnicode_FromWideChar(&" << return_expr << ", 1);\n";
  5173. } else if (TypeManager::is_unsigned_longlong(type)) {
  5174. indent(out, indent_level)
  5175. << "return PyLong_FromUnsignedLongLong(" << return_expr << ");\n";
  5176. } else if (TypeManager::is_longlong(type)) {
  5177. indent(out, indent_level)
  5178. << "return PyLong_FromLongLong(" << return_expr << ");\n";
  5179. } else if (TypeManager::is_unsigned_integer(type)){
  5180. out << "#if PY_MAJOR_VERSION >= 3\n";
  5181. indent(out, indent_level)
  5182. << "return PyLong_FromUnsignedLong(" << return_expr << ");\n";
  5183. out << "#else\n";
  5184. indent(out, indent_level)
  5185. << "return PyLongOrInt_FromUnsignedLong(" << return_expr << ");\n";
  5186. out << "#endif\n";
  5187. } else if (TypeManager::is_integer(type)) {
  5188. out << "#if PY_MAJOR_VERSION >= 3\n";
  5189. indent(out, indent_level)
  5190. << "return PyLong_FromLong(" << return_expr << ");\n";
  5191. out << "#else\n";
  5192. indent(out, indent_level)
  5193. << "return PyInt_FromLong(" << return_expr << ");\n";
  5194. out << "#endif\n";
  5195. } else if (TypeManager::is_float(type)) {
  5196. indent(out, indent_level)
  5197. << "return PyFloat_FromDouble(" << return_expr << ");\n";
  5198. } else if (TypeManager::is_char_pointer(type)) {
  5199. indent(out, indent_level) << "if (" << return_expr << " == NULL) {\n";
  5200. indent(out, indent_level) << " Py_INCREF(Py_None);\n";
  5201. indent(out, indent_level) << " return Py_None;\n";
  5202. indent(out, indent_level) << "} else {\n";
  5203. out << "#if PY_MAJOR_VERSION >= 3\n";
  5204. indent(out, indent_level) << " return "
  5205. << "PyUnicode_FromString(" << return_expr << ");\n";
  5206. out << "#else\n";
  5207. indent(out, indent_level) << " return "
  5208. << "PyString_FromString(" << return_expr << ");\n";
  5209. out << "#endif\n";
  5210. indent(out, indent_level) << "}\n";
  5211. } else if (TypeManager::is_wchar_pointer(type)) {
  5212. indent(out, indent_level) << "if (" << return_expr << " == NULL) {\n";
  5213. indent(out, indent_level) << " Py_INCREF(Py_None);\n";
  5214. indent(out, indent_level) << " return Py_None;\n";
  5215. indent(out, indent_level) << "} else {\n";
  5216. indent(out, indent_level) << " return "
  5217. << "PyUnicode_FromWideChar("
  5218. << return_expr << ", wcslen(" << return_expr << "));\n";
  5219. indent(out, indent_level) << "}\n";
  5220. } else if (TypeManager::is_pointer_to_PyObject(type)) {
  5221. indent(out, indent_level)
  5222. << "return " << return_expr << ";\n";
  5223. } else if (TypeManager::is_pointer_to_Py_buffer(type)) {
  5224. indent(out, indent_level) << "if (" << return_expr << " == NULL) {\n";
  5225. indent(out, indent_level) << " Py_INCREF(Py_None);\n";
  5226. indent(out, indent_level) << " return Py_None;\n";
  5227. indent(out, indent_level) << "} else {\n";
  5228. indent(out, indent_level) << " return "
  5229. << "PyMemoryView_FromBuffer(" << return_expr << ");\n";
  5230. indent(out, indent_level) << "}\n";
  5231. } else if (TypeManager::is_pointer(type)) {
  5232. bool is_const = TypeManager::is_const_pointer_to_anything(type);
  5233. bool owns_memory = remap->_return_value_needs_management;
  5234. // Note, we don't check for NULL here any more. This is now done by the
  5235. // appropriate CreateInstance(Typed) function.
  5236. if (manage_reference_counts && TypeManager::is_pointer_to_base(orig_type)) {
  5237. // Use a trick to transfer the reference count to avoid a pair of
  5238. // unnecessary ref() and unref() calls. Ideally we'd use move
  5239. // semantics, but py_panda.cxx cannot make use of PointerTo.
  5240. indent(out, indent_level) << "// Transfer ownership of return_value.\n";
  5241. indent(out, indent_level);
  5242. type->output_instance(out, "return_ptr", &parser);
  5243. out << " = " << return_expr << ";\n";
  5244. indent(out, indent_level) << "return_value.cheat() = NULL;\n";
  5245. return_expr = "return_ptr";
  5246. }
  5247. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  5248. if (TypeManager::is_struct(orig_type) || TypeManager::is_ref_to_anything(orig_type)) {
  5249. if (TypeManager::is_ref_to_anything(orig_type) || remap->_manage_reference_count) {
  5250. TypeIndex type_index = builder.get_type(TypeManager::unwrap(TypeManager::resolve_type(type)),false);
  5251. const InterrogateType &itype = idb->get_type(type_index);
  5252. if (!isExportThisRun(itype._cpptype)) {
  5253. _external_imports.insert(itype._cpptype);
  5254. }
  5255. write_python_instance(out, indent_level, return_expr, owns_memory, itype.get_scoped_name(), itype._cpptype, is_const);
  5256. } else {
  5257. TypeIndex type_index = builder.get_type(TypeManager::unwrap(TypeManager::resolve_type(orig_type)),false);
  5258. const InterrogateType &itype = idb->get_type(type_index);
  5259. if (!isExportThisRun(itype._cpptype)) {
  5260. _external_imports.insert(itype._cpptype);
  5261. }
  5262. write_python_instance(out, indent_level, return_expr, owns_memory, itype.get_scoped_name(), itype._cpptype, is_const);
  5263. }
  5264. } else if (TypeManager::is_struct(orig_type->as_pointer_type()->_pointing_at)) {
  5265. TypeIndex type_index = builder.get_type(TypeManager::unwrap(TypeManager::resolve_type(orig_type)),false);
  5266. const InterrogateType &itype = idb->get_type(type_index);
  5267. if (!isExportThisRun(itype._cpptype)) {
  5268. _external_imports.insert(itype._cpptype);
  5269. }
  5270. write_python_instance(out, indent_level, return_expr, owns_memory, itype.get_scoped_name(), itype._cpptype, is_const);
  5271. } else {
  5272. indent(out, indent_level) << "Should Never Reach This InterfaceMakerPythonNative::pack_python_value";
  5273. //<< "return PyLongOrInt_FromLong((int) " << return_expr << ");\n";
  5274. }
  5275. } else {
  5276. // Return None.
  5277. indent(out, indent_level)
  5278. << "return Py_BuildValue(\"\");\n";
  5279. }
  5280. }
  5281. ////////////////////////////////////////////////////////////////////
  5282. // Function: InterfaceMakerPythonName::write_make_seq
  5283. // Access: Public
  5284. // Description: Generates the synthetic method described by the
  5285. // MAKE_SEQ() macro.
  5286. ////////////////////////////////////////////////////////////////////
  5287. void InterfaceMakerPythonNative::
  5288. write_make_seq(ostream &out, Object *obj, const std::string &ClassName,
  5289. const std::string &cClassName, MakeSeq *make_seq) {
  5290. out << "/******************************************************************\n" << " * Python make_seq wrapper\n";
  5291. out << " *******************************************************************/\n";
  5292. out << "static PyObject *" << make_seq->_name + "(PyObject *self, PyObject *) {\n";
  5293. string element_name = methodNameFromCppName(make_seq->_element_name, ClassName, false);
  5294. // This used to be a list. But it should really be a tuple, I think,
  5295. // because it probably makes more sense for it to be immutable (as
  5296. // changes to it won't be visible on the C++ side anyway).
  5297. out << " " << cClassName << " *local_this = NULL;\n"
  5298. << " if (!Dtool_Call_ExtractThisPointer(self, Dtool_" << ClassName << ", (void **)&local_this)) {\n"
  5299. << " return NULL;\n"
  5300. << " }\n"
  5301. << "\n"
  5302. << " PyObject *getter = PyObject_GetAttrString(self, \"" << element_name << "\");\n"
  5303. << " if (getter == (PyObject *)NULL) {\n"
  5304. << " return NULL;\n"
  5305. << " }\n"
  5306. << "\n"
  5307. << " Py_ssize_t count = (Py_ssize_t)local_this->" << make_seq->_num_name << "();\n"
  5308. << " PyObject *tuple = PyTuple_New(count);\n"
  5309. << "\n"
  5310. << " for (Py_ssize_t i = 0; i < count; ++i) {\n"
  5311. << "#if PY_MAJOR_VERSION >= 3\n"
  5312. << " PyObject *index = PyLong_FromSsize_t(i);\n"
  5313. << "#else\n"
  5314. << " PyObject *index = PyInt_FromSsize_t(i);\n"
  5315. << "#endif\n"
  5316. << " PyObject *value = PyObject_CallFunctionObjArgs(getter, index, NULL);\n"
  5317. << " PyTuple_SET_ITEM(tuple, i, value);\n"
  5318. << " Py_DECREF(index);\n"
  5319. << " }\n"
  5320. << "\n"
  5321. << " if (Dtool_CheckErrorOccurred()) {\n"
  5322. << " Py_DECREF(tuple);\n"
  5323. << " return NULL;\n"
  5324. << " }\n"
  5325. << " return tuple;\n"
  5326. << "}\n"
  5327. << "\n";
  5328. }
  5329. ////////////////////////////////////////////////////////////////////
  5330. // Function: InterfaceMakerPythonNative::record_object
  5331. // Access: Protected
  5332. // Description: Records the indicated type, which may be a struct
  5333. // type, along with all of its associated methods, if
  5334. // any.
  5335. ////////////////////////////////////////////////////////////////////
  5336. InterfaceMaker::Object *InterfaceMakerPythonNative::
  5337. record_object(TypeIndex type_index) {
  5338. if (type_index == 0) {
  5339. return (Object *)NULL;
  5340. }
  5341. Objects::iterator oi = _objects.find(type_index);
  5342. if (oi != _objects.end()) {
  5343. return (*oi).second;
  5344. }
  5345. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  5346. const InterrogateType &itype = idb->get_type(type_index);
  5347. if (!is_cpp_type_legal(itype._cpptype)) {
  5348. return (Object *)NULL;
  5349. }
  5350. Object *object = new Object(itype);
  5351. bool inserted = _objects.insert(Objects::value_type(type_index, object)).second;
  5352. assert(inserted);
  5353. Function *function;
  5354. int num_constructors = itype.number_of_constructors();
  5355. for (int ci = 0; ci < num_constructors; ci++) {
  5356. function = record_function(itype, itype.get_constructor(ci));
  5357. if (is_function_legal(function)) {
  5358. object->_constructors.push_back(function);
  5359. }
  5360. }
  5361. int num_methods = itype.number_of_methods();
  5362. int mi;
  5363. for (mi = 0; mi < num_methods; mi++) {
  5364. function = record_function(itype, itype.get_method(mi));
  5365. if (is_function_legal(function)) {
  5366. object->_methods.push_back(function);
  5367. }
  5368. }
  5369. int num_casts = itype.number_of_casts();
  5370. for (mi = 0; mi < num_casts; mi++) {
  5371. function = record_function(itype, itype.get_cast(mi));
  5372. if (is_function_legal(function)) {
  5373. object->_methods.push_back(function);
  5374. }
  5375. }
  5376. int num_derivations = itype.number_of_derivations();
  5377. for (int di = 0; di < num_derivations; di++) {
  5378. TypeIndex d_type_Index = itype.get_derivation(di);
  5379. idb->get_type(d_type_Index);
  5380. if (!interrogate_type_is_unpublished(d_type_Index)) {
  5381. if (itype.derivation_has_upcast(di)) {
  5382. function = record_function(itype, itype.derivation_get_upcast(di));
  5383. if (is_function_legal(function)) {
  5384. object->_methods.push_back(function);
  5385. }
  5386. }
  5387. if (itype.derivation_has_downcast(di)) {
  5388. // Downcasts are methods of the base class, not the child class.
  5389. TypeIndex base_type_index = itype.get_derivation(di);
  5390. const InterrogateType &base_type = idb->get_type(base_type_index);
  5391. function = record_function(base_type, itype.derivation_get_downcast(di));
  5392. if (is_function_legal(function)) {
  5393. Object *pobject = record_object(base_type_index);
  5394. if (pobject != NULL) {
  5395. pobject->_methods.push_back(function);
  5396. }
  5397. }
  5398. }
  5399. }
  5400. }
  5401. int num_elements = itype.number_of_elements();
  5402. for (int ei = 0; ei < num_elements; ei++) {
  5403. ElementIndex element_index = itype.get_element(ei);
  5404. const InterrogateElement &ielement = idb->get_element(element_index);
  5405. Property *property = new Property(ielement);
  5406. if (ielement.has_setter()) {
  5407. FunctionIndex func_index = ielement.get_setter();
  5408. Function *setter = record_function(itype, func_index);
  5409. if (is_function_legal(setter)) {
  5410. property->_setter = setter;
  5411. }
  5412. }
  5413. if (ielement.has_getter()) {
  5414. FunctionIndex func_index = ielement.get_getter();
  5415. Function *getter = record_function(itype, func_index);
  5416. if (is_function_legal(getter)) {
  5417. property->_getter = getter;
  5418. }
  5419. }
  5420. if (property->_getter != NULL) {
  5421. object->_properties.push_back(property);
  5422. } else {
  5423. // No use exporting a property without a getter.
  5424. delete property;
  5425. }
  5426. }
  5427. object->check_protocols();
  5428. int num_nested = itype.number_of_nested_types();
  5429. for (int ni = 0; ni < num_nested; ni++) {
  5430. TypeIndex nested_index = itype.get_nested_type(ni);
  5431. record_object(nested_index);
  5432. }
  5433. return object;
  5434. }
  5435. ////////////////////////////////////////////////////////////////////
  5436. // Function: InterfaceMaker::generate_wrappers
  5437. // Access: Public, Virtual
  5438. // Description: Walks through the set of functions in the database
  5439. // and generates wrappers for each function, storing
  5440. // these in the database. No actual code should be
  5441. // output yet; this just updates the database with the
  5442. // wrapper information.
  5443. ////////////////////////////////////////////////////////////////////
  5444. void InterfaceMakerPythonNative::
  5445. generate_wrappers() {
  5446. inside_python_native = true;
  5447. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  5448. // We use a while loop rather than a simple for loop, because we
  5449. // might increase the number of types recursively during the
  5450. // traversal.
  5451. int ti = 0;
  5452. while (ti < idb->get_num_all_types()) {
  5453. TypeIndex type_index = idb->get_all_type(ti);
  5454. record_object(type_index);
  5455. ++ti;
  5456. }
  5457. int num_global_elements = idb->get_num_global_elements();
  5458. for (int gi = 0; gi < num_global_elements; ++gi) {
  5459. TypeIndex type_index = idb->get_global_element(gi);
  5460. record_object(type_index);
  5461. }
  5462. int num_functions = idb->get_num_global_functions();
  5463. for (int fi = 0; fi < num_functions; fi++) {
  5464. FunctionIndex func_index = idb->get_global_function(fi);
  5465. record_function(dummy_type, func_index);
  5466. }
  5467. int num_manifests = idb->get_num_global_manifests();
  5468. for (int mi = 0; mi < num_manifests; mi++) {
  5469. ManifestIndex manifest_index = idb->get_global_manifest(mi);
  5470. const InterrogateManifest &iman = idb->get_manifest(manifest_index);
  5471. if (iman.has_getter()) {
  5472. FunctionIndex func_index = iman.get_getter();
  5473. record_function(dummy_type, func_index);
  5474. }
  5475. }
  5476. int num_elements = idb->get_num_global_elements();
  5477. for (int ei = 0; ei < num_elements; ei++) {
  5478. ElementIndex element_index = idb->get_global_element(ei);
  5479. const InterrogateElement &ielement = idb->get_element(element_index);
  5480. if (ielement.has_getter()) {
  5481. FunctionIndex func_index = ielement.get_getter();
  5482. record_function(dummy_type, func_index);
  5483. }
  5484. if (ielement.has_setter()) {
  5485. FunctionIndex func_index = ielement.get_setter();
  5486. record_function(dummy_type, func_index);
  5487. }
  5488. }
  5489. inside_python_native = false;
  5490. }
  5491. //////////////////////////////////////////////
  5492. // Function :is_cpp_type_legal
  5493. //
  5494. // is the cpp object supported by by the dtool_py interface..
  5495. //////////////////////////////////////////////
  5496. bool InterfaceMakerPythonNative::
  5497. is_cpp_type_legal(CPPType *in_ctype) {
  5498. if (in_ctype == NULL) {
  5499. return false;
  5500. }
  5501. string name = in_ctype->get_local_name(&parser);
  5502. if (builder.in_ignoretype(name)) {
  5503. return false;
  5504. }
  5505. if (builder.in_forcetype(name)) {
  5506. return true;
  5507. }
  5508. //bool answer = false;
  5509. CPPType *type = TypeManager::resolve_type(in_ctype);
  5510. type = TypeManager::unwrap(type);
  5511. if (TypeManager::is_void(type)) {
  5512. return true;
  5513. } else if (TypeManager::is_basic_string_char(type)) {
  5514. return true;
  5515. } else if (TypeManager::is_basic_string_wchar(type)) {
  5516. return true;
  5517. } else if (TypeManager::is_simple(type)) {
  5518. return true;
  5519. } else if (TypeManager::is_pointer_to_simple(type)) {
  5520. return true;
  5521. } else if (TypeManager::is_exported(type)) {
  5522. return true;
  5523. } else if (TypeManager::is_pointer_to_PyObject(in_ctype)) {
  5524. return true;
  5525. } else if (TypeManager::is_pointer_to_Py_buffer(in_ctype)) {
  5526. return true;
  5527. }
  5528. //if (answer == false)
  5529. // printf(" -------------------- Bad Type ?? %s\n",type->get_local_name().c_str());
  5530. return false;
  5531. }
  5532. //////////////////////////////////////////////
  5533. // Function :isExportThisRun
  5534. //
  5535. //////////////////////////////////////////////
  5536. bool InterfaceMakerPythonNative::
  5537. isExportThisRun(CPPType *ctype) {
  5538. if (builder.in_forcetype(ctype->get_local_name(&parser))) {
  5539. return true;
  5540. }
  5541. if (!TypeManager::is_exported(ctype)) {
  5542. return false;
  5543. }
  5544. if (TypeManager::is_local(ctype)) {
  5545. return true;
  5546. }
  5547. return false;
  5548. }
  5549. //////////////////////////////////////////////
  5550. // Function : isExportThisRun
  5551. /////////////////////////////////////////////
  5552. bool InterfaceMakerPythonNative::
  5553. isExportThisRun(Function *func) {
  5554. if (func == NULL || !is_function_legal(func)) {
  5555. return false;
  5556. }
  5557. Function::Remaps::const_iterator ri;
  5558. for (ri = func->_remaps.begin(); ri != func->_remaps.end();) {
  5559. FunctionRemap *remap = (*ri);
  5560. return isExportThisRun(remap->_cpptype);
  5561. }
  5562. return false;
  5563. }
  5564. //////////////////////////////////////////////
  5565. // Function : is_remap_legal
  5566. //////////////////////////////////////////////
  5567. bool InterfaceMakerPythonNative::
  5568. is_remap_legal(FunctionRemap *remap) {
  5569. if (remap == NULL) {
  5570. return false;
  5571. }
  5572. // return must be legal and managable..
  5573. if (!is_cpp_type_legal(remap->_return_type->get_orig_type())) {
  5574. // printf(" is_remap_legal Return Is Bad %s\n",remap->_return_type->get_orig_type()->get_fully_scoped_name().c_str());
  5575. return false;
  5576. }
  5577. // We don't currently support returning pointers, but we accept
  5578. // them as function parameters.
  5579. if (TypeManager::is_pointer_to_simple(remap->_return_type->get_orig_type())) {
  5580. return false;
  5581. }
  5582. // ouch .. bad things will happen here .. do not even try..
  5583. if (remap->_ForcedVoidReturn) {
  5584. return false;
  5585. }
  5586. // all params must be legal
  5587. for (int pn = 0; pn < (int)remap->_parameters.size(); pn++) {
  5588. CPPType *orig_type = remap->_parameters[pn]._remap->get_orig_type();
  5589. if (!is_cpp_type_legal(orig_type)) {
  5590. return false;
  5591. }
  5592. }
  5593. // ok all looks ok.
  5594. return true;
  5595. }
  5596. //////////////////////////////////////////////
  5597. // Function : has_coerce_constructor
  5598. // Returns 1 if coerce constructor
  5599. // returns const, 2 if non-const.
  5600. //////////////////////////////////////////////
  5601. int InterfaceMakerPythonNative::
  5602. has_coerce_constructor(CPPStructType *type) {
  5603. if (type == NULL) {
  5604. return 0;
  5605. }
  5606. CPPScope *scope = type->get_scope();
  5607. if (scope == NULL) {
  5608. return 0;
  5609. }
  5610. int result = 0;
  5611. CPPScope::Functions::iterator fgi;
  5612. for (fgi = scope->_functions.begin(); fgi != scope->_functions.end(); ++fgi) {
  5613. CPPFunctionGroup *fgroup = fgi->second;
  5614. CPPFunctionGroup::Instances::iterator ii;
  5615. for (ii = fgroup->_instances.begin(); ii != fgroup->_instances.end(); ++ii) {
  5616. CPPInstance *inst = (*ii);
  5617. CPPFunctionType *ftype = inst->_type->as_function_type();
  5618. if (ftype == NULL) {
  5619. continue;
  5620. }
  5621. if (inst->_storage_class & CPPInstance::SC_explicit) {
  5622. // Skip it if it is marked not to allow coercion.
  5623. continue;
  5624. }
  5625. if (inst->_vis > min_vis) {
  5626. // Not published.
  5627. continue;
  5628. }
  5629. CPPParameterList::Parameters &params = ftype->_parameters->_parameters;
  5630. if (params.size() == 0) {
  5631. // It's useless if it doesn't take any parameters.
  5632. continue;
  5633. }
  5634. if (ftype->_flags & CPPFunctionType::F_constructor) {
  5635. if (params.size() == 1 &&
  5636. TypeManager::unwrap(params[0]->_type) == type) {
  5637. // Skip a copy constructor.
  5638. continue;
  5639. } else {
  5640. return 2;
  5641. }
  5642. } else if (fgroup->_name == "make" && (inst->_storage_class & CPPInstance::SC_static) != 0) {
  5643. if (TypeManager::is_const_pointer_or_ref(ftype->_return_type)) {
  5644. result = 1;
  5645. } else {
  5646. return 2;
  5647. }
  5648. }
  5649. }
  5650. }
  5651. return result;
  5652. }
  5653. //////////////////////////////////////////////
  5654. // Function : is_remap_coercion_possible
  5655. //////////////////////////////////////////////
  5656. bool InterfaceMakerPythonNative::
  5657. is_remap_coercion_possible(FunctionRemap *remap) {
  5658. if (remap == NULL) {
  5659. return false;
  5660. }
  5661. int pn = 0;
  5662. if (remap->_has_this) {
  5663. // Skip the "this" parameter. It's never coercible.
  5664. ++pn;
  5665. }
  5666. while (pn < (int)remap->_parameters.size()) {
  5667. CPPType *type = remap->_parameters[pn]._remap->get_new_type();
  5668. if (TypeManager::is_char_pointer(type)) {
  5669. } else if (TypeManager::is_wchar_pointer(type)) {
  5670. } else if (TypeManager::is_pointer_to_PyObject(type)) {
  5671. } else if (TypeManager::is_pointer_to_Py_buffer(type)) {
  5672. } else if (TypeManager::is_pointer_to_simple(type)) {
  5673. } else if (TypeManager::is_pointer(type)) {
  5674. // This is a pointer to an object, so we
  5675. // might be able to coerce a parameter to it.
  5676. CPPType *obj_type = TypeManager::unwrap(TypeManager::resolve_type(type));
  5677. if (has_coerce_constructor(obj_type->as_struct_type()) > 0) {
  5678. // It has a coercion constructor, so go for it.
  5679. return true;
  5680. }
  5681. }
  5682. ++pn;
  5683. }
  5684. return false;
  5685. }
  5686. ////////////////////////////////////////////////////////////////////////
  5687. // Function : is_function_legal
  5688. ////////////////////////////////////////////////////////////////////////
  5689. bool InterfaceMakerPythonNative::
  5690. is_function_legal(Function *func) {
  5691. Function::Remaps::const_iterator ri;
  5692. for (ri = func->_remaps.begin(); ri != func->_remaps.end(); ++ri) {
  5693. FunctionRemap *remap = (*ri);
  5694. if (is_remap_legal(remap)) {
  5695. // printf(" Function Is Marked Legal %s\n",func->_name.c_str());
  5696. return true;
  5697. }
  5698. }
  5699. // printf(" Function Is Marked Illegal %s\n",func->_name.c_str());
  5700. return false;
  5701. }
  5702. ////////////////////////////////////////////////////////
  5703. // Function : IsRunTimeTyped
  5704. ///////////////////////////////////////////////////////
  5705. bool InterfaceMakerPythonNative::
  5706. IsRunTimeTyped(const InterrogateType &itype) {
  5707. TypeIndex ptype_id = itype.get_outer_class();
  5708. if (ptype_id > 0) {
  5709. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  5710. InterrogateType ptype = idb->get_type(ptype_id);
  5711. return IsRunTimeTyped(ptype);
  5712. }
  5713. if (itype.get_name() == "TypedObject") {
  5714. return true;
  5715. }
  5716. return false;
  5717. }
  5718. //////////////////////////////////////////////////////////
  5719. // Function : DoesInheritFromIsClass
  5720. //
  5721. // Helper function to check cpp class inharatience..
  5722. ///////////////////////////////////////////////////////////
  5723. bool InterfaceMakerPythonNative::
  5724. DoesInheritFromIsClass(const CPPStructType *inclass, const std::string &name) {
  5725. if (inclass == NULL) {
  5726. return false;
  5727. }
  5728. std::string scoped_name = inclass->get_fully_scoped_name();
  5729. if (scoped_name == name) {
  5730. return true;
  5731. }
  5732. CPPStructType::Derivation::const_iterator bi;
  5733. for (bi = inclass->_derivation.begin();
  5734. bi != inclass->_derivation.end();
  5735. ++bi) {
  5736. const CPPStructType::Base &base = (*bi);
  5737. CPPStructType *base_type = TypeManager::resolve_type(base._base)->as_struct_type();
  5738. if (base_type != NULL) {
  5739. if (DoesInheritFromIsClass(base_type, name)) {
  5740. return true;
  5741. }
  5742. }
  5743. }
  5744. return false;
  5745. }
  5746. ////////////////////////////////////////////////////////////////////////////////////////////
  5747. // Function : HasAGetKeyFunction
  5748. //
  5749. // does the class have a supportable get_key() or get_hash() to return
  5750. // a usable Python hash? Returns the name of the method, or empty
  5751. // string if there is no suitable method.
  5752. //////////////////////////////////////////////////////////////////////////////////////////
  5753. string InterfaceMakerPythonNative::
  5754. HasAGetKeyFunction(const InterrogateType &itype_class) {
  5755. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  5756. int num_methods = itype_class.number_of_methods();
  5757. int mi;
  5758. for (mi = 0; mi < num_methods; mi++) {
  5759. FunctionIndex func_index = itype_class.get_method(mi);
  5760. const InterrogateFunction &ifunc = idb->get_function(func_index);
  5761. if (ifunc.get_name() == "get_key" || ifunc.get_name() == "get_hash") {
  5762. if (ifunc._instances != (InterrogateFunction::Instances *)NULL) {
  5763. InterrogateFunction::Instances::const_iterator ii;
  5764. for (ii = ifunc._instances->begin();
  5765. ii != ifunc._instances->end();
  5766. ++ii) {
  5767. CPPInstance *cppinst = (*ii).second;
  5768. CPPFunctionType *cppfunc = cppinst->_type->as_function_type();
  5769. if (cppfunc != NULL) {
  5770. if (cppfunc->_parameters != NULL &&
  5771. cppfunc->_return_type != NULL &&
  5772. TypeManager::is_integer(cppfunc->_return_type)) {
  5773. if (cppfunc->_parameters->_parameters.size() == 0) {
  5774. return ifunc.get_name();
  5775. }
  5776. }
  5777. }
  5778. }
  5779. }
  5780. }
  5781. }
  5782. return string();
  5783. }
  5784. ////////////////////////////////////////////////////////////////////////////////////////////
  5785. // Function : HasAGetClassTypeFunction
  5786. //
  5787. // does the class have a supportable GetClassType which returns a TypeHandle.
  5788. //////////////////////////////////////////////////////////////////////////////////////////
  5789. bool InterfaceMakerPythonNative::
  5790. HasAGetClassTypeFunction(const InterrogateType &itype_class) {
  5791. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  5792. int num_methods = itype_class.number_of_methods();
  5793. int mi;
  5794. for (mi = 0; mi < num_methods; mi++) {
  5795. FunctionIndex func_index = itype_class.get_method(mi);
  5796. const InterrogateFunction &ifunc = idb->get_function(func_index);
  5797. if (ifunc.get_name() == "get_class_type") {
  5798. if (ifunc._instances != (InterrogateFunction::Instances *)NULL) {
  5799. InterrogateFunction::Instances::const_iterator ii;
  5800. for (ii = ifunc._instances->begin();ii != ifunc._instances->end();++ii) {
  5801. CPPInstance *cppinst = (*ii).second;
  5802. CPPFunctionType *cppfunc = cppinst->_type->as_function_type();
  5803. if (cppfunc != NULL && cppfunc->_return_type != NULL &&
  5804. cppfunc->_parameters != NULL) {
  5805. CPPType *ret_type = TypeManager::unwrap(cppfunc->_return_type);
  5806. if (TypeManager::is_struct(ret_type) &&
  5807. ret_type->get_simple_name() == "TypeHandle") {
  5808. if (cppfunc->_parameters->_parameters.size() == 0) {
  5809. return true;
  5810. }
  5811. }
  5812. }
  5813. }
  5814. }
  5815. }
  5816. }
  5817. return false;
  5818. }
  5819. ////////////////////////////////////////////////////////////////////
  5820. // Function: InterfaceMakerPythonNative::NeedsAStrFunction
  5821. // Access: Private
  5822. // Description: Returns -1 if the class does not define write() (and
  5823. // therefore cannot support a __str__ function).
  5824. //
  5825. // Returns 1 if the class defines write(ostream).
  5826. //
  5827. // Returns 2 if the class defines write(ostream, int).
  5828. //
  5829. // Note that if you want specific behavior for Python
  5830. // str(), you should just define a __str__ function,
  5831. // which maps directly to the appropriate type slot.
  5832. ////////////////////////////////////////////////////////////////////
  5833. int InterfaceMakerPythonNative::
  5834. NeedsAStrFunction(const InterrogateType &itype_class) {
  5835. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  5836. int num_methods = itype_class.number_of_methods();
  5837. int mi;
  5838. for (mi = 0; mi < num_methods; ++mi) {
  5839. FunctionIndex func_index = itype_class.get_method(mi);
  5840. const InterrogateFunction &ifunc = idb->get_function(func_index);
  5841. if (ifunc.get_name() == "write") {
  5842. if (ifunc._instances != (InterrogateFunction::Instances *)NULL) {
  5843. InterrogateFunction::Instances::const_iterator ii;
  5844. for (ii = ifunc._instances->begin();
  5845. ii != ifunc._instances->end();
  5846. ++ii) {
  5847. CPPInstance *cppinst = (*ii).second;
  5848. CPPFunctionType *cppfunc = cppinst->_type->as_function_type();
  5849. if (cppfunc != NULL) {
  5850. if (cppfunc->_parameters != NULL &&
  5851. cppfunc->_return_type != NULL &&
  5852. TypeManager::is_void(cppfunc->_return_type)) {
  5853. if (cppfunc->_parameters->_parameters.size() == 1) {
  5854. CPPInstance *inst1 = cppfunc->_parameters->_parameters[0];
  5855. if (TypeManager::is_pointer_to_ostream(inst1->_type)) {
  5856. // write(ostream)
  5857. return 1;
  5858. }
  5859. }
  5860. if (cppfunc->_parameters->_parameters.size() == 2) {
  5861. CPPInstance *inst1 = cppfunc->_parameters->_parameters[0];
  5862. if (TypeManager::is_pointer_to_ostream(inst1->_type)) {
  5863. inst1 = cppfunc->_parameters->_parameters[1];
  5864. if (inst1->_initializer != NULL) {
  5865. // write(ostream, int = 0)
  5866. return 1;
  5867. }
  5868. if (TypeManager::is_integer(inst1->_type)) {
  5869. // write(ostream, int)
  5870. return 2;
  5871. }
  5872. }
  5873. }
  5874. }
  5875. }
  5876. }
  5877. }
  5878. }
  5879. }
  5880. return -1;
  5881. }
  5882. ////////////////////////////////////////////////////////////////////
  5883. // Function: InterfaceMakerPythonNative::NeedsAReprFunction
  5884. // Access: Private
  5885. // Description: Returns -1 if the class does not define output() or
  5886. // python_repr() (and therefore cannot support a
  5887. // __repr__ function).
  5888. //
  5889. // Returns 1 if the class defines python_repr(ostream, string).
  5890. //
  5891. // Returns 2 if the class defines output(ostream).
  5892. //
  5893. // Returns 3 if the class defines an extension
  5894. // function for python_repr(ostream, string).
  5895. //
  5896. // Note that defining python_repr is deprecated in
  5897. // favor of defining a __repr__ that returns a string,
  5898. // which maps directly to the appropriate type slot.
  5899. ////////////////////////////////////////////////////////////////////
  5900. int InterfaceMakerPythonNative::
  5901. NeedsAReprFunction(const InterrogateType &itype_class) {
  5902. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  5903. int num_methods = itype_class.number_of_methods();
  5904. int mi;
  5905. for (mi = 0; mi < num_methods; ++mi) {
  5906. FunctionIndex func_index = itype_class.get_method(mi);
  5907. const InterrogateFunction &ifunc = idb->get_function(func_index);
  5908. if (ifunc.get_name() == "python_repr") {
  5909. if (ifunc._instances != (InterrogateFunction::Instances *)NULL) {
  5910. InterrogateFunction::Instances::const_iterator ii;
  5911. for (ii = ifunc._instances->begin();
  5912. ii != ifunc._instances->end();
  5913. ++ii) {
  5914. CPPInstance *cppinst = (*ii).second;
  5915. CPPFunctionType *cppfunc = cppinst->_type->as_function_type();
  5916. if (cppfunc != NULL) {
  5917. if (cppfunc->_parameters != NULL &&
  5918. cppfunc->_return_type != NULL &&
  5919. TypeManager::is_void(cppfunc->_return_type)) {
  5920. if (cppfunc->_parameters->_parameters.size() == 2) {
  5921. CPPInstance *inst1 = cppfunc->_parameters->_parameters[0];
  5922. if (TypeManager::is_pointer_to_ostream(inst1->_type)) {
  5923. inst1 = cppfunc->_parameters->_parameters[1];
  5924. if (TypeManager::is_string(inst1->_type) ||
  5925. TypeManager::is_char_pointer(inst1->_type)) {
  5926. // python_repr(ostream, string)
  5927. if ((cppinst->_storage_class & CPPInstance::SC_extension) != 0) {
  5928. return 3;
  5929. } else {
  5930. return 1;
  5931. }
  5932. }
  5933. }
  5934. }
  5935. }
  5936. }
  5937. }
  5938. }
  5939. }
  5940. }
  5941. for (mi = 0; mi < num_methods; ++mi) {
  5942. FunctionIndex func_index = itype_class.get_method(mi);
  5943. const InterrogateFunction &ifunc = idb->get_function(func_index);
  5944. if (ifunc.get_name() == "output") {
  5945. if (ifunc._instances != (InterrogateFunction::Instances *)NULL) {
  5946. InterrogateFunction::Instances::const_iterator ii;
  5947. for (ii = ifunc._instances->begin();
  5948. ii != ifunc._instances->end();
  5949. ++ii) {
  5950. CPPInstance *cppinst = (*ii).second;
  5951. CPPFunctionType *cppfunc = cppinst->_type->as_function_type();
  5952. if (cppfunc != NULL) {
  5953. if (cppfunc->_parameters != NULL &&
  5954. cppfunc->_return_type != NULL &&
  5955. TypeManager::is_void(cppfunc->_return_type)) {
  5956. if (cppfunc->_parameters->_parameters.size() == 1) {
  5957. CPPInstance *inst1 = cppfunc->_parameters->_parameters[0];
  5958. if (TypeManager::is_pointer_to_ostream(inst1->_type)) {
  5959. // output(ostream)
  5960. return 2;
  5961. }
  5962. }
  5963. if (cppfunc->_parameters->_parameters.size() >= 2) {
  5964. CPPInstance *inst1 = cppfunc->_parameters->_parameters[0];
  5965. if (TypeManager::is_pointer_to_ostream(inst1->_type)) {
  5966. inst1 = cppfunc->_parameters->_parameters[1];
  5967. if (inst1->_initializer != NULL) {
  5968. // output(ostream, foo = bar, ...)
  5969. return 2;
  5970. }
  5971. }
  5972. }
  5973. }
  5974. }
  5975. }
  5976. }
  5977. }
  5978. }
  5979. return -1;
  5980. }
  5981. ////////////////////////////////////////////////////////////////////
  5982. // Function: InterfaceMakerPythonNative::NeedsARichCompareFunction
  5983. // Access: Private
  5984. // Description: Returns true if the class defines a rich comparison
  5985. // operator.
  5986. ////////////////////////////////////////////////////////////////////
  5987. bool InterfaceMakerPythonNative::
  5988. NeedsARichCompareFunction(const InterrogateType &itype_class) {
  5989. InterrogateDatabase *idb = InterrogateDatabase::get_ptr();
  5990. int num_methods = itype_class.number_of_methods();
  5991. int mi;
  5992. for (mi = 0; mi < num_methods; ++mi) {
  5993. FunctionIndex func_index = itype_class.get_method(mi);
  5994. const InterrogateFunction &ifunc = idb->get_function(func_index);
  5995. if (ifunc.get_name() == "operator <") {
  5996. return true;
  5997. }
  5998. if (ifunc.get_name() == "operator <=") {
  5999. return true;
  6000. }
  6001. if (ifunc.get_name() == "operator ==") {
  6002. return true;
  6003. }
  6004. if (ifunc.get_name() == "operator !=") {
  6005. return true;
  6006. }
  6007. if (ifunc.get_name() == "operator >") {
  6008. return true;
  6009. }
  6010. if (ifunc.get_name() == "operator >=") {
  6011. return true;
  6012. }
  6013. }
  6014. return false;
  6015. }
  6016. ////////////////////////////////////////////////////////////////////
  6017. // Function: InterfaceMakerPythonNative::output_quoted
  6018. // Access: Private
  6019. // Description: Outputs the indicated string as a single quoted,
  6020. // multi-line string to the generated C++ source code.
  6021. // The output point is left on the last line of the
  6022. // string, following the trailing quotation mark.
  6023. ////////////////////////////////////////////////////////////////////
  6024. void InterfaceMakerPythonNative::
  6025. output_quoted(ostream &out, int indent_level, const std::string &str,
  6026. bool first_line) {
  6027. indent(out, (first_line ? indent_level : 0))
  6028. << '"';
  6029. std::string::const_iterator si;
  6030. for (si = str.begin(); si != str.end();) {
  6031. switch (*si) {
  6032. case '"':
  6033. case '\\':
  6034. out << '\\' << *si;
  6035. break;
  6036. case '\n':
  6037. out << "\\n\"";
  6038. if (++si == str.end()) {
  6039. return;
  6040. }
  6041. out << "\n";
  6042. indent(out, indent_level)
  6043. << '"';
  6044. continue;
  6045. default:
  6046. if (!isprint(*si)) {
  6047. out << "\\" << oct << setw(3) << setfill('0') << (unsigned int)(*si)
  6048. << dec;
  6049. } else {
  6050. out << *si;
  6051. }
  6052. }
  6053. ++si;
  6054. }
  6055. out << '"';
  6056. }