interfaceMakerPythonNative.cxx 300 KB

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