as_scriptengine.cpp 172 KB

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