interfaceMakerPythonNative.cxx 263 KB

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