as_scriptengine.cpp 196 KB

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