interfaceMakerPythonNative.cxx 279 KB

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