as_scriptengine.cpp 189 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496
  1. /*
  2. AngelCode Scripting Library
  3. Copyright (c) 2003-2018 Andreas Jonsson
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any
  6. damages arising from the use of this software.
  7. Permission is granted to anyone to use this software for any
  8. purpose, including commercial applications, and to alter it and
  9. redistribute it freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you
  11. must not claim that you wrote the original software. If you use
  12. this software in a product, an acknowledgment in the product
  13. documentation would be appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and
  15. must not be misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source
  17. distribution.
  18. The original version of this library can be located at:
  19. http://www.angelcode.com/angelscript/
  20. Andreas Jonsson
  21. [email protected]
  22. */
  23. //
  24. // as_scriptengine.cpp
  25. //
  26. // The implementation of the script engine interface
  27. //
  28. #include <stdlib.h>
  29. #include "as_config.h"
  30. #include "as_scriptengine.h"
  31. #include "as_builder.h"
  32. #include "as_context.h"
  33. #include "as_string_util.h"
  34. #include "as_tokenizer.h"
  35. #include "as_texts.h"
  36. #include "as_module.h"
  37. #include "as_callfunc.h"
  38. #include "as_generic.h"
  39. #include "as_scriptobject.h"
  40. #include "as_compiler.h"
  41. #include "as_bytecode.h"
  42. #include "as_debug.h"
  43. BEGIN_AS_NAMESPACE
  44. #ifdef AS_PROFILE
  45. // Instantiate the profiler once
  46. CProfiler g_profiler;
  47. #endif
  48. extern "C"
  49. {
  50. AS_API const char * asGetLibraryVersion()
  51. {
  52. #ifdef _DEBUG
  53. return ANGELSCRIPT_VERSION_STRING " DEBUG";
  54. #else
  55. return ANGELSCRIPT_VERSION_STRING;
  56. #endif
  57. }
  58. AS_API const char * asGetLibraryOptions()
  59. {
  60. const char *string = " "
  61. // Options
  62. #ifdef AS_MAX_PORTABILITY
  63. "AS_MAX_PORTABILITY "
  64. #endif
  65. #ifdef AS_DEBUG
  66. "AS_DEBUG "
  67. #endif
  68. #ifdef AS_NO_CLASS_METHODS
  69. "AS_NO_CLASS_METHODS "
  70. #endif
  71. #ifdef AS_USE_DOUBLE_AS_FLOAT
  72. "AS_USE_DOUBLE_AS_FLOAT "
  73. #endif
  74. #ifdef AS_64BIT_PTR
  75. "AS_64BIT_PTR "
  76. #endif
  77. #ifdef AS_NO_THREADS
  78. "AS_NO_THREADS "
  79. #endif
  80. #ifdef AS_NO_ATOMIC
  81. "AS_NO_ATOMIC "
  82. #endif
  83. #ifdef AS_NO_COMPILER
  84. "AS_NO_COMPILER "
  85. #endif
  86. #ifdef AS_NO_MEMBER_INIT
  87. "AS_NO_MEMBER_INIT "
  88. #endif
  89. #ifdef AS_NO_THISCALL_FUNCTOR_METHOD
  90. "AS_NO_THISCALL_FUNCTOR_METHOD "
  91. #endif
  92. #ifdef AS_NO_EXCEPTIONS
  93. "AS_NO_EXCEPTIONS "
  94. #endif
  95. #ifdef WIP_16BYTE_ALIGN
  96. "WIP_16BYTE_ALIGN "
  97. #endif
  98. #ifdef AS_BIG_ENDIAN
  99. "AS_BIG_ENDIAN "
  100. #endif
  101. // Target system
  102. #ifdef AS_WIN
  103. "AS_WIN "
  104. #endif
  105. #ifdef AS_LINUX
  106. "AS_LINUX "
  107. #endif
  108. #ifdef AS_MAC
  109. "AS_MAC "
  110. #endif
  111. #ifdef AS_SUN
  112. "AS_SUN "
  113. #endif
  114. #ifdef AS_BSD
  115. "AS_BSD "
  116. #endif
  117. #ifdef AS_XBOX
  118. "AS_XBOX "
  119. #endif
  120. #ifdef AS_XBOX360
  121. "AS_XBOX360 "
  122. #endif
  123. #ifdef AS_PSP
  124. "AS_PSP "
  125. #endif
  126. #ifdef AS_PS2
  127. "AS_PS2 "
  128. #endif
  129. #ifdef AS_PS3
  130. "AS_PS3 "
  131. #endif
  132. #ifdef AS_PSVITA
  133. "AS_PSVITA "
  134. #endif
  135. #ifdef AS_DC
  136. "AS_DC "
  137. #endif
  138. #ifdef AS_GC
  139. "AS_GC "
  140. #endif
  141. #ifdef AS_WII
  142. "AS_WII "
  143. #endif
  144. #ifdef AS_WIIU
  145. "AS_WIIU "
  146. #endif
  147. #ifdef AS_IPHONE
  148. "AS_IPHONE "
  149. #endif
  150. #ifdef AS_ANDROID
  151. "AS_ANDROID "
  152. #endif
  153. #ifdef AS_HAIKU
  154. "AS_HAIKU "
  155. #endif
  156. #ifdef AS_ILLUMOS
  157. "AS_ILLUMOS "
  158. #endif
  159. #ifdef AS_MARMALADE
  160. "AS_MARMALADE "
  161. #endif
  162. // CPU family
  163. #ifdef AS_PPC
  164. "AS_PPC "
  165. #endif
  166. #ifdef AS_PPC_64
  167. "AS_PPC_64 "
  168. #endif
  169. #ifdef AS_X86
  170. "AS_X86 "
  171. #endif
  172. #ifdef AS_MIPS
  173. "AS_MIPS "
  174. #endif
  175. #ifdef AS_SH4
  176. "AS_SH4 "
  177. #endif
  178. #ifdef AS_XENON
  179. "AS_XENON "
  180. #endif
  181. #ifdef AS_ARM
  182. "AS_ARM "
  183. #endif
  184. #ifdef AS_SOFTFP
  185. "AS_SOFTFP "
  186. #endif
  187. #ifdef AS_X64_GCC
  188. "AS_X64_GCC "
  189. #endif
  190. #ifdef AS_X64_MSVC
  191. "AS_X64_MSVC "
  192. #endif
  193. #ifdef AS_SPARC
  194. "AS_SPARC "
  195. #endif
  196. ;
  197. return string;
  198. }
  199. AS_API asIScriptEngine *asCreateScriptEngine(asDWORD version)
  200. {
  201. // Verify the version that the application expects
  202. if( (version/10000) != (ANGELSCRIPT_VERSION/10000) )
  203. return 0;
  204. if( (version/100)%100 != (ANGELSCRIPT_VERSION/100)%100 )
  205. return 0;
  206. if( (version%100) > (ANGELSCRIPT_VERSION%100) )
  207. return 0;
  208. // Verify the size of the types
  209. asASSERT( sizeof(asBYTE) == 1 );
  210. asASSERT( sizeof(asWORD) == 2 );
  211. asASSERT( sizeof(asDWORD) == 4 );
  212. asASSERT( sizeof(asQWORD) == 8 );
  213. asASSERT( sizeof(asPWORD) == sizeof(void*) );
  214. // Verify the boolean type
  215. asASSERT( sizeof(bool) == AS_SIZEOF_BOOL );
  216. asASSERT( true == VALUE_OF_BOOLEAN_TRUE );
  217. // Verify endianess
  218. #ifdef AS_BIG_ENDIAN
  219. asDWORD dw = 0x00010203;
  220. asQWORD qw = ((asQWORD(0x00010203)<<32)|asQWORD(0x04050607));
  221. #else
  222. asDWORD dw = 0x03020100;
  223. // C++ didn't have a standard way of declaring 64bit literal constants until C++11, so
  224. // I'm forced to do it like this to avoid compilers warnings when compiling with the full
  225. // C++ compliance.
  226. asQWORD qw = ((asQWORD(0x07060504)<<32)|asQWORD(0x03020100));
  227. #endif
  228. asASSERT( memcmp("\x00\x01\x02\x03", &dw, 4) == 0 );
  229. asASSERT( memcmp("\x00\x01\x02\x03\x04\x05\x06\x07", &qw, 8) == 0 );
  230. UNUSED_VAR(dw);
  231. UNUSED_VAR(qw);
  232. return asNEW(asCScriptEngine)();
  233. }
  234. } // extern "C"
  235. // interface
  236. int asCScriptEngine::SetEngineProperty(asEEngineProp property, asPWORD value)
  237. {
  238. switch( property )
  239. {
  240. case asEP_ALLOW_UNSAFE_REFERENCES:
  241. ep.allowUnsafeReferences = value ? true : false;
  242. break;
  243. case asEP_OPTIMIZE_BYTECODE:
  244. ep.optimizeByteCode = value ? true : false;
  245. break;
  246. case asEP_COPY_SCRIPT_SECTIONS:
  247. ep.copyScriptSections = value ? true : false;
  248. break;
  249. case asEP_MAX_STACK_SIZE:
  250. if( value == 0 )
  251. {
  252. // Restore default: no limit and initially size 4KB
  253. ep.maximumContextStackSize = 0;
  254. }
  255. else
  256. {
  257. // The size is given in bytes, but we only store dwords
  258. ep.maximumContextStackSize = (asUINT)value/4;
  259. }
  260. break;
  261. case asEP_INIT_STACK_SIZE:
  262. if (value < 4)
  263. {
  264. // At least one dword
  265. ep.initContextStackSize = 1;
  266. }
  267. else
  268. {
  269. // The size is given in bytes, but we only store dwords
  270. ep.initContextStackSize = (asUINT)value / 4;
  271. }
  272. break;
  273. case asEP_USE_CHARACTER_LITERALS:
  274. ep.useCharacterLiterals = value ? true : false;
  275. break;
  276. case asEP_ALLOW_MULTILINE_STRINGS:
  277. ep.allowMultilineStrings = value ? true : false;
  278. break;
  279. case asEP_ALLOW_IMPLICIT_HANDLE_TYPES:
  280. ep.allowImplicitHandleTypes = value ? true : false;
  281. break;
  282. case asEP_BUILD_WITHOUT_LINE_CUES:
  283. ep.buildWithoutLineCues = value ? true : false;
  284. break;
  285. case asEP_INIT_GLOBAL_VARS_AFTER_BUILD:
  286. ep.initGlobalVarsAfterBuild = value ? true : false;
  287. break;
  288. case asEP_REQUIRE_ENUM_SCOPE:
  289. ep.requireEnumScope = value ? true : false;
  290. break;
  291. case asEP_SCRIPT_SCANNER:
  292. if( value <= 1 )
  293. ep.scanner = (int)value;
  294. else
  295. return asINVALID_ARG;
  296. break;
  297. case asEP_INCLUDE_JIT_INSTRUCTIONS:
  298. ep.includeJitInstructions = value ? true : false;
  299. break;
  300. case asEP_STRING_ENCODING:
  301. if( value <= 1 )
  302. ep.stringEncoding = (int)value;
  303. else
  304. return asINVALID_ARG;
  305. break;
  306. case asEP_PROPERTY_ACCESSOR_MODE:
  307. if( value <= 2 )
  308. ep.propertyAccessorMode = (int)value;
  309. else
  310. return asINVALID_ARG;
  311. break;
  312. case asEP_EXPAND_DEF_ARRAY_TO_TMPL:
  313. ep.expandDefaultArrayToTemplate = value ? true : false;
  314. break;
  315. case asEP_AUTO_GARBAGE_COLLECT:
  316. ep.autoGarbageCollect = value ? true : false;
  317. break;
  318. case asEP_DISALLOW_GLOBAL_VARS:
  319. ep.disallowGlobalVars = value ? true : false;
  320. break;
  321. case asEP_ALWAYS_IMPL_DEFAULT_CONSTRUCT:
  322. ep.alwaysImplDefaultConstruct = value ? true : false;
  323. break;
  324. case asEP_COMPILER_WARNINGS:
  325. if( value <= 2 )
  326. ep.compilerWarnings = (int)value;
  327. else
  328. return asINVALID_ARG;
  329. break;
  330. case asEP_DISALLOW_VALUE_ASSIGN_FOR_REF_TYPE:
  331. ep.disallowValueAssignForRefType = value ? true : false;
  332. break;
  333. case asEP_ALTER_SYNTAX_NAMED_ARGS:
  334. if( value <= 2 )
  335. ep.alterSyntaxNamedArgs = (int)value;
  336. else
  337. return asINVALID_ARG;
  338. break;
  339. case asEP_DISABLE_INTEGER_DIVISION:
  340. ep.disableIntegerDivision = value ? true : false;
  341. break;
  342. case asEP_DISALLOW_EMPTY_LIST_ELEMENTS:
  343. ep.disallowEmptyListElements = value ? true : false;
  344. break;
  345. case asEP_PRIVATE_PROP_AS_PROTECTED:
  346. ep.privatePropAsProtected = value ? true : false;
  347. break;
  348. case asEP_ALLOW_UNICODE_IDENTIFIERS:
  349. ep.allowUnicodeIdentifiers = value ? true : false;
  350. break;
  351. case asEP_HEREDOC_TRIM_MODE:
  352. if (value <= 2)
  353. ep.heredocTrimMode = (int)value;
  354. else
  355. return asINVALID_ARG;
  356. break;
  357. case asEP_MAX_NESTED_CALLS:
  358. if (value > 0xFFFFFFFF)
  359. ep.maxNestedCalls = 0xFFFFFFFF;
  360. else
  361. ep.maxNestedCalls = (asUINT)value;
  362. break;
  363. case asEP_GENERIC_CALL_MODE:
  364. if (value > 1)
  365. ep.genericCallMode = 1;
  366. else
  367. ep.genericCallMode = (asUINT)value;
  368. break;
  369. case asEP_INIT_CALL_STACK_SIZE:
  370. ep.initCallStackSize = (asUINT)value;
  371. break;
  372. case asEP_MAX_CALL_STACK_SIZE:
  373. ep.maxCallStackSize = (asUINT)value;
  374. break;
  375. default:
  376. return asINVALID_ARG;
  377. }
  378. return asSUCCESS;
  379. }
  380. // interface
  381. asPWORD asCScriptEngine::GetEngineProperty(asEEngineProp property) const
  382. {
  383. switch( property )
  384. {
  385. case asEP_ALLOW_UNSAFE_REFERENCES:
  386. return ep.allowUnsafeReferences;
  387. case asEP_OPTIMIZE_BYTECODE:
  388. return ep.optimizeByteCode;
  389. case asEP_COPY_SCRIPT_SECTIONS:
  390. return ep.copyScriptSections;
  391. case asEP_MAX_STACK_SIZE:
  392. return ep.maximumContextStackSize * 4;
  393. case asEP_INIT_STACK_SIZE:
  394. return ep.initContextStackSize * 4;
  395. case asEP_USE_CHARACTER_LITERALS:
  396. return ep.useCharacterLiterals;
  397. case asEP_ALLOW_MULTILINE_STRINGS:
  398. return ep.allowMultilineStrings;
  399. case asEP_ALLOW_IMPLICIT_HANDLE_TYPES:
  400. return ep.allowImplicitHandleTypes;
  401. case asEP_BUILD_WITHOUT_LINE_CUES:
  402. return ep.buildWithoutLineCues;
  403. case asEP_INIT_GLOBAL_VARS_AFTER_BUILD:
  404. return ep.initGlobalVarsAfterBuild;
  405. case asEP_REQUIRE_ENUM_SCOPE:
  406. return ep.requireEnumScope;
  407. case asEP_SCRIPT_SCANNER:
  408. return ep.scanner;
  409. case asEP_INCLUDE_JIT_INSTRUCTIONS:
  410. return ep.includeJitInstructions;
  411. case asEP_STRING_ENCODING:
  412. return ep.stringEncoding;
  413. case asEP_PROPERTY_ACCESSOR_MODE:
  414. return ep.propertyAccessorMode;
  415. case asEP_EXPAND_DEF_ARRAY_TO_TMPL:
  416. return ep.expandDefaultArrayToTemplate;
  417. case asEP_AUTO_GARBAGE_COLLECT:
  418. return ep.autoGarbageCollect;
  419. case asEP_DISALLOW_GLOBAL_VARS:
  420. return ep.disallowGlobalVars;
  421. case asEP_ALWAYS_IMPL_DEFAULT_CONSTRUCT:
  422. return ep.alwaysImplDefaultConstruct;
  423. case asEP_COMPILER_WARNINGS:
  424. return ep.compilerWarnings;
  425. case asEP_DISALLOW_VALUE_ASSIGN_FOR_REF_TYPE:
  426. return ep.disallowValueAssignForRefType;
  427. case asEP_ALTER_SYNTAX_NAMED_ARGS:
  428. return ep.alterSyntaxNamedArgs;
  429. case asEP_DISABLE_INTEGER_DIVISION:
  430. return ep.disableIntegerDivision;
  431. case asEP_DISALLOW_EMPTY_LIST_ELEMENTS:
  432. return ep.disallowEmptyListElements;
  433. case asEP_PRIVATE_PROP_AS_PROTECTED:
  434. return ep.privatePropAsProtected;
  435. case asEP_ALLOW_UNICODE_IDENTIFIERS:
  436. return ep.allowUnicodeIdentifiers;
  437. case asEP_HEREDOC_TRIM_MODE:
  438. return ep.heredocTrimMode;
  439. case asEP_MAX_NESTED_CALLS:
  440. return ep.maxNestedCalls;
  441. case asEP_GENERIC_CALL_MODE:
  442. return ep.genericCallMode;
  443. case asEP_INIT_CALL_STACK_SIZE:
  444. return ep.initCallStackSize;
  445. case asEP_MAX_CALL_STACK_SIZE:
  446. return ep.maxCallStackSize;
  447. default:
  448. return 0;
  449. }
  450. UNREACHABLE_RETURN;
  451. }
  452. // interface
  453. asIScriptFunction *asCScriptEngine::CreateDelegate(asIScriptFunction *func, void *obj)
  454. {
  455. if( func == 0 || obj == 0 )
  456. return 0;
  457. // The function must be a class method
  458. asITypeInfo *type = func->GetObjectType();
  459. if( type == 0 )
  460. return 0;
  461. // The object type must allow handles
  462. if( (type->GetFlags() & asOBJ_REF) == 0 || (type->GetFlags() & (asOBJ_SCOPED | asOBJ_NOHANDLE)) )
  463. return 0;
  464. // Create the delegate the same way it would be created by the scripts
  465. return AS_NAMESPACE_QUALIFIER CreateDelegate(reinterpret_cast<asCScriptFunction*>(func), obj);
  466. }
  467. asCScriptEngine::asCScriptEngine()
  468. {
  469. asCThreadManager::Prepare(0);
  470. shuttingDown = false;
  471. inDestructor = false;
  472. // Engine properties
  473. {
  474. ep.allowUnsafeReferences = false;
  475. ep.optimizeByteCode = true;
  476. ep.copyScriptSections = true;
  477. ep.maximumContextStackSize = 0; // no limit
  478. ep.initContextStackSize = 1024; // 4KB default init stack size
  479. ep.useCharacterLiterals = false;
  480. ep.allowMultilineStrings = false;
  481. ep.allowImplicitHandleTypes = false;
  482. // TODO: optimize: Maybe this should be turned off by default? If a debugger is not used
  483. // then this is just slowing down the execution.
  484. ep.buildWithoutLineCues = false;
  485. ep.initGlobalVarsAfterBuild = true;
  486. ep.requireEnumScope = false;
  487. ep.scanner = 1; // utf8. 0 = ascii
  488. ep.includeJitInstructions = false;
  489. ep.stringEncoding = 0; // utf8. 1 = utf16
  490. ep.propertyAccessorMode = 2; // 0 = disable, 1 = app registered only, 2 = app and script created
  491. ep.expandDefaultArrayToTemplate = false;
  492. ep.autoGarbageCollect = true;
  493. ep.disallowGlobalVars = false;
  494. ep.alwaysImplDefaultConstruct = false;
  495. ep.compilerWarnings = 1; // 0 = no warnings, 1 = warning, 2 = treat as error
  496. // TODO: 3.0.0: disallowValueAssignForRefType should be true by default
  497. ep.disallowValueAssignForRefType = false;
  498. ep.alterSyntaxNamedArgs = 0; // 0 = no alternate syntax, 1 = accept alternate syntax but warn, 2 = accept without warning
  499. ep.disableIntegerDivision = false;
  500. ep.disallowEmptyListElements = false;
  501. ep.privatePropAsProtected = false;
  502. ep.allowUnicodeIdentifiers = false;
  503. ep.heredocTrimMode = 1; // 0 = never trim, 1 = don't trim on single line, 2 = trim initial and final empty line
  504. ep.maxNestedCalls = 100;
  505. ep.genericCallMode = 1; // 0 = old (pre 2.33.0) behavior where generic ignored auto handles, 1 = treat handles like in native call
  506. ep.initCallStackSize = 10; // 10 levels of calls
  507. ep.maxCallStackSize = 0; // 0 = no limit
  508. }
  509. gc.engine = this;
  510. tok.engine = this;
  511. refCount.set(1);
  512. stringFactory = 0;
  513. configFailed = false;
  514. isPrepared = false;
  515. isBuilding = false;
  516. deferValidationOfTemplateTypes = false;
  517. lastModule = 0;
  518. typeIdSeqNbr = 0;
  519. currentGroup = &defaultGroup;
  520. defaultAccessMask = 0xFFFFFFFF; // All bits set so that built-in functions/types will be available to all modules
  521. msgCallback = 0;
  522. jitCompiler = 0;
  523. // Create the global namespace
  524. defaultNamespace = AddNameSpace("");
  525. requestCtxFunc = 0;
  526. returnCtxFunc = 0;
  527. ctxCallbackParam = 0;
  528. // We must set the namespace in the built-in types explicitly as
  529. // this wasn't done by the default constructor. If we do not do
  530. // this we will get null pointer access in other parts of the code
  531. scriptTypeBehaviours.nameSpace = defaultNamespace;
  532. functionBehaviours.nameSpace = defaultNamespace;
  533. // Reserve function id 0 for no function
  534. scriptFunctions.PushLast(0);
  535. // Reserve the first typeIds for the primitive types
  536. typeIdSeqNbr = asTYPEID_DOUBLE + 1;
  537. // Make sure typeId for the built-in primitives are defined according to asETypeIdFlags
  538. asASSERT( GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttVoid, false)) == asTYPEID_VOID );
  539. asASSERT( GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttBool, false)) == asTYPEID_BOOL );
  540. asASSERT( GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttInt8, false)) == asTYPEID_INT8 );
  541. asASSERT( GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttInt16, false)) == asTYPEID_INT16 );
  542. asASSERT( GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttInt, false)) == asTYPEID_INT32 );
  543. asASSERT( GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttInt64, false)) == asTYPEID_INT64 );
  544. asASSERT( GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttUInt8, false)) == asTYPEID_UINT8 );
  545. asASSERT( GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttUInt16, false)) == asTYPEID_UINT16 );
  546. asASSERT( GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttUInt, false)) == asTYPEID_UINT32 );
  547. asASSERT( GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttUInt64, false)) == asTYPEID_UINT64 );
  548. asASSERT( GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttFloat, false)) == asTYPEID_FLOAT );
  549. asASSERT( GetTypeIdFromDataType(asCDataType::CreatePrimitive(ttDouble, false)) == asTYPEID_DOUBLE );
  550. defaultArrayObjectType = 0;
  551. RegisterScriptObject(this);
  552. RegisterScriptFunction(this);
  553. #ifndef AS_NO_EXCEPTIONS
  554. translateExceptionCallback = false;
  555. #endif
  556. }
  557. void asCScriptEngine::DeleteDiscardedModules()
  558. {
  559. // TODO: redesign: Prevent more than one thread from entering this function at the same time.
  560. // If a thread is already doing the work for the clean-up the other thread should
  561. // simply return, as the first thread will continue.
  562. ACQUIRESHARED(engineRWLock);
  563. asUINT maxCount = discardedModules.GetLength();
  564. RELEASESHARED(engineRWLock);
  565. for( asUINT n = 0; n < maxCount; n++ )
  566. {
  567. ACQUIRESHARED(engineRWLock);
  568. asCModule *mod = discardedModules[n];
  569. RELEASESHARED(engineRWLock);
  570. if( !mod->HasExternalReferences(shuttingDown) )
  571. {
  572. asDELETE(mod, asCModule);
  573. n--;
  574. }
  575. ACQUIRESHARED(engineRWLock);
  576. // Determine the max count again, since another module may have been discarded during the processing
  577. maxCount = discardedModules.GetLength();
  578. RELEASESHARED(engineRWLock);
  579. }
  580. // Go over the list of global properties, to see if it is possible to clean
  581. // up some variables that are no longer referred to by any functions
  582. for( asUINT n = 0; n < globalProperties.GetLength(); n++ )
  583. {
  584. asCGlobalProperty *prop = globalProperties[n];
  585. if( prop && prop->refCount.get() == 1 )
  586. RemoveGlobalProperty(prop);
  587. }
  588. }
  589. asCScriptEngine::~asCScriptEngine()
  590. {
  591. // TODO: clean-up: Clean up redundant code
  592. inDestructor = true;
  593. asASSERT(refCount.get() == 0);
  594. // If ShutDown hasn't been called yet do it now
  595. if( !shuttingDown )
  596. {
  597. AddRef();
  598. ShutDownAndRelease();
  599. }
  600. // Unravel the registered interface
  601. if( defaultArrayObjectType )
  602. {
  603. defaultArrayObjectType->ReleaseInternal();
  604. defaultArrayObjectType = 0;
  605. }
  606. // Delete the functions for generated template types that may references object types
  607. for( asUINT n = 0; n < templateInstanceTypes.GetLength(); n++ )
  608. {
  609. asCObjectType *templateType = templateInstanceTypes[n];
  610. if( templateInstanceTypes[n] )
  611. templateType->DestroyInternal();
  612. }
  613. for( asUINT n = 0; n < listPatternTypes.GetLength(); n++ )
  614. {
  615. asCObjectType *type = listPatternTypes[n];
  616. if( type )
  617. type->ReleaseInternal();
  618. }
  619. listPatternTypes.SetLength(0);
  620. // No script types must have survived
  621. asASSERT( sharedScriptTypes.GetLength() == 0 );
  622. // It is allowed to create new references to the engine temporarily while destroying objects
  623. // but these references must be release immediately or else something is can go wrong later on
  624. if( refCount.get() > 0 )
  625. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ENGINE_REF_COUNT_ERROR_DURING_SHUTDOWN);
  626. mapTypeIdToTypeInfo.EraseAll();
  627. // First remove what is not used, so that other groups can be deleted safely
  628. defaultGroup.RemoveConfiguration(this, true);
  629. while( configGroups.GetLength() )
  630. {
  631. // Delete config groups in the right order
  632. asCConfigGroup *grp = configGroups.PopLast();
  633. if( grp )
  634. {
  635. grp->RemoveConfiguration(this);
  636. asDELETE(grp,asCConfigGroup);
  637. }
  638. }
  639. // Remove what is remaining
  640. defaultGroup.RemoveConfiguration(this);
  641. // Any remaining objects in templateInstanceTypes is from generated template instances
  642. for( asUINT n = 0; n < templateInstanceTypes.GetLength(); n++ )
  643. {
  644. asCObjectType *templateType = templateInstanceTypes[n];
  645. if( templateInstanceTypes[n] )
  646. templateType->ReleaseInternal();
  647. }
  648. templateInstanceTypes.SetLength(0);
  649. asCSymbolTable<asCGlobalProperty>::iterator it = registeredGlobalProps.List();
  650. for( ; it; it++ )
  651. {
  652. RemoveGlobalProperty(*it);
  653. (*it)->Release();
  654. }
  655. registeredGlobalProps.Clear();
  656. for( asUINT n = 0; n < templateSubTypes.GetLength(); n++ )
  657. {
  658. if( templateSubTypes[n] )
  659. {
  660. templateSubTypes[n]->DestroyInternal();
  661. templateSubTypes[n]->ReleaseInternal();
  662. }
  663. }
  664. templateSubTypes.SetLength(0);
  665. registeredTypeDefs.SetLength(0);
  666. registeredEnums.SetLength(0);
  667. registeredObjTypes.SetLength(0);
  668. asCSymbolTable<asCScriptFunction>::iterator funcIt = registeredGlobalFuncs.List();
  669. for( ; funcIt; funcIt++ )
  670. (*funcIt)->ReleaseInternal();
  671. registeredGlobalFuncs.Clear();
  672. scriptTypeBehaviours.ReleaseAllFunctions();
  673. functionBehaviours.ReleaseAllFunctions();
  674. for( asUINT n = 0; n < scriptFunctions.GetLength(); n++ )
  675. if( scriptFunctions[n] )
  676. {
  677. scriptFunctions[n]->DestroyInternal();
  678. // Set the engine pointer to null to signal that the function is no longer part of the engine
  679. scriptFunctions[n]->engine = 0;
  680. }
  681. scriptFunctions.SetLength(0);
  682. // Increase the internal ref count for these builtin object types, so the destructor is not called incorrectly
  683. scriptTypeBehaviours.AddRefInternal();
  684. functionBehaviours.AddRefInternal();
  685. // Destroy the funcdefs
  686. // As funcdefs are shared between modules it shouldn't be a problem to keep the objects until the engine is released
  687. for( asUINT n = 0; n < funcDefs.GetLength(); n++ )
  688. if( funcDefs[n] )
  689. {
  690. funcDefs[n]->DestroyInternal();
  691. funcDefs[n]->ReleaseInternal();
  692. }
  693. funcDefs.SetLength(0);
  694. // Free the global properties
  695. for( asUINT n = 0; n < globalProperties.GetLength(); n++ )
  696. {
  697. asCGlobalProperty *prop = globalProperties[n];
  698. if( prop )
  699. {
  700. asASSERT( prop->refCount.get() == 1 );
  701. RemoveGlobalProperty(prop);
  702. }
  703. }
  704. // Free the script section names
  705. for( asUINT n = 0; n < scriptSectionNames.GetLength(); n++ )
  706. asDELETE(scriptSectionNames[n],asCString);
  707. scriptSectionNames.SetLength(0);
  708. // Clean the user data
  709. for( asUINT n = 0; n < userData.GetLength(); n += 2 )
  710. {
  711. if( userData[n+1] )
  712. {
  713. for( asUINT c = 0; c < cleanEngineFuncs.GetLength(); c++ )
  714. if( cleanEngineFuncs[c].type == userData[n] )
  715. cleanEngineFuncs[c].cleanFunc(this);
  716. }
  717. }
  718. // Free namespaces
  719. for( asUINT n = 0; n < nameSpaces.GetLength(); n++ )
  720. asDELETE(nameSpaces[n], asSNameSpace);
  721. nameSpaces.SetLength(0);
  722. asCThreadManager::Unprepare();
  723. }
  724. // interface
  725. int asCScriptEngine::SetContextCallbacks(asREQUESTCONTEXTFUNC_t requestCtx, asRETURNCONTEXTFUNC_t returnCtx, void *param)
  726. {
  727. // Both callbacks or neither must be set
  728. if( (requestCtx == 0 && returnCtx != 0) || (requestCtx != 0 && returnCtx == 0) )
  729. return asINVALID_ARG;
  730. requestCtxFunc = requestCtx;
  731. returnCtxFunc = returnCtx;
  732. ctxCallbackParam = param;
  733. return 0;
  734. }
  735. // interface
  736. asIScriptContext *asCScriptEngine::RequestContext()
  737. {
  738. if( requestCtxFunc )
  739. {
  740. // The return callback must also exist
  741. asASSERT( returnCtxFunc );
  742. asIScriptContext *ctx = requestCtxFunc(this, ctxCallbackParam);
  743. return ctx;
  744. }
  745. // As fallback we create a new context
  746. return CreateContext();
  747. }
  748. // internal
  749. asCModule *asCScriptEngine::FindNewOwnerForSharedType(asCTypeInfo *in_type, asCModule *in_mod)
  750. {
  751. asASSERT( in_type->IsShared() );
  752. if( in_type->module != in_mod)
  753. return in_type->module;
  754. for( asUINT n = 0; n < scriptModules.GetLength(); n++ )
  755. {
  756. // TODO: optimize: If the modules already stored the shared types separately, this would be quicker
  757. int foundIdx = -1;
  758. asCModule *mod = scriptModules[n];
  759. if( mod == in_type->module ) continue;
  760. if( in_type->flags & asOBJ_ENUM )
  761. foundIdx = mod->enumTypes.IndexOf(CastToEnumType(in_type));
  762. else if (in_type->flags & asOBJ_TYPEDEF)
  763. foundIdx = mod->typeDefs.IndexOf(CastToTypedefType(in_type));
  764. else if (in_type->flags & asOBJ_FUNCDEF)
  765. foundIdx = mod->funcDefs.IndexOf(CastToFuncdefType(in_type));
  766. else if (in_type->flags & asOBJ_TEMPLATE)
  767. foundIdx = mod->templateInstances.IndexOf(CastToObjectType(in_type));
  768. else
  769. foundIdx = mod->classTypes.IndexOf(CastToObjectType(in_type));
  770. if( foundIdx >= 0 )
  771. {
  772. in_type->module = mod;
  773. break;
  774. }
  775. }
  776. return in_type->module;
  777. }
  778. // internal
  779. asCModule *asCScriptEngine::FindNewOwnerForSharedFunc(asCScriptFunction *in_func, asCModule *in_mod)
  780. {
  781. asASSERT( in_func->IsShared() );
  782. asASSERT(!(in_func->funcType & asFUNC_FUNCDEF));
  783. if( in_func->module != in_mod)
  784. return in_func->module;
  785. for( asUINT n = 0; n < scriptModules.GetLength(); n++ )
  786. {
  787. // TODO: optimize: If the modules already stored the shared types separately, this would be quicker
  788. int foundIdx = -1;
  789. asCModule *mod = scriptModules[n];
  790. if( mod == in_func->module ) continue;
  791. foundIdx = mod->scriptFunctions.IndexOf(in_func);
  792. if( foundIdx >= 0 )
  793. {
  794. in_func->module = mod;
  795. break;
  796. }
  797. }
  798. return in_func->module;
  799. }
  800. // interface
  801. void asCScriptEngine::ReturnContext(asIScriptContext *ctx)
  802. {
  803. if( returnCtxFunc )
  804. {
  805. returnCtxFunc(this, ctx, ctxCallbackParam);
  806. return;
  807. }
  808. // As fallback we just release the context
  809. if( ctx )
  810. ctx->Release();
  811. }
  812. // interface
  813. int asCScriptEngine::AddRef() const
  814. {
  815. asASSERT( refCount.get() > 0 || inDestructor );
  816. return refCount.atomicInc();
  817. }
  818. // interface
  819. int asCScriptEngine::Release() const
  820. {
  821. int r = refCount.atomicDec();
  822. if( r == 0 )
  823. {
  824. // It is possible that some function will temporarily increment the engine ref count
  825. // during clean-up for example while destroying the objects in the garbage collector.
  826. if( !inDestructor )
  827. asDELETE(const_cast<asCScriptEngine*>(this),asCScriptEngine);
  828. return 0;
  829. }
  830. return r;
  831. }
  832. // interface
  833. int asCScriptEngine::ShutDownAndRelease()
  834. {
  835. // Do a full garbage collection cycle to clean up any object that may still hold on to the engine
  836. GarbageCollect();
  837. // Set the flag that the engine is being shutdown now. This will speed up
  838. // the process, and will also allow the engine to warn about invalid calls
  839. shuttingDown = true;
  840. // Clear the context callbacks. If new context's are needed for the clean-up the engine will take care of this itself.
  841. // Context callbacks are normally used for pooling contexts, and if we allow new contexts to be created without being
  842. // immediately destroyed afterwards it means the engine's refcount will increase. This is turn may cause memory access
  843. // violations later on when the pool releases its contexts.
  844. SetContextCallbacks(0, 0, 0);
  845. // The modules must be deleted first, as they may use
  846. // object types from the config groups
  847. for( asUINT n = (asUINT)scriptModules.GetLength(); n-- > 0; )
  848. if( scriptModules[n] )
  849. scriptModules[n]->Discard();
  850. scriptModules.SetLength(0);
  851. // Do another full garbage collection to destroy the object types/functions
  852. // that may have been placed in the gc when destroying the modules
  853. GarbageCollect();
  854. // Do another sweep to delete discarded modules, that may not have
  855. // been deleted earlier due to still having external references
  856. DeleteDiscardedModules();
  857. // If the application hasn't registered GC behaviours for all types
  858. // that can form circular references with script types, then there
  859. // may still be objects in the GC.
  860. gc.ReportAndReleaseUndestroyedObjects();
  861. // Release the engine reference
  862. return Release();
  863. }
  864. // internal
  865. asSNameSpace *asCScriptEngine::AddNameSpace(const char *name)
  866. {
  867. // First check if it doesn't exist already
  868. asSNameSpace *ns = FindNameSpace(name);
  869. if( ns ) return ns;
  870. ns = asNEW(asSNameSpace);
  871. if( ns == 0 )
  872. {
  873. // Out of memory
  874. return 0;
  875. }
  876. ns->name = name;
  877. nameSpaces.PushLast(ns);
  878. return ns;
  879. }
  880. // internal
  881. asSNameSpace *asCScriptEngine::FindNameSpace(const char *name) const
  882. {
  883. // TODO: optimize: Improve linear search
  884. for( asUINT n = 0; n < nameSpaces.GetLength(); n++ )
  885. if( nameSpaces[n]->name == name )
  886. return nameSpaces[n];
  887. return 0;
  888. }
  889. // interface
  890. const char *asCScriptEngine::GetDefaultNamespace() const
  891. {
  892. return defaultNamespace->name.AddressOf();
  893. }
  894. // interface
  895. int asCScriptEngine::SetDefaultNamespace(const char *nameSpace)
  896. {
  897. if( nameSpace == 0 )
  898. return ConfigError(asINVALID_ARG, "SetDefaultNamespace", nameSpace, 0);
  899. asCString ns = nameSpace;
  900. if( ns != "" )
  901. {
  902. // Make sure the namespace is composed of alternating identifier and ::
  903. size_t pos = 0;
  904. bool expectIdentifier = true;
  905. size_t len;
  906. eTokenType t = ttIdentifier;
  907. for( ; pos < ns.GetLength(); pos += len)
  908. {
  909. t = tok.GetToken(ns.AddressOf() + pos, ns.GetLength() - pos, &len);
  910. if( (expectIdentifier && t != ttIdentifier) || (!expectIdentifier && t != ttScope) )
  911. return ConfigError(asINVALID_DECLARATION, "SetDefaultNamespace", nameSpace, 0);
  912. // Make sure parent namespaces are registred in case of nested namespaces
  913. if (expectIdentifier)
  914. AddNameSpace(ns.SubString(0, pos + len).AddressOf());
  915. expectIdentifier = !expectIdentifier;
  916. }
  917. // If the namespace ends with :: then strip it off
  918. if( t == ttScope )
  919. ns.SetLength(ns.GetLength()-2);
  920. }
  921. defaultNamespace = AddNameSpace(ns.AddressOf());
  922. return 0;
  923. }
  924. // interface
  925. void *asCScriptEngine::SetUserData(void *data, asPWORD type)
  926. {
  927. // As a thread might add a new new user data at the same time as another
  928. // it is necessary to protect both read and write access to the userData member
  929. ACQUIREEXCLUSIVE(engineRWLock);
  930. // It is not intended to store a lot of different types of userdata,
  931. // so a more complex structure like a associative map would just have
  932. // more overhead than a simple array.
  933. for( asUINT n = 0; n < userData.GetLength(); n += 2 )
  934. {
  935. if( userData[n] == type )
  936. {
  937. void *oldData = reinterpret_cast<void*>(userData[n+1]);
  938. userData[n+1] = reinterpret_cast<asPWORD>(data);
  939. RELEASEEXCLUSIVE(engineRWLock);
  940. return oldData;
  941. }
  942. }
  943. userData.PushLast(type);
  944. userData.PushLast(reinterpret_cast<asPWORD>(data));
  945. RELEASEEXCLUSIVE(engineRWLock);
  946. return 0;
  947. }
  948. // interface
  949. void *asCScriptEngine::GetUserData(asPWORD type) const
  950. {
  951. // There may be multiple threads reading, but when
  952. // setting the user data nobody must be reading.
  953. ACQUIRESHARED(engineRWLock);
  954. for( asUINT n = 0; n < userData.GetLength(); n += 2 )
  955. {
  956. if( userData[n] == type )
  957. {
  958. RELEASESHARED(engineRWLock);
  959. return reinterpret_cast<void*>(userData[n+1]);
  960. }
  961. }
  962. RELEASESHARED(engineRWLock);
  963. return 0;
  964. }
  965. // interface
  966. int asCScriptEngine::SetMessageCallback(const asSFuncPtr &callback, void *obj, asDWORD callConv)
  967. {
  968. msgCallback = true;
  969. msgCallbackObj = obj;
  970. bool isObj = false;
  971. if( (unsigned)callConv == asCALL_GENERIC || (unsigned)callConv == asCALL_THISCALL_OBJFIRST || (unsigned)callConv == asCALL_THISCALL_OBJLAST )
  972. {
  973. msgCallback = false;
  974. return asNOT_SUPPORTED;
  975. }
  976. if( (unsigned)callConv >= asCALL_THISCALL )
  977. {
  978. isObj = true;
  979. if( obj == 0 )
  980. {
  981. msgCallback = false;
  982. return asINVALID_ARG;
  983. }
  984. }
  985. int r = DetectCallingConvention(isObj, callback, callConv, 0, &msgCallbackFunc);
  986. if( r < 0 ) msgCallback = false;
  987. return r;
  988. }
  989. // interface
  990. int asCScriptEngine::ClearMessageCallback()
  991. {
  992. msgCallback = false;
  993. return 0;
  994. }
  995. // interface
  996. int asCScriptEngine::WriteMessage(const char *section, int row, int col, asEMsgType type, const char *message)
  997. {
  998. // Validate input parameters
  999. if( section == 0 ||
  1000. message == 0 )
  1001. return asINVALID_ARG;
  1002. // If there is no callback then there's nothing to do
  1003. if( !msgCallback )
  1004. return 0;
  1005. // If a pre-message has been set, then write that first
  1006. if( preMessage.isSet )
  1007. {
  1008. asSMessageInfo msg;
  1009. msg.section = preMessage.scriptname.AddressOf();
  1010. msg.row = preMessage.r;
  1011. msg.col = preMessage.c;
  1012. msg.type = asMSGTYPE_INFORMATION;
  1013. msg.message = preMessage.message.AddressOf();
  1014. if( msgCallbackFunc.callConv < ICC_THISCALL )
  1015. CallGlobalFunction(&msg, msgCallbackObj, &msgCallbackFunc, 0);
  1016. else
  1017. CallObjectMethod(msgCallbackObj, &msg, &msgCallbackFunc, 0);
  1018. preMessage.isSet = false;
  1019. }
  1020. // Write the message to the callback
  1021. asSMessageInfo msg;
  1022. msg.section = section;
  1023. msg.row = row;
  1024. msg.col = col;
  1025. msg.type = type;
  1026. msg.message = message;
  1027. if( msgCallbackFunc.callConv < ICC_THISCALL )
  1028. CallGlobalFunction(&msg, msgCallbackObj, &msgCallbackFunc, 0);
  1029. else
  1030. CallObjectMethod(msgCallbackObj, &msg, &msgCallbackFunc, 0);
  1031. return 0;
  1032. }
  1033. int asCScriptEngine::SetJITCompiler(asIJITCompiler *compiler)
  1034. {
  1035. jitCompiler = compiler;
  1036. return asSUCCESS;
  1037. }
  1038. asIJITCompiler *asCScriptEngine::GetJITCompiler() const
  1039. {
  1040. return jitCompiler;
  1041. }
  1042. // interface
  1043. asETokenClass asCScriptEngine::ParseToken(const char *string, size_t stringLength, asUINT *tokenLength) const
  1044. {
  1045. if( stringLength == 0 )
  1046. stringLength = strlen(string);
  1047. size_t len;
  1048. asETokenClass tc;
  1049. tok.GetToken(string, stringLength, &len, &tc);
  1050. if( tokenLength )
  1051. *tokenLength = (asUINT)len;
  1052. return tc;
  1053. }
  1054. // interface
  1055. asIScriptModule *asCScriptEngine::GetModule(const char *module, asEGMFlags flag)
  1056. {
  1057. asCModule *mod = GetModule(module, false);
  1058. if( flag == asGM_ALWAYS_CREATE )
  1059. {
  1060. if( mod != 0 )
  1061. mod->Discard();
  1062. return GetModule(module, true);
  1063. }
  1064. if( mod == 0 && flag == asGM_CREATE_IF_NOT_EXISTS )
  1065. return GetModule(module, true);
  1066. return mod;
  1067. }
  1068. // interface
  1069. int asCScriptEngine::DiscardModule(const char *module)
  1070. {
  1071. asCModule *mod = GetModule(module, false);
  1072. if( mod == 0 ) return asNO_MODULE;
  1073. mod->Discard();
  1074. return 0;
  1075. }
  1076. // interface
  1077. asUINT asCScriptEngine::GetModuleCount() const
  1078. {
  1079. ACQUIRESHARED(engineRWLock);
  1080. asUINT length = asUINT(scriptModules.GetLength());
  1081. RELEASESHARED(engineRWLock);
  1082. return length;
  1083. }
  1084. // interface
  1085. asIScriptModule *asCScriptEngine::GetModuleByIndex(asUINT index) const
  1086. {
  1087. asIScriptModule *mod = 0;
  1088. ACQUIRESHARED(engineRWLock);
  1089. if( index < scriptModules.GetLength() )
  1090. mod = scriptModules[index];
  1091. RELEASESHARED(engineRWLock);
  1092. return mod;
  1093. }
  1094. // internal
  1095. int asCScriptEngine::GetFactoryIdByDecl(const asCObjectType *ot, const char *decl)
  1096. {
  1097. asCModule *mod = 0;
  1098. // Is this a script class?
  1099. if( (ot->flags & asOBJ_SCRIPT_OBJECT) && ot->size > 0 )
  1100. mod = scriptFunctions[ot->beh.factories[0]]->module;
  1101. asCBuilder bld(this, mod);
  1102. // Don't write parser errors to the message callback
  1103. bld.silent = true;
  1104. asCScriptFunction func(this, mod, asFUNC_DUMMY);
  1105. int r = bld.ParseFunctionDeclaration(0, decl, &func, false, 0, 0, defaultNamespace);
  1106. if( r < 0 )
  1107. return asINVALID_DECLARATION;
  1108. // Search for matching factory function
  1109. int id = -1;
  1110. for( asUINT n = 0; n < ot->beh.factories.GetLength(); n++ )
  1111. {
  1112. asCScriptFunction *f = scriptFunctions[ot->beh.factories[n]];
  1113. if( f->IsSignatureEqual(&func) )
  1114. {
  1115. id = ot->beh.factories[n];
  1116. break;
  1117. }
  1118. }
  1119. if( id == -1 ) return asNO_FUNCTION;
  1120. return id;
  1121. }
  1122. // internal
  1123. int asCScriptEngine::GetMethodIdByDecl(const asCObjectType *ot, const char *decl, asCModule *mod)
  1124. {
  1125. asCBuilder bld(this, mod);
  1126. // Don't write parser errors to the message callback
  1127. bld.silent = true;
  1128. asCScriptFunction func(this, mod, asFUNC_DUMMY);
  1129. // Set the object type so that the signature can be properly compared
  1130. // This cast is OK, it will only be used for comparison
  1131. func.objectType = const_cast<asCObjectType*>(ot);
  1132. func.objectType->AddRefInternal();
  1133. int r = bld.ParseFunctionDeclaration(func.objectType, decl, &func, false);
  1134. if( r < 0 )
  1135. return asINVALID_DECLARATION;
  1136. // Search script functions for matching interface
  1137. int id = -1;
  1138. for( asUINT n = 0; n < ot->methods.GetLength(); ++n )
  1139. {
  1140. if( func.IsSignatureEqual(scriptFunctions[ot->methods[n]]) )
  1141. {
  1142. if( id == -1 )
  1143. id = ot->methods[n];
  1144. else
  1145. return asMULTIPLE_FUNCTIONS;
  1146. }
  1147. }
  1148. if( id == -1 ) return asNO_FUNCTION;
  1149. return id;
  1150. }
  1151. // internal
  1152. asCString asCScriptEngine::GetFunctionDeclaration(int funcId)
  1153. {
  1154. asCString str;
  1155. asCScriptFunction *func = GetScriptFunction(funcId);
  1156. if( func )
  1157. str = func->GetDeclarationStr();
  1158. return str;
  1159. }
  1160. // internal
  1161. asCScriptFunction *asCScriptEngine::GetScriptFunction(int funcId) const
  1162. {
  1163. if( funcId < 0 || funcId >= (int)scriptFunctions.GetLength() )
  1164. return 0;
  1165. return scriptFunctions[funcId];
  1166. }
  1167. // interface
  1168. asIScriptContext *asCScriptEngine::CreateContext()
  1169. {
  1170. asIScriptContext *ctx = 0;
  1171. CreateContext(&ctx, false);
  1172. return ctx;
  1173. }
  1174. // internal
  1175. int asCScriptEngine::CreateContext(asIScriptContext **context, bool isInternal)
  1176. {
  1177. *context = asNEW(asCContext)(this, !isInternal);
  1178. if( *context == 0 )
  1179. return asOUT_OF_MEMORY;
  1180. // We need to make sure the engine has been
  1181. // prepared before any context is executed
  1182. PrepareEngine();
  1183. return 0;
  1184. }
  1185. // interface
  1186. int asCScriptEngine::RegisterObjectProperty(const char *obj, const char *declaration, int byteOffset, int compositeOffset, bool isCompositeIndirect)
  1187. {
  1188. int r;
  1189. asCDataType dt;
  1190. asCBuilder bld(this, 0);
  1191. r = bld.ParseDataType(obj, &dt, defaultNamespace);
  1192. if( r < 0 )
  1193. return ConfigError(r, "RegisterObjectProperty", obj, declaration);
  1194. if (dt.GetTypeInfo() == 0 || (dt.IsObjectHandle() && !(dt.GetTypeInfo()->GetFlags() & asOBJ_IMPLICIT_HANDLE)))
  1195. return ConfigError(asINVALID_OBJECT, "RegisterObjectProperty", obj, declaration);
  1196. // Don't allow modifying generated template instances
  1197. if( dt.GetTypeInfo() && (dt.GetTypeInfo()->flags & asOBJ_TEMPLATE) && generatedTemplateTypes.Exists(CastToObjectType(dt.GetTypeInfo())) )
  1198. return ConfigError(asINVALID_TYPE, "RegisterObjectProperty", obj, declaration);
  1199. // Verify that the correct config group is used
  1200. if( currentGroup->FindType(dt.GetTypeInfo()->name.AddressOf()) == 0 )
  1201. return ConfigError(asWRONG_CONFIG_GROUP, "RegisterObjectProperty", obj, declaration);
  1202. asCDataType type;
  1203. asCString name;
  1204. if( (r = bld.VerifyProperty(&dt, declaration, name, type, 0)) < 0 )
  1205. return ConfigError(r, "RegisterObjectProperty", obj, declaration);
  1206. // The VM currently only supports 16bit offsets
  1207. // TODO: The VM needs to have support for 32bit offsets. Probably with a second ADDSi instruction
  1208. // However, when implementing this it is necessary for the bytecode serialization to support
  1209. // the switch between the instructions upon loading bytecode as the offset may not be the
  1210. // same on all platforms
  1211. if( byteOffset > 32767 || byteOffset < -32768 )
  1212. return ConfigError(asINVALID_ARG, "RegisterObjectProperty", obj, declaration);
  1213. // The composite offset must also obey the ADDSi restriction
  1214. if (compositeOffset > 32767 || compositeOffset < -32768)
  1215. return ConfigError(asINVALID_ARG, "RegisterObjectProperty", obj, declaration);
  1216. asCObjectProperty *prop = asNEW(asCObjectProperty);
  1217. if( prop == 0 )
  1218. return ConfigError(asOUT_OF_MEMORY, "RegisterObjectProperty", obj, declaration);
  1219. prop->name = name;
  1220. prop->type = type;
  1221. prop->byteOffset = byteOffset;
  1222. prop->isPrivate = false;
  1223. prop->isProtected = false;
  1224. prop->compositeOffset = compositeOffset;
  1225. prop->isCompositeIndirect = isCompositeIndirect;
  1226. prop->accessMask = defaultAccessMask;
  1227. CastToObjectType(dt.GetTypeInfo())->properties.PushLast(prop);
  1228. // Add references to types so they are not released too early
  1229. if( type.GetTypeInfo() )
  1230. {
  1231. type.GetTypeInfo()->AddRefInternal();
  1232. // Add template instances to the config group
  1233. if( (type.GetTypeInfo()->flags & asOBJ_TEMPLATE) && !currentGroup->types.Exists(type.GetTypeInfo()) )
  1234. currentGroup->types.PushLast(type.GetTypeInfo());
  1235. }
  1236. currentGroup->AddReferencesForType(this, type.GetTypeInfo());
  1237. return asSUCCESS;
  1238. }
  1239. // interface
  1240. int asCScriptEngine::RegisterInterface(const char *name)
  1241. {
  1242. if( name == 0 ) return ConfigError(asINVALID_NAME, "RegisterInterface", 0, 0);
  1243. // Verify if the name has been registered as a type already
  1244. if( GetRegisteredType(name, defaultNamespace) )
  1245. return asALREADY_REGISTERED;
  1246. // Use builder to parse the datatype
  1247. asCDataType dt;
  1248. asCBuilder bld(this, 0);
  1249. bool oldMsgCallback = msgCallback; msgCallback = false;
  1250. int r = bld.ParseDataType(name, &dt, defaultNamespace);
  1251. msgCallback = oldMsgCallback;
  1252. if( r >= 0 )
  1253. {
  1254. // If it is not in the defaultNamespace then the type was successfully parsed because
  1255. // it is declared in a parent namespace which shouldn't be treated as an error
  1256. if( dt.GetTypeInfo() && dt.GetTypeInfo()->nameSpace == defaultNamespace )
  1257. return ConfigError(asERROR, "RegisterInterface", name, 0);
  1258. }
  1259. // Make sure the name is not a reserved keyword
  1260. size_t tokenLen;
  1261. int token = tok.GetToken(name, strlen(name), &tokenLen);
  1262. if( token != ttIdentifier || strlen(name) != tokenLen )
  1263. return ConfigError(asINVALID_NAME, "RegisterInterface", name, 0);
  1264. r = bld.CheckNameConflict(name, 0, 0, defaultNamespace, true);
  1265. if( r < 0 )
  1266. return ConfigError(asNAME_TAKEN, "RegisterInterface", name, 0);
  1267. // Don't have to check against members of object
  1268. // types as they are allowed to use the names
  1269. // Register the object type for the interface
  1270. asCObjectType *st = asNEW(asCObjectType)(this);
  1271. if( st == 0 )
  1272. return ConfigError(asOUT_OF_MEMORY, "RegisterInterface", name, 0);
  1273. st->flags = asOBJ_REF | asOBJ_SCRIPT_OBJECT | asOBJ_SHARED;
  1274. st->size = 0; // Cannot be instantiated
  1275. st->name = name;
  1276. st->nameSpace = defaultNamespace;
  1277. // Use the default script class behaviours
  1278. st->beh.factory = 0;
  1279. st->beh.addref = scriptTypeBehaviours.beh.addref;
  1280. scriptFunctions[st->beh.addref]->AddRefInternal();
  1281. st->beh.release = scriptTypeBehaviours.beh.release;
  1282. scriptFunctions[st->beh.release]->AddRefInternal();
  1283. st->beh.copy = 0;
  1284. allRegisteredTypes.Insert(asSNameSpaceNamePair(st->nameSpace, st->name), st);
  1285. registeredObjTypes.PushLast(st);
  1286. currentGroup->types.PushLast(st);
  1287. return GetTypeIdByDecl(name);
  1288. }
  1289. // interface
  1290. int asCScriptEngine::RegisterInterfaceMethod(const char *intf, const char *declaration)
  1291. {
  1292. // Verify that the correct config group is set.
  1293. if( currentGroup->FindType(intf) == 0 )
  1294. return ConfigError(asWRONG_CONFIG_GROUP, "RegisterInterfaceMethod", intf, declaration);
  1295. asCDataType dt;
  1296. asCBuilder bld(this, 0);
  1297. int r = bld.ParseDataType(intf, &dt, defaultNamespace);
  1298. if( r < 0 )
  1299. return ConfigError(r, "RegisterInterfaceMethod", intf, declaration);
  1300. asCScriptFunction *func = asNEW(asCScriptFunction)(this, 0, asFUNC_INTERFACE);
  1301. if( func == 0 )
  1302. return ConfigError(asOUT_OF_MEMORY, "RegisterInterfaceMethod", intf, declaration);
  1303. func->objectType = CastToObjectType(dt.GetTypeInfo());
  1304. func->objectType->AddRefInternal();
  1305. r = bld.ParseFunctionDeclaration(func->objectType, declaration, func, false);
  1306. if( r < 0 )
  1307. {
  1308. func->funcType = asFUNC_DUMMY;
  1309. asDELETE(func,asCScriptFunction);
  1310. return ConfigError(asINVALID_DECLARATION, "RegisterInterfaceMethod", intf, declaration);
  1311. }
  1312. // Check name conflicts
  1313. r = bld.CheckNameConflictMember(dt.GetTypeInfo(), func->name.AddressOf(), 0, 0, false);
  1314. if( r < 0 )
  1315. {
  1316. func->funcType = asFUNC_DUMMY;
  1317. asDELETE(func,asCScriptFunction);
  1318. return ConfigError(asNAME_TAKEN, "RegisterInterfaceMethod", intf, declaration);
  1319. }
  1320. func->id = GetNextScriptFunctionId();
  1321. AddScriptFunction(func);
  1322. // The index into the interface's vftable chunk should be
  1323. // its index in the methods array.
  1324. func->vfTableIdx = int(func->objectType->methods.GetLength());
  1325. func->objectType->methods.PushLast(func->id);
  1326. func->ComputeSignatureId();
  1327. currentGroup->AddReferencesForFunc(this, func);
  1328. // Return function id as success
  1329. return func->id;
  1330. }
  1331. int asCScriptEngine::RegisterObjectType(const char *name, int byteSize, asDWORD flags)
  1332. {
  1333. int r;
  1334. isPrepared = false;
  1335. // Verify flags
  1336. // Must have either asOBJ_REF or asOBJ_VALUE
  1337. if( flags & asOBJ_REF )
  1338. {
  1339. // Can optionally have the asOBJ_GC, asOBJ_NOHANDLE, asOBJ_SCOPED, or asOBJ_TEMPLATE flag set, but nothing else
  1340. if( flags & ~(asOBJ_REF | asOBJ_GC | asOBJ_NOHANDLE | asOBJ_SCOPED | asOBJ_TEMPLATE | asOBJ_NOCOUNT | asOBJ_IMPLICIT_HANDLE) )
  1341. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1342. // flags are exclusive
  1343. if( (flags & asOBJ_GC) && (flags & (asOBJ_NOHANDLE|asOBJ_SCOPED|asOBJ_NOCOUNT)) )
  1344. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1345. if( (flags & asOBJ_NOHANDLE) && (flags & (asOBJ_GC|asOBJ_SCOPED|asOBJ_NOCOUNT|asOBJ_IMPLICIT_HANDLE)) )
  1346. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1347. if( (flags & asOBJ_SCOPED) && (flags & (asOBJ_GC|asOBJ_NOHANDLE|asOBJ_NOCOUNT|asOBJ_IMPLICIT_HANDLE)) )
  1348. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1349. if( (flags & asOBJ_NOCOUNT) && (flags & (asOBJ_GC|asOBJ_NOHANDLE|asOBJ_SCOPED)) )
  1350. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1351. // Implicit handle is only allowed if the engine property for this is turned on
  1352. if( !ep.allowImplicitHandleTypes && (flags & asOBJ_IMPLICIT_HANDLE) )
  1353. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1354. }
  1355. else if( flags & asOBJ_VALUE )
  1356. {
  1357. // Cannot use reference flags
  1358. if( flags & (asOBJ_REF | asOBJ_NOHANDLE | asOBJ_SCOPED | asOBJ_NOCOUNT | asOBJ_IMPLICIT_HANDLE) )
  1359. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1360. // Flags are exclusive
  1361. if( (flags & asOBJ_POD) && (flags & (asOBJ_ASHANDLE | asOBJ_TEMPLATE)) )
  1362. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1363. // If the app type is given, we must validate the flags
  1364. if( flags & asOBJ_APP_CLASS )
  1365. {
  1366. // Must not set the primitive or float flag
  1367. if( flags & (asOBJ_APP_PRIMITIVE | asOBJ_APP_FLOAT | asOBJ_APP_ARRAY) )
  1368. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1369. }
  1370. else
  1371. {
  1372. // Must not set the class properties, without the class flag
  1373. if( flags & (asOBJ_APP_CLASS_CONSTRUCTOR |
  1374. asOBJ_APP_CLASS_DESTRUCTOR |
  1375. asOBJ_APP_CLASS_ASSIGNMENT |
  1376. asOBJ_APP_CLASS_COPY_CONSTRUCTOR |
  1377. asOBJ_APP_CLASS_ALLINTS |
  1378. asOBJ_APP_CLASS_ALLFLOATS) )
  1379. {
  1380. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1381. }
  1382. }
  1383. if( flags & asOBJ_APP_PRIMITIVE )
  1384. {
  1385. if( flags & (asOBJ_APP_CLASS |
  1386. asOBJ_APP_FLOAT |
  1387. asOBJ_APP_ARRAY) )
  1388. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1389. }
  1390. else if( flags & asOBJ_APP_FLOAT )
  1391. {
  1392. if( flags & (asOBJ_APP_CLASS |
  1393. asOBJ_APP_PRIMITIVE |
  1394. asOBJ_APP_ARRAY) )
  1395. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1396. }
  1397. else if( flags & asOBJ_APP_ARRAY )
  1398. {
  1399. if( flags & (asOBJ_APP_CLASS |
  1400. asOBJ_APP_PRIMITIVE |
  1401. asOBJ_APP_FLOAT) )
  1402. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1403. }
  1404. }
  1405. else
  1406. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1407. // Don't allow anything else than the defined flags
  1408. #ifndef WIP_16BYTE_ALIGN
  1409. if( flags - (flags & asOBJ_MASK_VALID_FLAGS) )
  1410. #else
  1411. if( flags - (flags & (asOBJ_MASK_VALID_FLAGS | asOBJ_APP_ALIGN16)) )
  1412. #endif
  1413. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1414. // Value types must have a defined size
  1415. if( (flags & asOBJ_VALUE) && byteSize == 0 )
  1416. {
  1417. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_VALUE_TYPE_MUST_HAVE_SIZE);
  1418. return ConfigError(asINVALID_ARG, "RegisterObjectType", name, 0);
  1419. }
  1420. // Verify type name
  1421. if( name == 0 )
  1422. return ConfigError(asINVALID_NAME, "RegisterObjectType", name, 0);
  1423. asCString typeName;
  1424. asCBuilder bld(this, 0);
  1425. if( flags & asOBJ_TEMPLATE )
  1426. {
  1427. asCArray<asCString> subtypeNames;
  1428. r = bld.ParseTemplateDecl(name, &typeName, subtypeNames);
  1429. if( r < 0 )
  1430. return ConfigError(r, "RegisterObjectType", name, 0);
  1431. // Verify that the template name hasn't been registered as a type already
  1432. if( GetRegisteredType(typeName, defaultNamespace) )
  1433. // This is not an irrepairable error, as it may just be that the same type is registered twice
  1434. return asALREADY_REGISTERED;
  1435. asCObjectType *type = asNEW(asCObjectType)(this);
  1436. if( type == 0 )
  1437. return ConfigError(asOUT_OF_MEMORY, "RegisterObjectType", name, 0);
  1438. type->name = typeName;
  1439. type->nameSpace = defaultNamespace;
  1440. type->size = byteSize;
  1441. #ifdef WIP_16BYTE_ALIGN
  1442. // TODO: Types smaller than 4 don't need to be aligned to 4 byte boundaries
  1443. type->alignment = (flags & asOBJ_APP_ALIGN16) ? 16 : 4;
  1444. #endif
  1445. type->flags = flags;
  1446. type->accessMask = defaultAccessMask;
  1447. // Store it in the object types
  1448. allRegisteredTypes.Insert(asSNameSpaceNamePair(type->nameSpace, type->name), type);
  1449. currentGroup->types.PushLast(type);
  1450. registeredObjTypes.PushLast(type);
  1451. registeredTemplateTypes.PushLast(type);
  1452. // Define the template subtypes
  1453. for( asUINT subTypeIdx = 0; subTypeIdx < subtypeNames.GetLength(); subTypeIdx++ )
  1454. {
  1455. asCTypeInfo *subtype = 0;
  1456. for( asUINT n = 0; n < templateSubTypes.GetLength(); n++ )
  1457. {
  1458. if( templateSubTypes[n]->name == subtypeNames[subTypeIdx] )
  1459. {
  1460. subtype = templateSubTypes[n];
  1461. break;
  1462. }
  1463. }
  1464. if( subtype == 0 )
  1465. {
  1466. // Create the new subtype if not already existing
  1467. subtype = asNEW(asCTypeInfo)(this);
  1468. if( subtype == 0 )
  1469. return ConfigError(asOUT_OF_MEMORY, "RegisterObjectType", name, 0);
  1470. subtype->name = subtypeNames[subTypeIdx];
  1471. subtype->size = 0;
  1472. subtype->flags = asOBJ_TEMPLATE_SUBTYPE;
  1473. templateSubTypes.PushLast(subtype);
  1474. }
  1475. type->templateSubTypes.PushLast(asCDataType::CreateType(subtype, false));
  1476. subtype->AddRefInternal();
  1477. }
  1478. }
  1479. else
  1480. {
  1481. typeName = name;
  1482. // Verify if the name has been registered as a type already
  1483. if( GetRegisteredType(typeName, defaultNamespace) )
  1484. // This is not an irrepairable error, as it may just be that the same type is registered twice
  1485. return asALREADY_REGISTERED;
  1486. // Keep the most recent template generated instance type, so we know what it was before parsing the datatype
  1487. asCObjectType *mostRecentTemplateInstanceType = 0;
  1488. asUINT originalSizeOfGeneratedTemplateTypes = (asUINT)generatedTemplateTypes.GetLength();
  1489. if( originalSizeOfGeneratedTemplateTypes )
  1490. mostRecentTemplateInstanceType = generatedTemplateTypes[originalSizeOfGeneratedTemplateTypes-1];
  1491. // Use builder to parse the datatype
  1492. asCDataType dt;
  1493. bool oldMsgCallback = msgCallback; msgCallback = false;
  1494. r = bld.ParseDataType(name, &dt, defaultNamespace);
  1495. msgCallback = oldMsgCallback;
  1496. // If the builder fails or the namespace is different than the default
  1497. // namespace, then the type name is new and it should be registered
  1498. if( r < 0 || dt.GetTypeInfo()->nameSpace != defaultNamespace )
  1499. {
  1500. // Make sure the name is not a reserved keyword
  1501. size_t tokenLen;
  1502. int token = tok.GetToken(name, typeName.GetLength(), &tokenLen);
  1503. if( token != ttIdentifier || typeName.GetLength() != tokenLen )
  1504. return ConfigError(asINVALID_NAME, "RegisterObjectType", name, 0);
  1505. r = bld.CheckNameConflict(name, 0, 0, defaultNamespace, true);
  1506. if( r < 0 )
  1507. return ConfigError(asNAME_TAKEN, "RegisterObjectType", name, 0);
  1508. // Don't have to check against members of object
  1509. // types as they are allowed to use the names
  1510. // Put the data type in the list
  1511. asCObjectType *type = asNEW(asCObjectType)(this);
  1512. if( type == 0 )
  1513. return ConfigError(asOUT_OF_MEMORY, "RegisterObjectType", name, 0);
  1514. type->name = typeName;
  1515. type->nameSpace = defaultNamespace;
  1516. type->size = byteSize;
  1517. #ifdef WIP_16BYTE_ALIGN
  1518. // TODO: Types smaller than 4 don't need to be aligned to 4 byte boundaries
  1519. type->alignment = (flags & asOBJ_APP_ALIGN16) ? 16 : 4;
  1520. #endif
  1521. type->flags = flags;
  1522. type->accessMask = defaultAccessMask;
  1523. allRegisteredTypes.Insert(asSNameSpaceNamePair(type->nameSpace, type->name), type);
  1524. registeredObjTypes.PushLast(type);
  1525. currentGroup->types.PushLast(type);
  1526. }
  1527. else
  1528. {
  1529. // The application is registering a template specialization so we
  1530. // need to replace the template instance type with the new type.
  1531. // TODO: Template: We don't require the lower dimensions to be registered first for registered template types
  1532. // int[][] must not be allowed to be registered
  1533. // if int[] hasn't been registered first
  1534. if( dt.GetSubType().IsTemplate() )
  1535. return ConfigError(asLOWER_ARRAY_DIMENSION_NOT_REGISTERED, "RegisterObjectType", name, 0);
  1536. if( dt.IsReadOnly() ||
  1537. dt.IsReference() )
  1538. return ConfigError(asINVALID_TYPE, "RegisterObjectType", name, 0);
  1539. // Was the template instance type generated before?
  1540. if( generatedTemplateTypes.Exists(CastToObjectType(dt.GetTypeInfo())) &&
  1541. generatedTemplateTypes[generatedTemplateTypes.GetLength()-1] == mostRecentTemplateInstanceType )
  1542. {
  1543. asCString str;
  1544. str.Format(TXT_TEMPLATE_s_ALREADY_GENERATED_CANT_REGISTER, typeName.AddressOf());
  1545. WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  1546. return ConfigError(asNOT_SUPPORTED, "RegisterObjectType", name, 0);
  1547. }
  1548. // If this is not a generated template instance type, then it means it is an
  1549. // already registered template specialization
  1550. if( !generatedTemplateTypes.Exists(CastToObjectType(dt.GetTypeInfo())) )
  1551. return ConfigError(asALREADY_REGISTERED, "RegisterObjectType", name, 0);
  1552. // TODO: Add this again. The type is used by the factory stubs so we need to discount that
  1553. // Is the template instance type already being used?
  1554. // if( dt.GetTypeInfo()->GetRefCount() > 1 )
  1555. // return ConfigError(asNOT_SUPPORTED, "RegisterObjectType", name, 0);
  1556. // Put the data type in the list
  1557. asCObjectType *type = asNEW(asCObjectType)(this);
  1558. if( type == 0 )
  1559. return ConfigError(asOUT_OF_MEMORY, "RegisterObjectType", name, 0);
  1560. type->name = dt.GetTypeInfo()->name;
  1561. // The namespace will be the same as the original template type
  1562. type->nameSpace = dt.GetTypeInfo()->nameSpace;
  1563. type->templateSubTypes.PushLast(dt.GetSubType());
  1564. for( asUINT s = 0; s < type->templateSubTypes.GetLength(); s++ )
  1565. if( type->templateSubTypes[s].GetTypeInfo() )
  1566. type->templateSubTypes[s].GetTypeInfo()->AddRefInternal();
  1567. type->size = byteSize;
  1568. #ifdef WIP_16BYTE_ALIGN
  1569. // TODO: Types smaller than 4 don't need to be aligned to 4 byte boundaries
  1570. type->alignment = (flags & asOBJ_APP_ALIGN16) ? 16 : 4;
  1571. #endif
  1572. type->flags = flags;
  1573. type->accessMask = defaultAccessMask;
  1574. templateInstanceTypes.PushLast(type);
  1575. currentGroup->types.PushLast(type);
  1576. // Remove the template instance type, which will no longer be used.
  1577. // It is possible that multiple template instances are generated if
  1578. // they have any relationship, so all of them must be removed
  1579. while( generatedTemplateTypes.GetLength() > originalSizeOfGeneratedTemplateTypes )
  1580. RemoveTemplateInstanceType(generatedTemplateTypes[generatedTemplateTypes.GetLength()-1]);
  1581. }
  1582. }
  1583. // Return the type id as the success (except for template types)
  1584. if( flags & asOBJ_TEMPLATE )
  1585. return asSUCCESS;
  1586. return GetTypeIdByDecl(name);
  1587. }
  1588. // interface
  1589. int asCScriptEngine::RegisterObjectBehaviour(const char *datatype, asEBehaviours behaviour, const char *decl, const asSFuncPtr &funcPointer, asDWORD callConv, void *auxiliary, int compositeOffset, bool isCompositeIndirect)
  1590. {
  1591. if( datatype == 0 ) return ConfigError(asINVALID_ARG, "RegisterObjectBehaviour", datatype, decl);
  1592. // Determine the object type
  1593. asCBuilder bld(this, 0);
  1594. asCDataType type;
  1595. int r = bld.ParseDataType(datatype, &type, defaultNamespace);
  1596. if( r < 0 )
  1597. return ConfigError(r, "RegisterObjectBehaviour", datatype, decl);
  1598. if( type.GetTypeInfo() == 0 || (type.IsObjectHandle() && !(type.GetTypeInfo()->GetFlags() & asOBJ_IMPLICIT_HANDLE)) )
  1599. return ConfigError(asINVALID_TYPE, "RegisterObjectBehaviour", datatype, decl);
  1600. // Don't allow application to modify built-in types
  1601. if( type.GetTypeInfo() == &functionBehaviours ||
  1602. type.GetTypeInfo() == &scriptTypeBehaviours )
  1603. return ConfigError(asINVALID_TYPE, "RegisterObjectBehaviour", datatype, decl);
  1604. if( type.IsReadOnly() || type.IsReference() )
  1605. return ConfigError(asINVALID_TYPE, "RegisterObjectBehaviour", datatype, decl);
  1606. // Don't allow modifying generated template instances
  1607. if( type.GetTypeInfo() && (type.GetTypeInfo()->flags & asOBJ_TEMPLATE) && generatedTemplateTypes.Exists(CastToObjectType(type.GetTypeInfo())) )
  1608. return ConfigError(asINVALID_TYPE, "RegisterObjectBehaviour", datatype, decl);
  1609. return RegisterBehaviourToObjectType(CastToObjectType(type.GetTypeInfo()), behaviour, decl, funcPointer, callConv, auxiliary, compositeOffset, isCompositeIndirect);
  1610. }
  1611. // internal
  1612. int asCScriptEngine::RegisterBehaviourToObjectType(asCObjectType *objectType, asEBehaviours behaviour, const char *decl, const asSFuncPtr &funcPointer, asDWORD callConv, void *auxiliary, int compositeOffset, bool isCompositeIndirect)
  1613. {
  1614. #ifdef AS_MAX_PORTABILITY
  1615. if( callConv != asCALL_GENERIC )
  1616. return ConfigError(asNOT_SUPPORTED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1617. #endif
  1618. asSSystemFunctionInterface internal;
  1619. bool isMethod = !(behaviour == asBEHAVE_FACTORY ||
  1620. behaviour == asBEHAVE_LIST_FACTORY ||
  1621. behaviour == asBEHAVE_TEMPLATE_CALLBACK);
  1622. int r = DetectCallingConvention(isMethod, funcPointer, callConv, auxiliary, &internal);
  1623. if( r < 0 )
  1624. return ConfigError(r, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1625. internal.compositeOffset = compositeOffset;
  1626. internal.isCompositeIndirect = isCompositeIndirect;
  1627. if( (compositeOffset || isCompositeIndirect) && callConv != asCALL_THISCALL )
  1628. return ConfigError(asINVALID_ARG, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1629. // TODO: cleanup: This is identical to what is in RegisterMethodToObjectType
  1630. // If the object type is a template, make sure there are no generated instances already
  1631. if( objectType->flags & asOBJ_TEMPLATE )
  1632. {
  1633. for( asUINT n = 0; n < generatedTemplateTypes.GetLength(); n++ )
  1634. {
  1635. asCObjectType *tmpl = generatedTemplateTypes[n];
  1636. if( tmpl->name == objectType->name &&
  1637. tmpl->nameSpace == objectType->nameSpace &&
  1638. !(tmpl->templateSubTypes[0].GetTypeInfo() && (tmpl->templateSubTypes[0].GetTypeInfo()->flags & asOBJ_TEMPLATE_SUBTYPE)) )
  1639. {
  1640. asCString msg;
  1641. msg.Format(TXT_TEMPLATE_s_ALREADY_GENERATED_CANT_REGISTER, asCDataType::CreateType(tmpl, false).Format(tmpl->nameSpace).AddressOf());
  1642. WriteMessage("",0,0, asMSGTYPE_ERROR, msg.AddressOf());
  1643. return ConfigError(asERROR, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1644. }
  1645. }
  1646. }
  1647. isPrepared = false;
  1648. asSTypeBehaviour *beh = &objectType->beh;
  1649. // Verify function declaration
  1650. asCScriptFunction func(this, 0, asFUNC_DUMMY);
  1651. bool expectListPattern = behaviour == asBEHAVE_LIST_FACTORY || behaviour == asBEHAVE_LIST_CONSTRUCT;
  1652. asCScriptNode *listPattern = 0;
  1653. asCBuilder bld(this, 0);
  1654. r = bld.ParseFunctionDeclaration(objectType, decl, &func, true, &internal.paramAutoHandles, &internal.returnAutoHandle, 0, expectListPattern ? &listPattern : 0);
  1655. if( r < 0 )
  1656. {
  1657. if( listPattern )
  1658. listPattern->Destroy(this);
  1659. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1660. }
  1661. func.name.Format("$beh%d", behaviour);
  1662. if( behaviour != asBEHAVE_FACTORY && behaviour != asBEHAVE_LIST_FACTORY )
  1663. {
  1664. func.objectType = objectType;
  1665. func.objectType->AddRefInternal();
  1666. }
  1667. // Check if the method restricts that use of the template to value types or reference types
  1668. if( objectType->flags & asOBJ_TEMPLATE )
  1669. {
  1670. r = SetTemplateRestrictions(objectType, &func, "RegisterObjectBehaviour", decl);
  1671. if (r < 0)
  1672. return r;
  1673. }
  1674. if( behaviour == asBEHAVE_CONSTRUCT )
  1675. {
  1676. // Verify that the return type is void
  1677. if( func.returnType != asCDataType::CreatePrimitive(ttVoid, false) )
  1678. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1679. if( objectType->flags & asOBJ_SCRIPT_OBJECT )
  1680. {
  1681. // The script object is a special case
  1682. asASSERT(func.parameterTypes.GetLength() == 1);
  1683. beh->construct = AddBehaviourFunction(func, internal);
  1684. beh->factory = beh->construct;
  1685. scriptFunctions[beh->factory]->AddRefInternal();
  1686. beh->constructors.PushLast(beh->construct);
  1687. beh->factories.PushLast(beh->factory);
  1688. func.id = beh->construct;
  1689. }
  1690. else
  1691. {
  1692. // Verify that it is a value type
  1693. if( !(func.objectType->flags & asOBJ_VALUE) )
  1694. {
  1695. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
  1696. return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1697. }
  1698. // The templates take a hidden parameter with the object type
  1699. if( (objectType->flags & asOBJ_TEMPLATE) &&
  1700. (func.parameterTypes.GetLength() == 0 ||
  1701. !func.parameterTypes[0].IsReference()) )
  1702. {
  1703. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_FIRST_PARAM_MUST_BE_REF_FOR_TEMPLATE_FACTORY);
  1704. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1705. }
  1706. // TODO: Verify that the same constructor hasn't been registered already
  1707. // Store all constructors in a list
  1708. func.id = AddBehaviourFunction(func, internal);
  1709. beh->constructors.PushLast(func.id);
  1710. if( func.parameterTypes.GetLength() == 0 ||
  1711. (func.parameterTypes.GetLength() == 1 && (objectType->flags & asOBJ_TEMPLATE)) )
  1712. {
  1713. beh->construct = func.id;
  1714. }
  1715. else if( func.parameterTypes.GetLength() == 1 )
  1716. {
  1717. // Is this the copy constructor?
  1718. asCDataType paramType = func.parameterTypes[0];
  1719. // If the parameter is object, and const reference for input or inout,
  1720. // and same type as this class, then this is a copy constructor.
  1721. if( paramType.IsObject() && paramType.IsReference() && paramType.IsReadOnly() &&
  1722. (func.inOutFlags[0] & asTM_INREF) && paramType.GetTypeInfo() == objectType )
  1723. beh->copyconstruct = func.id;
  1724. }
  1725. }
  1726. }
  1727. else if( behaviour == asBEHAVE_DESTRUCT )
  1728. {
  1729. // Must be a value type
  1730. if( !(func.objectType->flags & asOBJ_VALUE) )
  1731. {
  1732. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
  1733. return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1734. }
  1735. if( beh->destruct )
  1736. return ConfigError(asALREADY_REGISTERED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1737. // Verify that the return type is void
  1738. if( func.returnType != asCDataType::CreatePrimitive(ttVoid, false) )
  1739. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1740. // Verify that there are no parameters
  1741. if( func.parameterTypes.GetLength() > 0 )
  1742. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1743. func.id = beh->destruct = AddBehaviourFunction(func, internal);
  1744. }
  1745. else if( behaviour == asBEHAVE_LIST_CONSTRUCT )
  1746. {
  1747. // Verify that the return type is void
  1748. if( func.returnType != asCDataType::CreatePrimitive(ttVoid, false) )
  1749. {
  1750. if( listPattern )
  1751. listPattern->Destroy(this);
  1752. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1753. }
  1754. // Verify that it is a value type
  1755. if( !(func.objectType->flags & asOBJ_VALUE) )
  1756. {
  1757. if( listPattern )
  1758. listPattern->Destroy(this);
  1759. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
  1760. return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1761. }
  1762. // Verify the parameters
  1763. if( func.parameterTypes.GetLength() != 1 || !func.parameterTypes[0].IsReference() )
  1764. {
  1765. if( listPattern )
  1766. listPattern->Destroy(this);
  1767. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_LIST_FACTORY_EXPECTS_1_REF_PARAM);
  1768. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1769. }
  1770. // Don't accept duplicates
  1771. if( beh->listFactory )
  1772. {
  1773. if( listPattern )
  1774. listPattern->Destroy(this);
  1775. return ConfigError(asALREADY_REGISTERED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1776. }
  1777. // Add the function
  1778. func.id = AddBehaviourFunction(func, internal);
  1779. // Re-use the listFactory member, as it is not possible to have both anyway
  1780. beh->listFactory = func.id;
  1781. // Store the list pattern for this function
  1782. r = scriptFunctions[func.id]->RegisterListPattern(decl, listPattern);
  1783. if( listPattern )
  1784. listPattern->Destroy(this);
  1785. if( r < 0 )
  1786. return ConfigError(r, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1787. }
  1788. else if( behaviour == asBEHAVE_FACTORY || behaviour == asBEHAVE_LIST_FACTORY )
  1789. {
  1790. // Must be a ref type and must not have asOBJ_NOHANDLE
  1791. if( !(objectType->flags & asOBJ_REF) || (objectType->flags & asOBJ_NOHANDLE) )
  1792. {
  1793. if( listPattern )
  1794. listPattern->Destroy(this);
  1795. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
  1796. return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1797. }
  1798. // Verify that the return type is a handle to the type
  1799. if( func.returnType != asCDataType::CreateObjectHandle(objectType, false) )
  1800. {
  1801. if( listPattern )
  1802. listPattern->Destroy(this);
  1803. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1804. }
  1805. // The templates take a hidden parameter with the object type
  1806. if( (objectType->flags & asOBJ_TEMPLATE) &&
  1807. (func.parameterTypes.GetLength() == 0 ||
  1808. !func.parameterTypes[0].IsReference()) )
  1809. {
  1810. if( listPattern )
  1811. listPattern->Destroy(this);
  1812. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_FIRST_PARAM_MUST_BE_REF_FOR_TEMPLATE_FACTORY);
  1813. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1814. }
  1815. if( behaviour == asBEHAVE_LIST_FACTORY )
  1816. {
  1817. // Make sure the factory takes a reference as its last parameter
  1818. if( objectType->flags & asOBJ_TEMPLATE )
  1819. {
  1820. if( func.parameterTypes.GetLength() != 2 || !func.parameterTypes[1].IsReference() )
  1821. {
  1822. if( listPattern )
  1823. listPattern->Destroy(this);
  1824. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_TEMPLATE_LIST_FACTORY_EXPECTS_2_REF_PARAMS);
  1825. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1826. }
  1827. }
  1828. else
  1829. {
  1830. if( func.parameterTypes.GetLength() != 1 || !func.parameterTypes[0].IsReference() )
  1831. {
  1832. if( listPattern )
  1833. listPattern->Destroy(this);
  1834. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_LIST_FACTORY_EXPECTS_1_REF_PARAM);
  1835. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1836. }
  1837. }
  1838. }
  1839. // TODO: Verify that the same factory function hasn't been registered already
  1840. // Don't accept duplicates
  1841. if( behaviour == asBEHAVE_LIST_FACTORY && beh->listFactory )
  1842. {
  1843. if( listPattern )
  1844. listPattern->Destroy(this);
  1845. return ConfigError(asALREADY_REGISTERED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1846. }
  1847. // Store all factory functions in a list
  1848. func.id = AddBehaviourFunction(func, internal);
  1849. // The list factory is a special factory and isn't stored together with the rest
  1850. if( behaviour != asBEHAVE_LIST_FACTORY )
  1851. beh->factories.PushLast(func.id);
  1852. if( (func.parameterTypes.GetLength() == 0) ||
  1853. (func.parameterTypes.GetLength() == 1 && (objectType->flags & asOBJ_TEMPLATE)) )
  1854. {
  1855. beh->factory = func.id;
  1856. }
  1857. else if( (func.parameterTypes.GetLength() == 1) ||
  1858. (func.parameterTypes.GetLength() == 2 && (objectType->flags & asOBJ_TEMPLATE)) )
  1859. {
  1860. if( behaviour == asBEHAVE_LIST_FACTORY )
  1861. {
  1862. beh->listFactory = func.id;
  1863. // Store the list pattern for this function
  1864. r = scriptFunctions[func.id]->RegisterListPattern(decl, listPattern);
  1865. if( listPattern )
  1866. listPattern->Destroy(this);
  1867. if( r < 0 )
  1868. return ConfigError(r, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1869. }
  1870. else
  1871. {
  1872. // Is this the copy factory?
  1873. asCDataType paramType = func.parameterTypes[func.parameterTypes.GetLength()-1];
  1874. // If the parameter is object, and const reference for input,
  1875. // and same type as this class, then this is a copy constructor.
  1876. if( paramType.IsObject() && paramType.IsReference() && paramType.IsReadOnly() && func.inOutFlags[func.parameterTypes.GetLength()-1] == asTM_INREF && paramType.GetTypeInfo() == objectType )
  1877. beh->copyfactory = func.id;
  1878. }
  1879. }
  1880. }
  1881. else if( behaviour == asBEHAVE_ADDREF )
  1882. {
  1883. // Must be a ref type and must not have asOBJ_NOHANDLE, nor asOBJ_SCOPED
  1884. if( !(func.objectType->flags & asOBJ_REF) ||
  1885. (func.objectType->flags & asOBJ_NOHANDLE) ||
  1886. (func.objectType->flags & asOBJ_SCOPED) ||
  1887. (func.objectType->flags & asOBJ_NOCOUNT) )
  1888. {
  1889. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
  1890. return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1891. }
  1892. if( beh->addref )
  1893. return ConfigError(asALREADY_REGISTERED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1894. // Verify that the return type is void
  1895. if( func.returnType != asCDataType::CreatePrimitive(ttVoid, false) )
  1896. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1897. // Verify that there are no parameters
  1898. if( func.parameterTypes.GetLength() > 0 )
  1899. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1900. func.id = beh->addref = AddBehaviourFunction(func, internal);
  1901. }
  1902. else if( behaviour == asBEHAVE_RELEASE )
  1903. {
  1904. // Must be a ref type and must not have asOBJ_NOHANDLE
  1905. if( !(func.objectType->flags & asOBJ_REF) ||
  1906. (func.objectType->flags & asOBJ_NOHANDLE) ||
  1907. (func.objectType->flags & asOBJ_NOCOUNT) )
  1908. {
  1909. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
  1910. return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1911. }
  1912. if( beh->release )
  1913. return ConfigError(asALREADY_REGISTERED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1914. // Verify that the return type is void
  1915. if( func.returnType != asCDataType::CreatePrimitive(ttVoid, false) )
  1916. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1917. // Verify that there are no parameters
  1918. if( func.parameterTypes.GetLength() > 0 )
  1919. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1920. func.id = beh->release = AddBehaviourFunction(func, internal);
  1921. }
  1922. else if( behaviour == asBEHAVE_TEMPLATE_CALLBACK )
  1923. {
  1924. // Must be a template type
  1925. if( !(func.objectType->flags & asOBJ_TEMPLATE) )
  1926. {
  1927. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
  1928. return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1929. }
  1930. if( beh->templateCallback )
  1931. return ConfigError(asALREADY_REGISTERED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1932. // Verify that the return type is bool
  1933. if( func.returnType != asCDataType::CreatePrimitive(ttBool, false) )
  1934. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1935. // Verify that there are two parameters
  1936. if( func.parameterTypes.GetLength() != 2 )
  1937. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1938. // The first parameter must be an inref (to receive the object type), and
  1939. // the second must be a bool out ref (to return if the type should or shouldn't be garbage collected)
  1940. if( func.inOutFlags[0] != asTM_INREF || func.inOutFlags[1] != asTM_OUTREF || !func.parameterTypes[1].IsEqualExceptRef(asCDataType::CreatePrimitive(ttBool, false)) )
  1941. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1942. func.id = beh->templateCallback = AddBehaviourFunction(func, internal);
  1943. }
  1944. else if( behaviour >= asBEHAVE_FIRST_GC &&
  1945. behaviour <= asBEHAVE_LAST_GC )
  1946. {
  1947. // Only allow GC behaviours for types registered to be garbage collected
  1948. if( !(func.objectType->flags & asOBJ_GC) )
  1949. {
  1950. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
  1951. return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1952. }
  1953. // Verify parameter count
  1954. if( (behaviour == asBEHAVE_GETREFCOUNT ||
  1955. behaviour == asBEHAVE_SETGCFLAG ||
  1956. behaviour == asBEHAVE_GETGCFLAG) &&
  1957. func.parameterTypes.GetLength() != 0 )
  1958. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1959. if( (behaviour == asBEHAVE_ENUMREFS ||
  1960. behaviour == asBEHAVE_RELEASEREFS) &&
  1961. func.parameterTypes.GetLength() != 1 )
  1962. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1963. // Verify return type
  1964. if( behaviour == asBEHAVE_GETREFCOUNT &&
  1965. func.returnType != asCDataType::CreatePrimitive(ttInt, false) )
  1966. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1967. if( behaviour == asBEHAVE_GETGCFLAG &&
  1968. func.returnType != asCDataType::CreatePrimitive(ttBool, false) )
  1969. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1970. if( (behaviour == asBEHAVE_SETGCFLAG ||
  1971. behaviour == asBEHAVE_ENUMREFS ||
  1972. behaviour == asBEHAVE_RELEASEREFS) &&
  1973. func.returnType != asCDataType::CreatePrimitive(ttVoid, false) )
  1974. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1975. if( behaviour == asBEHAVE_GETREFCOUNT )
  1976. func.id = beh->gcGetRefCount = AddBehaviourFunction(func, internal);
  1977. else if( behaviour == asBEHAVE_SETGCFLAG )
  1978. func.id = beh->gcSetFlag = AddBehaviourFunction(func, internal);
  1979. else if( behaviour == asBEHAVE_GETGCFLAG )
  1980. func.id = beh->gcGetFlag = AddBehaviourFunction(func, internal);
  1981. else if( behaviour == asBEHAVE_ENUMREFS )
  1982. func.id = beh->gcEnumReferences = AddBehaviourFunction(func, internal);
  1983. else if( behaviour == asBEHAVE_RELEASEREFS )
  1984. func.id = beh->gcReleaseAllReferences = AddBehaviourFunction(func, internal);
  1985. }
  1986. else if ( behaviour == asBEHAVE_GET_WEAKREF_FLAG )
  1987. {
  1988. // This behaviour is only allowed for reference types
  1989. if( !(func.objectType->flags & asOBJ_REF) )
  1990. {
  1991. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
  1992. return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1993. }
  1994. // Don't allow it if the type is registered with nohandle or scoped
  1995. if( func.objectType->flags & (asOBJ_NOHANDLE|asOBJ_SCOPED) )
  1996. {
  1997. WriteMessage("", 0, 0, asMSGTYPE_ERROR, TXT_ILLEGAL_BEHAVIOUR_FOR_TYPE);
  1998. return ConfigError(asILLEGAL_BEHAVIOUR_FOR_TYPE, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  1999. }
  2000. // Verify that the return type is a reference since it needs to return a pointer to an asISharedBool
  2001. if( !func.returnType.IsReference() )
  2002. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  2003. // Verify that there are no parameters
  2004. if( func.parameterTypes.GetLength() != 0 )
  2005. return ConfigError(asINVALID_DECLARATION, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  2006. if( beh->getWeakRefFlag )
  2007. return ConfigError(asALREADY_REGISTERED, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  2008. func.id = beh->getWeakRefFlag = AddBehaviourFunction(func, internal);
  2009. }
  2010. else
  2011. {
  2012. asASSERT(false);
  2013. return ConfigError(asINVALID_ARG, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  2014. }
  2015. if( func.id < 0 )
  2016. return ConfigError(func.id, "RegisterObjectBehaviour", objectType->name.AddressOf(), decl);
  2017. // Return function id as success
  2018. return func.id;
  2019. }
  2020. int asCScriptEngine::SetTemplateRestrictions(asCObjectType *templateType, asCScriptFunction *func, const char *caller, const char *decl)
  2021. {
  2022. asASSERT(templateType->flags & asOBJ_TEMPLATE);
  2023. for (asUINT subTypeIdx = 0; subTypeIdx < templateType->templateSubTypes.GetLength(); subTypeIdx++)
  2024. {
  2025. if (func->returnType.GetTypeInfo() == templateType->templateSubTypes[subTypeIdx].GetTypeInfo())
  2026. {
  2027. if (func->returnType.IsObjectHandle())
  2028. templateType->acceptValueSubType = false;
  2029. else if (!func->returnType.IsReference())
  2030. templateType->acceptRefSubType = false;
  2031. // Can't support template subtypes by value, since each type is treated differently in the ABI
  2032. if (!func->returnType.IsObjectHandle() && !func->returnType.IsReference())
  2033. return ConfigError(asNOT_SUPPORTED, caller, templateType->name.AddressOf(), decl);
  2034. }
  2035. for (asUINT n = 0; n < func->parameterTypes.GetLength(); n++)
  2036. {
  2037. if (func->parameterTypes[n].GetTypeInfo() == templateType->templateSubTypes[subTypeIdx].GetTypeInfo())
  2038. {
  2039. if (func->parameterTypes[n].IsObjectHandle() ||
  2040. (!ep.allowUnsafeReferences && func->parameterTypes[n].IsReference() && func->inOutFlags[n] == asTM_INOUTREF))
  2041. templateType->acceptValueSubType = false;
  2042. else if (!func->parameterTypes[n].IsReference())
  2043. templateType->acceptRefSubType = false;
  2044. // Can't support template subtypes by value, since each type is treated differently in the ABI
  2045. if (!func->parameterTypes[n].IsObjectHandle() && !func->parameterTypes[n].IsReference())
  2046. return ConfigError(asNOT_SUPPORTED, caller, templateType->name.AddressOf(), decl);
  2047. }
  2048. }
  2049. }
  2050. return asSUCCESS;
  2051. }
  2052. int asCScriptEngine::VerifyVarTypeNotInFunction(asCScriptFunction *func)
  2053. {
  2054. // Don't allow var type in this function
  2055. if( func->returnType.GetTokenType() == ttQuestion )
  2056. return asINVALID_DECLARATION;
  2057. for( unsigned int n = 0; n < func->parameterTypes.GetLength(); n++ )
  2058. if( func->parameterTypes[n].GetTokenType() == ttQuestion )
  2059. return asINVALID_DECLARATION;
  2060. return 0;
  2061. }
  2062. int asCScriptEngine::AddBehaviourFunction(asCScriptFunction &func, asSSystemFunctionInterface &internal)
  2063. {
  2064. asUINT n;
  2065. int id = GetNextScriptFunctionId();
  2066. asSSystemFunctionInterface *newInterface = asNEW(asSSystemFunctionInterface)(internal);
  2067. if( newInterface == 0 )
  2068. return asOUT_OF_MEMORY;
  2069. asCScriptFunction *f = asNEW(asCScriptFunction)(this, 0, asFUNC_SYSTEM);
  2070. if( f == 0 )
  2071. {
  2072. asDELETE(newInterface, asSSystemFunctionInterface);
  2073. return asOUT_OF_MEMORY;
  2074. }
  2075. asASSERT(func.name != "" && func.name != "f");
  2076. f->name = func.name;
  2077. f->sysFuncIntf = newInterface;
  2078. f->returnType = func.returnType;
  2079. f->objectType = func.objectType;
  2080. if( f->objectType )
  2081. f->objectType->AddRefInternal();
  2082. f->id = id;
  2083. f->SetReadOnly(func.IsReadOnly());
  2084. f->accessMask = defaultAccessMask;
  2085. f->parameterTypes = func.parameterTypes;
  2086. f->parameterNames = func.parameterNames;
  2087. f->inOutFlags = func.inOutFlags;
  2088. f->traits = func.traits;
  2089. for( n = 0; n < func.defaultArgs.GetLength(); n++ )
  2090. if( func.defaultArgs[n] )
  2091. f->defaultArgs.PushLast(asNEW(asCString)(*func.defaultArgs[n]));
  2092. else
  2093. f->defaultArgs.PushLast(0);
  2094. AddScriptFunction(f);
  2095. // If parameter type from other groups are used, add references
  2096. currentGroup->AddReferencesForFunc(this, f);
  2097. return id;
  2098. }
  2099. // interface
  2100. int asCScriptEngine::RegisterGlobalProperty(const char *declaration, void *pointer)
  2101. {
  2102. // Don't accept a null pointer
  2103. if( pointer == 0 )
  2104. return ConfigError(asINVALID_ARG, "RegisterGlobalProperty", declaration, 0);
  2105. asCDataType type;
  2106. asCString name;
  2107. int r;
  2108. asCBuilder bld(this, 0);
  2109. if( (r = bld.VerifyProperty(0, declaration, name, type, defaultNamespace)) < 0 )
  2110. return ConfigError(r, "RegisterGlobalProperty", declaration, 0);
  2111. // Don't allow registering references as global properties
  2112. if( type.IsReference() )
  2113. return ConfigError(asINVALID_TYPE, "RegisterGlobalProperty", declaration, 0);
  2114. // Store the property info
  2115. asCGlobalProperty *prop = AllocateGlobalProperty();
  2116. prop->name = name;
  2117. prop->nameSpace = defaultNamespace;
  2118. prop->type = type;
  2119. prop->accessMask = defaultAccessMask;
  2120. prop->SetRegisteredAddress(pointer);
  2121. varAddressMap.Insert(prop->GetAddressOfValue(), prop);
  2122. registeredGlobalProps.Put(prop);
  2123. prop->AddRef();
  2124. currentGroup->globalProps.PushLast(prop);
  2125. currentGroup->AddReferencesForType(this, type.GetTypeInfo());
  2126. return asSUCCESS;
  2127. }
  2128. // internal
  2129. asCGlobalProperty *asCScriptEngine::AllocateGlobalProperty()
  2130. {
  2131. asCGlobalProperty *prop = asNEW(asCGlobalProperty);
  2132. if( prop == 0 )
  2133. {
  2134. // Out of memory
  2135. return 0;
  2136. }
  2137. // First check the availability of a free slot
  2138. if( freeGlobalPropertyIds.GetLength() )
  2139. {
  2140. prop->id = freeGlobalPropertyIds.PopLast();
  2141. globalProperties[prop->id] = prop;
  2142. return prop;
  2143. }
  2144. prop->id = (asUINT)globalProperties.GetLength();
  2145. globalProperties.PushLast(prop);
  2146. return prop;
  2147. }
  2148. // internal
  2149. void asCScriptEngine::RemoveGlobalProperty(asCGlobalProperty *prop)
  2150. {
  2151. int index = globalProperties.IndexOf(prop);
  2152. if( index >= 0 )
  2153. {
  2154. freeGlobalPropertyIds.PushLast(index);
  2155. globalProperties[index] = 0;
  2156. asSMapNode<void*, asCGlobalProperty*> *node;
  2157. varAddressMap.MoveTo(&node, prop->GetAddressOfValue());
  2158. asASSERT(node);
  2159. if( node )
  2160. varAddressMap.Erase(node);
  2161. prop->Release();
  2162. }
  2163. }
  2164. // interface
  2165. asUINT asCScriptEngine::GetGlobalPropertyCount() const
  2166. {
  2167. return asUINT(registeredGlobalProps.GetSize());
  2168. }
  2169. // interface
  2170. // TODO: If the typeId ever encodes the const flag, then the isConst parameter should be removed
  2171. int asCScriptEngine::GetGlobalPropertyByIndex(asUINT index, const char **name, const char **nameSpace, int *typeId, bool *isConst, const char **configGroup, void **pointer, asDWORD *accessMask) const
  2172. {
  2173. const asCGlobalProperty *prop = registeredGlobalProps.Get(index);
  2174. if( !prop )
  2175. return asINVALID_ARG;
  2176. if( name ) *name = prop->name.AddressOf();
  2177. if( nameSpace ) *nameSpace = prop->nameSpace->name.AddressOf();
  2178. if( typeId ) *typeId = GetTypeIdFromDataType(prop->type);
  2179. if( isConst ) *isConst = prop->type.IsReadOnly();
  2180. if( pointer ) *pointer = prop->GetRegisteredAddress();
  2181. if( accessMask ) *accessMask = prop->accessMask;
  2182. if( configGroup )
  2183. {
  2184. asCConfigGroup *group = FindConfigGroupForGlobalVar(index);
  2185. if( group )
  2186. *configGroup = group->groupName.AddressOf();
  2187. else
  2188. *configGroup = 0;
  2189. }
  2190. return asSUCCESS;
  2191. }
  2192. // interface
  2193. int asCScriptEngine::GetGlobalPropertyIndexByName(const char *name) const
  2194. {
  2195. asSNameSpace *ns = defaultNamespace;
  2196. // Find the global var id
  2197. while( ns )
  2198. {
  2199. int id = registeredGlobalProps.GetFirstIndex(ns, name);
  2200. if( id >= 0 )
  2201. return id;
  2202. // Recursively search parent namespace
  2203. ns = GetParentNameSpace(ns);
  2204. }
  2205. return asNO_GLOBAL_VAR;
  2206. }
  2207. // interface
  2208. int asCScriptEngine::GetGlobalPropertyIndexByDecl(const char *decl) const
  2209. {
  2210. // This const cast is OK. The builder won't modify the engine
  2211. asCBuilder bld(const_cast<asCScriptEngine*>(this), 0);
  2212. // Don't write parser errors to the message callback
  2213. bld.silent = true;
  2214. asCString name;
  2215. asSNameSpace *ns;
  2216. asCDataType dt;
  2217. int r = bld.ParseVariableDeclaration(decl, defaultNamespace, name, ns, dt);
  2218. if( r < 0 )
  2219. return r;
  2220. // Search for a match
  2221. while( ns )
  2222. {
  2223. int id = registeredGlobalProps.GetFirstIndex(ns, name, asCCompGlobPropType(dt));
  2224. if( id >= 0 )
  2225. return id;
  2226. ns = GetParentNameSpace(ns);
  2227. }
  2228. return asNO_GLOBAL_VAR;
  2229. }
  2230. // interface
  2231. int asCScriptEngine::RegisterObjectMethod(const char *obj, const char *declaration, const asSFuncPtr &funcPointer, asDWORD callConv, void *auxiliary, int compositeOffset, bool isCompositeIndirect)
  2232. {
  2233. if( obj == 0 )
  2234. return ConfigError(asINVALID_ARG, "RegisterObjectMethod", obj, declaration);
  2235. // Determine the object type
  2236. asCDataType dt;
  2237. asCBuilder bld(this, 0);
  2238. int r = bld.ParseDataType(obj, &dt, defaultNamespace);
  2239. if( r < 0 )
  2240. return ConfigError(r, "RegisterObjectMethod", obj, declaration);
  2241. // Don't allow application to modify primitives or handles
  2242. if( dt.GetTypeInfo() == 0 || (dt.IsObjectHandle() && !(dt.GetTypeInfo()->GetFlags() & asOBJ_IMPLICIT_HANDLE)))
  2243. return ConfigError(asINVALID_ARG, "RegisterObjectMethod", obj, declaration);
  2244. // Don't allow application to modify built-in types or funcdefs
  2245. if( dt.GetTypeInfo() == &functionBehaviours ||
  2246. dt.GetTypeInfo() == &scriptTypeBehaviours ||
  2247. CastToFuncdefType(dt.GetTypeInfo()) )
  2248. return ConfigError(asINVALID_ARG, "RegisterObjectMethod", obj, declaration);
  2249. // Don't allow modifying generated template instances
  2250. if( dt.GetTypeInfo() && (dt.GetTypeInfo()->flags & asOBJ_TEMPLATE) && generatedTemplateTypes.Exists(CastToObjectType(dt.GetTypeInfo())) )
  2251. return ConfigError(asINVALID_TYPE, "RegisterObjectMethod", obj, declaration);
  2252. return RegisterMethodToObjectType(CastToObjectType(dt.GetTypeInfo()), declaration, funcPointer, callConv, auxiliary, compositeOffset, isCompositeIndirect);
  2253. }
  2254. // internal
  2255. int asCScriptEngine::RegisterMethodToObjectType(asCObjectType *objectType, const char *declaration, const asSFuncPtr &funcPointer, asDWORD callConv, void *auxiliary, int compositeOffset, bool isCompositeIndirect)
  2256. {
  2257. #ifdef AS_MAX_PORTABILITY
  2258. if( callConv != asCALL_GENERIC )
  2259. return ConfigError(asNOT_SUPPORTED, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
  2260. #endif
  2261. asSSystemFunctionInterface internal;
  2262. int r = DetectCallingConvention(true, funcPointer, callConv, auxiliary, &internal);
  2263. if( r < 0 )
  2264. return ConfigError(r, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
  2265. internal.compositeOffset = compositeOffset;
  2266. internal.isCompositeIndirect = isCompositeIndirect;
  2267. if( (compositeOffset || isCompositeIndirect) && callConv != asCALL_THISCALL )
  2268. return ConfigError(asINVALID_ARG, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
  2269. // TODO: cleanup: This is identical to what is in RegisterMethodToObjectType
  2270. // If the object type is a template, make sure there are no generated instances already
  2271. if( objectType->flags & asOBJ_TEMPLATE )
  2272. {
  2273. for( asUINT n = 0; n < generatedTemplateTypes.GetLength(); n++ )
  2274. {
  2275. asCObjectType *tmpl = generatedTemplateTypes[n];
  2276. if( tmpl->name == objectType->name &&
  2277. tmpl->nameSpace == objectType->nameSpace &&
  2278. !(tmpl->templateSubTypes[0].GetTypeInfo() && (tmpl->templateSubTypes[0].GetTypeInfo()->flags & asOBJ_TEMPLATE_SUBTYPE)) )
  2279. {
  2280. asCString msg;
  2281. msg.Format(TXT_TEMPLATE_s_ALREADY_GENERATED_CANT_REGISTER, asCDataType::CreateType(tmpl, false).Format(tmpl->nameSpace).AddressOf());
  2282. WriteMessage("",0,0, asMSGTYPE_ERROR, msg.AddressOf());
  2283. return ConfigError(asERROR, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
  2284. }
  2285. }
  2286. }
  2287. isPrepared = false;
  2288. // Put the system function in the list of system functions
  2289. asSSystemFunctionInterface *newInterface = asNEW(asSSystemFunctionInterface)(internal);
  2290. if( newInterface == 0 )
  2291. return ConfigError(asOUT_OF_MEMORY, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
  2292. asCScriptFunction *func = asNEW(asCScriptFunction)(this, 0, asFUNC_SYSTEM);
  2293. if( func == 0 )
  2294. {
  2295. asDELETE(newInterface, asSSystemFunctionInterface);
  2296. return ConfigError(asOUT_OF_MEMORY, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
  2297. }
  2298. func->sysFuncIntf = newInterface;
  2299. func->objectType = objectType;
  2300. func->objectType->AddRefInternal();
  2301. asCBuilder bld(this, 0);
  2302. r = bld.ParseFunctionDeclaration(func->objectType, declaration, func, true, &newInterface->paramAutoHandles, &newInterface->returnAutoHandle);
  2303. if( r < 0 )
  2304. {
  2305. // Set as dummy function before deleting
  2306. func->funcType = asFUNC_DUMMY;
  2307. asDELETE(func,asCScriptFunction);
  2308. return ConfigError(asINVALID_DECLARATION, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
  2309. }
  2310. // Check name conflicts
  2311. r = bld.CheckNameConflictMember(objectType, func->name.AddressOf(), 0, 0, false);
  2312. if( r < 0 )
  2313. {
  2314. func->funcType = asFUNC_DUMMY;
  2315. asDELETE(func,asCScriptFunction);
  2316. return ConfigError(asNAME_TAKEN, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
  2317. }
  2318. // Check against duplicate methods
  2319. if( func->name == "opConv" || func->name == "opImplConv" || func->name == "opCast" || func->name == "opImplCast" )
  2320. {
  2321. // opConv and opCast are special methods that the compiler differentiates between by the return type
  2322. for( asUINT n = 0; n < func->objectType->methods.GetLength(); n++ )
  2323. {
  2324. asCScriptFunction *f = scriptFunctions[func->objectType->methods[n]];
  2325. if( f->name == func->name &&
  2326. f->IsSignatureExceptNameEqual(func) )
  2327. {
  2328. func->funcType = asFUNC_DUMMY;
  2329. asDELETE(func,asCScriptFunction);
  2330. return ConfigError(asALREADY_REGISTERED, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
  2331. }
  2332. }
  2333. }
  2334. else
  2335. {
  2336. for( asUINT n = 0; n < func->objectType->methods.GetLength(); n++ )
  2337. {
  2338. asCScriptFunction *f = scriptFunctions[func->objectType->methods[n]];
  2339. if( f->name == func->name &&
  2340. f->IsSignatureExceptNameAndReturnTypeEqual(func) )
  2341. {
  2342. func->funcType = asFUNC_DUMMY;
  2343. asDELETE(func,asCScriptFunction);
  2344. return ConfigError(asALREADY_REGISTERED, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
  2345. }
  2346. }
  2347. }
  2348. func->id = GetNextScriptFunctionId();
  2349. func->objectType->methods.PushLast(func->id);
  2350. func->accessMask = defaultAccessMask;
  2351. AddScriptFunction(func);
  2352. // If parameter type from other groups are used, add references
  2353. currentGroup->AddReferencesForFunc(this, func);
  2354. // Check if the method restricts that use of the template to value types or reference types
  2355. if( func->objectType->flags & asOBJ_TEMPLATE )
  2356. {
  2357. r = SetTemplateRestrictions(func->objectType, func, "RegisterObjectMethod", declaration);
  2358. if (r < 0)
  2359. return r;
  2360. }
  2361. // TODO: beh.copy member will be removed, so this is not necessary
  2362. // Is this the default copy behaviour?
  2363. if( func->name == "opAssign" && func->parameterTypes.GetLength() == 1 && !func->IsReadOnly() &&
  2364. ((objectType->flags & asOBJ_SCRIPT_OBJECT) || func->parameterTypes[0].IsEqualExceptRefAndConst(asCDataType::CreateType(func->objectType, false))) )
  2365. {
  2366. if( func->objectType->beh.copy != 0 )
  2367. return ConfigError(asALREADY_REGISTERED, "RegisterObjectMethod", objectType->name.AddressOf(), declaration);
  2368. func->objectType->beh.copy = func->id;
  2369. func->AddRefInternal();
  2370. }
  2371. // Return the function id as success
  2372. return func->id;
  2373. }
  2374. // interface
  2375. int asCScriptEngine::RegisterGlobalFunction(const char *declaration, const asSFuncPtr &funcPointer, asDWORD callConv, void *auxiliary)
  2376. {
  2377. #ifdef AS_MAX_PORTABILITY
  2378. if( callConv != asCALL_GENERIC )
  2379. return ConfigError(asNOT_SUPPORTED, "RegisterGlobalFunction", declaration, 0);
  2380. #endif
  2381. asSSystemFunctionInterface internal;
  2382. int r = DetectCallingConvention(false, funcPointer, callConv, auxiliary, &internal);
  2383. if( r < 0 )
  2384. return ConfigError(r, "RegisterGlobalFunction", declaration, 0);
  2385. isPrepared = false;
  2386. // Put the system function in the list of system functions
  2387. asSSystemFunctionInterface *newInterface = asNEW(asSSystemFunctionInterface)(internal);
  2388. if( newInterface == 0 )
  2389. return ConfigError(asOUT_OF_MEMORY, "RegisterGlobalFunction", declaration, 0);
  2390. asCScriptFunction *func = asNEW(asCScriptFunction)(this, 0, asFUNC_SYSTEM);
  2391. if( func == 0 )
  2392. {
  2393. asDELETE(newInterface, asSSystemFunctionInterface);
  2394. return ConfigError(asOUT_OF_MEMORY, "RegisterGlobalFunction", declaration, 0);
  2395. }
  2396. func->sysFuncIntf = newInterface;
  2397. asCBuilder bld(this, 0);
  2398. r = bld.ParseFunctionDeclaration(0, declaration, func, true, &newInterface->paramAutoHandles, &newInterface->returnAutoHandle, defaultNamespace);
  2399. if( r < 0 )
  2400. {
  2401. // Set as dummy function before deleting
  2402. func->funcType = asFUNC_DUMMY;
  2403. asDELETE(func,asCScriptFunction);
  2404. return ConfigError(asINVALID_DECLARATION, "RegisterGlobalFunction", declaration, 0);
  2405. }
  2406. // TODO: namespace: What if the declaration defined an explicit namespace?
  2407. func->nameSpace = defaultNamespace;
  2408. // Check name conflicts
  2409. r = bld.CheckNameConflict(func->name.AddressOf(), 0, 0, defaultNamespace, false);
  2410. if( r < 0 )
  2411. {
  2412. // Set as dummy function before deleting
  2413. func->funcType = asFUNC_DUMMY;
  2414. asDELETE(func,asCScriptFunction);
  2415. return ConfigError(asNAME_TAKEN, "RegisterGlobalFunction", declaration, 0);
  2416. }
  2417. // Make sure the function is not identical to a previously registered function
  2418. asUINT n;
  2419. const asCArray<unsigned int> &idxs = registeredGlobalFuncs.GetIndexes(func->nameSpace, func->name);
  2420. for( n = 0; n < idxs.GetLength(); n++ )
  2421. {
  2422. asCScriptFunction *f = registeredGlobalFuncs.Get(idxs[n]);
  2423. if( f->IsSignatureExceptNameAndReturnTypeEqual(func) )
  2424. {
  2425. func->funcType = asFUNC_DUMMY;
  2426. asDELETE(func,asCScriptFunction);
  2427. return ConfigError(asALREADY_REGISTERED, "RegisterGlobalFunction", declaration, 0);
  2428. }
  2429. }
  2430. func->id = GetNextScriptFunctionId();
  2431. AddScriptFunction(func);
  2432. currentGroup->scriptFunctions.PushLast(func);
  2433. func->accessMask = defaultAccessMask;
  2434. registeredGlobalFuncs.Put(func);
  2435. // If parameter type from other groups are used, add references
  2436. currentGroup->AddReferencesForFunc(this, func);
  2437. // Return the function id as success
  2438. return func->id;
  2439. }
  2440. // interface
  2441. asUINT asCScriptEngine::GetGlobalFunctionCount() const
  2442. {
  2443. // Don't count the builtin delegate factory
  2444. return asUINT(registeredGlobalFuncs.GetSize()-1);
  2445. }
  2446. // interface
  2447. asIScriptFunction *asCScriptEngine::GetGlobalFunctionByIndex(asUINT index) const
  2448. {
  2449. // Don't count the builtin delegate factory
  2450. index++;
  2451. if( index >= registeredGlobalFuncs.GetSize() )
  2452. return 0;
  2453. return static_cast<asIScriptFunction*>(const_cast<asCScriptFunction*>(registeredGlobalFuncs.Get(index)));
  2454. }
  2455. // interface
  2456. asIScriptFunction *asCScriptEngine::GetGlobalFunctionByDecl(const char *decl) const
  2457. {
  2458. asCBuilder bld(const_cast<asCScriptEngine*>(this), 0);
  2459. // Don't write parser errors to the message callback
  2460. bld.silent = true;
  2461. asCScriptFunction func(const_cast<asCScriptEngine*>(this), 0, asFUNC_DUMMY);
  2462. int r = bld.ParseFunctionDeclaration(0, decl, &func, false, 0, 0, defaultNamespace);
  2463. if( r < 0 )
  2464. return 0;
  2465. asSNameSpace *ns = defaultNamespace;
  2466. // Search script functions for matching interface
  2467. while( ns )
  2468. {
  2469. asIScriptFunction *f = 0;
  2470. const asCArray<unsigned int> &idxs = registeredGlobalFuncs.GetIndexes(ns, func.name);
  2471. for( unsigned int n = 0; n < idxs.GetLength(); n++ )
  2472. {
  2473. const asCScriptFunction *funcPtr = registeredGlobalFuncs.Get(idxs[n]);
  2474. if( funcPtr->objectType == 0 &&
  2475. func.returnType == funcPtr->returnType &&
  2476. func.parameterTypes.GetLength() == funcPtr->parameterTypes.GetLength()
  2477. )
  2478. {
  2479. bool match = true;
  2480. for( asUINT p = 0; p < func.parameterTypes.GetLength(); ++p )
  2481. {
  2482. if( func.parameterTypes[p] != funcPtr->parameterTypes[p] )
  2483. {
  2484. match = false;
  2485. break;
  2486. }
  2487. }
  2488. if( match )
  2489. {
  2490. if( f == 0 )
  2491. f = const_cast<asCScriptFunction*>(funcPtr);
  2492. else
  2493. // Multiple functions
  2494. return 0;
  2495. }
  2496. }
  2497. }
  2498. if( f )
  2499. return f;
  2500. // Recursively search parent namespaces
  2501. ns = GetParentNameSpace(ns);
  2502. }
  2503. return 0;
  2504. }
  2505. asCTypeInfo *asCScriptEngine::GetRegisteredType(const asCString &type, asSNameSpace *ns) const
  2506. {
  2507. asSMapNode<asSNameSpaceNamePair, asCTypeInfo *> *cursor;
  2508. if( allRegisteredTypes.MoveTo(&cursor, asSNameSpaceNamePair(ns, type)) )
  2509. return cursor->value;
  2510. return 0;
  2511. }
  2512. void asCScriptEngine::PrepareEngine()
  2513. {
  2514. if( isPrepared ) return;
  2515. if( configFailed ) return;
  2516. asUINT n;
  2517. for( n = 0; n < scriptFunctions.GetLength(); n++ )
  2518. {
  2519. // Determine the host application interface
  2520. if( scriptFunctions[n] && scriptFunctions[n]->funcType == asFUNC_SYSTEM )
  2521. {
  2522. if( scriptFunctions[n]->sysFuncIntf->callConv == ICC_GENERIC_FUNC ||
  2523. scriptFunctions[n]->sysFuncIntf->callConv == ICC_GENERIC_METHOD )
  2524. PrepareSystemFunctionGeneric(scriptFunctions[n], scriptFunctions[n]->sysFuncIntf, this);
  2525. else
  2526. PrepareSystemFunction(scriptFunctions[n], scriptFunctions[n]->sysFuncIntf, this);
  2527. }
  2528. }
  2529. // Validate object type registrations
  2530. for( n = 0; n < registeredObjTypes.GetLength(); n++ )
  2531. {
  2532. asCObjectType *type = registeredObjTypes[n];
  2533. if( type && !(type->flags & asOBJ_SCRIPT_OBJECT) )
  2534. {
  2535. bool missingBehaviour = false;
  2536. const char *infoMsg = 0;
  2537. // Verify that GC types have all behaviours
  2538. if( type->flags & asOBJ_GC )
  2539. {
  2540. if (type->flags & asOBJ_REF)
  2541. {
  2542. if (type->beh.addref == 0 ||
  2543. type->beh.release == 0 ||
  2544. type->beh.gcGetRefCount == 0 ||
  2545. type->beh.gcSetFlag == 0 ||
  2546. type->beh.gcGetFlag == 0 ||
  2547. type->beh.gcEnumReferences == 0 ||
  2548. type->beh.gcReleaseAllReferences == 0)
  2549. {
  2550. infoMsg = TXT_GC_REQUIRE_ADD_REL_GC_BEHAVIOUR;
  2551. missingBehaviour = true;
  2552. }
  2553. }
  2554. else
  2555. {
  2556. if (type->beh.gcEnumReferences == 0)
  2557. {
  2558. infoMsg = TXT_VALUE_GC_REQUIRE_GC_BEHAVIOUR;
  2559. missingBehaviour = true;
  2560. }
  2561. }
  2562. }
  2563. // Verify that scoped ref types have the release behaviour
  2564. if( type->flags & asOBJ_SCOPED )
  2565. {
  2566. if( type->beh.release == 0 )
  2567. {
  2568. infoMsg = TXT_SCOPE_REQUIRE_REL_BEHAVIOUR;
  2569. missingBehaviour = true;
  2570. }
  2571. }
  2572. // Verify that ref types have add ref and release behaviours
  2573. if( (type->flags & asOBJ_REF) &&
  2574. !(type->flags & asOBJ_SCOPED) &&
  2575. !(type->flags & asOBJ_NOHANDLE) &&
  2576. !(type->flags & asOBJ_NOCOUNT) )
  2577. {
  2578. if( type->beh.addref == 0 ||
  2579. type->beh.release == 0 )
  2580. {
  2581. infoMsg = TXT_REF_REQUIRE_ADD_REL_BEHAVIOUR;
  2582. missingBehaviour = true;
  2583. }
  2584. }
  2585. // Verify that non-pod value types have the constructor and destructor registered
  2586. if( (type->flags & asOBJ_VALUE) &&
  2587. !(type->flags & asOBJ_POD) )
  2588. {
  2589. if( type->beh.constructors.GetLength() == 0 ||
  2590. type->beh.destruct == 0 )
  2591. {
  2592. infoMsg = TXT_NON_POD_REQUIRE_CONSTR_DESTR_BEHAVIOUR;
  2593. missingBehaviour = true;
  2594. }
  2595. }
  2596. if( missingBehaviour )
  2597. {
  2598. asCString str;
  2599. str.Format(TXT_TYPE_s_IS_MISSING_BEHAVIOURS, type->name.AddressOf());
  2600. WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  2601. WriteMessage("", 0, 0, asMSGTYPE_INFORMATION, infoMsg);
  2602. ConfigError(asINVALID_CONFIGURATION, 0, 0, 0);
  2603. }
  2604. }
  2605. }
  2606. isPrepared = true;
  2607. }
  2608. int asCScriptEngine::ConfigError(int err, const char *funcName, const char *arg1, const char *arg2)
  2609. {
  2610. configFailed = true;
  2611. if( funcName )
  2612. {
  2613. asCString str;
  2614. if( arg1 )
  2615. {
  2616. if( arg2 )
  2617. str.Format(TXT_FAILED_IN_FUNC_s_WITH_s_AND_s_s_d, funcName, arg1, arg2, errorNames[-err], err);
  2618. else
  2619. str.Format(TXT_FAILED_IN_FUNC_s_WITH_s_s_d, funcName, arg1, errorNames[-err], err);
  2620. }
  2621. else
  2622. str.Format(TXT_FAILED_IN_FUNC_s_s_d, funcName, errorNames[-err], err);
  2623. WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  2624. }
  2625. return err;
  2626. }
  2627. // interface
  2628. int asCScriptEngine::RegisterDefaultArrayType(const char *type)
  2629. {
  2630. asCBuilder bld(this, 0);
  2631. asCDataType dt;
  2632. int r = bld.ParseDataType(type, &dt, defaultNamespace);
  2633. if( r < 0 ) return r;
  2634. if( dt.GetTypeInfo() == 0 ||
  2635. !(dt.GetTypeInfo()->GetFlags() & asOBJ_TEMPLATE) )
  2636. return asINVALID_TYPE;
  2637. defaultArrayObjectType = CastToObjectType(dt.GetTypeInfo());
  2638. defaultArrayObjectType->AddRefInternal();
  2639. return 0;
  2640. }
  2641. // interface
  2642. int asCScriptEngine::GetDefaultArrayTypeId() const
  2643. {
  2644. if( defaultArrayObjectType )
  2645. return GetTypeIdFromDataType(asCDataType::CreateType(defaultArrayObjectType, false));
  2646. return asINVALID_TYPE;
  2647. }
  2648. // interface
  2649. int asCScriptEngine::RegisterStringFactory(const char *datatype, asIStringFactory *factory)
  2650. {
  2651. if (factory == 0)
  2652. return ConfigError(asINVALID_ARG, "RegisterStringFactory", datatype, 0);
  2653. // Parse the data type
  2654. asCBuilder bld(this, 0);
  2655. asCDataType dt;
  2656. int r = bld.ParseDataType(datatype, &dt, defaultNamespace, true);
  2657. if (r < 0)
  2658. return ConfigError(asINVALID_TYPE, "RegisterStringFactory", datatype, 0);
  2659. // Validate the type. It must not be reference or handle
  2660. if (dt.IsReference() || dt.IsObjectHandle())
  2661. return ConfigError(asINVALID_TYPE, "RegisterStringFactory", datatype, 0);
  2662. // All string literals will be treated as const
  2663. dt.MakeReadOnly(true);
  2664. stringType = dt;
  2665. stringFactory = factory;
  2666. return asSUCCESS;
  2667. }
  2668. // interface
  2669. int asCScriptEngine::GetStringFactoryReturnTypeId(asDWORD *flags) const
  2670. {
  2671. if( stringFactory == 0 )
  2672. return asNO_FUNCTION;
  2673. if( flags )
  2674. *flags = 0;
  2675. return GetTypeIdFromDataType(stringType);
  2676. }
  2677. // internal
  2678. asCModule *asCScriptEngine::GetModule(const char *name, bool create)
  2679. {
  2680. // Accept null as well as zero-length string
  2681. if( name == 0 ) name = "";
  2682. asCModule *retModule = 0;
  2683. ACQUIRESHARED(engineRWLock);
  2684. if( lastModule && lastModule->name == name )
  2685. retModule = lastModule;
  2686. else
  2687. {
  2688. // TODO: optimize: Improve linear search
  2689. for( asUINT n = 0; n < scriptModules.GetLength(); ++n )
  2690. if( scriptModules[n] && scriptModules[n]->name == name )
  2691. {
  2692. retModule = scriptModules[n];
  2693. break;
  2694. }
  2695. }
  2696. RELEASESHARED(engineRWLock);
  2697. if( retModule )
  2698. {
  2699. ACQUIREEXCLUSIVE(engineRWLock);
  2700. lastModule = retModule;
  2701. RELEASEEXCLUSIVE(engineRWLock);
  2702. return retModule;
  2703. }
  2704. if( create )
  2705. {
  2706. retModule = asNEW(asCModule)(name, this);
  2707. if( retModule == 0 )
  2708. {
  2709. // Out of memory
  2710. return 0;
  2711. }
  2712. ACQUIREEXCLUSIVE(engineRWLock);
  2713. scriptModules.PushLast(retModule);
  2714. lastModule = retModule;
  2715. RELEASEEXCLUSIVE(engineRWLock);
  2716. }
  2717. return retModule;
  2718. }
  2719. asCModule *asCScriptEngine::GetModuleFromFuncId(int id)
  2720. {
  2721. if( id < 0 ) return 0;
  2722. if( id >= (int)scriptFunctions.GetLength() ) return 0;
  2723. asCScriptFunction *func = scriptFunctions[id];
  2724. if( func == 0 ) return 0;
  2725. return func->module;
  2726. }
  2727. // internal
  2728. int asCScriptEngine::RequestBuild()
  2729. {
  2730. ACQUIREEXCLUSIVE(engineRWLock);
  2731. if( isBuilding )
  2732. {
  2733. RELEASEEXCLUSIVE(engineRWLock);
  2734. return asBUILD_IN_PROGRESS;
  2735. }
  2736. isBuilding = true;
  2737. RELEASEEXCLUSIVE(engineRWLock);
  2738. return 0;
  2739. }
  2740. // internal
  2741. void asCScriptEngine::BuildCompleted()
  2742. {
  2743. // Always free up pooled memory after a completed build
  2744. memoryMgr.FreeUnusedMemory();
  2745. isBuilding = false;
  2746. }
  2747. void asCScriptEngine::RemoveTemplateInstanceType(asCObjectType *t)
  2748. {
  2749. // If there is a module that still owns the generated type, then don't remove it
  2750. if( t->module )
  2751. return;
  2752. // Don't remove it if there are external refernces
  2753. if( t->externalRefCount.get() )
  2754. return;
  2755. // Only remove the template instance type if no config group is using it
  2756. if( defaultGroup.generatedTemplateInstances.Exists(t) )
  2757. return;
  2758. for( asUINT n = 0; n < configGroups.GetLength(); n++ )
  2759. if( configGroups[n]->generatedTemplateInstances.Exists(t) )
  2760. return;
  2761. t->DestroyInternal();
  2762. templateInstanceTypes.RemoveValue(t);
  2763. generatedTemplateTypes.RemoveValue(t);
  2764. t->ReleaseInternal();
  2765. }
  2766. // internal
  2767. asCObjectType *asCScriptEngine::GetTemplateInstanceType(asCObjectType *templateType, asCArray<asCDataType> &subTypes, asCModule *requestingModule)
  2768. {
  2769. asUINT n;
  2770. // Is there any template instance type or template specialization already with this subtype?
  2771. for( n = 0; n < templateInstanceTypes.GetLength(); n++ )
  2772. {
  2773. asCObjectType *type = templateInstanceTypes[n];
  2774. if( type &&
  2775. type->name == templateType->name &&
  2776. type->nameSpace == templateType->nameSpace &&
  2777. type->templateSubTypes == subTypes )
  2778. {
  2779. // If the template instance is generated, then the module should hold a reference
  2780. // to it so the config group can determine see that the template type is in use.
  2781. // Template specializations will be treated as normal types
  2782. if( requestingModule && generatedTemplateTypes.Exists(type) )
  2783. {
  2784. if( type->module == 0 )
  2785. {
  2786. // Set the ownership of this template type
  2787. // It may be without ownership if it was previously created from application with for example GetTypeInfoByDecl
  2788. type->module = requestingModule;
  2789. }
  2790. if( !requestingModule->templateInstances.Exists(type) )
  2791. {
  2792. requestingModule->templateInstances.PushLast(type);
  2793. type->AddRefInternal();
  2794. }
  2795. }
  2796. return templateInstanceTypes[n];
  2797. }
  2798. }
  2799. // No previous template instance exists
  2800. // Make sure this template supports the subtype
  2801. for( n = 0; n < subTypes.GetLength(); n++ )
  2802. {
  2803. if( !templateType->acceptValueSubType && (subTypes[n].IsPrimitive() || (subTypes[n].GetTypeInfo()->flags & asOBJ_VALUE)) )
  2804. return 0;
  2805. if( !templateType->acceptRefSubType && (subTypes[n].IsObject() && (subTypes[n].GetTypeInfo()->flags & asOBJ_REF)) )
  2806. return 0;
  2807. }
  2808. // Create a new template instance type based on the templateType
  2809. asCObjectType *ot = asNEW(asCObjectType)(this);
  2810. if( ot == 0 )
  2811. {
  2812. // Out of memory
  2813. return 0;
  2814. }
  2815. ot->templateSubTypes = subTypes;
  2816. ot->flags = templateType->flags;
  2817. ot->size = templateType->size;
  2818. ot->name = templateType->name;
  2819. ot->nameSpace = templateType->nameSpace;
  2820. // If the template is being requested from a module, then the module should hold a reference to the type
  2821. if( requestingModule )
  2822. {
  2823. // Set the ownership of this template type
  2824. ot->module = requestingModule;
  2825. requestingModule->templateInstances.PushLast(ot);
  2826. ot->AddRefInternal();
  2827. }
  2828. else
  2829. {
  2830. // If the template type is not requested directly from a module, then set the ownership
  2831. // of it to the same module as one of the subtypes. If none of the subtypes are owned by]
  2832. // any module, the template instance will be without ownership and can be removed from the
  2833. // engine at any time (unless the application holds an external reference).
  2834. for( n = 0; n < subTypes.GetLength(); n++ )
  2835. {
  2836. if( subTypes[n].GetTypeInfo() )
  2837. {
  2838. ot->module = subTypes[n].GetTypeInfo()->module;
  2839. if( ot->module )
  2840. {
  2841. ot->module->templateInstances.PushLast(ot);
  2842. ot->AddRefInternal();
  2843. break;
  2844. }
  2845. }
  2846. }
  2847. }
  2848. // Before filling in the methods, call the template instance callback behaviour to validate the type
  2849. if( templateType->beh.templateCallback )
  2850. {
  2851. // If the validation is deferred then the validation will be done later,
  2852. // so it is necessary to continue the preparation of the template instance type
  2853. if( !deferValidationOfTemplateTypes )
  2854. {
  2855. asCScriptFunction *callback = scriptFunctions[templateType->beh.templateCallback];
  2856. bool dontGarbageCollect = false;
  2857. if( !CallGlobalFunctionRetBool(ot, &dontGarbageCollect, callback->sysFuncIntf, callback) )
  2858. {
  2859. // The type cannot be instantiated
  2860. ot->templateSubTypes.SetLength(0);
  2861. if( ot->module )
  2862. {
  2863. ot->module->templateInstances.RemoveValue(ot);
  2864. ot->ReleaseInternal();
  2865. }
  2866. ot->ReleaseInternal();
  2867. return 0;
  2868. }
  2869. // If the callback said this template instance won't be garbage collected then remove the flag
  2870. if( dontGarbageCollect )
  2871. ot->flags &= ~asOBJ_GC;
  2872. }
  2873. ot->beh.templateCallback = templateType->beh.templateCallback;
  2874. scriptFunctions[ot->beh.templateCallback]->AddRefInternal();
  2875. }
  2876. ot->methods = templateType->methods;
  2877. for( n = 0; n < ot->methods.GetLength(); n++ )
  2878. scriptFunctions[ot->methods[n]]->AddRefInternal();
  2879. if( templateType->flags & asOBJ_REF )
  2880. {
  2881. // Store the real factory in the constructor. This is used by the CreateScriptObject function.
  2882. // Otherwise it wouldn't be necessary to store the real factory ids.
  2883. ot->beh.construct = templateType->beh.factory;
  2884. ot->beh.constructors = templateType->beh.factories;
  2885. }
  2886. else
  2887. {
  2888. ot->beh.construct = templateType->beh.construct;
  2889. ot->beh.constructors = templateType->beh.constructors;
  2890. }
  2891. for( n = 0; n < ot->beh.constructors.GetLength(); n++ )
  2892. scriptFunctions[ot->beh.constructors[n]]->AddRefInternal();
  2893. // Before proceeding with the generation of the template functions for the template instance it is necessary
  2894. // to include the new template instance type in the list of known types, otherwise it is possible that we get
  2895. // a infinite recursive loop as the template instance type is requested again during the generation of the
  2896. // template functions.
  2897. templateInstanceTypes.PushLast(ot);
  2898. // Store the template instance types that have been created automatically by the engine from a template type
  2899. // The object types in templateInstanceTypes that are not also in generatedTemplateTypes are registered template specializations
  2900. generatedTemplateTypes.PushLast(ot);
  2901. // Any child funcdefs must be copied to the template instance (with adjustments in case of template subtypes)
  2902. // This must be done before resolving other methods, to make sure the other methods that may refer to the
  2903. // templated funcdef will resolve to the new funcdef
  2904. for (n = 0; n < templateType->childFuncDefs.GetLength(); n++)
  2905. {
  2906. asCFuncdefType *funcdef = GenerateNewTemplateFuncdef(templateType, ot, templateType->childFuncDefs[n]);
  2907. funcdef->parentClass = ot;
  2908. ot->childFuncDefs.PushLast(funcdef);
  2909. }
  2910. // As the new template type is instantiated the engine should
  2911. // generate new functions to substitute the ones with the template subtype.
  2912. for( n = 0; n < ot->beh.constructors.GetLength(); n++ )
  2913. {
  2914. int funcId = ot->beh.constructors[n];
  2915. asCScriptFunction *func = scriptFunctions[funcId];
  2916. if( GenerateNewTemplateFunction(templateType, ot, func, &func) )
  2917. {
  2918. // Release the old function, the new one already has its ref count set to 1
  2919. scriptFunctions[funcId]->ReleaseInternal();
  2920. ot->beh.constructors[n] = func->id;
  2921. if( ot->beh.construct == funcId )
  2922. ot->beh.construct = func->id;
  2923. }
  2924. }
  2925. ot->beh.factory = 0;
  2926. if( templateType->flags & asOBJ_REF )
  2927. {
  2928. // Generate factory stubs for each of the factories
  2929. for( n = 0; n < ot->beh.constructors.GetLength(); n++ )
  2930. {
  2931. asCScriptFunction *func = GenerateTemplateFactoryStub(templateType, ot, ot->beh.constructors[n]);
  2932. ot->beh.factories.PushLast(func->id);
  2933. // Set the default factory as well
  2934. if( ot->beh.constructors[n] == ot->beh.construct )
  2935. ot->beh.factory = func->id;
  2936. }
  2937. }
  2938. else
  2939. {
  2940. // Generate factory stubs for each of the constructors
  2941. for( n = 0; n < ot->beh.constructors.GetLength(); n++ )
  2942. {
  2943. asCScriptFunction *func = GenerateTemplateFactoryStub(templateType, ot, ot->beh.constructors[n]);
  2944. if( ot->beh.constructors[n] == ot->beh.construct )
  2945. ot->beh.construct = func->id;
  2946. // Release previous constructor
  2947. scriptFunctions[ot->beh.constructors[n]]->ReleaseInternal();
  2948. ot->beh.constructors[n] = func->id;
  2949. }
  2950. }
  2951. // Generate stub for the list factory as well
  2952. if( templateType->beh.listFactory )
  2953. {
  2954. asCScriptFunction *func = GenerateTemplateFactoryStub(templateType, ot, templateType->beh.listFactory);
  2955. // Rename the function to easily identify it in LoadByteCode
  2956. func->name = "$list";
  2957. ot->beh.listFactory = func->id;
  2958. }
  2959. ot->beh.addref = templateType->beh.addref;
  2960. if( scriptFunctions[ot->beh.addref] ) scriptFunctions[ot->beh.addref]->AddRefInternal();
  2961. ot->beh.release = templateType->beh.release;
  2962. if( scriptFunctions[ot->beh.release] ) scriptFunctions[ot->beh.release]->AddRefInternal();
  2963. ot->beh.destruct = templateType->beh.destruct;
  2964. if( scriptFunctions[ot->beh.destruct] ) scriptFunctions[ot->beh.destruct]->AddRefInternal();
  2965. ot->beh.copy = templateType->beh.copy;
  2966. if( scriptFunctions[ot->beh.copy] ) scriptFunctions[ot->beh.copy]->AddRefInternal();
  2967. ot->beh.gcGetRefCount = templateType->beh.gcGetRefCount;
  2968. if( scriptFunctions[ot->beh.gcGetRefCount] ) scriptFunctions[ot->beh.gcGetRefCount]->AddRefInternal();
  2969. ot->beh.gcSetFlag = templateType->beh.gcSetFlag;
  2970. if( scriptFunctions[ot->beh.gcSetFlag] ) scriptFunctions[ot->beh.gcSetFlag]->AddRefInternal();
  2971. ot->beh.gcGetFlag = templateType->beh.gcGetFlag;
  2972. if( scriptFunctions[ot->beh.gcGetFlag] ) scriptFunctions[ot->beh.gcGetFlag]->AddRefInternal();
  2973. ot->beh.gcEnumReferences = templateType->beh.gcEnumReferences;
  2974. if( scriptFunctions[ot->beh.gcEnumReferences] ) scriptFunctions[ot->beh.gcEnumReferences]->AddRefInternal();
  2975. ot->beh.gcReleaseAllReferences = templateType->beh.gcReleaseAllReferences;
  2976. if( scriptFunctions[ot->beh.gcReleaseAllReferences] ) scriptFunctions[ot->beh.gcReleaseAllReferences]->AddRefInternal();
  2977. ot->beh.getWeakRefFlag = templateType->beh.getWeakRefFlag;
  2978. if( scriptFunctions[ot->beh.getWeakRefFlag] ) scriptFunctions[ot->beh.getWeakRefFlag]->AddRefInternal();
  2979. // As the new template type is instantiated, the engine should
  2980. // generate new functions to substitute the ones with the template subtype.
  2981. for( n = 0; n < ot->methods.GetLength(); n++ )
  2982. {
  2983. int funcId = ot->methods[n];
  2984. asCScriptFunction *func = scriptFunctions[funcId];
  2985. if( GenerateNewTemplateFunction(templateType, ot, func, &func) )
  2986. {
  2987. // Release the old function, the new one already has its ref count set to 1
  2988. scriptFunctions[funcId]->ReleaseInternal();
  2989. ot->methods[n] = func->id;
  2990. }
  2991. }
  2992. // Increase ref counter for sub type if it is an object type
  2993. for( n = 0; n < ot->templateSubTypes.GetLength(); n++ )
  2994. if( ot->templateSubTypes[n].GetTypeInfo() )
  2995. ot->templateSubTypes[n].GetTypeInfo()->AddRefInternal();
  2996. // Copy the properties to the template instance
  2997. for( n = 0; n < templateType->properties.GetLength(); n++ )
  2998. {
  2999. asCObjectProperty *prop = templateType->properties[n];
  3000. ot->properties.PushLast(asNEW(asCObjectProperty)(*prop));
  3001. if( prop->type.GetTypeInfo() )
  3002. prop->type.GetTypeInfo()->AddRefInternal();
  3003. }
  3004. return ot;
  3005. }
  3006. // interface
  3007. asILockableSharedBool *asCScriptEngine::GetWeakRefFlagOfScriptObject(void *obj, const asITypeInfo *type) const
  3008. {
  3009. // Make sure it is not a null pointer
  3010. if( obj == 0 || type == 0 ) return 0;
  3011. const asCObjectType *objType = static_cast<const asCObjectType *>(type);
  3012. asILockableSharedBool *dest = 0;
  3013. if( objType->beh.getWeakRefFlag )
  3014. {
  3015. // Call the getweakrefflag behaviour
  3016. dest = reinterpret_cast<asILockableSharedBool*>(CallObjectMethodRetPtr(obj, objType->beh.getWeakRefFlag));
  3017. }
  3018. return dest;
  3019. }
  3020. // internal
  3021. // orig is the parameter type that is to be replaced
  3022. // tmpl is the registered template. Used to find which subtype is being replaced
  3023. // ot is the new template instance that is being created. Used to find the target type
  3024. asCDataType asCScriptEngine::DetermineTypeForTemplate(const asCDataType &orig, asCObjectType *tmpl, asCObjectType *ot)
  3025. {
  3026. asCDataType dt;
  3027. if( orig.GetTypeInfo() && (orig.GetTypeInfo()->flags & asOBJ_TEMPLATE_SUBTYPE) )
  3028. {
  3029. bool found = false;
  3030. for( asUINT n = 0; n < tmpl->templateSubTypes.GetLength(); n++ )
  3031. {
  3032. if( orig.GetTypeInfo() == tmpl->templateSubTypes[n].GetTypeInfo() )
  3033. {
  3034. found = true;
  3035. dt = ot->templateSubTypes[n];
  3036. if( orig.IsObjectHandle() && !ot->templateSubTypes[n].IsObjectHandle() )
  3037. {
  3038. dt.MakeHandle(true, true);
  3039. asASSERT(dt.IsObjectHandle());
  3040. if( orig.IsHandleToConst() )
  3041. dt.MakeHandleToConst(true);
  3042. dt.MakeReference(orig.IsReference());
  3043. dt.MakeReadOnly(orig.IsReadOnly());
  3044. }
  3045. else
  3046. {
  3047. // The target type is a handle, then check if the application
  3048. // wants this handle to be to a const object. This is done by
  3049. // flagging the type with 'if_handle_then_const' in the declaration.
  3050. if (dt.IsObjectHandle() && orig.HasIfHandleThenConst())
  3051. dt.MakeHandleToConst(true);
  3052. dt.MakeReference(orig.IsReference());
  3053. dt.MakeReadOnly(ot->templateSubTypes[n].IsReadOnly() || orig.IsReadOnly());
  3054. // If the target is a @& then don't make the handle const,
  3055. // as it is not possible to declare functions with @const &
  3056. if (orig.IsReference() && dt.IsObjectHandle())
  3057. dt.MakeReadOnly(false);
  3058. }
  3059. break;
  3060. }
  3061. }
  3062. asASSERT( found );
  3063. UNUSED_VAR( found );
  3064. }
  3065. else if( orig.GetTypeInfo() == tmpl )
  3066. {
  3067. if( orig.IsObjectHandle() )
  3068. dt = asCDataType::CreateObjectHandle(ot, false);
  3069. else
  3070. dt = asCDataType::CreateType(ot, false);
  3071. dt.MakeReference(orig.IsReference());
  3072. dt.MakeReadOnly(orig.IsReadOnly());
  3073. }
  3074. else if( orig.GetTypeInfo() && (orig.GetTypeInfo()->flags & asOBJ_TEMPLATE) )
  3075. {
  3076. // The type is itself a template, so it is necessary to find the correct template instance type
  3077. asCArray<asCDataType> tmplSubTypes;
  3078. asCObjectType *origType = CastToObjectType(orig.GetTypeInfo());
  3079. bool needInstance = true;
  3080. // Find the matching replacements for the subtypes
  3081. for( asUINT n = 0; n < origType->templateSubTypes.GetLength(); n++ )
  3082. {
  3083. if( origType->templateSubTypes[n].GetTypeInfo() == 0 ||
  3084. !(origType->templateSubTypes[n].GetTypeInfo()->flags & asOBJ_TEMPLATE_SUBTYPE) )
  3085. {
  3086. // The template is already an instance so we shouldn't attempt to create another instance
  3087. needInstance = false;
  3088. break;
  3089. }
  3090. for( asUINT m = 0; m < tmpl->templateSubTypes.GetLength(); m++ )
  3091. if( origType->templateSubTypes[n].GetTypeInfo() == tmpl->templateSubTypes[m].GetTypeInfo() )
  3092. tmplSubTypes.PushLast(ot->templateSubTypes[m]);
  3093. if( tmplSubTypes.GetLength() != n+1 )
  3094. {
  3095. asASSERT( false );
  3096. return orig;
  3097. }
  3098. }
  3099. asCObjectType *ntype = origType;
  3100. if( needInstance )
  3101. {
  3102. // Always find the original template type when creating a new template instance otherwise the
  3103. // generation will fail since it will attempt to create factory stubs when they already exists, etc
  3104. for( asUINT n = 0; n < registeredTemplateTypes.GetLength(); n++ )
  3105. if( registeredTemplateTypes[n]->name == origType->name &&
  3106. registeredTemplateTypes[n]->nameSpace == origType->nameSpace )
  3107. {
  3108. origType = registeredTemplateTypes[n];
  3109. break;
  3110. }
  3111. ntype = GetTemplateInstanceType(origType, tmplSubTypes, ot->module);
  3112. if( ntype == 0 )
  3113. {
  3114. // It not possible to instantiate the subtype
  3115. asASSERT( false );
  3116. ntype = tmpl;
  3117. }
  3118. }
  3119. if( orig.IsObjectHandle() )
  3120. dt = asCDataType::CreateObjectHandle(ntype, false);
  3121. else
  3122. dt = asCDataType::CreateType(ntype, false);
  3123. dt.MakeReference(orig.IsReference());
  3124. dt.MakeReadOnly(orig.IsReadOnly());
  3125. }
  3126. else if (orig.GetTypeInfo() && (orig.GetTypeInfo()->flags & asOBJ_FUNCDEF) && CastToFuncdefType(orig.GetTypeInfo())->parentClass == tmpl)
  3127. {
  3128. // The type is a child funcdef. Find the corresponding child funcdef in the template instance
  3129. for (asUINT n = 0; n < ot->childFuncDefs.GetLength(); n++)
  3130. {
  3131. if (ot->childFuncDefs[n]->name == orig.GetTypeInfo()->name)
  3132. {
  3133. dt = orig;
  3134. dt.SetTypeInfo(ot->childFuncDefs[n]);
  3135. }
  3136. }
  3137. }
  3138. else
  3139. dt = orig;
  3140. return dt;
  3141. }
  3142. // internal
  3143. asCScriptFunction *asCScriptEngine::GenerateTemplateFactoryStub(asCObjectType *templateType, asCObjectType *ot, int factoryId)
  3144. {
  3145. asCScriptFunction *factory = scriptFunctions[factoryId];
  3146. // By first instantiating the function as a dummy and then changing it to be a script function
  3147. // I avoid having it added to the garbage collector. As it is known that this object will stay
  3148. // alive until the template instance is no longer used there is no need to have the GC check
  3149. // this function all the time.
  3150. asCScriptFunction *func = asNEW(asCScriptFunction)(this, 0, asFUNC_DUMMY);
  3151. if( func == 0 )
  3152. {
  3153. // Out of memory
  3154. return 0;
  3155. }
  3156. func->funcType = asFUNC_SCRIPT;
  3157. func->AllocateScriptFunctionData();
  3158. func->id = GetNextScriptFunctionId();
  3159. AddScriptFunction(func);
  3160. func->traits = factory->traits;
  3161. func->SetShared(true);
  3162. if( templateType->flags & asOBJ_REF )
  3163. {
  3164. func->name = "$fact";
  3165. func->returnType = asCDataType::CreateObjectHandle(ot, false);
  3166. }
  3167. else
  3168. {
  3169. func->name = "$beh0";
  3170. func->returnType = factory->returnType; // constructors return nothing
  3171. func->objectType = ot;
  3172. func->objectType->AddRefInternal();
  3173. }
  3174. // Skip the first parameter as this is the object type pointer that the stub will add
  3175. func->parameterTypes.SetLength(factory->parameterTypes.GetLength()-1);
  3176. func->parameterNames.SetLength(factory->parameterNames.GetLength()-1);
  3177. func->inOutFlags.SetLength(factory->inOutFlags.GetLength()-1);
  3178. func->defaultArgs.SetLength(factory->defaultArgs.GetLength()-1);
  3179. for( asUINT p = 1; p < factory->parameterTypes.GetLength(); p++ )
  3180. {
  3181. func->parameterTypes[p-1] = factory->parameterTypes[p];
  3182. func->parameterNames[p-1] = factory->parameterNames[p];
  3183. func->inOutFlags[p-1] = factory->inOutFlags[p];
  3184. func->defaultArgs[p-1] = factory->defaultArgs[p] ? asNEW(asCString)(*factory->defaultArgs[p]) : 0;
  3185. }
  3186. func->scriptData->objVariablesOnHeap = 0;
  3187. // Generate the bytecode for the factory stub
  3188. asUINT bcLength = asBCTypeSize[asBCInfo[asBC_OBJTYPE].type] +
  3189. asBCTypeSize[asBCInfo[asBC_CALLSYS].type] +
  3190. asBCTypeSize[asBCInfo[asBC_RET].type];
  3191. if( ep.includeJitInstructions )
  3192. bcLength += asBCTypeSize[asBCInfo[asBC_JitEntry].type];
  3193. if( templateType->flags & asOBJ_VALUE )
  3194. bcLength += asBCTypeSize[asBCInfo[asBC_SwapPtr].type];
  3195. func->scriptData->byteCode.SetLength(bcLength);
  3196. asDWORD *bc = func->scriptData->byteCode.AddressOf();
  3197. if( ep.includeJitInstructions )
  3198. {
  3199. *(asBYTE*)bc = asBC_JitEntry;
  3200. *(asPWORD*)(bc+1) = 0;
  3201. bc += asBCTypeSize[asBCInfo[asBC_JitEntry].type];
  3202. }
  3203. *(asBYTE*)bc = asBC_OBJTYPE;
  3204. *(asPWORD*)(bc+1) = (asPWORD)ot;
  3205. bc += asBCTypeSize[asBCInfo[asBC_OBJTYPE].type];
  3206. if( templateType->flags & asOBJ_VALUE )
  3207. {
  3208. // Swap the object pointer with the object type
  3209. *(asBYTE*)bc = asBC_SwapPtr;
  3210. bc += asBCTypeSize[asBCInfo[asBC_SwapPtr].type];
  3211. }
  3212. *(asBYTE*)bc = asBC_CALLSYS;
  3213. *(asDWORD*)(bc+1) = factoryId;
  3214. bc += asBCTypeSize[asBCInfo[asBC_CALLSYS].type];
  3215. *(asBYTE*)bc = asBC_RET;
  3216. *(((asWORD*)bc)+1) = (asWORD)func->GetSpaceNeededForArguments() + (func->objectType ? AS_PTR_SIZE : 0);
  3217. func->AddReferences();
  3218. func->scriptData->stackNeeded = AS_PTR_SIZE;
  3219. // Tell the virtual machine not to clean up the object on exception
  3220. func->dontCleanUpOnException = true;
  3221. func->JITCompile();
  3222. // Need to translate the list pattern too so the VM and compiler will know the correct type of the members
  3223. if( factory->listPattern )
  3224. {
  3225. asSListPatternNode *n = factory->listPattern;
  3226. asSListPatternNode *last = 0;
  3227. while( n )
  3228. {
  3229. asSListPatternNode *newNode = n->Duplicate();
  3230. if( newNode->type == asLPT_TYPE )
  3231. {
  3232. asSListPatternDataTypeNode *typeNode = reinterpret_cast<asSListPatternDataTypeNode*>(newNode);
  3233. typeNode->dataType = DetermineTypeForTemplate(typeNode->dataType, templateType, ot);
  3234. }
  3235. if( last )
  3236. last->next = newNode;
  3237. else
  3238. func->listPattern = newNode;
  3239. last = newNode;
  3240. n = n->next;
  3241. }
  3242. }
  3243. return func;
  3244. }
  3245. bool asCScriptEngine::RequireTypeReplacement(asCDataType &type, asCObjectType *templateType)
  3246. {
  3247. if( type.GetTypeInfo() == templateType ) return true;
  3248. if( type.GetTypeInfo() && (type.GetTypeInfo()->flags & asOBJ_TEMPLATE_SUBTYPE) ) return true;
  3249. if( type.GetTypeInfo() && (type.GetTypeInfo()->flags & asOBJ_TEMPLATE) )
  3250. {
  3251. asCObjectType *ot = CastToObjectType(type.GetTypeInfo());
  3252. for( asUINT n = 0; n < ot->templateSubTypes.GetLength(); n++ )
  3253. if( ot->templateSubTypes[n].GetTypeInfo() &&
  3254. ot->templateSubTypes[n].GetTypeInfo()->flags & asOBJ_TEMPLATE_SUBTYPE )
  3255. return true;
  3256. }
  3257. if (type.GetTypeInfo() && (type.GetTypeInfo()->flags & asOBJ_FUNCDEF) && CastToFuncdefType(type.GetTypeInfo())->parentClass == templateType)
  3258. return true;
  3259. return false;
  3260. }
  3261. bool asCScriptEngine::GenerateNewTemplateFunction(asCObjectType *templateType, asCObjectType *ot, asCScriptFunction *func, asCScriptFunction **newFunc)
  3262. {
  3263. // Due to the objectType it is always required to generate a new function,
  3264. // even if none of the function arguments needs to be changed.
  3265. /*
  3266. // TODO: Can we store the new function in some other optimized way to avoid
  3267. // duplicating all information just because of the different objectType member?
  3268. bool needNewFunc = false;
  3269. if( RequireTypeReplacement(func->returnType, templateType) )
  3270. needNewFunc = true;
  3271. else
  3272. {
  3273. for( asUINT p = 0; p < func->parameterTypes.GetLength(); p++ )
  3274. {
  3275. if( RequireTypeReplacement(func->parameterTypes[p], templateType) )
  3276. {
  3277. needNewFunc = true;
  3278. break;
  3279. }
  3280. }
  3281. }
  3282. if( !needNewFunc )
  3283. return false;
  3284. */
  3285. asCScriptFunction *func2 = asNEW(asCScriptFunction)(this, 0, func->funcType);
  3286. if( func2 == 0 )
  3287. {
  3288. // Out of memory
  3289. return false;
  3290. }
  3291. func2->name = func->name;
  3292. func2->returnType = DetermineTypeForTemplate(func->returnType, templateType, ot);
  3293. func2->parameterTypes.SetLength(func->parameterTypes.GetLength());
  3294. for (asUINT p = 0; p < func->parameterTypes.GetLength(); p++)
  3295. func2->parameterTypes[p] = DetermineTypeForTemplate(func->parameterTypes[p], templateType, ot);
  3296. for (asUINT n = 0; n < func->defaultArgs.GetLength(); n++)
  3297. if (func->defaultArgs[n])
  3298. func2->defaultArgs.PushLast(asNEW(asCString)(*func->defaultArgs[n]));
  3299. else
  3300. func2->defaultArgs.PushLast(0);
  3301. // TODO: template: Must be careful when instantiating templates for garbage collected types
  3302. // If the template hasn't been registered with the behaviours, it shouldn't
  3303. // permit instantiation of garbage collected types that in turn may refer to
  3304. // this instance.
  3305. func2->parameterNames = func->parameterNames;
  3306. func2->inOutFlags = func->inOutFlags;
  3307. func2->traits = func->traits;
  3308. func2->SetReadOnly(func->IsReadOnly());
  3309. func2->objectType = ot;
  3310. func2->objectType->AddRefInternal();
  3311. func2->sysFuncIntf = asNEW(asSSystemFunctionInterface)(*func->sysFuncIntf);
  3312. // Adjust the clean up instructions
  3313. if( func2->sysFuncIntf->callConv == ICC_GENERIC_FUNC ||
  3314. func2->sysFuncIntf->callConv == ICC_GENERIC_METHOD )
  3315. PrepareSystemFunctionGeneric(func2, func2->sysFuncIntf, this);
  3316. else
  3317. PrepareSystemFunction(func2, func2->sysFuncIntf, this);
  3318. func2->id = GetNextScriptFunctionId();
  3319. AddScriptFunction(func2);
  3320. // Return the new function
  3321. *newFunc = func2;
  3322. return true;
  3323. }
  3324. asCFuncdefType *asCScriptEngine::GenerateNewTemplateFuncdef(asCObjectType *templateType, asCObjectType *ot, asCFuncdefType *func)
  3325. {
  3326. // TODO: Only generate the new funcdef if it used the template subtypes.
  3327. // Remember to also update the clean up in asCObjectType::DestroyInternal so it doesn't delete
  3328. // child funcdefs that have not been created specificially for the template instance.
  3329. // Perhaps a new funcdef is always needed, since the funcdef will have a reference to the
  3330. // parent class (in this case the template instance).
  3331. asCScriptFunction *func2 = asNEW(asCScriptFunction)(this, 0, func->funcdef->funcType);
  3332. if (func2 == 0)
  3333. {
  3334. // Out of memory
  3335. return 0;
  3336. }
  3337. func2->name = func->name;
  3338. func2->returnType = DetermineTypeForTemplate(func->funcdef->returnType, templateType, ot);
  3339. func2->parameterTypes.SetLength(func->funcdef->parameterTypes.GetLength());
  3340. for (asUINT p = 0; p < func->funcdef->parameterTypes.GetLength(); p++)
  3341. func2->parameterTypes[p] = DetermineTypeForTemplate(func->funcdef->parameterTypes[p], templateType, ot);
  3342. // TODO: template: Must be careful when instantiating templates for garbage collected types
  3343. // If the template hasn't been registered with the behaviours, it shouldn't
  3344. // permit instantiation of garbage collected types that in turn may refer to
  3345. // this instance.
  3346. func2->inOutFlags = func->funcdef->inOutFlags;
  3347. func2->SetReadOnly(func->funcdef->IsReadOnly());
  3348. asASSERT(func->funcdef->objectType == 0);
  3349. asASSERT(func->funcdef->sysFuncIntf == 0);
  3350. func2->id = GetNextScriptFunctionId();
  3351. AddScriptFunction(func2);
  3352. asCFuncdefType *fdt2 = asNEW(asCFuncdefType)(this, func2);
  3353. funcDefs.PushLast(fdt2); // don't increase refCount as the constructor already set it to 1
  3354. // Return the new function
  3355. return fdt2;
  3356. }
  3357. void asCScriptEngine::CallObjectMethod(void *obj, int func) const
  3358. {
  3359. asCScriptFunction *s = scriptFunctions[func];
  3360. asASSERT( s != 0 );
  3361. CallObjectMethod(obj, s->sysFuncIntf, s);
  3362. }
  3363. void asCScriptEngine::CallObjectMethod(void *obj, asSSystemFunctionInterface *i, asCScriptFunction *s) const
  3364. {
  3365. #if defined(__GNUC__) || defined(AS_PSVITA)
  3366. if( i->callConv == ICC_GENERIC_METHOD )
  3367. {
  3368. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, obj, 0);
  3369. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3370. f(&gen);
  3371. }
  3372. else if( i->callConv == ICC_THISCALL || i->callConv == ICC_VIRTUAL_THISCALL )
  3373. {
  3374. // For virtual thiscalls we must call the method as a true class method
  3375. // so that the compiler will lookup the function address in the vftable
  3376. union
  3377. {
  3378. asSIMPLEMETHOD_t mthd;
  3379. struct
  3380. {
  3381. asFUNCTION_t func;
  3382. asPWORD baseOffset; // Same size as the pointer
  3383. } f;
  3384. } p;
  3385. obj = (void*) ((char*) obj + i->compositeOffset);
  3386. if(i->isCompositeIndirect)
  3387. obj = *((void**)obj);
  3388. p.f.func = (asFUNCTION_t)(i->func);
  3389. p.f.baseOffset = asPWORD(i->baseOffset);
  3390. void (asCSimpleDummy::*f)() = p.mthd;
  3391. (((asCSimpleDummy*)obj)->*f)();
  3392. }
  3393. else /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
  3394. {
  3395. void (*f)(void *) = (void (*)(void *))(i->func);
  3396. f(obj);
  3397. }
  3398. #else
  3399. #ifndef AS_NO_CLASS_METHODS
  3400. if( i->callConv == ICC_THISCALL )
  3401. {
  3402. union
  3403. {
  3404. asSIMPLEMETHOD_t mthd;
  3405. asFUNCTION_t func;
  3406. } p;
  3407. p.func = (asFUNCTION_t)(i->func);
  3408. void (asCSimpleDummy::*f)() = p.mthd;
  3409. obj = (void*) ((char*) obj + i->compositeOffset);
  3410. if(i->isCompositeIndirect)
  3411. obj = *((void**)obj);
  3412. obj = (void*)(asPWORD(obj) + i->baseOffset);
  3413. (((asCSimpleDummy*)obj)->*f)();
  3414. }
  3415. else
  3416. #endif
  3417. if( i->callConv == ICC_GENERIC_METHOD )
  3418. {
  3419. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, obj, 0);
  3420. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3421. f(&gen);
  3422. }
  3423. else /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
  3424. {
  3425. void (*f)(void *) = (void (*)(void *))(i->func);
  3426. f(obj);
  3427. }
  3428. #endif
  3429. }
  3430. bool asCScriptEngine::CallObjectMethodRetBool(void *obj, int func) const
  3431. {
  3432. asCScriptFunction *s = scriptFunctions[func];
  3433. asASSERT( s != 0 );
  3434. asSSystemFunctionInterface *i = s->sysFuncIntf;
  3435. #if defined(__GNUC__) || defined(AS_PSVITA)
  3436. if( i->callConv == ICC_GENERIC_METHOD )
  3437. {
  3438. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, obj, 0);
  3439. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3440. f(&gen);
  3441. return *(bool*)gen.GetReturnPointer();
  3442. }
  3443. else if( i->callConv == ICC_THISCALL || i->callConv == ICC_VIRTUAL_THISCALL )
  3444. {
  3445. // For virtual thiscalls we must call the method as a true class method so that the compiler will lookup the function address in the vftable
  3446. union
  3447. {
  3448. asSIMPLEMETHOD_t mthd;
  3449. struct
  3450. {
  3451. asFUNCTION_t func;
  3452. asPWORD baseOffset;
  3453. } f;
  3454. } p;
  3455. obj = (void*) ((char*) obj + i->compositeOffset);
  3456. if(i->isCompositeIndirect)
  3457. obj = *((void**)obj);
  3458. p.f.func = (asFUNCTION_t)(i->func);
  3459. p.f.baseOffset = asPWORD(i->baseOffset);
  3460. bool (asCSimpleDummy::*f)() = (bool (asCSimpleDummy::*)())(p.mthd);
  3461. return (((asCSimpleDummy*)obj)->*f)();
  3462. }
  3463. else /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
  3464. {
  3465. bool (*f)(void *) = (bool (*)(void *))(i->func);
  3466. return f(obj);
  3467. }
  3468. #else
  3469. #ifndef AS_NO_CLASS_METHODS
  3470. if( i->callConv == ICC_THISCALL )
  3471. {
  3472. union
  3473. {
  3474. asSIMPLEMETHOD_t mthd;
  3475. asFUNCTION_t func;
  3476. } p;
  3477. p.func = (asFUNCTION_t)(i->func);
  3478. bool (asCSimpleDummy::*f)() = (bool (asCSimpleDummy::*)())p.mthd;
  3479. obj = (void*) ((char*) obj + i->compositeOffset);
  3480. if(i->isCompositeIndirect)
  3481. obj = *((void**)obj);
  3482. obj = (void*)(asPWORD(obj) + i->baseOffset);
  3483. return (((asCSimpleDummy*)obj)->*f)();
  3484. }
  3485. else
  3486. #endif
  3487. if( i->callConv == ICC_GENERIC_METHOD )
  3488. {
  3489. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, obj, 0);
  3490. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3491. f(&gen);
  3492. return *(bool*)gen.GetReturnPointer();
  3493. }
  3494. else /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
  3495. {
  3496. bool (*f)(void *) = (bool (*)(void *))(i->func);
  3497. return f(obj);
  3498. }
  3499. #endif
  3500. }
  3501. int asCScriptEngine::CallObjectMethodRetInt(void *obj, int func) const
  3502. {
  3503. asCScriptFunction *s = scriptFunctions[func];
  3504. asASSERT( s != 0 );
  3505. asSSystemFunctionInterface *i = s->sysFuncIntf;
  3506. #if defined(__GNUC__) || defined(AS_PSVITA)
  3507. if( i->callConv == ICC_GENERIC_METHOD )
  3508. {
  3509. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, obj, 0);
  3510. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3511. f(&gen);
  3512. return *(int*)gen.GetReturnPointer();
  3513. }
  3514. else if( i->callConv == ICC_THISCALL || i->callConv == ICC_VIRTUAL_THISCALL )
  3515. {
  3516. // For virtual thiscalls we must call the method as a true class method so that the compiler will lookup the function address in the vftable
  3517. union
  3518. {
  3519. asSIMPLEMETHOD_t mthd;
  3520. struct
  3521. {
  3522. asFUNCTION_t func;
  3523. asPWORD baseOffset;
  3524. } f;
  3525. } p;
  3526. p.f.func = (asFUNCTION_t)(i->func);
  3527. p.f.baseOffset = asPWORD(i->baseOffset);
  3528. obj = (void*) ((char*) obj + i->compositeOffset);
  3529. if(i->isCompositeIndirect)
  3530. obj = *((void**)obj);
  3531. int (asCSimpleDummy::*f)() = (int (asCSimpleDummy::*)())(p.mthd);
  3532. return (((asCSimpleDummy*)obj)->*f)();
  3533. }
  3534. else /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
  3535. {
  3536. int (*f)(void *) = (int (*)(void *))(i->func);
  3537. return f(obj);
  3538. }
  3539. #else
  3540. #ifndef AS_NO_CLASS_METHODS
  3541. if( i->callConv == ICC_THISCALL )
  3542. {
  3543. union
  3544. {
  3545. asSIMPLEMETHOD_t mthd;
  3546. asFUNCTION_t func;
  3547. } p;
  3548. p.func = (asFUNCTION_t)(i->func);
  3549. int (asCSimpleDummy::*f)() = (int (asCSimpleDummy::*)())p.mthd;
  3550. obj = (void*) ((char*) obj + i->compositeOffset);
  3551. if(i->isCompositeIndirect)
  3552. obj = *((void**)obj);
  3553. obj = (void*)(asPWORD(obj) + i->baseOffset);
  3554. return (((asCSimpleDummy*)obj)->*f)();
  3555. }
  3556. else
  3557. #endif
  3558. if( i->callConv == ICC_GENERIC_METHOD )
  3559. {
  3560. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, obj, 0);
  3561. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3562. f(&gen);
  3563. return *(int*)gen.GetReturnPointer();
  3564. }
  3565. else /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
  3566. {
  3567. int (*f)(void *) = (int (*)(void *))(i->func);
  3568. return f(obj);
  3569. }
  3570. #endif
  3571. }
  3572. void *asCScriptEngine::CallObjectMethodRetPtr(void *obj, int func) const
  3573. {
  3574. asCScriptFunction *s = scriptFunctions[func];
  3575. asASSERT( s != 0 );
  3576. asSSystemFunctionInterface *i = s->sysFuncIntf;
  3577. #if defined(__GNUC__) || defined(AS_PSVITA)
  3578. if( i->callConv == ICC_GENERIC_METHOD )
  3579. {
  3580. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, obj, 0);
  3581. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3582. f(&gen);
  3583. return *(void**)gen.GetReturnPointer();
  3584. }
  3585. else if( i->callConv == ICC_THISCALL || i->callConv == ICC_VIRTUAL_THISCALL )
  3586. {
  3587. // For virtual thiscalls we must call the method as a true class method so that the compiler will lookup the function address in the vftable
  3588. union
  3589. {
  3590. asSIMPLEMETHOD_t mthd;
  3591. struct
  3592. {
  3593. asFUNCTION_t func;
  3594. asPWORD baseOffset;
  3595. } f;
  3596. } p;
  3597. p.f.func = (asFUNCTION_t)(i->func);
  3598. p.f.baseOffset = asPWORD(i->baseOffset);
  3599. obj = (void*) ((char*) obj + i->compositeOffset);
  3600. if(i->isCompositeIndirect)
  3601. obj = *((void**)obj);
  3602. void *(asCSimpleDummy::*f)() = (void *(asCSimpleDummy::*)())(p.mthd);
  3603. return (((asCSimpleDummy*)obj)->*f)();
  3604. }
  3605. else /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
  3606. {
  3607. void *(*f)(void *) = (void *(*)(void *))(i->func);
  3608. return f(obj);
  3609. }
  3610. #else
  3611. #ifndef AS_NO_CLASS_METHODS
  3612. if( i->callConv == ICC_THISCALL )
  3613. {
  3614. union
  3615. {
  3616. asSIMPLEMETHOD_t mthd;
  3617. asFUNCTION_t func;
  3618. } p;
  3619. p.func = (asFUNCTION_t)(i->func);
  3620. void *(asCSimpleDummy::*f)() = (void *(asCSimpleDummy::*)())p.mthd;
  3621. obj = (void*) ((char*) obj + i->compositeOffset);
  3622. if(i->isCompositeIndirect)
  3623. obj = *((void**)obj);
  3624. obj = (void*)(asPWORD(obj) + i->baseOffset);
  3625. return (((asCSimpleDummy*)obj)->*f)();
  3626. }
  3627. else
  3628. #endif
  3629. if( i->callConv == ICC_GENERIC_METHOD )
  3630. {
  3631. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, obj, 0);
  3632. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3633. f(&gen);
  3634. return *(void **)gen.GetReturnPointer();
  3635. }
  3636. else /*if( i->callConv == ICC_CDECL_OBJLAST || i->callConv == ICC_CDECL_OBJFIRST )*/
  3637. {
  3638. void *(*f)(void *) = (void *(*)(void *))(i->func);
  3639. return f(obj);
  3640. }
  3641. #endif
  3642. }
  3643. void *asCScriptEngine::CallObjectMethodRetPtr(void *obj, int param1, asCScriptFunction *func) const
  3644. {
  3645. asASSERT( obj != 0 );
  3646. asASSERT( func != 0 );
  3647. asSSystemFunctionInterface *i = func->sysFuncIntf;
  3648. #ifndef AS_NO_CLASS_METHODS
  3649. if( i->callConv == ICC_THISCALL || i->callConv == ICC_VIRTUAL_THISCALL )
  3650. {
  3651. #if defined(__GNUC__) || defined(AS_PSVITA)
  3652. // For virtual thiscalls we must call the method as a true class method so that the compiler will lookup the function address in the vftable
  3653. union
  3654. {
  3655. asSIMPLEMETHOD_t mthd;
  3656. struct
  3657. {
  3658. asFUNCTION_t func;
  3659. asPWORD baseOffset;
  3660. } f;
  3661. } p;
  3662. p.f.func = (asFUNCTION_t)(i->func);
  3663. p.f.baseOffset = asPWORD(i->baseOffset);
  3664. obj = (void*) ((char*) obj + i->compositeOffset);
  3665. if(i->isCompositeIndirect)
  3666. obj = *((void**)obj);
  3667. void *(asCSimpleDummy::*f)(int) = (void *(asCSimpleDummy::*)(int))(p.mthd);
  3668. return (((asCSimpleDummy*)obj)->*f)(param1);
  3669. #else
  3670. union
  3671. {
  3672. asSIMPLEMETHOD_t mthd;
  3673. asFUNCTION_t func;
  3674. } p;
  3675. p.func = (asFUNCTION_t)(i->func);
  3676. void *(asCSimpleDummy::*f)(int) = (void *(asCSimpleDummy::*)(int))p.mthd;
  3677. obj = (void*) ((char*) obj + i->compositeOffset);
  3678. if(i->isCompositeIndirect)
  3679. obj = *((void**)obj);
  3680. obj = (void*)(asPWORD(obj) + i->baseOffset);
  3681. return (((asCSimpleDummy*)obj)->*f)(param1);
  3682. #endif
  3683. }
  3684. else
  3685. #endif
  3686. if( i->callConv == ICC_GENERIC_METHOD )
  3687. {
  3688. asCGeneric gen(const_cast<asCScriptEngine*>(this), func, obj, reinterpret_cast<asDWORD*>(&param1));
  3689. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3690. f(&gen);
  3691. return *(void **)gen.GetReturnPointer();
  3692. }
  3693. else if( i->callConv == ICC_CDECL_OBJLAST )
  3694. {
  3695. void *(*f)(int, void *) = (void *(*)(int, void *))(i->func);
  3696. return f(param1, obj);
  3697. }
  3698. else /*if( i->callConv == ICC_CDECL_OBJFIRST )*/
  3699. {
  3700. void *(*f)(void *, int) = (void *(*)(void *, int))(i->func);
  3701. return f(obj, param1);
  3702. }
  3703. }
  3704. void *asCScriptEngine::CallGlobalFunctionRetPtr(int func) const
  3705. {
  3706. asCScriptFunction *s = scriptFunctions[func];
  3707. asASSERT( s != 0 );
  3708. return CallGlobalFunctionRetPtr(s->sysFuncIntf, s);
  3709. }
  3710. void *asCScriptEngine::CallGlobalFunctionRetPtr(int func, void *param1) const
  3711. {
  3712. asCScriptFunction *s = scriptFunctions[func];
  3713. asASSERT( s != 0 );
  3714. return CallGlobalFunctionRetPtr(s->sysFuncIntf, s, param1);
  3715. }
  3716. void *asCScriptEngine::CallGlobalFunctionRetPtr(asSSystemFunctionInterface *i, asCScriptFunction *s) const
  3717. {
  3718. if( i->callConv == ICC_CDECL )
  3719. {
  3720. void *(*f)() = (void *(*)())(i->func);
  3721. return f();
  3722. }
  3723. else if( i->callConv == ICC_STDCALL )
  3724. {
  3725. typedef void *(STDCALL *func_t)();
  3726. func_t f = (func_t)(i->func);
  3727. return f();
  3728. }
  3729. else
  3730. {
  3731. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, 0, 0);
  3732. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3733. f(&gen);
  3734. return *(void**)gen.GetReturnPointer();
  3735. }
  3736. }
  3737. void *asCScriptEngine::CallGlobalFunctionRetPtr(asSSystemFunctionInterface *i, asCScriptFunction *s, void *param1) const
  3738. {
  3739. if( i->callConv == ICC_CDECL )
  3740. {
  3741. void *(*f)(void *) = (void *(*)(void *))(i->func);
  3742. return f(param1);
  3743. }
  3744. else if( i->callConv == ICC_STDCALL )
  3745. {
  3746. typedef void *(STDCALL *func_t)(void *);
  3747. func_t f = (func_t)(i->func);
  3748. return f(param1);
  3749. }
  3750. else
  3751. {
  3752. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, 0, (asDWORD*)&param1);
  3753. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3754. f(&gen);
  3755. return *(void**)gen.GetReturnPointer();
  3756. }
  3757. }
  3758. void asCScriptEngine::CallObjectMethod(void *obj, void *param, int func) const
  3759. {
  3760. asCScriptFunction *s = scriptFunctions[func];
  3761. asASSERT( s != 0 );
  3762. CallObjectMethod(obj, param, s->sysFuncIntf, s);
  3763. }
  3764. void asCScriptEngine::CallObjectMethod(void *obj, void *param, asSSystemFunctionInterface *i, asCScriptFunction *s) const
  3765. {
  3766. #if defined(__GNUC__) || defined(AS_PSVITA)
  3767. if( i->callConv == ICC_CDECL_OBJLAST )
  3768. {
  3769. void (*f)(void *, void *) = (void (*)(void *, void *))(i->func);
  3770. f(param, obj);
  3771. }
  3772. else if( i->callConv == ICC_GENERIC_METHOD )
  3773. {
  3774. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, obj, (asDWORD*)&param);
  3775. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3776. f(&gen);
  3777. }
  3778. else if( i->callConv == ICC_VIRTUAL_THISCALL || i->callConv == ICC_THISCALL )
  3779. {
  3780. // For virtual thiscalls we must call the method as a true class method
  3781. // so that the compiler will lookup the function address in the vftable
  3782. union
  3783. {
  3784. asSIMPLEMETHOD_t mthd;
  3785. struct
  3786. {
  3787. asFUNCTION_t func;
  3788. asPWORD baseOffset; // Same size as the pointer
  3789. } f;
  3790. } p;
  3791. p.f.func = (asFUNCTION_t)(i->func);
  3792. p.f.baseOffset = asPWORD(i->baseOffset);
  3793. obj = (void*) ((char*) obj + i->compositeOffset);
  3794. if(i->isCompositeIndirect)
  3795. obj = *((void**)obj);
  3796. void (asCSimpleDummy::*f)(void*) = (void (asCSimpleDummy::*)(void*))(p.mthd);
  3797. (((asCSimpleDummy*)obj)->*f)(param);
  3798. }
  3799. else /*if( i->callConv == ICC_CDECL_OBJFIRST */
  3800. {
  3801. void (*f)(void *, void *) = (void (*)(void *, void *))(i->func);
  3802. f(obj, param);
  3803. }
  3804. #else
  3805. #ifndef AS_NO_CLASS_METHODS
  3806. if( i->callConv == ICC_THISCALL )
  3807. {
  3808. union
  3809. {
  3810. asSIMPLEMETHOD_t mthd;
  3811. asFUNCTION_t func;
  3812. } p;
  3813. p.func = (asFUNCTION_t)(i->func);
  3814. void (asCSimpleDummy::*f)(void *) = (void (asCSimpleDummy::*)(void *))(p.mthd);
  3815. obj = (void*) ((char*) obj + i->compositeOffset);
  3816. if(i->isCompositeIndirect)
  3817. obj = *((void**)obj);
  3818. obj = (void*)(asPWORD(obj) + i->baseOffset);
  3819. (((asCSimpleDummy*)obj)->*f)(param);
  3820. }
  3821. else
  3822. #endif
  3823. if( i->callConv == ICC_CDECL_OBJLAST )
  3824. {
  3825. void (*f)(void *, void *) = (void (*)(void *, void *))(i->func);
  3826. f(param, obj);
  3827. }
  3828. else if( i->callConv == ICC_GENERIC_METHOD )
  3829. {
  3830. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, obj, (asDWORD*)&param);
  3831. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3832. f(&gen);
  3833. }
  3834. else /*if( i->callConv == ICC_CDECL_OBJFIRST )*/
  3835. {
  3836. void (*f)(void *, void *) = (void (*)(void *, void *))(i->func);
  3837. f(obj, param);
  3838. }
  3839. #endif
  3840. }
  3841. void asCScriptEngine::CallGlobalFunction(void *param1, void *param2, asSSystemFunctionInterface *i, asCScriptFunction *s) const
  3842. {
  3843. if( i->callConv == ICC_CDECL )
  3844. {
  3845. void (*f)(void *, void *) = (void (*)(void *, void *))(i->func);
  3846. f(param1, param2);
  3847. }
  3848. else if( i->callConv == ICC_STDCALL )
  3849. {
  3850. typedef void (STDCALL *func_t)(void *, void *);
  3851. func_t f = (func_t)(i->func);
  3852. f(param1, param2);
  3853. }
  3854. else
  3855. {
  3856. // We must guarantee the order of the arguments which is why we copy them to this
  3857. // array. Otherwise the compiler may put them anywhere it likes, or even keep them
  3858. // in the registers which causes problem.
  3859. void *params[2] = {param1, param2};
  3860. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, 0, (asDWORD*)&params);
  3861. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3862. f(&gen);
  3863. }
  3864. }
  3865. bool asCScriptEngine::CallGlobalFunctionRetBool(void *param1, void *param2, asSSystemFunctionInterface *i, asCScriptFunction *s) const
  3866. {
  3867. if( i->callConv == ICC_CDECL )
  3868. {
  3869. bool (*f)(void *, void *) = (bool (*)(void *, void *))(i->func);
  3870. return f(param1, param2);
  3871. }
  3872. else if( i->callConv == ICC_STDCALL )
  3873. {
  3874. typedef bool (STDCALL *func_t)(void *, void *);
  3875. func_t f = (func_t)(i->func);
  3876. return f(param1, param2);
  3877. }
  3878. else
  3879. {
  3880. // TODO: When simulating a 64bit environment by defining AS_64BIT_PTR on a 32bit platform this code
  3881. // fails, because the stack given to asCGeneric is not prepared with two 64bit arguments.
  3882. // We must guarantee the order of the arguments which is why we copy them to this
  3883. // array. Otherwise the compiler may put them anywhere it likes, or even keep them
  3884. // in the registers which causes problem.
  3885. void *params[2] = {param1, param2};
  3886. asCGeneric gen(const_cast<asCScriptEngine*>(this), s, 0, (asDWORD*)params);
  3887. void (*f)(asIScriptGeneric *) = (void (*)(asIScriptGeneric *))(i->func);
  3888. f(&gen);
  3889. return *(bool*)gen.GetReturnPointer();
  3890. }
  3891. }
  3892. void *asCScriptEngine::CallAlloc(const asCObjectType *type) const
  3893. {
  3894. // Allocate 4 bytes as the smallest size. Otherwise CallSystemFunction may try to
  3895. // copy a DWORD onto a smaller memory block, in case the object type is return in registers.
  3896. // Pad to the next even 4 bytes to avoid asBC_CPY writing outside of allocated buffer for registered POD types
  3897. asUINT size = type->size;
  3898. if( size & 0x3 )
  3899. size += 4 - (size & 0x3);
  3900. #ifndef WIP_16BYTE_ALIGN
  3901. #if defined(AS_DEBUG)
  3902. return ((asALLOCFUNCDEBUG_t)userAlloc)(size, __FILE__, __LINE__);
  3903. #else
  3904. return userAlloc(size);
  3905. #endif
  3906. #else
  3907. #if defined(AS_DEBUG)
  3908. return ((asALLOCALIGNEDFUNCDEBUG_t)userAllocAligned)(size, type->alignment, __FILE__, __LINE__);
  3909. #else
  3910. return userAllocAligned(size, type->alignment);
  3911. #endif
  3912. #endif
  3913. }
  3914. void asCScriptEngine::CallFree(void *obj) const
  3915. {
  3916. #ifndef WIP_16BYTE_ALIGN
  3917. userFree(obj);
  3918. #else
  3919. userFreeAligned(obj);
  3920. #endif
  3921. }
  3922. // interface
  3923. int asCScriptEngine::NotifyGarbageCollectorOfNewObject(void *obj, asITypeInfo *type)
  3924. {
  3925. return gc.AddScriptObjectToGC(obj, static_cast<asCObjectType*>(type));
  3926. }
  3927. // interface
  3928. int asCScriptEngine::GetObjectInGC(asUINT idx, asUINT *seqNbr, void **obj, asITypeInfo **type)
  3929. {
  3930. return gc.GetObjectInGC(idx, seqNbr, obj, type);
  3931. }
  3932. // interface
  3933. int asCScriptEngine::GarbageCollect(asDWORD flags, asUINT iterations)
  3934. {
  3935. int r = gc.GarbageCollect(flags, iterations);
  3936. if( r == 0 )
  3937. {
  3938. // Delete any modules that have been discarded previously but not
  3939. // removed due to being referred to by objects in the garbage collector
  3940. DeleteDiscardedModules();
  3941. }
  3942. return r;
  3943. }
  3944. // interface
  3945. void asCScriptEngine::GetGCStatistics(asUINT *currentSize, asUINT *totalDestroyed, asUINT *totalDetected, asUINT *newObjects, asUINT *totalNewDestroyed) const
  3946. {
  3947. gc.GetStatistics(currentSize, totalDestroyed, totalDetected, newObjects, totalNewDestroyed);
  3948. }
  3949. // interface
  3950. void asCScriptEngine::GCEnumCallback(void *reference)
  3951. {
  3952. gc.GCEnumCallback(reference);
  3953. }
  3954. // interface
  3955. void asCScriptEngine::ForwardGCEnumReferences(void *ref, asITypeInfo *type)
  3956. {
  3957. asCTypeInfo *t = reinterpret_cast<asCTypeInfo*>(type);
  3958. if ((t->flags & asOBJ_VALUE) && (t->flags & asOBJ_GC))
  3959. {
  3960. CallObjectMethod(ref, this, CastToObjectType(t)->beh.gcEnumReferences);
  3961. }
  3962. }
  3963. // interface
  3964. void asCScriptEngine::ForwardGCReleaseReferences(void *ref, asITypeInfo *type)
  3965. {
  3966. asCTypeInfo *t = reinterpret_cast<asCTypeInfo*>(type);
  3967. if ((t->flags & asOBJ_VALUE) && (t->flags & asOBJ_GC))
  3968. {
  3969. CallObjectMethod(ref, this, CastToObjectType(t)->beh.gcReleaseAllReferences);
  3970. }
  3971. }
  3972. // interface
  3973. void asCScriptEngine::SetCircularRefDetectedCallback(asCIRCULARREFFUNC_t callback, void *param)
  3974. {
  3975. gc.circularRefDetectCallbackFunc = callback;
  3976. gc.circularRefDetectCallbackParam = param;
  3977. }
  3978. int asCScriptEngine::GetTypeIdFromDataType(const asCDataType &dtIn) const
  3979. {
  3980. if( dtIn.IsNullHandle() ) return asTYPEID_VOID;
  3981. if( dtIn.GetTypeInfo() == 0 )
  3982. {
  3983. // Primitives have pre-fixed typeIds
  3984. switch( dtIn.GetTokenType() )
  3985. {
  3986. case ttVoid: return asTYPEID_VOID;
  3987. case ttBool: return asTYPEID_BOOL;
  3988. case ttInt8: return asTYPEID_INT8;
  3989. case ttInt16: return asTYPEID_INT16;
  3990. case ttInt: return asTYPEID_INT32;
  3991. case ttInt64: return asTYPEID_INT64;
  3992. case ttUInt8: return asTYPEID_UINT8;
  3993. case ttUInt16: return asTYPEID_UINT16;
  3994. case ttUInt: return asTYPEID_UINT32;
  3995. case ttUInt64: return asTYPEID_UINT64;
  3996. case ttFloat: return asTYPEID_FLOAT;
  3997. case ttDouble: return asTYPEID_DOUBLE;
  3998. default:
  3999. // All types should be covered by the above. The variable type is not really a type
  4000. asASSERT(dtIn.GetTokenType() == ttQuestion);
  4001. return -1;
  4002. }
  4003. }
  4004. int typeId = -1;
  4005. asCTypeInfo *ot = dtIn.GetTypeInfo();
  4006. asASSERT(ot != &functionBehaviours);
  4007. // Object's hold the typeId themselves
  4008. typeId = ot->typeId;
  4009. if( typeId == -1 )
  4010. {
  4011. ACQUIREEXCLUSIVE(engineRWLock);
  4012. // Make sure another thread didn't determine the typeId while we were waiting for the lock
  4013. if( ot->typeId == -1 )
  4014. {
  4015. typeId = typeIdSeqNbr++;
  4016. if( ot->flags & asOBJ_SCRIPT_OBJECT ) typeId |= asTYPEID_SCRIPTOBJECT;
  4017. else if( ot->flags & asOBJ_TEMPLATE ) typeId |= asTYPEID_TEMPLATE;
  4018. else if( ot->flags & asOBJ_ENUM ) {} // TODO: Should we have a specific bit for this?
  4019. else typeId |= asTYPEID_APPOBJECT;
  4020. ot->typeId = typeId;
  4021. mapTypeIdToTypeInfo.Insert(typeId, ot);
  4022. }
  4023. RELEASEEXCLUSIVE(engineRWLock);
  4024. }
  4025. // Add flags according to the requested type
  4026. if( dtIn.GetTypeInfo() && !(dtIn.GetTypeInfo()->flags & asOBJ_ASHANDLE) )
  4027. {
  4028. // The ASHANDLE types behave like handles, but are really
  4029. // value types so the typeId is never returned as a handle
  4030. if( dtIn.IsObjectHandle() )
  4031. typeId |= asTYPEID_OBJHANDLE;
  4032. if( dtIn.IsHandleToConst() )
  4033. typeId |= asTYPEID_HANDLETOCONST;
  4034. }
  4035. return typeId;
  4036. }
  4037. asCDataType asCScriptEngine::GetDataTypeFromTypeId(int typeId) const
  4038. {
  4039. int baseId = typeId & (asTYPEID_MASK_OBJECT | asTYPEID_MASK_SEQNBR);
  4040. if( typeId <= asTYPEID_DOUBLE )
  4041. {
  4042. eTokenType type[] = {ttVoid, ttBool, ttInt8, ttInt16, ttInt, ttInt64, ttUInt8, ttUInt16, ttUInt, ttUInt64, ttFloat, ttDouble};
  4043. return asCDataType::CreatePrimitive(type[typeId], false);
  4044. }
  4045. // First check if the typeId is an object type
  4046. asCTypeInfo *ot = 0;
  4047. ACQUIRESHARED(engineRWLock);
  4048. asSMapNode<int,asCTypeInfo*> *cursor = 0;
  4049. if( mapTypeIdToTypeInfo.MoveTo(&cursor, baseId) )
  4050. ot = mapTypeIdToTypeInfo.GetValue(cursor);
  4051. RELEASESHARED(engineRWLock);
  4052. if( ot )
  4053. {
  4054. asCDataType dt = asCDataType::CreateType(ot, false);
  4055. if( typeId & asTYPEID_OBJHANDLE )
  4056. dt.MakeHandle(true, true);
  4057. if( typeId & asTYPEID_HANDLETOCONST )
  4058. dt.MakeHandleToConst(true);
  4059. return dt;
  4060. }
  4061. return asCDataType();
  4062. }
  4063. asCObjectType *asCScriptEngine::GetObjectTypeFromTypeId(int typeId) const
  4064. {
  4065. asCDataType dt = GetDataTypeFromTypeId(typeId);
  4066. return CastToObjectType(dt.GetTypeInfo());
  4067. }
  4068. void asCScriptEngine::RemoveFromTypeIdMap(asCTypeInfo *type)
  4069. {
  4070. ACQUIREEXCLUSIVE(engineRWLock);
  4071. asSMapNode<int,asCTypeInfo*> *cursor = 0;
  4072. mapTypeIdToTypeInfo.MoveFirst(&cursor);
  4073. while( cursor )
  4074. {
  4075. if(mapTypeIdToTypeInfo.GetValue(cursor) == type )
  4076. {
  4077. mapTypeIdToTypeInfo.Erase(cursor);
  4078. break;
  4079. }
  4080. mapTypeIdToTypeInfo.MoveNext(&cursor, cursor);
  4081. }
  4082. RELEASEEXCLUSIVE(engineRWLock);
  4083. }
  4084. // interface
  4085. asITypeInfo *asCScriptEngine::GetTypeInfoByDecl(const char *decl) const
  4086. {
  4087. asCDataType dt;
  4088. // This cast is ok, because we are not changing anything in the engine
  4089. asCBuilder bld(const_cast<asCScriptEngine*>(this), 0);
  4090. // Don't write parser errors to the message callback
  4091. bld.silent = true;
  4092. int r = bld.ParseDataType(decl, &dt, defaultNamespace);
  4093. if (r < 0)
  4094. return 0;
  4095. return dt.GetTypeInfo();
  4096. }
  4097. // interface
  4098. int asCScriptEngine::GetTypeIdByDecl(const char *decl) const
  4099. {
  4100. asCDataType dt;
  4101. // This cast is ok, because we are not changing anything in the engine
  4102. asCBuilder bld(const_cast<asCScriptEngine*>(this), 0);
  4103. // Don't write parser errors to the message callback
  4104. bld.silent = true;
  4105. int r = bld.ParseDataType(decl, &dt, defaultNamespace);
  4106. if( r < 0 )
  4107. return asINVALID_TYPE;
  4108. return GetTypeIdFromDataType(dt);
  4109. }
  4110. // interface
  4111. const char *asCScriptEngine::GetTypeDeclaration(int typeId, bool includeNamespace) const
  4112. {
  4113. asCDataType dt = GetDataTypeFromTypeId(typeId);
  4114. asCString *tempString = &asCThreadManager::GetLocalData()->string;
  4115. *tempString = dt.Format(defaultNamespace, includeNamespace);
  4116. return tempString->AddressOf();
  4117. }
  4118. // interface
  4119. int asCScriptEngine::GetSizeOfPrimitiveType(int typeId) const
  4120. {
  4121. asCDataType dt = GetDataTypeFromTypeId(typeId);
  4122. if( !dt.IsPrimitive() ) return 0;
  4123. return dt.GetSizeInMemoryBytes();
  4124. }
  4125. // interface
  4126. int asCScriptEngine::RefCastObject(void *obj, asITypeInfo *fromType, asITypeInfo *toType, void **newPtr, bool useOnlyImplicitCast)
  4127. {
  4128. if( newPtr == 0 ) return asINVALID_ARG;
  4129. *newPtr = 0;
  4130. if( fromType == 0 || toType == 0 ) return asINVALID_ARG;
  4131. // A null-pointer can always be cast to another type, so it will always be successful
  4132. if( obj == 0 )
  4133. return asSUCCESS;
  4134. if( fromType == toType )
  4135. {
  4136. *newPtr = obj;
  4137. AddRefScriptObject(*newPtr, toType);
  4138. return asSUCCESS;
  4139. }
  4140. // Check for funcdefs
  4141. if ((fromType->GetFlags() & asOBJ_FUNCDEF) && (toType->GetFlags() & asOBJ_FUNCDEF))
  4142. {
  4143. asCFuncdefType *fromFunc = CastToFuncdefType(reinterpret_cast<asCTypeInfo*>(fromType));
  4144. asCFuncdefType *toFunc = CastToFuncdefType(reinterpret_cast<asCTypeInfo*>(toType));
  4145. if (fromFunc && toFunc && fromFunc->funcdef->IsSignatureExceptNameEqual(toFunc->funcdef))
  4146. {
  4147. *newPtr = obj;
  4148. AddRefScriptObject(*newPtr, toType);
  4149. return asSUCCESS;
  4150. }
  4151. return asSUCCESS;
  4152. }
  4153. // Look for ref cast behaviours
  4154. asCScriptFunction *universalCastFunc = 0;
  4155. asCObjectType *from = reinterpret_cast<asCObjectType*>(fromType);
  4156. for( asUINT n = 0; n < from->methods.GetLength(); n++ )
  4157. {
  4158. asCScriptFunction *func = scriptFunctions[from->methods[n]];
  4159. if( func->name == "opImplCast" ||
  4160. (!useOnlyImplicitCast && func->name == "opCast") )
  4161. {
  4162. if( func->returnType.GetTypeInfo() == toType )
  4163. {
  4164. *newPtr = CallObjectMethodRetPtr(obj, func->id);
  4165. // The ref cast behaviour returns a handle with incremented
  4166. // ref counter, so there is no need to call AddRef explicitly
  4167. // unless the function is registered with autohandle
  4168. if( func->sysFuncIntf->returnAutoHandle )
  4169. AddRefScriptObject(*newPtr, toType);
  4170. return asSUCCESS;
  4171. }
  4172. else if( func->returnType.GetTokenType() == ttVoid &&
  4173. func->parameterTypes.GetLength() == 1 &&
  4174. func->parameterTypes[0].GetTokenType() == ttQuestion )
  4175. {
  4176. universalCastFunc = func;
  4177. }
  4178. }
  4179. }
  4180. // One last chance if the object has a void opCast(?&out) behaviour
  4181. if( universalCastFunc )
  4182. {
  4183. // TODO: Add proper error handling
  4184. asIScriptContext *ctx = RequestContext();
  4185. ctx->Prepare(universalCastFunc);
  4186. ctx->SetObject(obj);
  4187. ctx->SetArgVarType(0, newPtr, toType->GetTypeId() | asTYPEID_OBJHANDLE);
  4188. ctx->Execute();
  4189. ReturnContext(ctx);
  4190. // The opCast(?&out) method already incremented the
  4191. // refCount so there is no need to do it manually
  4192. return asSUCCESS;
  4193. }
  4194. // For script classes and interfaces there is a quick route
  4195. if( (fromType->GetFlags() & asOBJ_SCRIPT_OBJECT) && (toType->GetFlags() & asOBJ_SCRIPT_OBJECT) )
  4196. {
  4197. if( fromType == toType )
  4198. {
  4199. *newPtr = obj;
  4200. reinterpret_cast<asCScriptObject*>(*newPtr)->AddRef();
  4201. return asSUCCESS;
  4202. }
  4203. // Up casts to base class or interface can be done implicitly
  4204. if( fromType->DerivesFrom(toType) ||
  4205. fromType->Implements(toType) )
  4206. {
  4207. *newPtr = obj;
  4208. reinterpret_cast<asCScriptObject*>(*newPtr)->AddRef();
  4209. return asSUCCESS;
  4210. }
  4211. // Down casts to derived class or from interface can only be done explicitly
  4212. if( !useOnlyImplicitCast )
  4213. {
  4214. // Get the true type of the object so the explicit cast can evaluate all possibilities
  4215. asITypeInfo *trueType = reinterpret_cast<asCScriptObject*>(obj)->GetObjectType();
  4216. if (trueType->DerivesFrom(toType) ||
  4217. trueType->Implements(toType))
  4218. {
  4219. *newPtr = obj;
  4220. reinterpret_cast<asCScriptObject*>(*newPtr)->AddRef();
  4221. return asSUCCESS;
  4222. }
  4223. }
  4224. }
  4225. // The cast is not available, but it is still a success
  4226. return asSUCCESS;
  4227. }
  4228. // interface
  4229. void *asCScriptEngine::CreateScriptObject(const asITypeInfo *type)
  4230. {
  4231. if( type == 0 ) return 0;
  4232. asCObjectType *objType = const_cast<asCObjectType*>(reinterpret_cast<const asCObjectType *>(type));
  4233. void *ptr = 0;
  4234. // Check that there is a default factory for ref types
  4235. if( objType->beh.factory == 0 && (objType->flags & asOBJ_REF) )
  4236. {
  4237. // TODO: How to report the reason the object couldn't be created, without writing to the message callback? optional argument with return code?
  4238. // TODO: Warn about the invalid call to message callback. Make it an optional, so the warning can be turned off
  4239. // asCString str;
  4240. // str.Format(TXT_FAILED_IN_FUNC_s_s_d, "CreateScriptObject", errorNames[-asNO_FUNCTION], asNO_FUNCTION);
  4241. // WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  4242. return 0;
  4243. }
  4244. // Construct the object
  4245. if( objType->flags & asOBJ_SCRIPT_OBJECT )
  4246. {
  4247. // Call the script class' default factory with a context
  4248. ptr = ScriptObjectFactory(objType, this);
  4249. }
  4250. else if( (objType->flags & asOBJ_TEMPLATE) && (objType->flags & asOBJ_REF) )
  4251. {
  4252. // The registered factory that takes the object type is moved
  4253. // to the construct behaviour when the type is instantiated
  4254. #ifdef AS_NO_EXCEPTIONS
  4255. ptr = CallGlobalFunctionRetPtr(objType->beh.construct, objType);
  4256. #else
  4257. try
  4258. {
  4259. ptr = CallGlobalFunctionRetPtr(objType->beh.construct, objType);
  4260. }
  4261. catch (...)
  4262. {
  4263. asCContext *ctx = reinterpret_cast<asCContext*>(asGetActiveContext());
  4264. if (ctx)
  4265. ctx->HandleAppException();
  4266. }
  4267. #endif
  4268. }
  4269. else if( objType->flags & asOBJ_REF )
  4270. {
  4271. // Call the default factory directly
  4272. #ifdef AS_NO_EXCEPTIONS
  4273. ptr = CallGlobalFunctionRetPtr(objType->beh.factory);
  4274. #else
  4275. try
  4276. {
  4277. ptr = CallGlobalFunctionRetPtr(objType->beh.factory);
  4278. }
  4279. catch(...)
  4280. {
  4281. asCContext *ctx = reinterpret_cast<asCContext*>(asGetActiveContext());
  4282. if( ctx )
  4283. ctx->HandleAppException();
  4284. }
  4285. #endif
  4286. }
  4287. else
  4288. {
  4289. // Make sure there is a default constructor or that it is a POD type
  4290. if( objType->beh.construct == 0 && !(objType->flags & asOBJ_POD) )
  4291. {
  4292. // TODO: How to report the reason the object couldn't be created, without writing to the message callback? optional argument with return code?
  4293. // TODO: Warn about the invalid call to message callback. Make it an optional, so the warning can be turned off
  4294. // asCString str;
  4295. // str.Format(TXT_FAILED_IN_FUNC_s_s_d, "CreateScriptObject", errorNames[-asNO_FUNCTION], asNO_FUNCTION);
  4296. // WriteMessage("", 0, 0, asMSGTYPE_ERROR, str.AddressOf());
  4297. return 0;
  4298. }
  4299. // Manually allocate the memory, then call the default constructor
  4300. ptr = CallAlloc(objType);
  4301. int funcIndex = objType->beh.construct;
  4302. if (funcIndex)
  4303. {
  4304. if (objType->flags & asOBJ_TEMPLATE)
  4305. {
  4306. // Templates of value types create script functions as the constructors
  4307. CallScriptObjectMethod(ptr, funcIndex);
  4308. }
  4309. else
  4310. {
  4311. #ifdef AS_NO_EXCEPTIONS
  4312. CallObjectMethod(ptr, funcIndex);
  4313. #else
  4314. try
  4315. {
  4316. CallObjectMethod(ptr, funcIndex);
  4317. }
  4318. catch (...)
  4319. {
  4320. asCContext *ctx = reinterpret_cast<asCContext*>(asGetActiveContext());
  4321. if (ctx)
  4322. ctx->HandleAppException();
  4323. // Free the memory
  4324. CallFree(ptr);
  4325. ptr = 0;
  4326. }
  4327. #endif
  4328. }
  4329. }
  4330. }
  4331. return ptr;
  4332. }
  4333. // internal
  4334. int asCScriptEngine::CallScriptObjectMethod(void *obj, int funcId)
  4335. {
  4336. asIScriptContext *ctx = 0;
  4337. int r = 0;
  4338. bool isNested = false;
  4339. // Use nested call in the context if there is an active context
  4340. ctx = asGetActiveContext();
  4341. if (ctx)
  4342. {
  4343. // It may not always be possible to reuse the current context,
  4344. // in which case we'll have to create a new one any way.
  4345. if (ctx->GetEngine() == this && ctx->PushState() == asSUCCESS)
  4346. isNested = true;
  4347. else
  4348. ctx = 0;
  4349. }
  4350. if (ctx == 0)
  4351. {
  4352. // Request a context from the engine
  4353. ctx = RequestContext();
  4354. if (ctx == 0)
  4355. {
  4356. // TODO: How to best report this failure?
  4357. return asERROR;
  4358. }
  4359. }
  4360. r = ctx->Prepare(scriptFunctions[funcId]);
  4361. if (r < 0)
  4362. {
  4363. if (isNested)
  4364. ctx->PopState();
  4365. else
  4366. ReturnContext(ctx);
  4367. // TODO: How to best report this failure?
  4368. return asERROR;
  4369. }
  4370. // Set the object
  4371. ctx->SetObject(obj);
  4372. for (;;)
  4373. {
  4374. r = ctx->Execute();
  4375. // We can't allow this execution to be suspended
  4376. // so resume the execution immediately
  4377. if (r != asEXECUTION_SUSPENDED)
  4378. break;
  4379. }
  4380. if (r != asEXECUTION_FINISHED)
  4381. {
  4382. if (isNested)
  4383. {
  4384. ctx->PopState();
  4385. // If the execution was aborted or an exception occurred,
  4386. // then we should forward that to the outer execution.
  4387. if (r == asEXECUTION_EXCEPTION)
  4388. {
  4389. // TODO: How to improve this exception
  4390. ctx->SetException(TXT_EXCEPTION_IN_NESTED_CALL);
  4391. }
  4392. else if (r == asEXECUTION_ABORTED)
  4393. ctx->Abort();
  4394. }
  4395. else
  4396. ReturnContext(ctx);
  4397. // TODO: How to best report the error?
  4398. return asERROR;
  4399. }
  4400. if (isNested)
  4401. ctx->PopState();
  4402. else
  4403. ReturnContext(ctx);
  4404. return asSUCCESS;
  4405. }
  4406. // interface
  4407. void *asCScriptEngine::CreateUninitializedScriptObject(const asITypeInfo *type)
  4408. {
  4409. // This function only works for script classes. Registered types cannot be created this way.
  4410. if( type == 0 || !(type->GetFlags() & asOBJ_SCRIPT_OBJECT) )
  4411. return 0;
  4412. asCObjectType *objType = const_cast<asCObjectType*>(reinterpret_cast<const asCObjectType*>(type));
  4413. // Construct the object, but do not call the actual constructor that initializes the members
  4414. // The initialization will be done by the application afterwards, e.g. through serialization.
  4415. asCScriptObject *obj = reinterpret_cast<asCScriptObject*>(CallAlloc(objType));
  4416. // Pre-initialize the memory so there are no invalid pointers
  4417. ScriptObject_ConstructUnitialized(objType, obj);
  4418. return obj;
  4419. }
  4420. // interface
  4421. void *asCScriptEngine::CreateScriptObjectCopy(void *origObj, const asITypeInfo *type)
  4422. {
  4423. if( origObj == 0 || type == 0 ) return 0;
  4424. void *newObj = 0;
  4425. const asCObjectType *ot = reinterpret_cast<const asCObjectType*>(type);
  4426. if ((ot->flags & asOBJ_SCRIPT_OBJECT) && ot->beh.copyfactory)
  4427. {
  4428. // Call the script class' default factory with a context
  4429. newObj = ScriptObjectCopyFactory(ot, origObj, this);
  4430. }
  4431. else if (ot->beh.copyfactory)
  4432. {
  4433. // Call the copy factory which will allocate the memory then copy the original object
  4434. #ifdef AS_NO_EXCEPTIONS
  4435. newObj = CallGlobalFunctionRetPtr(ot->beh.copyfactory, origObj);
  4436. #else
  4437. try
  4438. {
  4439. newObj = CallGlobalFunctionRetPtr(ot->beh.copyfactory, origObj);
  4440. }
  4441. catch (...)
  4442. {
  4443. asCContext *ctx = reinterpret_cast<asCContext*>(asGetActiveContext());
  4444. if (ctx)
  4445. ctx->HandleAppException();
  4446. }
  4447. #endif
  4448. }
  4449. else if( ot->beh.copyconstruct )
  4450. {
  4451. // Manually allocate the memory, then call the copy constructor
  4452. newObj = CallAlloc(ot);
  4453. #ifdef AS_NO_EXCEPTIONS
  4454. CallObjectMethod(newObj, origObj, ot->beh.copyconstruct);
  4455. #else
  4456. try
  4457. {
  4458. CallObjectMethod(newObj, origObj, ot->beh.copyconstruct);
  4459. }
  4460. catch(...)
  4461. {
  4462. asCContext *ctx = reinterpret_cast<asCContext*>(asGetActiveContext());
  4463. if( ctx )
  4464. ctx->HandleAppException();
  4465. // Free the memory
  4466. CallFree(newObj);
  4467. newObj = 0;
  4468. }
  4469. #endif
  4470. }
  4471. else
  4472. {
  4473. // Allocate the object and then do a value assign
  4474. newObj = CreateScriptObject(type);
  4475. if( newObj == 0 ) return 0;
  4476. AssignScriptObject(newObj, origObj, type);
  4477. }
  4478. return newObj;
  4479. }
  4480. // internal
  4481. void asCScriptEngine::ConstructScriptObjectCopy(void *mem, void *obj, asCObjectType *type)
  4482. {
  4483. if( type == 0 || mem == 0 || obj == 0 ) return;
  4484. // This function is only meant to be used for value types
  4485. asASSERT( type->flags & asOBJ_VALUE );
  4486. // Call the copy constructor if available, else call the default constructor followed by the opAssign
  4487. int funcIndex = type->beh.copyconstruct;
  4488. if( funcIndex )
  4489. {
  4490. CallObjectMethod(mem, obj, funcIndex);
  4491. }
  4492. else
  4493. {
  4494. funcIndex = type->beh.construct;
  4495. if( funcIndex )
  4496. CallObjectMethod(mem, funcIndex);
  4497. AssignScriptObject(mem, obj, type);
  4498. }
  4499. }
  4500. // interface
  4501. int asCScriptEngine::AssignScriptObject(void *dstObj, void *srcObj, const asITypeInfo *type)
  4502. {
  4503. // TODO: Warn about invalid call in message stream (make it optional)
  4504. if( type == 0 || dstObj == 0 || srcObj == 0 ) return asINVALID_ARG;
  4505. const asCObjectType *objType = reinterpret_cast<const asCObjectType*>(type);
  4506. // If value assign for ref types has been disabled, then don't do anything if the type is a ref type
  4507. if (ep.disallowValueAssignForRefType && (objType->flags & asOBJ_REF) && !(objType->flags & asOBJ_SCOPED))
  4508. {
  4509. asIScriptContext *ctx = asGetActiveContext();
  4510. if (ctx)
  4511. ctx->SetException("Cannot do value assignment");
  4512. return asNOT_SUPPORTED;
  4513. }
  4514. // Must not copy if the opAssign is not available and the object is not a POD object
  4515. if( objType->beh.copy )
  4516. {
  4517. asCScriptFunction *func = scriptFunctions[objType->beh.copy];
  4518. if( func->funcType == asFUNC_SYSTEM )
  4519. CallObjectMethod(dstObj, srcObj, objType->beh.copy);
  4520. else
  4521. {
  4522. // Call the script class' opAssign method
  4523. asASSERT( objType->flags & asOBJ_SCRIPT_OBJECT );
  4524. reinterpret_cast<asCScriptObject*>(dstObj)->CopyFrom(reinterpret_cast<asCScriptObject*>(srcObj));
  4525. }
  4526. }
  4527. else if( objType->size && (objType->flags & asOBJ_POD) )
  4528. {
  4529. memcpy(dstObj, srcObj, objType->size);
  4530. }
  4531. return asSUCCESS;
  4532. }
  4533. // interface
  4534. void asCScriptEngine::AddRefScriptObject(void *obj, const asITypeInfo *type)
  4535. {
  4536. // Make sure it is not a null pointer
  4537. if( obj == 0 || type == 0 ) return;
  4538. const asCTypeInfo *ti = static_cast<const asCTypeInfo*>(type);
  4539. if (ti->flags & asOBJ_FUNCDEF)
  4540. {
  4541. CallObjectMethod(obj, functionBehaviours.beh.addref);
  4542. }
  4543. else
  4544. {
  4545. asCObjectType *objType = CastToObjectType(const_cast<asCTypeInfo*>(ti));
  4546. if (objType && objType->beh.addref)
  4547. {
  4548. // Call the addref behaviour
  4549. CallObjectMethod(obj, objType->beh.addref);
  4550. }
  4551. }
  4552. }
  4553. // interface
  4554. void asCScriptEngine::ReleaseScriptObject(void *obj, const asITypeInfo *type)
  4555. {
  4556. // Make sure it is not a null pointer
  4557. if( obj == 0 || type == 0 ) return;
  4558. const asCTypeInfo *ti = static_cast<const asCTypeInfo*>(type);
  4559. if (ti->flags & asOBJ_FUNCDEF)
  4560. {
  4561. CallObjectMethod(obj, functionBehaviours.beh.release);
  4562. }
  4563. else
  4564. {
  4565. asCObjectType *objType = CastToObjectType(const_cast<asCTypeInfo*>(ti));
  4566. if (objType && objType->flags & asOBJ_REF)
  4567. {
  4568. asASSERT((objType->flags & asOBJ_NOCOUNT) || objType->beh.release);
  4569. if (objType->beh.release)
  4570. {
  4571. // Call the release behaviour
  4572. CallObjectMethod(obj, objType->beh.release);
  4573. }
  4574. }
  4575. else if( objType )
  4576. {
  4577. // Call the destructor
  4578. if (objType->beh.destruct)
  4579. CallObjectMethod(obj, objType->beh.destruct);
  4580. else if (objType->flags & asOBJ_LIST_PATTERN)
  4581. DestroyList((asBYTE*)obj, objType);
  4582. // We'll have to trust that the memory for the object was allocated with CallAlloc.
  4583. // This is true if the object was created in the context, or with CreateScriptObject.
  4584. // Then free the memory
  4585. CallFree(obj);
  4586. }
  4587. }
  4588. }
  4589. // interface
  4590. int asCScriptEngine::BeginConfigGroup(const char *groupName)
  4591. {
  4592. // Make sure the group name doesn't already exist
  4593. for( asUINT n = 0; n < configGroups.GetLength(); n++ )
  4594. {
  4595. if( configGroups[n]->groupName == groupName )
  4596. return asNAME_TAKEN;
  4597. }
  4598. if( currentGroup != &defaultGroup )
  4599. return asNOT_SUPPORTED;
  4600. asCConfigGroup *group = asNEW(asCConfigGroup)();
  4601. if( group == 0 )
  4602. return asOUT_OF_MEMORY;
  4603. group->groupName = groupName;
  4604. configGroups.PushLast(group);
  4605. currentGroup = group;
  4606. return 0;
  4607. }
  4608. // interface
  4609. int asCScriptEngine::EndConfigGroup()
  4610. {
  4611. // Raise error if trying to end the default config
  4612. if( currentGroup == &defaultGroup )
  4613. return asERROR;
  4614. currentGroup = &defaultGroup;
  4615. return 0;
  4616. }
  4617. // interface
  4618. int asCScriptEngine::RemoveConfigGroup(const char *groupName)
  4619. {
  4620. // It is not allowed to remove a group that is still in use.
  4621. // It would be possible to change the code in such a way that
  4622. // the group could be removed even though it was still in use,
  4623. // but that would cause severe negative impact on runtime
  4624. // performance, since the VM would then have to be able handle
  4625. // situations where the types, functions, and global variables
  4626. // can be removed at any time.
  4627. for( asUINT n = 0; n < configGroups.GetLength(); n++ )
  4628. {
  4629. if( configGroups[n]->groupName == groupName )
  4630. {
  4631. asCConfigGroup *group = configGroups[n];
  4632. // Remove any unused generated template instances
  4633. // before verifying if the config group is still in use.
  4634. // RemoveTemplateInstanceType() checks if the instance is in use
  4635. for( asUINT g = generatedTemplateTypes.GetLength(); g-- > 0; )
  4636. RemoveTemplateInstanceType(generatedTemplateTypes[g]);
  4637. // Make sure the group isn't referenced by anyone
  4638. if( group->refCount > 0 )
  4639. return asCONFIG_GROUP_IS_IN_USE;
  4640. // Verify if any objects registered in this group is still alive
  4641. if( group->HasLiveObjects() )
  4642. return asCONFIG_GROUP_IS_IN_USE;
  4643. // Remove the group from the list
  4644. if( n == configGroups.GetLength() - 1 )
  4645. configGroups.PopLast();
  4646. else
  4647. configGroups[n] = configGroups.PopLast();
  4648. // Remove the configurations registered with this group
  4649. group->RemoveConfiguration(this);
  4650. asDELETE(group,asCConfigGroup);
  4651. }
  4652. }
  4653. return 0;
  4654. }
  4655. asCConfigGroup *asCScriptEngine::FindConfigGroupForFunction(int funcId) const
  4656. {
  4657. for( asUINT n = 0; n < configGroups.GetLength(); n++ )
  4658. {
  4659. // Check global functions
  4660. asUINT m;
  4661. for( m = 0; m < configGroups[n]->scriptFunctions.GetLength(); m++ )
  4662. {
  4663. if( configGroups[n]->scriptFunctions[m]->id == funcId )
  4664. return configGroups[n];
  4665. }
  4666. }
  4667. return 0;
  4668. }
  4669. asCConfigGroup *asCScriptEngine::FindConfigGroupForGlobalVar(int gvarId) const
  4670. {
  4671. for( asUINT n = 0; n < configGroups.GetLength(); n++ )
  4672. {
  4673. for( asUINT m = 0; m < configGroups[n]->globalProps.GetLength(); m++ )
  4674. {
  4675. if( int(configGroups[n]->globalProps[m]->id) == gvarId )
  4676. return configGroups[n];
  4677. }
  4678. }
  4679. return 0;
  4680. }
  4681. asCConfigGroup *asCScriptEngine::FindConfigGroupForTypeInfo(const asCTypeInfo *objType) const
  4682. {
  4683. for( asUINT n = 0; n < configGroups.GetLength(); n++ )
  4684. {
  4685. for( asUINT m = 0; m < configGroups[n]->types.GetLength(); m++ )
  4686. {
  4687. if( configGroups[n]->types[m] == objType )
  4688. return configGroups[n];
  4689. }
  4690. }
  4691. return 0;
  4692. }
  4693. asCConfigGroup *asCScriptEngine::FindConfigGroupForFuncDef(const asCFuncdefType *funcDef) const
  4694. {
  4695. for( asUINT n = 0; n < configGroups.GetLength(); n++ )
  4696. {
  4697. asCFuncdefType *f = const_cast<asCFuncdefType*>(funcDef);
  4698. if( configGroups[n]->types.Exists(f) )
  4699. return configGroups[n];
  4700. }
  4701. return 0;
  4702. }
  4703. // interface
  4704. asDWORD asCScriptEngine::SetDefaultAccessMask(asDWORD defaultMask)
  4705. {
  4706. asDWORD old = defaultAccessMask;
  4707. defaultAccessMask = defaultMask;
  4708. return old;
  4709. }
  4710. int asCScriptEngine::GetNextScriptFunctionId()
  4711. {
  4712. // This function only returns the next function id that
  4713. // should be used. It doesn't update the internal arrays.
  4714. if( freeScriptFunctionIds.GetLength() )
  4715. return freeScriptFunctionIds[freeScriptFunctionIds.GetLength()-1];
  4716. return (int)scriptFunctions.GetLength();
  4717. }
  4718. void asCScriptEngine::AddScriptFunction(asCScriptFunction *func)
  4719. {
  4720. // Update the internal arrays with the function id that is now used
  4721. if( freeScriptFunctionIds.GetLength() && freeScriptFunctionIds[freeScriptFunctionIds.GetLength()-1] == func->id )
  4722. freeScriptFunctionIds.PopLast();
  4723. if( asUINT(func->id) == scriptFunctions.GetLength() )
  4724. scriptFunctions.PushLast(func);
  4725. else
  4726. {
  4727. // The slot should be empty or already set with the function, which happens if an existing shared function is reused
  4728. asASSERT( scriptFunctions[func->id] == 0 || scriptFunctions[func->id] == func );
  4729. scriptFunctions[func->id] = func;
  4730. }
  4731. }
  4732. void asCScriptEngine::RemoveScriptFunction(asCScriptFunction *func)
  4733. {
  4734. if( func == 0 || func->id < 0 ) return;
  4735. int id = func->id & ~FUNC_IMPORTED;
  4736. if( func->funcType == asFUNC_IMPORTED )
  4737. {
  4738. if( id >= (int)importedFunctions.GetLength() ) return;
  4739. if( importedFunctions[id] )
  4740. {
  4741. // Remove the function from the list of script functions
  4742. if( id == (int)importedFunctions.GetLength() - 1 )
  4743. {
  4744. importedFunctions.PopLast();
  4745. }
  4746. else
  4747. {
  4748. importedFunctions[id] = 0;
  4749. freeImportedFunctionIdxs.PushLast(id);
  4750. }
  4751. }
  4752. }
  4753. else
  4754. {
  4755. if( id >= (int)scriptFunctions.GetLength() ) return;
  4756. asASSERT( func == scriptFunctions[id] );
  4757. if( scriptFunctions[id] )
  4758. {
  4759. // Remove the function from the list of script functions
  4760. if( id == (int)scriptFunctions.GetLength() - 1 )
  4761. {
  4762. scriptFunctions.PopLast();
  4763. }
  4764. else
  4765. {
  4766. scriptFunctions[id] = 0;
  4767. freeScriptFunctionIds.PushLast(id);
  4768. }
  4769. // Is the function used as signature id?
  4770. if( func->signatureId == id )
  4771. {
  4772. // Remove the signature id
  4773. signatureIds.RemoveValue(func);
  4774. // Update all functions using the signature id
  4775. int newSigId = 0;
  4776. for( asUINT n = 0; n < scriptFunctions.GetLength(); n++ )
  4777. {
  4778. if( scriptFunctions[n] && scriptFunctions[n]->signatureId == id )
  4779. {
  4780. if( newSigId == 0 )
  4781. {
  4782. newSigId = scriptFunctions[n]->id;
  4783. signatureIds.PushLast(scriptFunctions[n]);
  4784. }
  4785. scriptFunctions[n]->signatureId = newSigId;
  4786. }
  4787. }
  4788. }
  4789. }
  4790. }
  4791. }
  4792. // internal
  4793. void asCScriptEngine::RemoveFuncdef(asCFuncdefType *funcdef)
  4794. {
  4795. funcDefs.RemoveValue(funcdef);
  4796. }
  4797. // interface
  4798. int asCScriptEngine::RegisterFuncdef(const char *decl)
  4799. {
  4800. if( decl == 0 ) return ConfigError(asINVALID_ARG, "RegisterFuncdef", decl, 0);
  4801. // Parse the function declaration
  4802. asCScriptFunction *func = asNEW(asCScriptFunction)(this, 0, asFUNC_FUNCDEF);
  4803. if( func == 0 )
  4804. return ConfigError(asOUT_OF_MEMORY, "RegisterFuncdef", decl, 0);
  4805. asCBuilder bld(this, 0);
  4806. asCObjectType *parentClass = 0;
  4807. int r = bld.ParseFunctionDeclaration(0, decl, func, false, 0, 0, defaultNamespace, 0, &parentClass);
  4808. if( r < 0 )
  4809. {
  4810. // Set as dummy function before deleting
  4811. func->funcType = asFUNC_DUMMY;
  4812. asDELETE(func,asCScriptFunction);
  4813. return ConfigError(asINVALID_DECLARATION, "RegisterFuncdef", decl, 0);
  4814. }
  4815. // Check name conflicts
  4816. r = bld.CheckNameConflict(func->name.AddressOf(), 0, 0, defaultNamespace, true);
  4817. if( r < 0 )
  4818. {
  4819. asDELETE(func,asCScriptFunction);
  4820. return ConfigError(asNAME_TAKEN, "RegisterFuncdef", decl, 0);
  4821. }
  4822. func->id = GetNextScriptFunctionId();
  4823. AddScriptFunction(func);
  4824. asCFuncdefType *fdt = asNEW(asCFuncdefType)(this, func);
  4825. funcDefs.PushLast(fdt); // doesn't increase refcount
  4826. registeredFuncDefs.PushLast(fdt); // doesn't increase refcount
  4827. allRegisteredTypes.Insert(asSNameSpaceNamePair(fdt->nameSpace, fdt->name), fdt); // constructor already set the ref count to 1
  4828. currentGroup->types.PushLast(fdt);
  4829. if (parentClass)
  4830. {
  4831. parentClass->childFuncDefs.PushLast(fdt);
  4832. fdt->parentClass = parentClass;
  4833. // Check if the method restricts that use of the template to value types or reference types
  4834. if (parentClass->flags & asOBJ_TEMPLATE)
  4835. {
  4836. r = SetTemplateRestrictions(parentClass, func, "RegisterFuncdef", decl);
  4837. if (r < 0)
  4838. return r;
  4839. }
  4840. }
  4841. // If parameter type from other groups are used, add references
  4842. currentGroup->AddReferencesForFunc(this, func);
  4843. // Return the type id as success
  4844. return GetTypeIdFromDataType(asCDataType::CreateType(fdt, false));
  4845. }
  4846. // interface
  4847. asUINT asCScriptEngine::GetFuncdefCount() const
  4848. {
  4849. return asUINT(registeredFuncDefs.GetLength());
  4850. }
  4851. // interface
  4852. asITypeInfo *asCScriptEngine::GetFuncdefByIndex(asUINT index) const
  4853. {
  4854. if( index >= registeredFuncDefs.GetLength() )
  4855. return 0;
  4856. return registeredFuncDefs[index];
  4857. }
  4858. // internal
  4859. asCFuncdefType *asCScriptEngine::FindMatchingFuncdef(asCScriptFunction *func, asCModule *module)
  4860. {
  4861. asCFuncdefType *funcDef = func->funcdefType;
  4862. if (funcDef == 0)
  4863. {
  4864. // Check if there is any matching funcdefs already in the engine that can be reused
  4865. for (asUINT n = 0; n < funcDefs.GetLength(); n++)
  4866. {
  4867. if (funcDefs[n]->funcdef->IsSignatureExceptNameEqual(func))
  4868. {
  4869. if (func->IsShared() && !funcDefs[n]->funcdef->IsShared())
  4870. continue;
  4871. funcDef = funcDefs[n];
  4872. break;
  4873. }
  4874. }
  4875. }
  4876. if (funcDef == 0)
  4877. {
  4878. // Create a matching funcdef
  4879. asCScriptFunction *fd = asNEW(asCScriptFunction)(this, 0, asFUNC_FUNCDEF);
  4880. fd->name = func->name;
  4881. fd->nameSpace = func->nameSpace;
  4882. fd->SetShared(func->IsShared());
  4883. fd->returnType = func->returnType;
  4884. fd->parameterTypes = func->parameterTypes;
  4885. fd->inOutFlags = func->inOutFlags;
  4886. funcDef = asNEW(asCFuncdefType)(this, fd);
  4887. funcDefs.PushLast(funcDef); // doesn't increase the refCount
  4888. fd->id = GetNextScriptFunctionId();
  4889. AddScriptFunction(fd);
  4890. if (module)
  4891. {
  4892. // Add the new funcdef to the module so it will
  4893. // be available when saving the bytecode
  4894. funcDef->module = module;
  4895. module->funcDefs.PushLast(funcDef); // the refCount was already accounted for in the constructor
  4896. }
  4897. // Observe, if the funcdef is created without informing a module a reference will be stored in the
  4898. // engine's funcDefs array, but it will not be owned by any module. This means that it will live on
  4899. // until the engine is released.
  4900. }
  4901. if (funcDef && module && funcDef->module && funcDef->module != module)
  4902. {
  4903. // Unless this is a registered funcDef the returned funcDef must
  4904. // be stored as part of the module for saving/loading bytecode
  4905. if (!module->funcDefs.Exists(funcDef))
  4906. {
  4907. module->funcDefs.PushLast(funcDef);
  4908. funcDef->AddRefInternal();
  4909. }
  4910. else
  4911. {
  4912. asASSERT(funcDef->IsShared());
  4913. }
  4914. }
  4915. return funcDef;
  4916. }
  4917. // interface
  4918. // TODO: typedef: Accept complex types for the typedefs
  4919. int asCScriptEngine::RegisterTypedef(const char *type, const char *decl)
  4920. {
  4921. if( type == 0 ) return ConfigError(asINVALID_NAME, "RegisterTypedef", type, decl);
  4922. // Verify if the name has been registered as a type already
  4923. // TODO: Must check against registered funcdefs too
  4924. if( GetRegisteredType(type, defaultNamespace) )
  4925. // Let the application recover from this error, for example if the same typedef is registered twice
  4926. return asALREADY_REGISTERED;
  4927. // Grab the data type
  4928. size_t tokenLen;
  4929. eTokenType token;
  4930. asCDataType dataType;
  4931. // Create the data type
  4932. token = tok.GetToken(decl, strlen(decl), &tokenLen);
  4933. switch(token)
  4934. {
  4935. case ttBool:
  4936. case ttInt:
  4937. case ttInt8:
  4938. case ttInt16:
  4939. case ttInt64:
  4940. case ttUInt:
  4941. case ttUInt8:
  4942. case ttUInt16:
  4943. case ttUInt64:
  4944. case ttFloat:
  4945. case ttDouble:
  4946. if( strlen(decl) != tokenLen )
  4947. {
  4948. return ConfigError(asINVALID_TYPE, "RegisterTypedef", type, decl);
  4949. }
  4950. break;
  4951. default:
  4952. return ConfigError(asINVALID_TYPE, "RegisterTypedef", type, decl);
  4953. }
  4954. dataType = asCDataType::CreatePrimitive(token, false);
  4955. // Make sure the name is not a reserved keyword
  4956. token = tok.GetToken(type, strlen(type), &tokenLen);
  4957. if( token != ttIdentifier || strlen(type) != tokenLen )
  4958. return ConfigError(asINVALID_NAME, "RegisterTypedef", type, decl);
  4959. asCBuilder bld(this, 0);
  4960. int r = bld.CheckNameConflict(type, 0, 0, defaultNamespace, true);
  4961. if( r < 0 )
  4962. return ConfigError(asNAME_TAKEN, "RegisterTypedef", type, decl);
  4963. // Don't have to check against members of object
  4964. // types as they are allowed to use the names
  4965. // Put the data type in the list
  4966. asCTypedefType *td = asNEW(asCTypedefType)(this);
  4967. if( td == 0 )
  4968. return ConfigError(asOUT_OF_MEMORY, "RegisterTypedef", type, decl);
  4969. td->flags = asOBJ_TYPEDEF;
  4970. td->size = dataType.GetSizeInMemoryBytes();
  4971. td->name = type;
  4972. td->nameSpace = defaultNamespace;
  4973. td->aliasForType = dataType;
  4974. allRegisteredTypes.Insert(asSNameSpaceNamePair(td->nameSpace, td->name), td);
  4975. registeredTypeDefs.PushLast(td);
  4976. currentGroup->types.PushLast(td);
  4977. return GetTypeIdByDecl(type);
  4978. }
  4979. // interface
  4980. asUINT asCScriptEngine::GetTypedefCount() const
  4981. {
  4982. return asUINT(registeredTypeDefs.GetLength());
  4983. }
  4984. // interface
  4985. asITypeInfo *asCScriptEngine::GetTypedefByIndex(asUINT index) const
  4986. {
  4987. if( index >= registeredTypeDefs.GetLength() )
  4988. return 0;
  4989. return registeredTypeDefs[index];
  4990. }
  4991. // interface
  4992. int asCScriptEngine::RegisterEnum(const char *name)
  4993. {
  4994. // Check the name
  4995. if( NULL == name )
  4996. return ConfigError(asINVALID_NAME, "RegisterEnum", name, 0);
  4997. // Verify if the name has been registered as a type already
  4998. if( GetRegisteredType(name, defaultNamespace) )
  4999. return asALREADY_REGISTERED;
  5000. // Use builder to parse the datatype
  5001. asCDataType dt;
  5002. asCBuilder bld(this, 0);
  5003. bool oldMsgCallback = msgCallback; msgCallback = false;
  5004. int r = bld.ParseDataType(name, &dt, defaultNamespace);
  5005. msgCallback = oldMsgCallback;
  5006. if( r >= 0 )
  5007. {
  5008. // If it is not in the defaultNamespace then the type was successfully parsed because
  5009. // it is declared in a parent namespace which shouldn't be treated as an error
  5010. if( dt.GetTypeInfo() && dt.GetTypeInfo()->nameSpace == defaultNamespace )
  5011. return ConfigError(asERROR, "RegisterEnum", name, 0);
  5012. }
  5013. // Make sure the name is not a reserved keyword
  5014. size_t tokenLen;
  5015. int token = tok.GetToken(name, strlen(name), &tokenLen);
  5016. if( token != ttIdentifier || strlen(name) != tokenLen )
  5017. return ConfigError(asINVALID_NAME, "RegisterEnum", name, 0);
  5018. r = bld.CheckNameConflict(name, 0, 0, defaultNamespace, true);
  5019. if( r < 0 )
  5020. return ConfigError(asNAME_TAKEN, "RegisterEnum", name, 0);
  5021. asCEnumType *st = asNEW(asCEnumType)(this);
  5022. if( st == 0 )
  5023. return ConfigError(asOUT_OF_MEMORY, "RegisterEnum", name, 0);
  5024. asCDataType dataType;
  5025. dataType.CreatePrimitive(ttInt, false);
  5026. st->flags = asOBJ_ENUM | asOBJ_SHARED;
  5027. st->size = 4;
  5028. st->name = name;
  5029. st->nameSpace = defaultNamespace;
  5030. allRegisteredTypes.Insert(asSNameSpaceNamePair(st->nameSpace, st->name), st);
  5031. registeredEnums.PushLast(st);
  5032. currentGroup->types.PushLast(st);
  5033. return GetTypeIdByDecl(name);
  5034. }
  5035. // interface
  5036. int asCScriptEngine::RegisterEnumValue(const char *typeName, const char *valueName, int value)
  5037. {
  5038. // Verify that the correct config group is used
  5039. if( currentGroup->FindType(typeName) == 0 )
  5040. return ConfigError(asWRONG_CONFIG_GROUP, "RegisterEnumValue", typeName, valueName);
  5041. asCDataType dt;
  5042. int r;
  5043. asCBuilder bld(this, 0);
  5044. r = bld.ParseDataType(typeName, &dt, defaultNamespace);
  5045. if( r < 0 )
  5046. return ConfigError(r, "RegisterEnumValue", typeName, valueName);
  5047. // Store the enum value
  5048. asCEnumType *ot = CastToEnumType(dt.GetTypeInfo());
  5049. if( ot == 0 )
  5050. return ConfigError(asINVALID_TYPE, "RegisterEnumValue", typeName, valueName);
  5051. if( NULL == valueName )
  5052. return ConfigError(asINVALID_NAME, "RegisterEnumValue", typeName, valueName);
  5053. asUINT tokenLen = 0;
  5054. asETokenClass tokenClass = ParseToken(valueName, 0, &tokenLen);
  5055. if( tokenClass != asTC_IDENTIFIER || tokenLen != strlen(valueName) )
  5056. return ConfigError(asINVALID_NAME, "RegisterEnumValue", typeName, valueName);
  5057. for( unsigned int n = 0; n < ot->enumValues.GetLength(); n++ )
  5058. {
  5059. if( ot->enumValues[n]->name == valueName )
  5060. return ConfigError(asALREADY_REGISTERED, "RegisterEnumValue", typeName, valueName);
  5061. }
  5062. asSEnumValue *e = asNEW(asSEnumValue);
  5063. if( e == 0 )
  5064. return ConfigError(asOUT_OF_MEMORY, "RegisterEnumValue", typeName, valueName);
  5065. e->name = valueName;
  5066. e->value = value;
  5067. ot->enumValues.PushLast(e);
  5068. return asSUCCESS;
  5069. }
  5070. // interface
  5071. asUINT asCScriptEngine::GetEnumCount() const
  5072. {
  5073. return registeredEnums.GetLength();
  5074. }
  5075. // interface
  5076. asITypeInfo *asCScriptEngine::GetEnumByIndex(asUINT index) const
  5077. {
  5078. if( index >= registeredEnums.GetLength() )
  5079. return 0;
  5080. return registeredEnums[index];
  5081. }
  5082. // interface
  5083. asUINT asCScriptEngine::GetObjectTypeCount() const
  5084. {
  5085. return asUINT(registeredObjTypes.GetLength());
  5086. }
  5087. // interface
  5088. asITypeInfo *asCScriptEngine::GetObjectTypeByIndex(asUINT index) const
  5089. {
  5090. if( index >= registeredObjTypes.GetLength() )
  5091. return 0;
  5092. return registeredObjTypes[index];
  5093. }
  5094. // interface
  5095. asITypeInfo *asCScriptEngine::GetTypeInfoByName(const char *name) const
  5096. {
  5097. asSNameSpace *ns = defaultNamespace;
  5098. while (ns)
  5099. {
  5100. // Check the object types
  5101. for (asUINT n = 0; n < registeredObjTypes.GetLength(); n++)
  5102. {
  5103. if (registeredObjTypes[n]->name == name &&
  5104. registeredObjTypes[n]->nameSpace == ns)
  5105. return registeredObjTypes[n];
  5106. }
  5107. // Perhaps it is a template type? In this case
  5108. // the returned type will be the generic type
  5109. for (asUINT n = 0; n < registeredTemplateTypes.GetLength(); n++)
  5110. {
  5111. if (registeredTemplateTypes[n]->name == name &&
  5112. registeredTemplateTypes[n]->nameSpace == ns)
  5113. return registeredTemplateTypes[n];
  5114. }
  5115. // Check the enum types
  5116. for (asUINT n = 0; n < registeredEnums.GetLength(); n++)
  5117. {
  5118. if (registeredEnums[n]->name == name &&
  5119. registeredEnums[n]->nameSpace == ns)
  5120. return registeredEnums[n];
  5121. }
  5122. // Check the typedefs
  5123. for (asUINT n = 0; n < registeredTypeDefs.GetLength();n++)
  5124. {
  5125. if (registeredTypeDefs[n]->name == name &&
  5126. registeredTypeDefs[n]->nameSpace == ns)
  5127. return registeredTypeDefs[n];
  5128. }
  5129. // Recursively search parent namespace
  5130. ns = GetParentNameSpace(ns);
  5131. }
  5132. return 0;
  5133. }
  5134. // interface
  5135. asITypeInfo *asCScriptEngine::GetTypeInfoById(int typeId) const
  5136. {
  5137. asCDataType dt = GetDataTypeFromTypeId(typeId);
  5138. // Is the type id valid?
  5139. if (!dt.IsValid()) return 0;
  5140. return dt.GetTypeInfo();
  5141. }
  5142. // interface
  5143. asIScriptFunction *asCScriptEngine::GetFunctionById(int funcId) const
  5144. {
  5145. return GetScriptFunction(funcId);
  5146. }
  5147. // internal
  5148. bool asCScriptEngine::IsTemplateType(const char *name) const
  5149. {
  5150. // Only look in the list of template types (not instance types)
  5151. for( unsigned int n = 0; n < registeredTemplateTypes.GetLength(); n++ )
  5152. {
  5153. asCObjectType *type = registeredTemplateTypes[n];
  5154. if( type && type->name == name )
  5155. return true;
  5156. }
  5157. return false;
  5158. }
  5159. // internal
  5160. int asCScriptEngine::GetScriptSectionNameIndex(const char *name)
  5161. {
  5162. ACQUIREEXCLUSIVE(engineRWLock);
  5163. // TODO: These names are only released when the engine is freed. The assumption is that
  5164. // the same script section names will be reused instead of there always being new
  5165. // names. Is this assumption valid? Do we need to add reference counting?
  5166. // Store the script section names for future reference
  5167. for( asUINT n = 0; n < scriptSectionNames.GetLength(); n++ )
  5168. {
  5169. if( scriptSectionNames[n]->Compare(name) == 0 )
  5170. {
  5171. RELEASEEXCLUSIVE(engineRWLock);
  5172. return n;
  5173. }
  5174. }
  5175. asCString *str = asNEW(asCString)(name);
  5176. if( str )
  5177. scriptSectionNames.PushLast(str);
  5178. int r = int(scriptSectionNames.GetLength()-1);
  5179. RELEASEEXCLUSIVE(engineRWLock);
  5180. return r;
  5181. }
  5182. // interface
  5183. void asCScriptEngine::SetEngineUserDataCleanupCallback(asCLEANENGINEFUNC_t callback, asPWORD type)
  5184. {
  5185. ACQUIREEXCLUSIVE(engineRWLock);
  5186. for( asUINT n = 0; n < cleanEngineFuncs.GetLength(); n++ )
  5187. {
  5188. if( cleanEngineFuncs[n].type == type )
  5189. {
  5190. cleanEngineFuncs[n].cleanFunc = callback;
  5191. RELEASEEXCLUSIVE(engineRWLock);
  5192. return;
  5193. }
  5194. }
  5195. SEngineClean otc = {type, callback};
  5196. cleanEngineFuncs.PushLast(otc);
  5197. RELEASEEXCLUSIVE(engineRWLock);
  5198. }
  5199. // interface
  5200. void asCScriptEngine::SetModuleUserDataCleanupCallback(asCLEANMODULEFUNC_t callback, asPWORD type)
  5201. {
  5202. ACQUIREEXCLUSIVE(engineRWLock);
  5203. for( asUINT n = 0; n < cleanModuleFuncs.GetLength(); n++ )
  5204. {
  5205. if( cleanModuleFuncs[n].type == type )
  5206. {
  5207. cleanModuleFuncs[n].cleanFunc = callback;
  5208. RELEASEEXCLUSIVE(engineRWLock);
  5209. return;
  5210. }
  5211. }
  5212. SModuleClean otc = {type, callback};
  5213. cleanModuleFuncs.PushLast(otc);
  5214. RELEASEEXCLUSIVE(engineRWLock);
  5215. }
  5216. // interface
  5217. void asCScriptEngine::SetContextUserDataCleanupCallback(asCLEANCONTEXTFUNC_t callback, asPWORD type)
  5218. {
  5219. ACQUIREEXCLUSIVE(engineRWLock);
  5220. for( asUINT n = 0; n < cleanContextFuncs.GetLength(); n++ )
  5221. {
  5222. if( cleanContextFuncs[n].type == type )
  5223. {
  5224. cleanContextFuncs[n].cleanFunc = callback;
  5225. RELEASEEXCLUSIVE(engineRWLock);
  5226. return;
  5227. }
  5228. }
  5229. SContextClean otc = {type, callback};
  5230. cleanContextFuncs.PushLast(otc);
  5231. RELEASEEXCLUSIVE(engineRWLock);
  5232. }
  5233. // interface
  5234. void asCScriptEngine::SetFunctionUserDataCleanupCallback(asCLEANFUNCTIONFUNC_t callback, asPWORD type)
  5235. {
  5236. ACQUIREEXCLUSIVE(engineRWLock);
  5237. for( asUINT n = 0; n < cleanFunctionFuncs.GetLength(); n++ )
  5238. {
  5239. if( cleanFunctionFuncs[n].type == type )
  5240. {
  5241. cleanFunctionFuncs[n].cleanFunc = callback;
  5242. RELEASEEXCLUSIVE(engineRWLock);
  5243. return;
  5244. }
  5245. }
  5246. SFunctionClean otc = {type, callback};
  5247. cleanFunctionFuncs.PushLast(otc);
  5248. RELEASEEXCLUSIVE(engineRWLock);
  5249. }
  5250. // interface
  5251. void asCScriptEngine::SetTypeInfoUserDataCleanupCallback(asCLEANTYPEINFOFUNC_t callback, asPWORD type)
  5252. {
  5253. ACQUIREEXCLUSIVE(engineRWLock);
  5254. for( asUINT n = 0; n < cleanTypeInfoFuncs.GetLength(); n++ )
  5255. {
  5256. if( cleanTypeInfoFuncs[n].type == type )
  5257. {
  5258. cleanTypeInfoFuncs[n].cleanFunc = callback;
  5259. RELEASEEXCLUSIVE(engineRWLock);
  5260. return;
  5261. }
  5262. }
  5263. STypeInfoClean otc = {type, callback};
  5264. cleanTypeInfoFuncs.PushLast(otc);
  5265. RELEASEEXCLUSIVE(engineRWLock);
  5266. }
  5267. // interface
  5268. void asCScriptEngine::SetScriptObjectUserDataCleanupCallback(asCLEANSCRIPTOBJECTFUNC_t callback, asPWORD type)
  5269. {
  5270. ACQUIREEXCLUSIVE(engineRWLock);
  5271. for( asUINT n = 0; n < cleanScriptObjectFuncs.GetLength(); n++ )
  5272. {
  5273. if( cleanScriptObjectFuncs[n].type == type )
  5274. {
  5275. cleanScriptObjectFuncs[n].cleanFunc = callback;
  5276. RELEASEEXCLUSIVE(engineRWLock);
  5277. return;
  5278. }
  5279. }
  5280. SScriptObjClean soc = {type, callback};
  5281. cleanScriptObjectFuncs.PushLast(soc);
  5282. RELEASEEXCLUSIVE(engineRWLock);
  5283. }
  5284. // interface
  5285. int asCScriptEngine::SetTranslateAppExceptionCallback(asSFuncPtr callback, void *param, int callConv)
  5286. {
  5287. #ifdef AS_NO_EXCEPTIONS
  5288. return asNOT_SUPPORTED;
  5289. #else
  5290. if (callback.ptr.f.func == 0)
  5291. {
  5292. // Clear the callback
  5293. translateExceptionCallback = false;
  5294. return asSUCCESS;
  5295. }
  5296. // Detect the new callback
  5297. translateExceptionCallback = true;
  5298. translateExceptionCallbackObj = param;
  5299. bool isObj = false;
  5300. if ((unsigned)callConv == asCALL_GENERIC || (unsigned)callConv == asCALL_THISCALL_OBJFIRST || (unsigned)callConv == asCALL_THISCALL_OBJLAST)
  5301. return asNOT_SUPPORTED;
  5302. if ((unsigned)callConv >= asCALL_THISCALL)
  5303. {
  5304. isObj = true;
  5305. if (param == 0)
  5306. {
  5307. translateExceptionCallback = false;
  5308. return asINVALID_ARG;
  5309. }
  5310. }
  5311. int r = DetectCallingConvention(isObj, callback, callConv, 0, &translateExceptionCallbackFunc);
  5312. if (r < 0)
  5313. translateExceptionCallback = false;
  5314. return r;
  5315. #endif
  5316. }
  5317. // internal
  5318. asCObjectType *asCScriptEngine::GetListPatternType(int listPatternFuncId)
  5319. {
  5320. // Get the object type either from the constructor's object for value types
  5321. // or from the factory's return type for reference types
  5322. asCObjectType *ot = scriptFunctions[listPatternFuncId]->objectType;
  5323. if( ot == 0 )
  5324. ot = CastToObjectType(scriptFunctions[listPatternFuncId]->returnType.GetTypeInfo());
  5325. asASSERT( ot );
  5326. // Check if this object type already has a list pattern type
  5327. for( asUINT n = 0; n < listPatternTypes.GetLength(); n++ )
  5328. {
  5329. if( listPatternTypes[n]->templateSubTypes[0].GetTypeInfo() == ot )
  5330. return listPatternTypes[n];
  5331. }
  5332. // Create a new list pattern type for the given object type
  5333. asCObjectType *lpt = asNEW(asCObjectType)(this);
  5334. lpt->templateSubTypes.PushLast(asCDataType::CreateType(ot, false));
  5335. lpt->flags = asOBJ_LIST_PATTERN;
  5336. listPatternTypes.PushLast(lpt);
  5337. return lpt;
  5338. }
  5339. // internal
  5340. void asCScriptEngine::DestroyList(asBYTE *buffer, const asCObjectType *listPatternType)
  5341. {
  5342. asASSERT( listPatternType && (listPatternType->flags & asOBJ_LIST_PATTERN) );
  5343. // Get the list pattern from the listFactory function
  5344. // TODO: runtime optimize: Store the used list factory in the listPatternType itself
  5345. // TODO: runtime optimize: Keep a flag to indicate if there is really a need to free anything
  5346. asCObjectType *ot = CastToObjectType(listPatternType->templateSubTypes[0].GetTypeInfo());
  5347. asCScriptFunction *listFactory = scriptFunctions[ot->beh.listFactory];
  5348. asASSERT( listFactory );
  5349. asSListPatternNode *node = listFactory->listPattern;
  5350. DestroySubList(buffer, node);
  5351. asASSERT( node->type == asLPT_END );
  5352. }
  5353. // internal
  5354. void asCScriptEngine::DestroySubList(asBYTE *&buffer, asSListPatternNode *&node)
  5355. {
  5356. asASSERT( node->type == asLPT_START );
  5357. int count = 0;
  5358. node = node->next;
  5359. while( node )
  5360. {
  5361. if( node->type == asLPT_REPEAT || node->type == asLPT_REPEAT_SAME )
  5362. {
  5363. // Align the offset to 4 bytes boundary
  5364. if( (asPWORD(buffer) & 0x3) )
  5365. buffer += 4 - (asPWORD(buffer) & 0x3);
  5366. // Determine how many times the pattern repeat
  5367. count = *(asUINT*)buffer;
  5368. buffer += 4;
  5369. if( count == 0 )
  5370. {
  5371. // Skip the sub pattern that was expected to be repeated, otherwise
  5372. // we'll try to delete things that don't exist in the buffer
  5373. node = node->next;
  5374. if( node->type == asLPT_START )
  5375. {
  5376. int subCount = 1;
  5377. do
  5378. {
  5379. node = node->next;
  5380. if( node->type == asLPT_START )
  5381. subCount++;
  5382. else if( node->type == asLPT_END )
  5383. subCount--;
  5384. } while( subCount > 0 );
  5385. return;
  5386. }
  5387. }
  5388. }
  5389. else if( node->type == asLPT_TYPE )
  5390. {
  5391. // If we're not in a repeat iteration, then only 1 value should be destroyed
  5392. if( count <= 0 )
  5393. count = 1;
  5394. asCDataType dt = reinterpret_cast<asSListPatternDataTypeNode*>(node)->dataType;
  5395. bool isVarType = dt.GetTokenType() == ttQuestion;
  5396. while( count-- )
  5397. {
  5398. if( isVarType )
  5399. {
  5400. // Align the offset to 4 bytes boundary
  5401. if( (asPWORD(buffer) & 0x3) )
  5402. buffer += 4 - (asPWORD(buffer) & 0x3);
  5403. int typeId = *(int*)buffer;
  5404. buffer += 4;
  5405. dt = GetDataTypeFromTypeId(typeId);
  5406. }
  5407. asCTypeInfo *ti = dt.GetTypeInfo();
  5408. if( ti && (ti->flags & asOBJ_ENUM) == 0 )
  5409. {
  5410. // Free all instances of this type
  5411. if( ti->flags & asOBJ_VALUE )
  5412. {
  5413. asUINT size = ti->GetSize();
  5414. // Align the offset to 4 bytes boundary
  5415. if( size >= 4 && (asPWORD(buffer) & 0x3) )
  5416. buffer += 4 - (asPWORD(buffer) & 0x3);
  5417. asCObjectType *ot = CastToObjectType(ti);
  5418. if( ot && ot->beh.destruct )
  5419. {
  5420. // Only call the destructor if the object has been created
  5421. // We'll assume the object has been created if any byte in
  5422. // the memory is different from 0.
  5423. // TODO: This is not really correct, as bytes may have been
  5424. // modified by the constructor, but then an exception
  5425. // thrown aborting the initialization. The engine
  5426. // really should be keeping track of which objects has
  5427. // been successfully initialized.
  5428. for( asUINT n = 0; n < size; n++ )
  5429. {
  5430. if( buffer[n] != 0 )
  5431. {
  5432. void *ptr = (void*)buffer;
  5433. CallObjectMethod(ptr, ot->beh.destruct);
  5434. break;
  5435. }
  5436. }
  5437. }
  5438. // Advance the pointer in the buffer
  5439. buffer += size;
  5440. }
  5441. else
  5442. {
  5443. // Align the offset to 4 bytes boundary
  5444. if( asPWORD(buffer) & 0x3 )
  5445. buffer += 4 - (asPWORD(buffer) & 0x3);
  5446. // Call the release behaviour
  5447. void *ptr = *(void**)buffer;
  5448. if( ptr )
  5449. ReleaseScriptObject(ptr, ti);
  5450. buffer += AS_PTR_SIZE*4;
  5451. }
  5452. }
  5453. else
  5454. {
  5455. asUINT size = dt.GetSizeInMemoryBytes();
  5456. // Align the offset to 4 bytes boundary
  5457. if( size >= 4 && (asPWORD(buffer) & 0x3) )
  5458. buffer += 4 - (asPWORD(buffer) & 0x3);
  5459. // Advance the buffer
  5460. buffer += size;
  5461. }
  5462. }
  5463. }
  5464. else if( node->type == asLPT_START )
  5465. {
  5466. // If we're not in a repeat iteration, then only 1 value should be destroyed
  5467. if( count <= 0 )
  5468. count = 1;
  5469. while( count-- )
  5470. {
  5471. asSListPatternNode *subList = node;
  5472. DestroySubList(buffer, subList);
  5473. asASSERT( subList->type == asLPT_END );
  5474. if( count == 0 )
  5475. node = subList;
  5476. }
  5477. }
  5478. else if( node->type == asLPT_END )
  5479. {
  5480. return;
  5481. }
  5482. else
  5483. {
  5484. asASSERT( false );
  5485. }
  5486. node = node->next;
  5487. }
  5488. }
  5489. // internal
  5490. asSNameSpace *asCScriptEngine::GetParentNameSpace(asSNameSpace *ns) const
  5491. {
  5492. if( ns == 0 ) return 0;
  5493. if( ns == nameSpaces[0] ) return 0;
  5494. asCString scope = ns->name;
  5495. int pos = scope.FindLast("::");
  5496. if( pos >= 0 )
  5497. {
  5498. scope = scope.SubString(0, pos);
  5499. return FindNameSpace(scope.AddressOf());
  5500. }
  5501. return nameSpaces[0];
  5502. }
  5503. END_AS_NAMESPACE