interfaceMakerPythonNative.cxx 257 KB

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