interfaceMakerPythonNative.cxx 279 KB

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