as_scriptengine.cpp 193 KB

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