interfaceMakerPythonNative.cxx 318 KB

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