interfaceMakerPythonNative.cxx 285 KB

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