interfaceMakerPythonNative.cxx 299 KB

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