interfaceMakerPythonNative.cxx 287 KB

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