interfaceMakerPythonNative.cxx 268 KB

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