interfaceMakerPythonNative.cxx 269 KB

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