2
0

interfaceMakerPythonNative.cxx 287 KB

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