interfaceMakerPythonNative.cxx 262 KB

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