as_builder.cpp 138 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797
  1. /*
  2. AngelCode Scripting Library
  3. Copyright (c) 2003-2013 Andreas Jonsson
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any
  6. damages arising from the use of this software.
  7. Permission is granted to anyone to use this software for any
  8. purpose, including commercial applications, and to alter it and
  9. redistribute it freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you
  11. must not claim that you wrote the original software. If you use
  12. this software in a product, an acknowledgment in the product
  13. documentation would be appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and
  15. must not be misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source
  17. distribution.
  18. The original version of this library can be located at:
  19. http://www.angelcode.com/angelscript/
  20. Andreas Jonsson
  21. [email protected]
  22. */
  23. // Modified by Lasse Oorni for Urho3D
  24. //
  25. // as_builder.cpp
  26. //
  27. // This is the class that manages the compilation of the scripts
  28. //
  29. #include "as_config.h"
  30. #include "as_builder.h"
  31. #include "as_parser.h"
  32. #include "as_compiler.h"
  33. #include "as_tokendef.h"
  34. #include "as_string_util.h"
  35. #include "as_outputbuffer.h"
  36. #include "as_texts.h"
  37. #include "as_scriptobject.h"
  38. #include "as_debug.h"
  39. BEGIN_AS_NAMESPACE
  40. #ifndef AS_NO_COMPILER
  41. // asCSymbolTable template specializations for sGlobalVariableDescription entries
  42. template<>
  43. void asCSymbolTable<sGlobalVariableDescription>::GetKey(const sGlobalVariableDescription *entry, asCString &key) const
  44. {
  45. // TODO: optimize: The key should be a struct, composed of namespace pointer and the name string
  46. asSNameSpace *ns = entry->property->nameSpace;
  47. asCString name = entry->property->name;
  48. key = ns->name + "::" + name;
  49. }
  50. // Comparator for exact variable search
  51. class asCCompGlobVarType : public asIFilter
  52. {
  53. public:
  54. const asCDataType &m_type;
  55. asCCompGlobVarType(const asCDataType &type) : m_type(type) {}
  56. bool operator()(const void *p) const
  57. {
  58. const sGlobalVariableDescription* desc = reinterpret_cast<const sGlobalVariableDescription*>(p);
  59. return desc->datatype == m_type;
  60. }
  61. private:
  62. // The assignment operator is required for MSVC9, otherwise it will complain that it is not possible to auto generate the operator
  63. asCCompGlobVarType &operator=(const asCCompGlobVarType &) {return *this;}
  64. };
  65. #endif
  66. asCBuilder::asCBuilder(asCScriptEngine *engine, asCModule *module)
  67. {
  68. this->engine = engine;
  69. this->module = module;
  70. }
  71. asCBuilder::~asCBuilder()
  72. {
  73. #ifndef AS_NO_COMPILER
  74. asUINT n;
  75. // Free all functions
  76. for( n = 0; n < functions.GetLength(); n++ )
  77. {
  78. if( functions[n] )
  79. {
  80. if( functions[n]->node )
  81. {
  82. functions[n]->node->Destroy(engine);
  83. }
  84. asDELETE(functions[n],sFunctionDescription);
  85. }
  86. functions[n] = 0;
  87. }
  88. // Free all global variables
  89. asCSymbolTable<sGlobalVariableDescription>::iterator it = globVariables.List();
  90. while( it )
  91. {
  92. if( (*it)->nextNode )
  93. (*it)->nextNode->Destroy(engine);
  94. asDELETE((*it),sGlobalVariableDescription);
  95. it++;
  96. }
  97. globVariables.Clear();
  98. // Free all the loaded files
  99. for( n = 0; n < scripts.GetLength(); n++ )
  100. {
  101. if( scripts[n] )
  102. {
  103. asDELETE(scripts[n],asCScriptCode);
  104. }
  105. scripts[n] = 0;
  106. }
  107. // Free all class declarations
  108. for( n = 0; n < classDeclarations.GetLength(); n++ )
  109. {
  110. if( classDeclarations[n] )
  111. {
  112. if( classDeclarations[n]->node )
  113. {
  114. classDeclarations[n]->node->Destroy(engine);
  115. }
  116. asDELETE(classDeclarations[n],sClassDeclaration);
  117. classDeclarations[n] = 0;
  118. }
  119. }
  120. for( n = 0; n < interfaceDeclarations.GetLength(); n++ )
  121. {
  122. if( interfaceDeclarations[n] )
  123. {
  124. if( interfaceDeclarations[n]->node )
  125. {
  126. interfaceDeclarations[n]->node->Destroy(engine);
  127. }
  128. asDELETE(interfaceDeclarations[n],sClassDeclaration);
  129. interfaceDeclarations[n] = 0;
  130. }
  131. }
  132. for( n = 0; n < namedTypeDeclarations.GetLength(); n++ )
  133. {
  134. if( namedTypeDeclarations[n] )
  135. {
  136. if( namedTypeDeclarations[n]->node )
  137. {
  138. namedTypeDeclarations[n]->node->Destroy(engine);
  139. }
  140. asDELETE(namedTypeDeclarations[n],sClassDeclaration);
  141. namedTypeDeclarations[n] = 0;
  142. }
  143. }
  144. for( n = 0; n < funcDefs.GetLength(); n++ )
  145. {
  146. if( funcDefs[n] )
  147. {
  148. if( funcDefs[n]->node )
  149. funcDefs[n]->node->Destroy(engine);
  150. asDELETE(funcDefs[n],sFuncDef);
  151. funcDefs[n] = 0;
  152. }
  153. }
  154. for( n = 0; n < mixinClasses.GetLength(); n++ )
  155. {
  156. if( mixinClasses[n] )
  157. {
  158. if( mixinClasses[n]->node )
  159. mixinClasses[n]->node->Destroy(engine);
  160. asDELETE(mixinClasses[n],sMixinClass);
  161. mixinClasses[n] = 0;
  162. }
  163. }
  164. #endif // AS_NO_COMPILER
  165. }
  166. void asCBuilder::Reset()
  167. {
  168. numErrors = 0;
  169. numWarnings = 0;
  170. preMessage.isSet = false;
  171. }
  172. #ifndef AS_NO_COMPILER
  173. int asCBuilder::AddCode(const char *name, const char *code, int codeLength, int lineOffset, int sectionIdx, bool makeCopy)
  174. {
  175. asCScriptCode *script = asNEW(asCScriptCode);
  176. if( script == 0 )
  177. return asOUT_OF_MEMORY;
  178. int r = script->SetCode(name, code, codeLength, makeCopy);
  179. script->lineOffset = lineOffset;
  180. script->idx = sectionIdx;
  181. scripts.PushLast(script);
  182. return r;
  183. }
  184. int asCBuilder::Build()
  185. {
  186. Reset();
  187. ParseScripts();
  188. CompileInterfaces();
  189. CompileClasses();
  190. CompileGlobalVariables();
  191. CompileFunctions();
  192. // TODO: Attempt to reorder the initialization of global variables so that
  193. // they do not access other uninitialized global variables out-of-order
  194. // The builder needs to check for each of the global variable, what functions
  195. // that are accessed, and what global variables are access by these functions.
  196. if( numWarnings > 0 && engine->ep.compilerWarnings == 2 )
  197. WriteError(TXT_WARNINGS_TREATED_AS_ERROR, 0, 0);
  198. if( numErrors > 0 )
  199. return asERROR;
  200. return asSUCCESS;
  201. }
  202. int asCBuilder::CompileGlobalVar(const char *sectionName, const char *code, int lineOffset)
  203. {
  204. Reset();
  205. // Add the string to the script code
  206. asCScriptCode *script = asNEW(asCScriptCode);
  207. if( script == 0 )
  208. return asOUT_OF_MEMORY;
  209. script->SetCode(sectionName, code, true);
  210. script->lineOffset = lineOffset;
  211. script->idx = engine->GetScriptSectionNameIndex(sectionName ? sectionName : "");
  212. scripts.PushLast(script);
  213. // Parse the string
  214. asCParser parser(this);
  215. if( parser.ParseScript(scripts[0]) < 0 )
  216. return asERROR;
  217. asCScriptNode *node = parser.GetScriptNode();
  218. // Make sure there is nothing else than the global variable in the script code
  219. if( node == 0 ||
  220. node->firstChild == 0 ||
  221. node->firstChild != node->lastChild ||
  222. node->firstChild->nodeType != snDeclaration )
  223. {
  224. WriteError(TXT_ONLY_ONE_VARIABLE_ALLOWED, script, 0);
  225. return asERROR;
  226. }
  227. node = node->firstChild;
  228. node->DisconnectParent();
  229. RegisterGlobalVar(node, script, module->defaultNamespace);
  230. CompileGlobalVariables();
  231. if( numWarnings > 0 && engine->ep.compilerWarnings == 2 )
  232. WriteError(TXT_WARNINGS_TREATED_AS_ERROR, 0, 0);
  233. if( numErrors > 0 )
  234. {
  235. // Remove the variable from the module, if it was registered
  236. if( globVariables.GetSize() > 0 )
  237. module->RemoveGlobalVar(module->GetGlobalVarCount()-1);
  238. return asERROR;
  239. }
  240. return 0;
  241. }
  242. #endif
  243. int asCBuilder::ValidateDefaultArgs(asCScriptCode *script, asCScriptNode *node, asCScriptFunction *func)
  244. {
  245. int firstArgWithDefaultValue = -1;
  246. for( asUINT n = 0; n < func->defaultArgs.GetLength(); n++ )
  247. {
  248. if( func->defaultArgs[n] )
  249. firstArgWithDefaultValue = n;
  250. else if( firstArgWithDefaultValue >= 0 )
  251. {
  252. asCString str;
  253. str.Format(TXT_DEF_ARG_MISSING_IN_FUNC_s, func->GetDeclaration());
  254. WriteError(str, script, node);
  255. return asINVALID_DECLARATION;
  256. }
  257. }
  258. return 0;
  259. }
  260. #ifndef AS_NO_COMPILER
  261. int asCBuilder::CompileFunction(const char *sectionName, const char *code, int lineOffset, asDWORD compileFlags, asCScriptFunction **outFunc)
  262. {
  263. asASSERT(outFunc != 0);
  264. Reset();
  265. // Add the string to the script code
  266. asCScriptCode *script = asNEW(asCScriptCode);
  267. if( script == 0 )
  268. return asOUT_OF_MEMORY;
  269. script->SetCode(sectionName, code, true);
  270. script->lineOffset = lineOffset;
  271. script->idx = engine->GetScriptSectionNameIndex(sectionName ? sectionName : "");
  272. scripts.PushLast(script);
  273. // Parse the string
  274. asCParser parser(this);
  275. if( parser.ParseScript(scripts[0]) < 0 )
  276. return asERROR;
  277. asCScriptNode *node = parser.GetScriptNode();
  278. // Make sure there is nothing else than the function in the script code
  279. if( node == 0 ||
  280. node->firstChild == 0 ||
  281. node->firstChild != node->lastChild ||
  282. node->firstChild->nodeType != snFunction )
  283. {
  284. WriteError(TXT_ONLY_ONE_FUNCTION_ALLOWED, script, 0);
  285. return asERROR;
  286. }
  287. // Find the function node
  288. node = node->firstChild;
  289. // Create the function
  290. bool isConstructor, isDestructor, isPrivate, isFinal, isOverride, isShared;
  291. asCScriptFunction *func = asNEW(asCScriptFunction)(engine, compileFlags & asCOMP_ADD_TO_MODULE ? module : 0, asFUNC_SCRIPT);
  292. if( func == 0 )
  293. return asOUT_OF_MEMORY;
  294. asCArray<asCString> parameterNames;
  295. GetParsedFunctionDetails(node, scripts[0], 0, func->name, func->returnType, parameterNames, func->parameterTypes, func->inOutFlags, func->defaultArgs, func->isReadOnly, isConstructor, isDestructor, isPrivate, isFinal, isOverride, isShared, module->defaultNamespace);
  296. func->id = engine->GetNextScriptFunctionId();
  297. func->scriptSectionIdx = engine->GetScriptSectionNameIndex(sectionName ? sectionName : "");
  298. func->nameSpace = module->defaultNamespace;
  299. // Make sure the default args are declared correctly
  300. int r = ValidateDefaultArgs(script, node, func);
  301. if( r < 0 )
  302. {
  303. func->Release();
  304. return asERROR;
  305. }
  306. // Tell the engine that the function exists already so the compiler can access it
  307. if( compileFlags & asCOMP_ADD_TO_MODULE )
  308. {
  309. int r = CheckNameConflict(func->name.AddressOf(), node, scripts[0], module->defaultNamespace);
  310. if( r < 0 )
  311. {
  312. func->Orphan(module);
  313. return asERROR;
  314. }
  315. module->globalFunctions.Put(func);
  316. func->AddRef();
  317. module->AddScriptFunction(func);
  318. }
  319. else
  320. engine->SetScriptFunction(func);
  321. // Fill in the function info for the builder too
  322. node->DisconnectParent();
  323. sFunctionDescription *funcDesc = asNEW(sFunctionDescription);
  324. if( funcDesc == 0 )
  325. {
  326. func->Release();
  327. return asOUT_OF_MEMORY;
  328. }
  329. functions.PushLast(funcDesc);
  330. funcDesc->script = scripts[0];
  331. funcDesc->node = node;
  332. funcDesc->name = func->name;
  333. funcDesc->funcId = func->id;
  334. funcDesc->paramNames = parameterNames;
  335. funcDesc->isExistingShared = false;
  336. asCCompiler compiler(engine);
  337. compiler.CompileFunction(this, functions[0]->script, parameterNames, functions[0]->node, func, 0);
  338. if( numWarnings > 0 && engine->ep.compilerWarnings == 2 )
  339. WriteError(TXT_WARNINGS_TREATED_AS_ERROR, 0, 0);
  340. if( numErrors > 0 )
  341. {
  342. // If the function was added to the module then remove it again
  343. if( compileFlags & asCOMP_ADD_TO_MODULE )
  344. {
  345. module->globalFunctions.Erase(module->globalFunctions.GetIndex(func));
  346. module->scriptFunctions.RemoveValue(func);
  347. func->Release();
  348. func->Orphan(module);
  349. }
  350. func->Release();
  351. return asERROR;
  352. }
  353. // Return the function
  354. *outFunc = func;
  355. return asSUCCESS;
  356. }
  357. void asCBuilder::ParseScripts()
  358. {
  359. TimeIt("asCBuilder::ParseScripts");
  360. asCArray<asCParser*> parsers((int)scripts.GetLength());
  361. // Parse all the files as if they were one
  362. asUINT n = 0;
  363. for( n = 0; n < scripts.GetLength(); n++ )
  364. {
  365. asCParser *parser = asNEW(asCParser)(this);
  366. if( parser != 0 )
  367. {
  368. parsers.PushLast(parser);
  369. // Parse the script file
  370. parser->ParseScript(scripts[n]);
  371. }
  372. }
  373. if( numErrors == 0 )
  374. {
  375. // Find all type declarations
  376. for( n = 0; n < scripts.GetLength(); n++ )
  377. {
  378. asCScriptNode *node = parsers[n]->GetScriptNode();
  379. RegisterTypesFromScript(node, scripts[n], engine->nameSpaces[0]);
  380. }
  381. // Register the complete function definitions
  382. for( n = 0; n < funcDefs.GetLength(); n++ )
  383. {
  384. CompleteFuncDef(funcDefs[n]);
  385. }
  386. // Register script methods found in the interfaces
  387. for( n = 0; n < interfaceDeclarations.GetLength(); n++ )
  388. {
  389. sClassDeclaration *decl = interfaceDeclarations[n];
  390. asCScriptNode *node = decl->node->firstChild->next;
  391. // Skip list of inherited interfaces
  392. while( node && node->nodeType == snIdentifier )
  393. node = node->next;
  394. while( node )
  395. {
  396. asCScriptNode *next = node->next;
  397. if( node->nodeType == snFunction )
  398. {
  399. node->DisconnectParent();
  400. RegisterScriptFunctionFromNode(node, decl->script, decl->objType, true, false, 0, decl->isExistingShared);
  401. }
  402. else if( node->nodeType == snVirtualProperty )
  403. {
  404. node->DisconnectParent();
  405. RegisterVirtualProperty(node, decl->script, decl->objType, true, false, 0, decl->isExistingShared);
  406. }
  407. node = next;
  408. }
  409. }
  410. // Register script methods found in the classes
  411. for( n = 0; n < classDeclarations.GetLength(); n++ )
  412. {
  413. sClassDeclaration *decl = classDeclarations[n];
  414. asCScriptNode *node = decl->node->firstChild->next;
  415. // Skip list of classes and interfaces
  416. while( node && node->nodeType == snIdentifier )
  417. node = node->next;
  418. while( node )
  419. {
  420. asCScriptNode *next = node->next;
  421. if( node->nodeType == snFunction )
  422. {
  423. node->DisconnectParent();
  424. RegisterScriptFunctionFromNode(node, decl->script, decl->objType, false, false, 0, decl->isExistingShared);
  425. }
  426. else if( node->nodeType == snVirtualProperty )
  427. {
  428. node->DisconnectParent();
  429. RegisterVirtualProperty(node, decl->script, decl->objType, false, false, 0, decl->isExistingShared);
  430. }
  431. node = next;
  432. }
  433. // Make sure the default factory & constructor exists for classes
  434. if( decl->objType->beh.construct == engine->scriptTypeBehaviours.beh.construct )
  435. {
  436. if( decl->objType->beh.constructors.GetLength() == 1 || engine->ep.alwaysImplDefaultConstruct )
  437. {
  438. AddDefaultConstructor(decl->objType, decl->script);
  439. }
  440. else
  441. {
  442. // As the class has another constructor we shouldn't provide the default constructor
  443. if( decl->objType->beh.construct )
  444. {
  445. engine->scriptFunctions[decl->objType->beh.construct]->Release();
  446. decl->objType->beh.construct = 0;
  447. decl->objType->beh.constructors.RemoveIndex(0);
  448. }
  449. if( decl->objType->beh.factory )
  450. {
  451. engine->scriptFunctions[decl->objType->beh.factory]->Release();
  452. decl->objType->beh.factory = 0;
  453. decl->objType->beh.factories.RemoveIndex(0);
  454. }
  455. if( decl->objType->beh.copy )
  456. {
  457. engine->scriptFunctions[decl->objType->beh.copy]->Release();
  458. decl->objType->beh.copy = 0;
  459. }
  460. }
  461. }
  462. }
  463. // Find other global nodes
  464. for( n = 0; n < scripts.GetLength(); n++ )
  465. {
  466. // Find other global nodes
  467. asCScriptNode *node = parsers[n]->GetScriptNode();
  468. RegisterNonTypesFromScript(node, scripts[n], engine->nameSpaces[0]);
  469. }
  470. }
  471. for( n = 0; n < parsers.GetLength(); n++ )
  472. {
  473. asDELETE(parsers[n],asCParser);
  474. }
  475. }
  476. void asCBuilder::RegisterTypesFromScript(asCScriptNode *node, asCScriptCode *script, asSNameSpace *ns)
  477. {
  478. asASSERT(node->nodeType == snScript);
  479. // Find structure definitions first
  480. node = node->firstChild;
  481. while( node )
  482. {
  483. asCScriptNode *next = node->next;
  484. if( node->nodeType == snNamespace )
  485. {
  486. // Recursively register the entities defined in the namespace
  487. asCString nsName;
  488. nsName.Assign(&script->code[node->firstChild->tokenPos], node->firstChild->tokenLength);
  489. if( ns->name != "" )
  490. nsName = ns->name + "::" + nsName;
  491. asSNameSpace *nsChild = engine->AddNameSpace(nsName.AddressOf());
  492. RegisterTypesFromScript(node->lastChild, script, nsChild);
  493. }
  494. else
  495. {
  496. if( node->nodeType == snClass )
  497. {
  498. node->DisconnectParent();
  499. RegisterClass(node, script, ns);
  500. }
  501. else if( node->nodeType == snInterface )
  502. {
  503. node->DisconnectParent();
  504. RegisterInterface(node, script, ns);
  505. }
  506. else if( node->nodeType == snEnum )
  507. {
  508. node->DisconnectParent();
  509. RegisterEnum(node, script, ns);
  510. }
  511. else if( node->nodeType == snTypedef )
  512. {
  513. node->DisconnectParent();
  514. RegisterTypedef(node, script, ns);
  515. }
  516. else if( node->nodeType == snFuncDef )
  517. {
  518. node->DisconnectParent();
  519. RegisterFuncDef(node, script, ns);
  520. }
  521. else if( node->nodeType == snMixin )
  522. {
  523. node->DisconnectParent();
  524. RegisterMixinClass(node, script, ns);
  525. }
  526. }
  527. node = next;
  528. }
  529. }
  530. void asCBuilder::RegisterNonTypesFromScript(asCScriptNode *node, asCScriptCode *script, asSNameSpace *ns)
  531. {
  532. node = node->firstChild;
  533. while( node )
  534. {
  535. asCScriptNode *next = node->next;
  536. if( node->nodeType == snNamespace )
  537. {
  538. // Determine the name of the namespace
  539. asCString nsName;
  540. nsName.Assign(&script->code[node->firstChild->tokenPos], node->firstChild->tokenLength);
  541. if( ns->name != "" )
  542. nsName = ns->name + "::" + nsName;
  543. // Declare the namespace, then add the entities
  544. asSNameSpace *nsChild = engine->AddNameSpace(nsName.AddressOf());
  545. RegisterNonTypesFromScript(node->lastChild, script, nsChild);
  546. }
  547. else
  548. {
  549. node->DisconnectParent();
  550. if( node->nodeType == snFunction )
  551. RegisterScriptFunctionFromNode(node, script, 0, false, true, ns);
  552. else if( node->nodeType == snDeclaration )
  553. RegisterGlobalVar(node, script, ns);
  554. else if( node->nodeType == snVirtualProperty )
  555. RegisterVirtualProperty(node, script, 0, false, true, ns);
  556. else if( node->nodeType == snImport )
  557. RegisterImportedFunction(module->GetNextImportedFunctionId(), node, script, ns);
  558. else
  559. {
  560. // Unused script node
  561. int r, c;
  562. script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  563. WriteWarning(script->name, TXT_UNUSED_SCRIPT_NODE, r, c);
  564. node->Destroy(engine);
  565. }
  566. }
  567. node = next;
  568. }
  569. }
  570. void asCBuilder::CompileFunctions()
  571. {
  572. // Compile each function
  573. for( asUINT n = 0; n < functions.GetLength(); n++ )
  574. {
  575. sFunctionDescription *current = functions[n];
  576. if( current == 0 ) continue;
  577. // Don't compile the function again if it was an existing shared function
  578. if( current->isExistingShared ) continue;
  579. asCCompiler compiler(engine);
  580. asCScriptFunction *func = engine->scriptFunctions[current->funcId];
  581. // Find the class declaration for constructors
  582. sClassDeclaration *classDecl = 0;
  583. if( current->objType && current->name == current->objType->name )
  584. {
  585. for( asUINT n = 0; n < classDeclarations.GetLength(); n++ )
  586. {
  587. if( classDeclarations[n]->objType == current->objType )
  588. {
  589. classDecl = classDeclarations[n];
  590. break;
  591. }
  592. }
  593. }
  594. if( current->node )
  595. {
  596. int r, c;
  597. current->script->ConvertPosToRowCol(current->node->tokenPos, &r, &c);
  598. asCString str = func->GetDeclarationStr();
  599. str.Format(TXT_COMPILING_s, str.AddressOf());
  600. WriteInfo(current->script->name, str, r, c, true);
  601. // When compiling a constructor need to pass the class declaration for member initializations
  602. compiler.CompileFunction(this, current->script, current->paramNames, current->node, func, classDecl);
  603. preMessage.isSet = false;
  604. }
  605. else if( current->name == current->objType->name )
  606. {
  607. asCScriptNode *node = classDecl->node;
  608. int r = 0, c = 0;
  609. if( node )
  610. current->script->ConvertPosToRowCol(node->tokenPos, &r, &c);
  611. asCString str = func->GetDeclarationStr();
  612. str.Format(TXT_COMPILING_s, str.AddressOf());
  613. WriteInfo(current->script->name, str, r, c, true);
  614. // This is the default constructor that is generated
  615. // automatically if not implemented by the user.
  616. compiler.CompileDefaultConstructor(this, current->script, node, func, classDecl);
  617. preMessage.isSet = false;
  618. }
  619. }
  620. }
  621. #endif
  622. // Called from module and engine
  623. int asCBuilder::ParseDataType(const char *datatype, asCDataType *result, asSNameSpace *implicitNamespace, bool isReturnType)
  624. {
  625. Reset();
  626. asCScriptCode source;
  627. source.SetCode("", datatype, true);
  628. asCParser parser(this);
  629. int r = parser.ParseDataType(&source, isReturnType);
  630. if( r < 0 )
  631. return asINVALID_TYPE;
  632. // Get data type and property name
  633. asCScriptNode *dataType = parser.GetScriptNode()->firstChild;
  634. *result = CreateDataTypeFromNode(dataType, &source, implicitNamespace, true);
  635. if( isReturnType )
  636. *result = ModifyDataTypeFromNode(*result, dataType->next, &source, 0, 0);
  637. if( numErrors > 0 )
  638. return asINVALID_TYPE;
  639. return asSUCCESS;
  640. }
  641. int asCBuilder::ParseTemplateDecl(const char *decl, asCString *name, asCArray<asCString> &subtypeNames)
  642. {
  643. Reset();
  644. asCScriptCode source;
  645. source.SetCode("", decl, true);
  646. asCParser parser(this);
  647. int r = parser.ParseTemplateDecl(&source);
  648. if( r < 0 )
  649. return asINVALID_TYPE;
  650. // Get the template name and subtype names
  651. asCScriptNode *node = parser.GetScriptNode()->firstChild;
  652. name->Assign(&decl[node->tokenPos], node->tokenLength);
  653. while( (node = node->next) )
  654. {
  655. asCString subtypeName;
  656. subtypeName.Assign(&decl[node->tokenPos], node->tokenLength);
  657. subtypeNames.PushLast(subtypeName);
  658. }
  659. // TODO: template: check for name conflicts
  660. if( numErrors > 0 )
  661. return asINVALID_DECLARATION;
  662. return asSUCCESS;
  663. }
  664. int asCBuilder::VerifyProperty(asCDataType *dt, const char *decl, asCString &name, asCDataType &type, asSNameSpace *ns)
  665. {
  666. // Either datatype or namespace must be informed
  667. asASSERT( dt || ns );
  668. Reset();
  669. if( dt )
  670. {
  671. // Verify that the object type exist
  672. if( dt->GetObjectType() == 0 )
  673. return asINVALID_OBJECT;
  674. }
  675. // Check property declaration and type
  676. asCScriptCode source;
  677. source.SetCode(TXT_PROPERTY, decl, true);
  678. asCParser parser(this);
  679. int r = parser.ParsePropertyDeclaration(&source);
  680. if( r < 0 )
  681. return asINVALID_DECLARATION;
  682. // Get data type and property name
  683. asCScriptNode *dataType = parser.GetScriptNode()->firstChild;
  684. asCScriptNode *nameNode = dataType->next;
  685. // If an object property is registered, then use the
  686. // object's namespace, otherwise use the specified namespace
  687. type = CreateDataTypeFromNode(dataType, &source, dt ? dt->GetObjectType()->nameSpace : ns);
  688. name.Assign(&decl[nameNode->tokenPos], nameNode->tokenLength);
  689. // Validate that the type really can be a registered property
  690. // We cannot use CanBeInstanciated, as it is allowed to register
  691. // properties of type that cannot otherwise be instanciated
  692. if( type.GetFuncDef() && !type.IsObjectHandle() )
  693. {
  694. // Function definitions must always be handles
  695. return asINVALID_DECLARATION;
  696. }
  697. // Verify property name
  698. if( dt )
  699. {
  700. if( CheckNameConflictMember(dt->GetObjectType(), name.AddressOf(), nameNode, &source, true) < 0 )
  701. return asNAME_TAKEN;
  702. }
  703. else
  704. {
  705. if( CheckNameConflict(name.AddressOf(), nameNode, &source, ns) < 0 )
  706. return asNAME_TAKEN;
  707. }
  708. if( numErrors > 0 )
  709. return asINVALID_DECLARATION;
  710. return asSUCCESS;
  711. }
  712. asCObjectProperty *asCBuilder::GetObjectProperty(asCDataType &obj, const char *prop)
  713. {
  714. asASSERT(obj.GetObjectType() != 0);
  715. // TODO: optimize: Improve linear search
  716. asCArray<asCObjectProperty *> &props = obj.GetObjectType()->properties;
  717. for( asUINT n = 0; n < props.GetLength(); n++ )
  718. {
  719. if( props[n]->name == prop )
  720. {
  721. if( module->accessMask & props[n]->accessMask )
  722. return props[n];
  723. else
  724. return 0;
  725. }
  726. }
  727. return 0;
  728. }
  729. asCGlobalProperty *asCBuilder::GetGlobalProperty(const char *prop, asSNameSpace *ns, bool *isCompiled, bool *isPureConstant, asQWORD *constantValue, bool *isAppProp)
  730. {
  731. if( isCompiled ) *isCompiled = true;
  732. if( isPureConstant ) *isPureConstant = false;
  733. if( isAppProp ) *isAppProp = false;
  734. // Check application registered properties
  735. asCString name(prop);
  736. asCGlobalProperty *globProp = engine->registeredGlobalProps.GetFirst(ns, name);
  737. if( globProp )
  738. {
  739. if( module )
  740. {
  741. // Determine if the module has access to the property
  742. if( module->accessMask & globProp->accessMask )
  743. {
  744. if( isAppProp ) *isAppProp = true;
  745. return globProp;
  746. }
  747. }
  748. else
  749. {
  750. // We're not compiling a module right now, so it must be a registered global property
  751. if( isAppProp ) *isAppProp = true;
  752. return globProp;
  753. }
  754. }
  755. #ifndef AS_NO_COMPILER
  756. // Check properties being compiled now
  757. sGlobalVariableDescription* desc = globVariables.GetFirst(ns, prop);
  758. if( desc && !desc->isEnumValue )
  759. {
  760. if( isCompiled ) *isCompiled = desc->isCompiled;
  761. if( isPureConstant ) *isPureConstant = desc->isPureConstant;
  762. if( constantValue ) *constantValue = desc->constantValue;
  763. return desc->property;
  764. }
  765. #else
  766. UNUSED_VAR(constantValue);
  767. #endif
  768. // Check previously compiled global variables
  769. if( module )
  770. return module->scriptGlobals.GetFirst(ns, prop);
  771. return 0;
  772. }
  773. int asCBuilder::ParseFunctionDeclaration(asCObjectType *objType, const char *decl, asCScriptFunction *func, bool isSystemFunction, asCArray<bool> *paramAutoHandles, bool *returnAutoHandle, asSNameSpace *ns)
  774. {
  775. asASSERT( objType || ns );
  776. // TODO: Can't we use GetParsedFunctionDetails to do most of what is done in this function?
  777. Reset();
  778. asCScriptCode source;
  779. source.SetCode(TXT_SYSTEM_FUNCTION, decl, true);
  780. asCParser parser(this);
  781. int r = parser.ParseFunctionDefinition(&source);
  782. if( r < 0 )
  783. return asINVALID_DECLARATION;
  784. asCScriptNode *node = parser.GetScriptNode();
  785. // Determine scope
  786. asCScriptNode *n = node->firstChild->next->next;
  787. asCString scope = GetScopeFromNode(n, &source, &n);
  788. func->nameSpace = engine->FindNameSpace(scope.AddressOf());
  789. if( func->nameSpace == 0 )
  790. return asINVALID_DECLARATION;
  791. // Find name
  792. func->name.Assign(&source.code[n->tokenPos], n->tokenLength);
  793. // Initialize a script function object for registration
  794. bool autoHandle;
  795. // Scoped reference types are allowed to use handle when returned from application functions
  796. func->returnType = CreateDataTypeFromNode(node->firstChild, &source, objType ? objType->nameSpace : ns, true, objType);
  797. func->returnType = ModifyDataTypeFromNode(func->returnType, node->firstChild->next, &source, 0, &autoHandle);
  798. if( autoHandle && (!func->returnType.IsObjectHandle() || func->returnType.IsReference()) )
  799. return asINVALID_DECLARATION;
  800. if( returnAutoHandle ) *returnAutoHandle = autoHandle;
  801. // Reference types cannot be returned by value from system functions
  802. if( isSystemFunction &&
  803. (func->returnType.GetObjectType() &&
  804. (func->returnType.GetObjectType()->flags & asOBJ_REF)) &&
  805. !(func->returnType.IsReference() ||
  806. func->returnType.IsObjectHandle()) )
  807. return asINVALID_DECLARATION;
  808. // Count number of parameters
  809. int paramCount = 0;
  810. asCScriptNode *paramList = n->next;
  811. n = paramList->firstChild;
  812. while( n )
  813. {
  814. paramCount++;
  815. n = n->next->next;
  816. if( n && n->nodeType == snIdentifier )
  817. n = n->next;
  818. if( n && n->nodeType == snExpression )
  819. n = n->next;
  820. }
  821. // Preallocate memory
  822. func->parameterTypes.Allocate(paramCount, false);
  823. func->inOutFlags.Allocate(paramCount, false);
  824. func->defaultArgs.Allocate(paramCount, false);
  825. if( paramAutoHandles ) paramAutoHandles->Allocate(paramCount, false);
  826. n = paramList->firstChild;
  827. while( n )
  828. {
  829. asETypeModifiers inOutFlags;
  830. asCDataType type = CreateDataTypeFromNode(n, &source, objType ? objType->nameSpace : ns, false, objType);
  831. type = ModifyDataTypeFromNode(type, n->next, &source, &inOutFlags, &autoHandle);
  832. // Reference types cannot be passed by value to system functions
  833. if( isSystemFunction &&
  834. (type.GetObjectType() &&
  835. (type.GetObjectType()->flags & asOBJ_REF)) &&
  836. !(type.IsReference() ||
  837. type.IsObjectHandle()) )
  838. return asINVALID_DECLARATION;
  839. // Store the parameter type
  840. func->parameterTypes.PushLast(type);
  841. func->inOutFlags.PushLast(inOutFlags);
  842. // Don't permit void parameters
  843. if( type.GetTokenType() == ttVoid )
  844. return asINVALID_DECLARATION;
  845. if( autoHandle && (!type.IsObjectHandle() || type.IsReference()) )
  846. return asINVALID_DECLARATION;
  847. if( paramAutoHandles ) paramAutoHandles->PushLast(autoHandle);
  848. // Make sure that var type parameters are references
  849. if( type.GetTokenType() == ttQuestion &&
  850. !type.IsReference() )
  851. return asINVALID_DECLARATION;
  852. // Move to next parameter
  853. n = n->next->next;
  854. if( n && n->nodeType == snIdentifier )
  855. n = n->next;
  856. if( n && n->nodeType == snExpression )
  857. {
  858. // Strip out white space and comments to better share the string
  859. asCString *defaultArgStr = asNEW(asCString);
  860. if( defaultArgStr )
  861. {
  862. *defaultArgStr = GetCleanExpressionString(n, &source);
  863. func->defaultArgs.PushLast(defaultArgStr);
  864. }
  865. n = n->next;
  866. }
  867. else
  868. func->defaultArgs.PushLast(0);
  869. }
  870. // Set the read-only flag if const is declared after parameter list
  871. if( node->lastChild->nodeType == snUndefined && node->lastChild->tokenType == ttConst )
  872. {
  873. if( objType == 0 )
  874. return asINVALID_DECLARATION;
  875. func->isReadOnly = true;
  876. }
  877. else
  878. func->isReadOnly = false;
  879. // Make sure the default args are declared correctly
  880. ValidateDefaultArgs(&source, node, func);
  881. if( numErrors > 0 || numWarnings > 0 )
  882. return asINVALID_DECLARATION;
  883. return 0;
  884. }
  885. int asCBuilder::ParseVariableDeclaration(const char *decl, asSNameSpace *implicitNamespace, asCString &outName, asSNameSpace *&outNamespace, asCDataType &outDt)
  886. {
  887. Reset();
  888. asCScriptCode source;
  889. source.SetCode(TXT_VARIABLE_DECL, decl, true);
  890. asCParser parser(this);
  891. int r = parser.ParsePropertyDeclaration(&source);
  892. if( r < 0 )
  893. return asINVALID_DECLARATION;
  894. asCScriptNode *node = parser.GetScriptNode();
  895. // Determine the scope from declaration
  896. asCScriptNode *n = node->firstChild->next;
  897. outNamespace = GetNameSpaceFromNode(n, &source, implicitNamespace, &n);
  898. if( outNamespace == 0 )
  899. return asINVALID_DECLARATION;
  900. // Find name
  901. outName.Assign(&source.code[n->tokenPos], n->tokenLength);
  902. // Initialize a script variable object for registration
  903. outDt = CreateDataTypeFromNode(node->firstChild, &source, implicitNamespace);
  904. if( numErrors > 0 || numWarnings > 0 )
  905. return asINVALID_DECLARATION;
  906. return 0;
  907. }
  908. int asCBuilder::CheckNameConflictMember(asCObjectType *t, const char *name, asCScriptNode *node, asCScriptCode *code, bool isProperty)
  909. {
  910. // It's not necessary to check against object types
  911. // TODO: optimize: Improve linear search
  912. asCArray<asCObjectProperty *> &props = t->properties;
  913. for( asUINT n = 0; n < props.GetLength(); n++ )
  914. {
  915. if( props[n]->name == name )
  916. {
  917. if( code )
  918. {
  919. asCString str;
  920. str.Format(TXT_NAME_CONFLICT_s_OBJ_PROPERTY, name);
  921. WriteError(str, code, node);
  922. }
  923. return -1;
  924. }
  925. }
  926. // Property names must be checked against method names
  927. if( isProperty )
  928. {
  929. asCArray<int> methods = t->methods;
  930. for( asUINT n = 0; n < methods.GetLength(); n++ )
  931. {
  932. if( engine->scriptFunctions[methods[n]]->name == name )
  933. {
  934. if( code )
  935. {
  936. asCString str;
  937. str.Format(TXT_NAME_CONFLICT_s_METHOD, name);
  938. WriteError(str, code, node);
  939. }
  940. return -1;
  941. }
  942. }
  943. }
  944. return 0;
  945. }
  946. int asCBuilder::CheckNameConflict(const char *name, asCScriptNode *node, asCScriptCode *code, asSNameSpace *ns)
  947. {
  948. // Check against registered object types
  949. if( engine->GetObjectType(name, ns) != 0 )
  950. {
  951. if( code )
  952. {
  953. asCString str;
  954. str.Format(TXT_NAME_CONFLICT_s_EXTENDED_TYPE, name);
  955. WriteError(str, code, node);
  956. }
  957. return -1;
  958. }
  959. // TODO: Must verify global properties in all config groups, whether the module has access or not
  960. // Check against global properties
  961. asCGlobalProperty *prop = GetGlobalProperty(name, ns, 0, 0, 0, 0);
  962. if( prop )
  963. {
  964. if( code )
  965. {
  966. asCString str;
  967. str.Format(TXT_NAME_CONFLICT_s_GLOBAL_PROPERTY, name);
  968. WriteError(str, code, node);
  969. }
  970. return -1;
  971. }
  972. // TODO: Property names must be checked against function names
  973. #ifndef AS_NO_COMPILER
  974. // Check against class types
  975. asUINT n;
  976. for( n = 0; n < classDeclarations.GetLength(); n++ )
  977. {
  978. if( classDeclarations[n]->name == name &&
  979. classDeclarations[n]->objType->nameSpace == ns )
  980. {
  981. if( code )
  982. {
  983. asCString str;
  984. str.Format(TXT_NAME_CONFLICT_s_STRUCT, name);
  985. WriteError(str, code, node);
  986. }
  987. return -1;
  988. }
  989. }
  990. // Check against named types
  991. for( n = 0; n < namedTypeDeclarations.GetLength(); n++ )
  992. {
  993. if( namedTypeDeclarations[n]->name == name &&
  994. namedTypeDeclarations[n]->objType->nameSpace == ns )
  995. {
  996. if( code )
  997. {
  998. asCString str;
  999. str.Format(TXT_NAME_CONFLICT_s_IS_NAMED_TYPE, name);
  1000. WriteError(str, code, node);
  1001. }
  1002. return -1;
  1003. }
  1004. }
  1005. // Must check for name conflicts with funcdefs
  1006. for( n = 0; n < funcDefs.GetLength(); n++ )
  1007. {
  1008. if( funcDefs[n]->name == name &&
  1009. module->funcDefs[funcDefs[n]->idx]->nameSpace == ns )
  1010. {
  1011. if( code )
  1012. {
  1013. asCString str;
  1014. str.Format(TXT_NAME_CONFLICT_s_IS_FUNCDEF, name);
  1015. WriteError(str, code, node);
  1016. }
  1017. return -1;
  1018. }
  1019. }
  1020. // Check against mixin classes
  1021. if( GetMixinClass(name, ns) )
  1022. {
  1023. if( code )
  1024. {
  1025. asCString str;
  1026. str.Format(TXT_NAME_CONFLICT_s_IS_MIXIN, name);
  1027. WriteError(str, code, node);
  1028. }
  1029. return -1;
  1030. }
  1031. #endif
  1032. return 0;
  1033. }
  1034. #ifndef AS_NO_COMPILER
  1035. sMixinClass *asCBuilder::GetMixinClass(const char *name, asSNameSpace *ns)
  1036. {
  1037. for( asUINT n = 0; n < mixinClasses.GetLength(); n++ )
  1038. if( mixinClasses[n]->name == name &&
  1039. mixinClasses[n]->ns == ns )
  1040. return mixinClasses[n];
  1041. return 0;
  1042. }
  1043. int asCBuilder::RegisterFuncDef(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns)
  1044. {
  1045. // Find the name
  1046. asASSERT( node->firstChild->nodeType == snDataType );
  1047. asCScriptNode *n = node->firstChild->next->next;
  1048. asCString name;
  1049. name.Assign(&file->code[n->tokenPos], n->tokenLength);
  1050. // Check for name conflict with other types
  1051. int r = CheckNameConflict(name.AddressOf(), node, file, ns);
  1052. if( asSUCCESS != r )
  1053. {
  1054. node->Destroy(engine);
  1055. return r;
  1056. }
  1057. // The function definition should be stored as a asCScriptFunction so that the application
  1058. // can use the asIScriptFunction interface to enumerate the return type and parameters
  1059. // The return type and parameter types aren't determined in this function. A second pass is
  1060. // necessary after all type declarations have been identified. The second pass is implemented
  1061. // in CompleteFuncDef().
  1062. sFuncDef *fd = asNEW(sFuncDef);
  1063. if( fd == 0 )
  1064. {
  1065. node->Destroy(engine);
  1066. return asOUT_OF_MEMORY;
  1067. }
  1068. fd->name = name;
  1069. fd->node = node;
  1070. fd->script = file;
  1071. fd->idx = module->AddFuncDef(name, ns);
  1072. funcDefs.PushLast(fd);
  1073. return 0;
  1074. }
  1075. void asCBuilder::CompleteFuncDef(sFuncDef *funcDef)
  1076. {
  1077. asCDataType returnType;
  1078. asCArray<asCString> parameterNames;
  1079. asCArray<asCDataType> parameterTypes;
  1080. asCArray<asETypeModifiers> inOutFlags;
  1081. asCArray<asCString *> defaultArgs;
  1082. bool isConstMethod;
  1083. bool isConstructor;
  1084. bool isDestructor;
  1085. bool isPrivate;
  1086. bool isOverride;
  1087. bool isFinal;
  1088. bool isShared;
  1089. asCScriptFunction *func = module->funcDefs[funcDef->idx];
  1090. asASSERT( func );
  1091. GetParsedFunctionDetails(funcDef->node, funcDef->script, 0, funcDef->name, returnType, parameterNames, parameterTypes, inOutFlags, defaultArgs, isConstMethod, isConstructor, isDestructor, isPrivate, isOverride, isFinal, isShared, func->nameSpace);
  1092. if( func )
  1093. {
  1094. func->returnType = returnType;
  1095. for( asUINT p = 0; p < parameterTypes.GetLength(); p++ )
  1096. {
  1097. func->parameterTypes.PushLast(parameterTypes[p]);
  1098. func->inOutFlags.PushLast(inOutFlags[p]);
  1099. // Don't copy the default arg expression as it is not allowed for function definitions
  1100. }
  1101. // TODO: Should we force the use of 'shared' for this check to be done?
  1102. // Check if there is another identical funcdef from another module and if so reuse that instead
  1103. for( asUINT n = 0; n < engine->funcDefs.GetLength(); n++ )
  1104. {
  1105. asCScriptFunction *f2 = engine->funcDefs[n];
  1106. if( f2 == 0 || func == f2 )
  1107. continue;
  1108. if( f2->name == func->name &&
  1109. f2->nameSpace == func->nameSpace &&
  1110. f2->IsSignatureExceptNameEqual(func) )
  1111. {
  1112. // Replace our funcdef for the existing one
  1113. funcDef->idx = f2->id;
  1114. module->funcDefs[module->funcDefs.IndexOf(func)] = f2;
  1115. f2->AddRef();
  1116. engine->funcDefs.RemoveValue(func);
  1117. func->Release();
  1118. // funcdefs aren't destroyed when the refCount reaches zero so we need to manually delete them
  1119. asDELETE(func, asCScriptFunction);
  1120. break;
  1121. }
  1122. }
  1123. }
  1124. }
  1125. int asCBuilder::RegisterGlobalVar(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns)
  1126. {
  1127. // Has the application disabled global vars?
  1128. if( engine->ep.disallowGlobalVars )
  1129. WriteError(TXT_GLOBAL_VARS_NOT_ALLOWED, file, node);
  1130. // What data type is it?
  1131. asCDataType type = CreateDataTypeFromNode(node->firstChild, file, ns);
  1132. if( !type.CanBeInstanciated() )
  1133. {
  1134. asCString str;
  1135. // TODO: Change to "'type' cannot be declared as variable"
  1136. str.Format(TXT_DATA_TYPE_CANT_BE_s, type.Format().AddressOf());
  1137. int r, c;
  1138. file->ConvertPosToRowCol(node->tokenPos, &r, &c);
  1139. WriteError(str, file, node);
  1140. }
  1141. asCScriptNode *n = node->firstChild->next;
  1142. while( n )
  1143. {
  1144. // Verify that the name isn't taken
  1145. asCString name(&file->code[n->tokenPos], n->tokenLength);
  1146. CheckNameConflict(name.AddressOf(), n, file, ns);
  1147. // Register the global variable
  1148. sGlobalVariableDescription *gvar = asNEW(sGlobalVariableDescription);
  1149. if( gvar == 0 )
  1150. {
  1151. node->Destroy(engine);
  1152. return asOUT_OF_MEMORY;
  1153. }
  1154. gvar->script = file;
  1155. gvar->name = name;
  1156. gvar->isCompiled = false;
  1157. gvar->datatype = type;
  1158. gvar->isEnumValue = false;
  1159. // TODO: Give error message if wrong
  1160. asASSERT(!gvar->datatype.IsReference());
  1161. gvar->idNode = n;
  1162. gvar->nextNode = 0;
  1163. if( n->next &&
  1164. (n->next->nodeType == snAssignment ||
  1165. n->next->nodeType == snArgList ||
  1166. n->next->nodeType == snInitList ) )
  1167. {
  1168. gvar->nextNode = n->next;
  1169. n->next->DisconnectParent();
  1170. }
  1171. gvar->property = module->AllocateGlobalProperty(name.AddressOf(), gvar->datatype, ns);
  1172. gvar->index = gvar->property->id;
  1173. globVariables.Put(gvar);
  1174. n = n->next;
  1175. }
  1176. node->Destroy(engine);
  1177. return 0;
  1178. }
  1179. int asCBuilder::RegisterMixinClass(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns)
  1180. {
  1181. asCScriptNode *cl = node->firstChild;
  1182. asASSERT( cl->nodeType == snClass );
  1183. asCScriptNode *n = cl->firstChild;
  1184. // Skip potential 'final' and 'shared' tokens
  1185. while( n->tokenType == ttIdentifier &&
  1186. (file->TokenEquals(n->tokenPos, n->tokenLength, FINAL_TOKEN) ||
  1187. file->TokenEquals(n->tokenPos, n->tokenLength, SHARED_TOKEN)) )
  1188. {
  1189. // Report error, because mixin class cannot be final or shared
  1190. asCString msg;
  1191. msg.Format(TXT_MIXIN_CANNOT_BE_DECLARED_AS_s, asCString(&file->code[n->tokenPos], n->tokenLength).AddressOf());
  1192. WriteError(msg, file, n);
  1193. asCScriptNode *tmp = n;
  1194. n = n->next;
  1195. // Remove the invalid node, so compilation can continue as if it wasn't there
  1196. tmp->DisconnectParent();
  1197. tmp->Destroy(engine);
  1198. }
  1199. asCString name(&file->code[n->tokenPos], n->tokenLength);
  1200. int r, c;
  1201. file->ConvertPosToRowCol(n->tokenPos, &r, &c);
  1202. CheckNameConflict(name.AddressOf(), n, file, ns);
  1203. sMixinClass *decl = asNEW(sMixinClass);
  1204. if( decl == 0 )
  1205. {
  1206. node->Destroy(engine);
  1207. return asOUT_OF_MEMORY;
  1208. }
  1209. mixinClasses.PushLast(decl);
  1210. decl->name = name;
  1211. decl->ns = ns;
  1212. decl->node = cl;
  1213. decl->script = file;
  1214. // Clean up memory
  1215. cl->DisconnectParent();
  1216. node->Destroy(engine);
  1217. return 0;
  1218. }
  1219. int asCBuilder::RegisterClass(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns)
  1220. {
  1221. asCScriptNode *n = node->firstChild;
  1222. bool isFinal = false;
  1223. bool isShared = false;
  1224. if( n->tokenType == ttIdentifier && file->TokenEquals(n->tokenPos, n->tokenLength, FINAL_TOKEN) )
  1225. {
  1226. isFinal = true;
  1227. n = n->next;
  1228. }
  1229. if( n->tokenType == ttIdentifier && file->TokenEquals(n->tokenPos, n->tokenLength, SHARED_TOKEN) )
  1230. {
  1231. isShared = true;
  1232. n = n->next;
  1233. // Check for final again
  1234. if( n->tokenType == ttIdentifier && file->TokenEquals(n->tokenPos, n->tokenLength, FINAL_TOKEN) )
  1235. {
  1236. isFinal = true;
  1237. n = n->next;
  1238. }
  1239. }
  1240. asCString name(&file->code[n->tokenPos], n->tokenLength);
  1241. int r, c;
  1242. file->ConvertPosToRowCol(n->tokenPos, &r, &c);
  1243. CheckNameConflict(name.AddressOf(), n, file, ns);
  1244. sClassDeclaration *decl = asNEW(sClassDeclaration);
  1245. if( decl == 0 )
  1246. {
  1247. node->Destroy(engine);
  1248. return asOUT_OF_MEMORY;
  1249. }
  1250. classDeclarations.PushLast(decl);
  1251. decl->name = name;
  1252. decl->script = file;
  1253. decl->node = node;
  1254. // If this type is shared and there already exist another shared
  1255. // type of the same name, then that one should be used instead of
  1256. // creating a new one.
  1257. if( isShared )
  1258. {
  1259. for( asUINT n = 0; n < engine->classTypes.GetLength(); n++ )
  1260. {
  1261. asCObjectType *st = engine->classTypes[n];
  1262. if( st &&
  1263. st->IsShared() &&
  1264. st->name == name &&
  1265. st->nameSpace == ns &&
  1266. !st->IsInterface() )
  1267. {
  1268. // We'll use the existing type
  1269. decl->isExistingShared = true;
  1270. decl->objType = st;
  1271. module->classTypes.PushLast(st);
  1272. st->AddRef();
  1273. return 0;
  1274. }
  1275. }
  1276. }
  1277. // Create a new object type for this class
  1278. asCObjectType *st = asNEW(asCObjectType)(engine);
  1279. if( st == 0 )
  1280. return asOUT_OF_MEMORY;
  1281. // By default all script classes are marked as garbage collected.
  1282. // Only after the complete structure and relationship between classes
  1283. // is known, can the flag be cleared for those objects that truly cannot
  1284. // form circular references. This is important because a template
  1285. // callback may be called with a script class before the compilation
  1286. // complete, and until it is known, the callback must assume the class
  1287. // is garbage collected.
  1288. st->flags = asOBJ_REF | asOBJ_SCRIPT_OBJECT | asOBJ_GC;
  1289. if( isShared )
  1290. st->flags |= asOBJ_SHARED;
  1291. if( isFinal )
  1292. st->flags |= asOBJ_NOINHERIT;
  1293. if( node->tokenType == ttHandle )
  1294. st->flags |= asOBJ_IMPLICIT_HANDLE;
  1295. st->size = sizeof(asCScriptObject);
  1296. st->name = name;
  1297. st->nameSpace = ns;
  1298. st->module = module;
  1299. module->classTypes.PushLast(st);
  1300. engine->classTypes.PushLast(st);
  1301. st->AddRef();
  1302. decl->objType = st;
  1303. // Use the default script class behaviours
  1304. st->beh = engine->scriptTypeBehaviours.beh;
  1305. // TODO: Move this to asCObjectType so that the asCRestore can reuse it
  1306. engine->scriptFunctions[st->beh.addref]->AddRef();
  1307. engine->scriptFunctions[st->beh.release]->AddRef();
  1308. engine->scriptFunctions[st->beh.gcEnumReferences]->AddRef();
  1309. engine->scriptFunctions[st->beh.gcGetFlag]->AddRef();
  1310. engine->scriptFunctions[st->beh.gcGetRefCount]->AddRef();
  1311. engine->scriptFunctions[st->beh.gcReleaseAllReferences]->AddRef();
  1312. engine->scriptFunctions[st->beh.gcSetFlag]->AddRef();
  1313. engine->scriptFunctions[st->beh.copy]->AddRef();
  1314. engine->scriptFunctions[st->beh.factory]->AddRef();
  1315. engine->scriptFunctions[st->beh.construct]->AddRef();
  1316. // TODO: weak: Should not do this if the class has been declared with noweak
  1317. engine->scriptFunctions[st->beh.getWeakRefFlag]->AddRef();
  1318. for( asUINT i = 1; i < st->beh.operators.GetLength(); i += 2 )
  1319. engine->scriptFunctions[st->beh.operators[i]]->AddRef();
  1320. return 0;
  1321. }
  1322. int asCBuilder::RegisterInterface(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns)
  1323. {
  1324. asCScriptNode *n = node->firstChild;
  1325. asCString name(&file->code[n->tokenPos], n->tokenLength);
  1326. bool isShared = false;
  1327. if( name == SHARED_TOKEN )
  1328. {
  1329. isShared = true;
  1330. n = n->next;
  1331. name.Assign(&file->code[n->tokenPos], n->tokenLength);
  1332. }
  1333. int r, c;
  1334. file->ConvertPosToRowCol(n->tokenPos, &r, &c);
  1335. CheckNameConflict(name.AddressOf(), n, file, ns);
  1336. sClassDeclaration *decl = asNEW(sClassDeclaration);
  1337. if( decl == 0 )
  1338. {
  1339. node->Destroy(engine);
  1340. return asOUT_OF_MEMORY;
  1341. }
  1342. interfaceDeclarations.PushLast(decl);
  1343. decl->name = name;
  1344. decl->script = file;
  1345. decl->node = node;
  1346. // If this type is shared and there already exist another shared
  1347. // type of the same name, then that one should be used instead of
  1348. // creating a new one.
  1349. if( isShared )
  1350. {
  1351. for( asUINT n = 0; n < engine->classTypes.GetLength(); n++ )
  1352. {
  1353. asCObjectType *st = engine->classTypes[n];
  1354. if( st &&
  1355. st->IsShared() &&
  1356. st->name == name &&
  1357. st->nameSpace == ns &&
  1358. st->IsInterface() )
  1359. {
  1360. // We'll use the existing type
  1361. decl->isExistingShared = true;
  1362. decl->objType = st;
  1363. module->classTypes.PushLast(st);
  1364. st->AddRef();
  1365. return 0;
  1366. }
  1367. }
  1368. }
  1369. // Register the object type for the interface
  1370. asCObjectType *st = asNEW(asCObjectType)(engine);
  1371. if( st == 0 )
  1372. return asOUT_OF_MEMORY;
  1373. st->flags = asOBJ_REF | asOBJ_SCRIPT_OBJECT;
  1374. if( isShared )
  1375. st->flags |= asOBJ_SHARED;
  1376. st->size = 0; // Cannot be instanciated
  1377. st->name = name;
  1378. st->nameSpace = ns;
  1379. module->classTypes.PushLast(st);
  1380. engine->classTypes.PushLast(st);
  1381. st->AddRef();
  1382. decl->objType = st;
  1383. // Use the default script class behaviours
  1384. st->beh.construct = 0;
  1385. st->beh.addref = engine->scriptTypeBehaviours.beh.addref;
  1386. engine->scriptFunctions[st->beh.addref]->AddRef();
  1387. st->beh.release = engine->scriptTypeBehaviours.beh.release;
  1388. engine->scriptFunctions[st->beh.release]->AddRef();
  1389. st->beh.copy = 0;
  1390. return 0;
  1391. }
  1392. void asCBuilder::CompileGlobalVariables()
  1393. {
  1394. bool compileSucceeded = true;
  1395. // Store state of compilation (errors, warning, output)
  1396. int currNumErrors = numErrors;
  1397. int currNumWarnings = numWarnings;
  1398. // Backup the original message stream
  1399. bool msgCallback = engine->msgCallback;
  1400. asSSystemFunctionInterface msgCallbackFunc = engine->msgCallbackFunc;
  1401. void *msgCallbackObj = engine->msgCallbackObj;
  1402. // Set the new temporary message stream
  1403. asCOutputBuffer outBuffer;
  1404. engine->SetMessageCallback(asMETHOD(asCOutputBuffer, Callback), &outBuffer, asCALL_THISCALL);
  1405. asCOutputBuffer finalOutput;
  1406. asCScriptFunction *initFunc = 0;
  1407. asCSymbolTable<asCGlobalProperty> initOrder;
  1408. // We first try to compile all the primitive global variables, and only after that
  1409. // compile the non-primitive global variables. This permits the constructors
  1410. // for the complex types to use the already initialized variables of primitive
  1411. // type. Note, we currently don't know which global variables are used in the
  1412. // constructors, so we cannot guarantee that variables of complex types are
  1413. // initialized in the correct order, so we won't reorder those.
  1414. bool compilingPrimitives = true;
  1415. // Compile each global variable
  1416. while( compileSucceeded )
  1417. {
  1418. compileSucceeded = false;
  1419. int accumErrors = 0;
  1420. int accumWarnings = 0;
  1421. // Restore state of compilation
  1422. finalOutput.Clear();
  1423. asCSymbolTable<sGlobalVariableDescription>::iterator it = globVariables.List();
  1424. for( ; it; it++ )
  1425. {
  1426. sGlobalVariableDescription *gvar = *it;
  1427. if( gvar->isCompiled )
  1428. continue;
  1429. asCByteCode init(engine);
  1430. numWarnings = 0;
  1431. numErrors = 0;
  1432. outBuffer.Clear();
  1433. // Skip this for now if we're not compiling complex types yet
  1434. if( compilingPrimitives && !gvar->datatype.IsPrimitive() )
  1435. continue;
  1436. if( gvar->nextNode )
  1437. {
  1438. int r, c;
  1439. gvar->script->ConvertPosToRowCol(gvar->nextNode->tokenPos, &r, &c);
  1440. asCString str = gvar->datatype.Format();
  1441. str += " " + gvar->name;
  1442. str.Format(TXT_COMPILING_s, str.AddressOf());
  1443. WriteInfo(gvar->script->name, str, r, c, true);
  1444. }
  1445. if( gvar->isEnumValue )
  1446. {
  1447. int r;
  1448. if( gvar->nextNode )
  1449. {
  1450. asCCompiler comp(engine);
  1451. asCScriptFunction func(engine, module, asFUNC_DUMMY);
  1452. // Set the namespace that should be used during the compilation
  1453. func.nameSpace = gvar->datatype.GetObjectType()->nameSpace;
  1454. // Temporarily switch the type of the variable to int so it can be compiled properly
  1455. asCDataType saveType;
  1456. saveType = gvar->datatype;
  1457. gvar->datatype = asCDataType::CreatePrimitive(ttInt, true);
  1458. r = comp.CompileGlobalVariable(this, gvar->script, gvar->nextNode, gvar, &func);
  1459. gvar->datatype = saveType;
  1460. }
  1461. else
  1462. {
  1463. r = 0;
  1464. // When there is no assignment the value is the last + 1
  1465. int enumVal = 0;
  1466. asCSymbolTable<sGlobalVariableDescription>::iterator prev_it = it;
  1467. prev_it--;
  1468. if( prev_it )
  1469. {
  1470. sGlobalVariableDescription *gvar2 = *prev_it;
  1471. if(gvar2->datatype == gvar->datatype )
  1472. {
  1473. // The integer value is stored in the lower bytes
  1474. enumVal = (*(int*)&gvar2->constantValue) + 1;
  1475. if( !gvar2->isCompiled )
  1476. {
  1477. // TODO: Need to get the correct script position
  1478. int row, col;
  1479. gvar->script->ConvertPosToRowCol(0, &row, &col);
  1480. asCString str = gvar->datatype.Format();
  1481. str += " " + gvar->name;
  1482. str.Format(TXT_COMPILING_s, str.AddressOf());
  1483. WriteInfo(gvar->script->name, str, row, col, true);
  1484. str.Format(TXT_UNINITIALIZED_GLOBAL_VAR_s, gvar2->name.AddressOf());
  1485. WriteError(gvar->script->name, str, row, col);
  1486. r = -1;
  1487. }
  1488. }
  1489. }
  1490. // The integer value is stored in the lower bytes
  1491. *(int*)&gvar->constantValue = enumVal;
  1492. }
  1493. if( r >= 0 )
  1494. {
  1495. // Set the value as compiled
  1496. gvar->isCompiled = true;
  1497. compileSucceeded = true;
  1498. }
  1499. }
  1500. else
  1501. {
  1502. // Compile the global variable
  1503. initFunc = asNEW(asCScriptFunction)(engine, module, asFUNC_DUMMY);
  1504. if( initFunc == 0 )
  1505. {
  1506. // Out of memory
  1507. return;
  1508. }
  1509. // Set the namespace that should be used for this function
  1510. initFunc->nameSpace = gvar->property->nameSpace;
  1511. asCCompiler comp(engine);
  1512. int r = comp.CompileGlobalVariable(this, gvar->script, gvar->nextNode, gvar, initFunc);
  1513. if( r >= 0 )
  1514. {
  1515. // Compilation succeeded
  1516. gvar->isCompiled = true;
  1517. compileSucceeded = true;
  1518. }
  1519. else
  1520. {
  1521. // Compilation failed
  1522. asDELETE(initFunc, asCScriptFunction);
  1523. initFunc = 0;
  1524. }
  1525. }
  1526. if( gvar->isCompiled )
  1527. {
  1528. // Add warnings for this constant to the total build
  1529. if( numWarnings )
  1530. {
  1531. currNumWarnings += numWarnings;
  1532. if( msgCallback )
  1533. outBuffer.SendToCallback(engine, &msgCallbackFunc, msgCallbackObj);
  1534. }
  1535. // Determine order of variable initializations
  1536. if( gvar->property && !gvar->isEnumValue )
  1537. initOrder.Put(gvar->property);
  1538. // Does the function contain more than just a SUSPEND followed by a RET instruction?
  1539. if( initFunc && initFunc->byteCode.GetLength() > 2 )
  1540. {
  1541. // Create the init function for this variable
  1542. initFunc->id = engine->GetNextScriptFunctionId();
  1543. engine->SetScriptFunction(initFunc);
  1544. // Finalize the init function for this variable
  1545. initFunc->funcType = asFUNC_SCRIPT;
  1546. initFunc->returnType = asCDataType::CreatePrimitive(ttVoid, false);
  1547. initFunc->scriptSectionIdx = engine->GetScriptSectionNameIndex(gvar->script->name.AddressOf());
  1548. gvar->property->SetInitFunc(initFunc);
  1549. initFunc->Release();
  1550. initFunc = 0;
  1551. }
  1552. else if( initFunc )
  1553. {
  1554. // Destroy the function as it won't be used
  1555. asDELETE(initFunc, asCScriptFunction);
  1556. initFunc = 0;
  1557. }
  1558. // Convert enums to true enum values, so subsequent compilations can access it as an enum
  1559. if( gvar->isEnumValue )
  1560. {
  1561. asCObjectType *objectType = gvar->datatype.GetObjectType();
  1562. asASSERT(NULL != objectType);
  1563. asSEnumValue *e = asNEW(asSEnumValue);
  1564. if( e == 0 )
  1565. {
  1566. // Out of memory
  1567. numErrors++;
  1568. return;
  1569. }
  1570. e->name = gvar->name;
  1571. e->value = *(int*)&gvar->constantValue;
  1572. objectType->enumValues.PushLast(e);
  1573. }
  1574. }
  1575. else
  1576. {
  1577. // Add output to final output
  1578. finalOutput.Append(outBuffer);
  1579. accumErrors += numErrors;
  1580. accumWarnings += numWarnings;
  1581. }
  1582. preMessage.isSet = false;
  1583. }
  1584. if( !compileSucceeded )
  1585. {
  1586. if( compilingPrimitives )
  1587. {
  1588. // No more primitives could be compiled, so
  1589. // switch to compiling the complex variables
  1590. compilingPrimitives = false;
  1591. compileSucceeded = true;
  1592. }
  1593. else
  1594. {
  1595. // No more variables can be compiled
  1596. // Add errors and warnings to total build
  1597. currNumWarnings += accumWarnings;
  1598. currNumErrors += accumErrors;
  1599. if( msgCallback )
  1600. finalOutput.SendToCallback(engine, &msgCallbackFunc, msgCallbackObj);
  1601. }
  1602. }
  1603. }
  1604. // Restore states
  1605. engine->msgCallback = msgCallback;
  1606. engine->msgCallbackFunc = msgCallbackFunc;
  1607. engine->msgCallbackObj = msgCallbackObj;
  1608. numWarnings = currNumWarnings;
  1609. numErrors = currNumErrors;
  1610. // Set the correct order of initialization
  1611. if( numErrors == 0 )
  1612. {
  1613. // If the length of the arrays are not the same, then this is the compilation
  1614. // of a single variable, in which case the initialization order of the previous
  1615. // variables must be preserved.
  1616. if( module->scriptGlobals.GetSize() == initOrder.GetSize() )
  1617. module->scriptGlobals.SwapWith(initOrder);
  1618. }
  1619. // Delete the enum expressions
  1620. asCSymbolTableIterator<sGlobalVariableDescription> it = globVariables.List();
  1621. while( it )
  1622. {
  1623. sGlobalVariableDescription *gvar = *it;
  1624. if( gvar->isEnumValue )
  1625. {
  1626. // Remove from symboltable. This has to be done prior to freeing the memeory
  1627. globVariables.Erase(it.GetIndex());
  1628. // Destroy the gvar property
  1629. if( gvar->nextNode )
  1630. {
  1631. gvar->nextNode->Destroy(engine);
  1632. gvar->nextNode = 0;
  1633. }
  1634. if( gvar->property )
  1635. {
  1636. asDELETE(gvar->property, asCGlobalProperty);
  1637. gvar->property = 0;
  1638. }
  1639. asDELETE(gvar, sGlobalVariableDescription);
  1640. }
  1641. it++;
  1642. }
  1643. }
  1644. int asCBuilder::GetNamespaceAndNameFromNode(asCScriptNode *n, asCScriptCode *script, asSNameSpace *implicitNs, asSNameSpace *&outNs, asCString &outName)
  1645. {
  1646. asASSERT( n->nodeType == snIdentifier );
  1647. // Get the optional scope from the node
  1648. asSNameSpace *ns = GetNameSpaceFromNode(n->firstChild, script, implicitNs, 0);
  1649. if( ns == 0 )
  1650. return -1;
  1651. // Get the name
  1652. asCString name(&script->code[n->lastChild->tokenPos], n->lastChild->tokenLength);
  1653. outNs = ns;
  1654. outName = name;
  1655. return 0;
  1656. }
  1657. void asCBuilder::AddInterfaceFromMixinToClass(sClassDeclaration *decl, asCScriptNode *errNode, sMixinClass *mixin)
  1658. {
  1659. // Determine what interfaces that the mixin implements
  1660. asCScriptNode *node = mixin->node;
  1661. asASSERT(node->nodeType == snClass);
  1662. // Skip the name of the mixin
  1663. node = node->firstChild->next;
  1664. while( node && node->nodeType == snIdentifier )
  1665. {
  1666. bool ok = true;
  1667. asSNameSpace *ns;
  1668. asCString name;
  1669. if( GetNamespaceAndNameFromNode(node, mixin->script, mixin->ns, ns, name) < 0 )
  1670. ok = false;
  1671. else
  1672. {
  1673. // Find the object type for the interface
  1674. asCObjectType *objType = GetObjectType(name.AddressOf(), ns);
  1675. // Check that the object type is an interface
  1676. if( objType && objType->size == 0 && (objType->flags & asOBJ_SCRIPT_OBJECT) )
  1677. {
  1678. // Only add the interface if the class doesn't already implement it
  1679. if( !decl->objType->Implements(objType) )
  1680. AddInterfaceToClass(decl, errNode, objType);
  1681. }
  1682. else
  1683. {
  1684. WriteError(TXT_MIXIN_CLASS_CANNOT_INHERIT, mixin->script, node);
  1685. ok = false;
  1686. }
  1687. }
  1688. if( !ok )
  1689. {
  1690. // Remove this node so the error isn't reported again
  1691. asCScriptNode *delNode = node;
  1692. node = node->prev;
  1693. delNode->DisconnectParent();
  1694. delNode->Destroy(engine);
  1695. }
  1696. node = node->next;
  1697. }
  1698. }
  1699. void asCBuilder::AddInterfaceToClass(sClassDeclaration *decl, asCScriptNode *errNode, asCObjectType *intfType)
  1700. {
  1701. // A shared type may only implement from shared interfaces
  1702. if( decl->objType->IsShared() && !intfType->IsShared() )
  1703. {
  1704. asCString msg;
  1705. msg.Format(TXT_SHARED_CANNOT_IMPLEMENT_NON_SHARED_s, intfType->name.AddressOf());
  1706. WriteError(msg, decl->script, errNode);
  1707. return;
  1708. }
  1709. if( decl->isExistingShared )
  1710. {
  1711. // If the class is an existing shared class, then just check if the
  1712. // interface exists in the original declaration too
  1713. if( !decl->objType->Implements(intfType) )
  1714. {
  1715. asCString str;
  1716. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, decl->objType->GetName());
  1717. WriteError(str, decl->script, errNode);
  1718. return;
  1719. }
  1720. }
  1721. else
  1722. {
  1723. // If the interface is already in the class then don't add it again
  1724. if( decl->objType->Implements(intfType) )
  1725. return;
  1726. // Add the interface to the class
  1727. decl->objType->interfaces.PushLast(intfType);
  1728. // Add the inherited interfaces too
  1729. // For interfaces this will be done outside to handle out-of-order declarations
  1730. if( !decl->objType->IsInterface() )
  1731. {
  1732. for( asUINT n = 0; n < intfType->interfaces.GetLength(); n++ )
  1733. AddInterfaceToClass(decl, errNode, intfType->interfaces[n]);
  1734. }
  1735. }
  1736. }
  1737. void asCBuilder::CompileInterfaces()
  1738. {
  1739. asUINT n;
  1740. for( n = 0; n < interfaceDeclarations.GetLength(); n++ )
  1741. {
  1742. sClassDeclaration *intfDecl = interfaceDeclarations[n];
  1743. asCObjectType *intfType = intfDecl->objType;
  1744. asCScriptNode *node = intfDecl->node;
  1745. asASSERT(node && node->nodeType == snInterface);
  1746. node = node->firstChild;
  1747. // Skip the 'shared' keyword
  1748. if( intfType->IsShared() )
  1749. node = node->next;
  1750. // Skip the name
  1751. node = node->next;
  1752. // Verify the inherited interfaces
  1753. while( node && node->nodeType == snIdentifier )
  1754. {
  1755. asSNameSpace *ns;
  1756. asCString name;
  1757. if( GetNamespaceAndNameFromNode(node, intfDecl->script, intfType->nameSpace, ns, name) < 0 )
  1758. {
  1759. node = node->next;
  1760. continue;
  1761. }
  1762. // Find the object type for the interface
  1763. asCObjectType *objType = GetObjectType(name.AddressOf(), ns);
  1764. // Check that the object type is an interface
  1765. bool ok = true;
  1766. if( objType && objType->size == 0 && (objType->flags & asOBJ_SCRIPT_OBJECT) )
  1767. {
  1768. // Check that the implemented interface is shared if the base interface is shared
  1769. if( intfType->IsShared() && !objType->IsShared() )
  1770. {
  1771. asCString str;
  1772. str.Format(TXT_SHARED_CANNOT_IMPLEMENT_NON_SHARED_s, objType->GetName());
  1773. WriteError(str, intfDecl->script, node);
  1774. ok = false;
  1775. }
  1776. }
  1777. else
  1778. {
  1779. WriteError(TXT_INTERFACE_CAN_ONLY_IMPLEMENT_INTERFACE, intfDecl->script, node);
  1780. ok = false;
  1781. }
  1782. if( ok )
  1783. {
  1784. // Make sure none of the implemented interfaces implement from this one
  1785. asCObjectType *base = objType;
  1786. while( base != 0 )
  1787. {
  1788. if( base == intfType )
  1789. {
  1790. WriteError(TXT_CANNOT_IMPLEMENT_SELF, intfDecl->script, node);
  1791. ok = false;
  1792. break;
  1793. }
  1794. // At this point there is at most one implemented interface
  1795. if( base->interfaces.GetLength() )
  1796. base = base->interfaces[0];
  1797. else
  1798. break;
  1799. }
  1800. }
  1801. if( ok )
  1802. AddInterfaceToClass(intfDecl, node, objType);
  1803. // Remove the nodes so they aren't parsed again
  1804. asCScriptNode *delNode = node;
  1805. node = node->next;
  1806. delNode->DisconnectParent();
  1807. delNode->Destroy(engine);
  1808. }
  1809. }
  1810. // Order the interfaces with inheritances so that the inherited
  1811. // of inherited interfaces can be added properly
  1812. for( n = 0; n < interfaceDeclarations.GetLength(); n++ )
  1813. {
  1814. sClassDeclaration *intfDecl = interfaceDeclarations[n];
  1815. asCObjectType *intfType = intfDecl->objType;
  1816. if( intfType->interfaces.GetLength() == 0 ) continue;
  1817. // If any of the derived interfaces are found after this interface, then move this to the end of the list
  1818. for( asUINT m = n+1; m < interfaceDeclarations.GetLength(); m++ )
  1819. {
  1820. if( intfType->Implements(interfaceDeclarations[m]->objType) )
  1821. {
  1822. interfaceDeclarations.RemoveIndex(n);
  1823. interfaceDeclarations.PushLast(intfDecl);
  1824. // Decrease index so that we don't skip an entry
  1825. n--;
  1826. break;
  1827. }
  1828. }
  1829. }
  1830. // Now recursively add the additional inherited interfaces
  1831. for( n = 0; n < interfaceDeclarations.GetLength(); n++ )
  1832. {
  1833. sClassDeclaration *intfDecl = interfaceDeclarations[n];
  1834. asCObjectType *intfType = intfDecl->objType;
  1835. // As new interfaces will be added to the end of the list, all
  1836. // interfaces will be traversed the same as recursively
  1837. for( asUINT m = 0; m < intfType->interfaces.GetLength(); m++ )
  1838. {
  1839. asCObjectType *base = intfType->interfaces[m];
  1840. // Add any interfaces not already implemented
  1841. for( asUINT l = 0; l < base->interfaces.GetLength(); l++ )
  1842. AddInterfaceToClass(intfDecl, intfDecl->node, base->interfaces[l]);
  1843. // Add the methods from the implemented interface
  1844. for( asUINT m = 0; m < base->methods.GetLength(); m++ )
  1845. {
  1846. // If the derived interface implements the same method, then don't add the base interface' method
  1847. asCScriptFunction *baseFunc = GetFunctionDescription(base->methods[m]);
  1848. asCScriptFunction *derivedFunc = 0;
  1849. bool found = false;
  1850. for( asUINT d = 0; d < intfType->methods.GetLength(); d++ )
  1851. {
  1852. derivedFunc = GetFunctionDescription(intfType->methods[d]);
  1853. if( derivedFunc->IsSignatureEqual(baseFunc) )
  1854. {
  1855. found = true;
  1856. break;
  1857. }
  1858. }
  1859. if( !found )
  1860. {
  1861. // Add the method
  1862. intfType->methods.PushLast(baseFunc->id);
  1863. baseFunc->AddRef();
  1864. }
  1865. }
  1866. }
  1867. }
  1868. }
  1869. void asCBuilder::CompileClasses()
  1870. {
  1871. asUINT n;
  1872. asCArray<sClassDeclaration*> toValidate((int)classDeclarations.GetLength());
  1873. // Determine class inheritances and interfaces
  1874. for( n = 0; n < classDeclarations.GetLength(); n++ )
  1875. {
  1876. sClassDeclaration *decl = classDeclarations[n];
  1877. asCScriptCode *file = decl->script;
  1878. // Find the base class that this class inherits from
  1879. bool multipleInheritance = false;
  1880. asCScriptNode *node = decl->node->firstChild;
  1881. if( decl->objType->IsShared() )
  1882. {
  1883. // Skip the keyword 'shared'
  1884. asASSERT(node->tokenType == ttIdentifier);
  1885. node = node->next;
  1886. }
  1887. if( decl->objType->flags & asOBJ_NOINHERIT )
  1888. {
  1889. // skip the keyword 'final'
  1890. asASSERT(node->tokenType == ttIdentifier);
  1891. node = node->next;
  1892. }
  1893. // Skip the name of the class
  1894. asASSERT(node->tokenType == ttIdentifier);
  1895. node = node->next;
  1896. while( node && node->nodeType == snIdentifier )
  1897. {
  1898. asSNameSpace *ns;
  1899. asCString name;
  1900. if( GetNamespaceAndNameFromNode(node, file, decl->objType->nameSpace, ns, name) < 0 )
  1901. {
  1902. node = node->next;
  1903. continue;
  1904. }
  1905. // Find the object type for the interface
  1906. asCObjectType *objType = GetObjectType(name.AddressOf(), ns);
  1907. if( objType == 0 )
  1908. {
  1909. // Check if the name is a mixin class
  1910. sMixinClass *mixin = GetMixinClass(name.AddressOf(), ns);
  1911. if( !mixin )
  1912. {
  1913. asCString str;
  1914. str.Format(TXT_IDENTIFIER_s_NOT_DATA_TYPE, name.AddressOf());
  1915. WriteError(str, file, node);
  1916. }
  1917. else
  1918. AddInterfaceFromMixinToClass(decl, node, mixin);
  1919. }
  1920. else if( !(objType->flags & asOBJ_SCRIPT_OBJECT) ||
  1921. objType->flags & asOBJ_NOINHERIT )
  1922. {
  1923. // Either the class is not a script class or interface
  1924. // or the class has been declared as 'final'
  1925. asCString str;
  1926. str.Format(TXT_CANNOT_INHERIT_FROM_s_FINAL, objType->name.AddressOf());
  1927. WriteError(str, file, node);
  1928. }
  1929. else if( objType->size != 0 )
  1930. {
  1931. // The class inherits from another script class
  1932. if( !decl->isExistingShared && decl->objType->derivedFrom != 0 )
  1933. {
  1934. if( !multipleInheritance )
  1935. {
  1936. WriteError(TXT_CANNOT_INHERIT_FROM_MULTIPLE_CLASSES, file, node);
  1937. multipleInheritance = true;
  1938. }
  1939. }
  1940. else
  1941. {
  1942. // Make sure none of the base classes inherit from this one
  1943. asCObjectType *base = objType;
  1944. bool error = false;
  1945. while( base != 0 )
  1946. {
  1947. if( base == decl->objType )
  1948. {
  1949. WriteError(TXT_CANNOT_INHERIT_FROM_SELF, file, node);
  1950. error = true;
  1951. break;
  1952. }
  1953. base = base->derivedFrom;
  1954. }
  1955. if( !error )
  1956. {
  1957. // A shared type may only inherit from other shared types
  1958. if( (decl->objType->IsShared()) && !(objType->IsShared()) )
  1959. {
  1960. asCString msg;
  1961. msg.Format(TXT_SHARED_CANNOT_INHERIT_FROM_NON_SHARED_s, objType->name.AddressOf());
  1962. WriteError(msg, file, node);
  1963. error = true;
  1964. }
  1965. }
  1966. if( !error )
  1967. {
  1968. if( decl->isExistingShared )
  1969. {
  1970. // Verify that the base class is the same as the original shared type
  1971. if( decl->objType->derivedFrom != objType )
  1972. {
  1973. asCString str;
  1974. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, decl->objType->GetName());
  1975. WriteError(str, file, node);
  1976. }
  1977. }
  1978. else
  1979. {
  1980. // Set the base class
  1981. decl->objType->derivedFrom = objType;
  1982. objType->AddRef();
  1983. }
  1984. }
  1985. }
  1986. }
  1987. else
  1988. {
  1989. // The class implements an interface
  1990. AddInterfaceToClass(decl, node, objType);
  1991. }
  1992. node = node->next;
  1993. }
  1994. }
  1995. // Order class declarations so that base classes are compiled before derived classes.
  1996. // This will allow the derived classes to copy properties and methods in the next step.
  1997. for( n = 0; n < classDeclarations.GetLength(); n++ )
  1998. {
  1999. sClassDeclaration *decl = classDeclarations[n];
  2000. asCObjectType *derived = decl->objType;
  2001. asCObjectType *base = derived->derivedFrom;
  2002. if( base == 0 ) continue;
  2003. // If the base class is found after the derived class, then move the derived class to the end of the list
  2004. for( asUINT m = n+1; m < classDeclarations.GetLength(); m++ )
  2005. {
  2006. sClassDeclaration *declBase = classDeclarations[m];
  2007. if( base == declBase->objType )
  2008. {
  2009. classDeclarations.RemoveIndex(n);
  2010. classDeclarations.PushLast(decl);
  2011. // Decrease index so that we don't skip an entry
  2012. n--;
  2013. break;
  2014. }
  2015. }
  2016. }
  2017. // Go through each of the classes and register the object type descriptions
  2018. for( n = 0; n < classDeclarations.GetLength(); n++ )
  2019. {
  2020. sClassDeclaration *decl = classDeclarations[n];
  2021. if( decl->isExistingShared )
  2022. {
  2023. // Set the declaration as validated already, so that other
  2024. // types that contain this will accept this type
  2025. decl->validState = 1;
  2026. // We'll still validate the declaration to make sure nothing new is
  2027. // added to the shared class that wasn't there in the previous
  2028. // compilation. We do not care if something that is there in the previous
  2029. // declaration is not included in the new declaration though.
  2030. }
  2031. // Methods included from mixin classes should take precedence over inherited methods
  2032. IncludeMethodsFromMixins(decl);
  2033. // Add all properties and methods from the base class
  2034. if( !decl->isExistingShared && decl->objType->derivedFrom )
  2035. {
  2036. asCObjectType *baseType = decl->objType->derivedFrom;
  2037. // The derived class inherits all interfaces from the base class
  2038. for( unsigned int n = 0; n < baseType->interfaces.GetLength(); n++ )
  2039. {
  2040. if( !decl->objType->Implements(baseType->interfaces[n]) )
  2041. decl->objType->interfaces.PushLast(baseType->interfaces[n]);
  2042. }
  2043. // TODO: Need to check for name conflict with new class methods
  2044. // Copy properties from base class to derived class
  2045. for( asUINT p = 0; p < baseType->properties.GetLength(); p++ )
  2046. {
  2047. asCObjectProperty *prop = AddPropertyToClass(decl, baseType->properties[p]->name, baseType->properties[p]->type, baseType->properties[p]->isPrivate);
  2048. // The properties must maintain the same offset
  2049. asASSERT(prop && prop->byteOffset == baseType->properties[p]->byteOffset); UNUSED_VAR(prop);
  2050. }
  2051. // Copy methods from base class to derived class
  2052. for( asUINT m = 0; m < baseType->methods.GetLength(); m++ )
  2053. {
  2054. // If the derived class implements the same method, then don't add the base class' method
  2055. asCScriptFunction *baseFunc = GetFunctionDescription(baseType->methods[m]);
  2056. asCScriptFunction *derivedFunc = 0;
  2057. bool found = false;
  2058. for( asUINT d = 0; d < decl->objType->methods.GetLength(); d++ )
  2059. {
  2060. derivedFunc = GetFunctionDescription(decl->objType->methods[d]);
  2061. if( derivedFunc->name == baseFunc->name &&
  2062. derivedFunc->IsSignatureExceptNameAndReturnTypeEqual(baseFunc) )
  2063. {
  2064. if( baseFunc->returnType != derivedFunc->returnType )
  2065. {
  2066. asCString msg;
  2067. msg.Format(TXT_DERIVED_METHOD_MUST_HAVE_SAME_RETTYPE_s, baseFunc->GetDeclaration());
  2068. WriteError(msg, decl->script, decl->node);
  2069. }
  2070. if( baseFunc->IsFinal() )
  2071. {
  2072. asCString msg;
  2073. msg.Format(TXT_METHOD_CANNOT_OVERRIDE_s, baseFunc->GetDeclaration());
  2074. WriteError(msg, decl->script, decl->node);
  2075. }
  2076. // Move the function from the methods array to the virtualFunctionTable
  2077. decl->objType->methods.RemoveIndex(d);
  2078. decl->objType->virtualFunctionTable.PushLast(derivedFunc);
  2079. found = true;
  2080. break;
  2081. }
  2082. }
  2083. if( !found )
  2084. {
  2085. // Push the base class function on the virtual function table
  2086. decl->objType->virtualFunctionTable.PushLast(baseType->virtualFunctionTable[m]);
  2087. baseType->virtualFunctionTable[m]->AddRef();
  2088. }
  2089. decl->objType->methods.PushLast(baseType->methods[m]);
  2090. engine->scriptFunctions[baseType->methods[m]]->AddRef();
  2091. }
  2092. }
  2093. // Move this class' methods into the virtual function table
  2094. if( !decl->isExistingShared )
  2095. {
  2096. for( asUINT m = 0; m < decl->objType->methods.GetLength(); m++ )
  2097. {
  2098. asCScriptFunction *func = GetFunctionDescription(decl->objType->methods[m]);
  2099. if( func->funcType != asFUNC_VIRTUAL )
  2100. {
  2101. // Move the reference from the method list to the virtual function list
  2102. decl->objType->methods.RemoveIndex(m);
  2103. decl->objType->virtualFunctionTable.PushLast(func);
  2104. // Substitute the function description in the method list for a virtual method
  2105. // Make sure the methods are in the same order as the virtual function table
  2106. decl->objType->methods.PushLast(CreateVirtualFunction(func, (int)decl->objType->virtualFunctionTable.GetLength() - 1));
  2107. m--;
  2108. }
  2109. }
  2110. }
  2111. // Enumerate each of the declared properties
  2112. asCScriptNode *node = decl->node->firstChild->next;
  2113. if( decl->objType->IsShared() )
  2114. node = node->next;
  2115. if( decl->objType->flags & asOBJ_NOINHERIT )
  2116. node = node->next;
  2117. // Skip list of classes and interfaces
  2118. while( node && node->nodeType == snIdentifier )
  2119. node = node->next;
  2120. while( node )
  2121. {
  2122. if( node->nodeType == snDeclaration )
  2123. {
  2124. asCScriptNode *n = node->firstChild;
  2125. // Is the property declared as private?
  2126. bool isPrivate = false;
  2127. if( n && n->tokenType == ttPrivate )
  2128. {
  2129. isPrivate = true;
  2130. n = n->next;
  2131. }
  2132. // Determine the type of the property
  2133. asCScriptCode *file = decl->script;
  2134. asCDataType dt = CreateDataTypeFromNode(n, file, decl->objType->nameSpace);
  2135. if( decl->objType->IsShared() && dt.GetObjectType() && !dt.GetObjectType()->IsShared() )
  2136. {
  2137. asCString msg;
  2138. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, dt.GetObjectType()->name.AddressOf());
  2139. WriteError(msg, file, node);
  2140. }
  2141. if( dt.IsReadOnly() )
  2142. WriteError(TXT_PROPERTY_CANT_BE_CONST, file, node);
  2143. // Multiple properties can be declared separated by ,
  2144. n = n->next;
  2145. while( n )
  2146. {
  2147. asCString name(&file->code[n->tokenPos], n->tokenLength);
  2148. if( !decl->isExistingShared )
  2149. {
  2150. CheckNameConflictMember(decl->objType, name.AddressOf(), n, file, true);
  2151. AddPropertyToClass(decl, name, dt, isPrivate, file, n);
  2152. }
  2153. else
  2154. {
  2155. // Verify that the property exists in the original declaration
  2156. bool found = false;
  2157. for( asUINT p = 0; p < decl->objType->properties.GetLength(); p++ )
  2158. {
  2159. asCObjectProperty *prop = decl->objType->properties[p];
  2160. if( prop->isPrivate == isPrivate &&
  2161. prop->name == name &&
  2162. prop->type.IsEqualExceptRef(dt) )
  2163. {
  2164. found = true;
  2165. break;
  2166. }
  2167. }
  2168. if( !found )
  2169. {
  2170. asCString str;
  2171. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, decl->objType->GetName());
  2172. WriteError(str, file, n);
  2173. }
  2174. }
  2175. // Skip the initialization node
  2176. if( n->next && n->next->nodeType != snIdentifier )
  2177. n = n->next;
  2178. n = n->next;
  2179. }
  2180. }
  2181. else
  2182. asASSERT(false);
  2183. node = node->next;
  2184. }
  2185. // Add properties from included mixin classes that don't conflict with existing properties
  2186. IncludePropertiesFromMixins(decl);
  2187. if( !decl->isExistingShared )
  2188. toValidate.PushLast(decl);
  2189. }
  2190. // TODO: Warn if a method overrides a base method without marking it as 'override'.
  2191. // It must be possible to turn off this warning through engine property.
  2192. // TODO: A base class should be able to mark a method as 'abstract'. This will
  2193. // allow a base class to provide a partial implementation, but still force
  2194. // derived classes to implement specific methods.
  2195. // Verify that all interface methods are implemented in the classes
  2196. // We do this here so the base class' methods have already been inherited
  2197. for( n = 0; n < classDeclarations.GetLength(); n++ )
  2198. {
  2199. sClassDeclaration *decl = classDeclarations[n];
  2200. if( decl->isExistingShared ) continue;
  2201. asCArray<bool> overrideValidations(decl->objType->GetMethodCount());
  2202. for( asUINT k = 0; k < decl->objType->methods.GetLength(); k++ )
  2203. overrideValidations.PushLast( !static_cast<asCScriptFunction*>(decl->objType->GetMethodByIndex(k, false))->IsOverride() );
  2204. for( asUINT m = 0; m < decl->objType->interfaces.GetLength(); m++ )
  2205. {
  2206. asCObjectType *objType = decl->objType->interfaces[m];
  2207. for( asUINT i = 0; i < objType->methods.GetLength(); i++ )
  2208. {
  2209. // Only check the interface methods that was explicitly declared in this interface
  2210. // Methods that was inherited from other interfaces will be checked in those interfaces
  2211. if( objType != engine->scriptFunctions[objType->methods[i]]->objectType )
  2212. continue;
  2213. asUINT overrideIndex;
  2214. if( !DoesMethodExist(decl->objType, objType->methods[i], &overrideIndex) )
  2215. {
  2216. asCString str;
  2217. str.Format(TXT_MISSING_IMPLEMENTATION_OF_s,
  2218. engine->GetFunctionDeclaration(objType->methods[i]).AddressOf());
  2219. WriteError(str, decl->script, decl->node);
  2220. }
  2221. else
  2222. overrideValidations[overrideIndex] = true;
  2223. }
  2224. }
  2225. bool hasBaseClass = decl->objType->derivedFrom != 0;
  2226. for( asUINT j = 0; j < overrideValidations.GetLength(); j++ )
  2227. {
  2228. if( !overrideValidations[j] && (!hasBaseClass || !DoesMethodExist(decl->objType->derivedFrom, decl->objType->methods[j])) )
  2229. {
  2230. asCString msg;
  2231. msg.Format(TXT_METHOD_s_DOES_NOT_OVERRIDE, decl->objType->GetMethodByIndex(j, false)->GetDeclaration());
  2232. WriteError(msg, decl->script, decl->node);
  2233. }
  2234. }
  2235. }
  2236. // Verify that the declared structures are valid, e.g. that the structure
  2237. // doesn't contain a member of its own type directly or indirectly
  2238. while( toValidate.GetLength() > 0 )
  2239. {
  2240. asUINT numClasses = (asUINT)toValidate.GetLength();
  2241. asCArray<sClassDeclaration*> toValidateNext((int)toValidate.GetLength());
  2242. while( toValidate.GetLength() > 0 )
  2243. {
  2244. sClassDeclaration *decl = toValidate[toValidate.GetLength()-1];
  2245. int validState = 1;
  2246. for( asUINT n = 0; n < decl->objType->properties.GetLength(); n++ )
  2247. {
  2248. // A valid structure is one that uses only primitives or other valid objects
  2249. asCObjectProperty *prop = decl->objType->properties[n];
  2250. asCDataType dt = prop->type;
  2251. if( dt.IsTemplate() )
  2252. {
  2253. asCDataType sub = dt;
  2254. while( sub.IsTemplate() && !sub.IsObjectHandle() )
  2255. sub = sub.GetSubType();
  2256. dt = sub;
  2257. }
  2258. if( dt.IsObject() && !dt.IsObjectHandle() )
  2259. {
  2260. // Find the class declaration
  2261. sClassDeclaration *pdecl = 0;
  2262. for( asUINT p = 0; p < classDeclarations.GetLength(); p++ )
  2263. {
  2264. if( classDeclarations[p]->objType == dt.GetObjectType() )
  2265. {
  2266. pdecl = classDeclarations[p];
  2267. break;
  2268. }
  2269. }
  2270. if( pdecl )
  2271. {
  2272. if( pdecl->objType == decl->objType )
  2273. {
  2274. WriteError(TXT_ILLEGAL_MEMBER_TYPE, decl->script, decl->node);
  2275. validState = 2;
  2276. break;
  2277. }
  2278. else if( pdecl->validState != 1 )
  2279. {
  2280. validState = pdecl->validState;
  2281. break;
  2282. }
  2283. }
  2284. }
  2285. }
  2286. if( validState == 1 )
  2287. {
  2288. decl->validState = 1;
  2289. toValidate.PopLast();
  2290. }
  2291. else if( validState == 2 )
  2292. {
  2293. decl->validState = 2;
  2294. toValidate.PopLast();
  2295. }
  2296. else
  2297. {
  2298. toValidateNext.PushLast(toValidate.PopLast());
  2299. }
  2300. }
  2301. toValidate = toValidateNext;
  2302. toValidateNext.SetLength(0);
  2303. if( numClasses == toValidate.GetLength() )
  2304. {
  2305. WriteError(TXT_ILLEGAL_MEMBER_TYPE, toValidate[0]->script, toValidate[0]->node);
  2306. break;
  2307. }
  2308. }
  2309. if( numErrors > 0 ) return;
  2310. // Verify which script classes can really form circular references, and mark only those as garbage collected.
  2311. // TODO: runtime optimize: This algorithm can be further improved by checking the types that inherits from
  2312. // a base class. If the base class is not shared all the classes that derive from it
  2313. // are known at compile time, and can thus be checked for potential circular references too.
  2314. //
  2315. // Observe, that doing this would conflict with another potential future feature, which is to
  2316. // allow incremental builds, i.e. allow application to add or replace classes in an
  2317. // existing module. However, the applications that want to use that should use a special
  2318. // build flag to not finalize the module.
  2319. // Urho3D: disable garbage collection from script classes
  2320. /*
  2321. for( n = 0; n < classDeclarations.GetLength(); n++ )
  2322. {
  2323. sClassDeclaration *decl = classDeclarations[n];
  2324. // Existing shared classes won't be re-evaluated
  2325. if( decl->isExistingShared ) continue;
  2326. asCObjectType *ot = decl->objType;
  2327. // Is there some path in which this structure is involved in circular references?
  2328. bool gc = false;
  2329. for( asUINT p = 0; p < ot->properties.GetLength(); p++ )
  2330. {
  2331. asCDataType dt = ot->properties[p]->type;
  2332. if( !dt.IsObject() )
  2333. continue;
  2334. if( dt.IsObjectHandle() )
  2335. {
  2336. // If it is known that the handle can't be involved in a circular reference
  2337. // then this object doesn't need to be marked as garbage collected.
  2338. asCObjectType *prop = dt.GetObjectType();
  2339. if( prop->flags & asOBJ_SCRIPT_OBJECT )
  2340. {
  2341. // For script objects, treat non-final classes as if they can contain references
  2342. // as it is not known what derived classes might do. For final types, check all
  2343. // properties to determine if any of those can cause a circular reference.
  2344. if( prop->flags & asOBJ_NOINHERIT )
  2345. {
  2346. for( asUINT sp = 0; sp < prop->properties.GetLength(); sp++ )
  2347. {
  2348. asCDataType sdt = prop->properties[sp]->type;
  2349. if( sdt.IsObject() )
  2350. {
  2351. if( sdt.IsObjectHandle() )
  2352. {
  2353. // TODO: runtime optimize: If the handle is again to a final class, then we can recursively check if the circular reference can occur
  2354. if( sdt.GetObjectType()->flags & (asOBJ_SCRIPT_OBJECT | asOBJ_GC) )
  2355. {
  2356. gc = true;
  2357. break;
  2358. }
  2359. }
  2360. else if( sdt.GetObjectType()->flags & asOBJ_GC )
  2361. {
  2362. // TODO: runtime optimize: Just because the member type is a potential circle doesn't mean that this one is.
  2363. // Only if the object is of a type that can reference this type, either directly or indirectly
  2364. gc = true;
  2365. break;
  2366. }
  2367. }
  2368. }
  2369. if( gc )
  2370. break;
  2371. }
  2372. else
  2373. {
  2374. // Assume it is garbage collected as it is not known at compile time what might inherit from this type
  2375. gc = true;
  2376. break;
  2377. }
  2378. }
  2379. else if( prop->flags & asOBJ_GC )
  2380. {
  2381. // If a type is not a script object, adopt its GC flag
  2382. gc = true;
  2383. break;
  2384. }
  2385. }
  2386. else if( dt.GetObjectType()->flags & asOBJ_GC )
  2387. {
  2388. // TODO: runtime optimize: Just because the member type is a potential circle doesn't mean that this one is.
  2389. // Only if the object is of a type that can reference this type, either directly or indirectly
  2390. gc = true;
  2391. break;
  2392. }
  2393. }
  2394. // Update the flag in the object type
  2395. if( gc )
  2396. ot->flags |= asOBJ_GC;
  2397. else
  2398. ot->flags &= ~asOBJ_GC;
  2399. }
  2400. */
  2401. }
  2402. void asCBuilder::IncludeMethodsFromMixins(sClassDeclaration *decl)
  2403. {
  2404. asCScriptNode *node = decl->node->firstChild;
  2405. // Skip the 'final' and 'shared' keywords
  2406. if( decl->objType->IsShared() )
  2407. node = node->next;
  2408. if( decl->objType->flags & asOBJ_NOINHERIT )
  2409. node = node->next;
  2410. // Skip the name of the class
  2411. node = node->next;
  2412. // Find the included mixin classes
  2413. while( node && node->nodeType == snIdentifier )
  2414. {
  2415. asSNameSpace *ns;
  2416. asCString name;
  2417. if( GetNamespaceAndNameFromNode(node, decl->script, decl->objType->nameSpace, ns, name) < 0 )
  2418. {
  2419. node = node->next;
  2420. continue;
  2421. }
  2422. sMixinClass *mixin = GetMixinClass(name.AddressOf(), ns);
  2423. if( mixin )
  2424. {
  2425. // Find methods from mixin declaration
  2426. asCScriptNode *n = mixin->node->firstChild;
  2427. // Skip to the member declarations
  2428. // Possible keywords 'final' and 'shared' are removed in RegisterMixinClass so we don't need to worry about those here
  2429. while( n && n->nodeType == snIdentifier )
  2430. n = n->next;
  2431. // Add methods from the mixin that are not already existing in the class
  2432. while( n )
  2433. {
  2434. if( n->nodeType == snFunction )
  2435. {
  2436. // Instead of disconnecting the node, we need to clone it, otherwise other
  2437. // classes that include the same mixin will not see the methods
  2438. asCScriptNode *copy = n->CreateCopy(engine);
  2439. // Register the method, but only if it doesn't already exist in the class
  2440. RegisterScriptFunctionFromNode(copy, mixin->script, decl->objType, false, false, 0, false, true);
  2441. }
  2442. else if( n->nodeType == snVirtualProperty )
  2443. {
  2444. // TODO: mixin: Support virtual properties too
  2445. WriteError("The virtual property syntax is currently not supported for mixin classes", mixin->script, n);
  2446. //RegisterVirtualProperty(node, decl->script, decl->objType, false, false);
  2447. }
  2448. n = n->next;
  2449. }
  2450. }
  2451. node = node->next;
  2452. }
  2453. }
  2454. void asCBuilder::IncludePropertiesFromMixins(sClassDeclaration *decl)
  2455. {
  2456. asCScriptNode *node = decl->node->firstChild;
  2457. // Skip the 'final' and 'shared' keywords
  2458. if( decl->objType->IsShared() )
  2459. node = node->next;
  2460. if( decl->objType->flags & asOBJ_NOINHERIT )
  2461. node = node->next;
  2462. // Skip the name of the class
  2463. node = node->next;
  2464. // Find the included mixin classes
  2465. while( node && node->nodeType == snIdentifier )
  2466. {
  2467. asSNameSpace *ns;
  2468. asCString name;
  2469. if( GetNamespaceAndNameFromNode(node, decl->script, decl->objType->nameSpace, ns, name) < 0 )
  2470. {
  2471. node = node->next;
  2472. continue;
  2473. }
  2474. sMixinClass *mixin = GetMixinClass(name.AddressOf(), ns);
  2475. if( mixin )
  2476. {
  2477. // Find properties from mixin declaration
  2478. asCScriptNode *n = mixin->node->firstChild;
  2479. // Skip to the member declarations
  2480. // Possible keywords 'final' and 'shared' are removed in RegisterMixinClass so we don't need to worry about those here
  2481. while( n && n->nodeType == snIdentifier )
  2482. n = n->next;
  2483. // Add properties from the mixin that are not already existing in the class
  2484. while( n )
  2485. {
  2486. if( n->nodeType == snDeclaration )
  2487. {
  2488. asCScriptNode *n2 = n->firstChild;
  2489. bool isPrivate = false;
  2490. if( n2 && n2->tokenType == ttPrivate )
  2491. {
  2492. isPrivate = true;
  2493. n2 = n2->next;
  2494. }
  2495. asCScriptCode *file = mixin->script;
  2496. asCDataType dt = CreateDataTypeFromNode(n2, file, mixin->ns);
  2497. if( decl->objType->IsShared() && dt.GetObjectType() && !dt.GetObjectType()->IsShared() )
  2498. {
  2499. asCString msg;
  2500. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, dt.GetObjectType()->name.AddressOf());
  2501. WriteError(msg, file, n);
  2502. WriteInfo(TXT_WHILE_INCLUDING_MIXIN, decl->script, node);
  2503. }
  2504. if( dt.IsReadOnly() )
  2505. WriteError(TXT_PROPERTY_CANT_BE_CONST, file, n);
  2506. n2 = n2->next;
  2507. while( n2 )
  2508. {
  2509. asCString name(&file->code[n2->tokenPos], n2->tokenLength);
  2510. // Add the property only if it doesn't already exist in the class
  2511. bool exists = false;
  2512. for( asUINT p = 0; p < decl->objType->properties.GetLength(); p++ )
  2513. if( decl->objType->properties[p]->name == name )
  2514. {
  2515. exists = true;
  2516. break;
  2517. }
  2518. if( !exists )
  2519. {
  2520. if( !decl->isExistingShared )
  2521. {
  2522. // It must not conflict with the name of methods
  2523. int r = CheckNameConflictMember(decl->objType, name.AddressOf(), n2, file, true);
  2524. if( r < 0 )
  2525. WriteInfo(TXT_WHILE_INCLUDING_MIXIN, decl->script, node);
  2526. AddPropertyToClass(decl, name, dt, isPrivate, file, n2);
  2527. }
  2528. else
  2529. {
  2530. // Verify that the property exists in the original declaration
  2531. bool found = false;
  2532. for( asUINT p = 0; p < decl->objType->properties.GetLength(); p++ )
  2533. {
  2534. asCObjectProperty *prop = decl->objType->properties[p];
  2535. if( prop->isPrivate == isPrivate &&
  2536. prop->name == name &&
  2537. prop->type == dt )
  2538. {
  2539. found = true;
  2540. break;
  2541. }
  2542. }
  2543. if( !found )
  2544. {
  2545. asCString str;
  2546. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, decl->objType->GetName());
  2547. WriteError(str, decl->script, decl->node);
  2548. WriteInfo(TXT_WHILE_INCLUDING_MIXIN, decl->script, node);
  2549. }
  2550. }
  2551. }
  2552. // Skip the initialization expression
  2553. if( n2->next && n2->next->nodeType != snIdentifier )
  2554. n2 = n2->next;
  2555. n2 = n2->next;
  2556. }
  2557. }
  2558. n = n->next;
  2559. }
  2560. }
  2561. node = node->next;
  2562. }
  2563. }
  2564. int asCBuilder::CreateVirtualFunction(asCScriptFunction *func, int idx)
  2565. {
  2566. asCScriptFunction *vf = asNEW(asCScriptFunction)(engine, module, asFUNC_VIRTUAL);
  2567. if( vf == 0 )
  2568. return asOUT_OF_MEMORY;
  2569. vf->name = func->name;
  2570. vf->returnType = func->returnType;
  2571. vf->parameterTypes = func->parameterTypes;
  2572. vf->inOutFlags = func->inOutFlags;
  2573. vf->id = engine->GetNextScriptFunctionId();
  2574. vf->scriptSectionIdx = func->scriptSectionIdx;
  2575. vf->isReadOnly = func->isReadOnly;
  2576. vf->objectType = func->objectType;
  2577. vf->signatureId = func->signatureId;
  2578. vf->isPrivate = func->isPrivate;
  2579. vf->isFinal = func->isFinal;
  2580. vf->isOverride = func->isOverride;
  2581. vf->vfTableIdx = idx;
  2582. vf->defaultArgs = func->defaultArgs;
  2583. // Copy the default arg strings to avoid multiple deletes on the same object
  2584. for( asUINT n = 0; n < vf->defaultArgs.GetLength(); n++ )
  2585. if( vf->defaultArgs[n] )
  2586. vf->defaultArgs[n] = asNEW(asCString)(*vf->defaultArgs[n]);
  2587. module->AddScriptFunction(vf);
  2588. // Add a dummy to the builder so that it doesn't mix up function ids
  2589. functions.PushLast(0);
  2590. return vf->id;
  2591. }
  2592. asCObjectProperty *asCBuilder::AddPropertyToClass(sClassDeclaration *decl, const asCString &name, const asCDataType &dt, bool isPrivate, asCScriptCode *file, asCScriptNode *node)
  2593. {
  2594. // If the declaration node is not given, then
  2595. // this property is inherited from a base class
  2596. if( node )
  2597. {
  2598. // Check if the property is allowed
  2599. if( !dt.CanBeInstanciated() )
  2600. {
  2601. if( file && node )
  2602. {
  2603. asCString str;
  2604. str.Format(TXT_DATA_TYPE_CANT_BE_s, dt.Format().AddressOf());
  2605. WriteError(str, file, node);
  2606. }
  2607. return 0;
  2608. }
  2609. // Register the initialization expression (if any) to be compiled later
  2610. asCScriptNode *declNode = node;
  2611. asCScriptNode *initNode = 0;
  2612. if( node->next && node->next->nodeType != snIdentifier )
  2613. {
  2614. asASSERT( node->next->nodeType == snAssignment );
  2615. initNode = node->next;
  2616. }
  2617. sPropertyInitializer p(name, declNode, initNode, file);
  2618. decl->propInits.PushLast(p);
  2619. }
  2620. // Add the property to the object type
  2621. return decl->objType->AddPropertyToClass(name, dt, isPrivate);
  2622. }
  2623. bool asCBuilder::DoesMethodExist(asCObjectType *objType, int methodId, asUINT *methodIndex)
  2624. {
  2625. asCScriptFunction *method = GetFunctionDescription(methodId);
  2626. for( asUINT n = 0; n < objType->methods.GetLength(); n++ )
  2627. {
  2628. asCScriptFunction *m = GetFunctionDescription(objType->methods[n]);
  2629. if( m->name != method->name ) continue;
  2630. if( m->returnType != method->returnType ) continue;
  2631. if( m->isReadOnly != method->isReadOnly ) continue;
  2632. if( m->parameterTypes != method->parameterTypes ) continue;
  2633. if( m->inOutFlags != method->inOutFlags ) continue;
  2634. if( methodIndex )
  2635. *methodIndex = n;
  2636. return true;
  2637. }
  2638. return false;
  2639. }
  2640. void asCBuilder::AddDefaultConstructor(asCObjectType *objType, asCScriptCode *file)
  2641. {
  2642. int funcId = engine->GetNextScriptFunctionId();
  2643. asCDataType returnType = asCDataType::CreatePrimitive(ttVoid, false);
  2644. asCArray<asCDataType> parameterTypes;
  2645. asCArray<asETypeModifiers> inOutFlags;
  2646. asCArray<asCString *> defaultArgs;
  2647. // Add the script function
  2648. module->AddScriptFunction(file->idx, funcId, objType->name, returnType, parameterTypes, inOutFlags, defaultArgs, false, objType);
  2649. // Set it as default constructor
  2650. if( objType->beh.construct )
  2651. engine->scriptFunctions[objType->beh.construct]->Release();
  2652. objType->beh.construct = funcId;
  2653. objType->beh.constructors[0] = funcId;
  2654. engine->scriptFunctions[funcId]->AddRef();
  2655. // The bytecode for the default constructor will be generated
  2656. // only after the potential inheritance has been established
  2657. sFunctionDescription *func = asNEW(sFunctionDescription);
  2658. if( func == 0 )
  2659. {
  2660. // Out of memory
  2661. return;
  2662. }
  2663. functions.PushLast(func);
  2664. func->script = file;
  2665. func->node = 0;
  2666. func->name = objType->name;
  2667. func->objType = objType;
  2668. func->funcId = funcId;
  2669. func->isExistingShared = false;
  2670. // Add a default factory as well
  2671. funcId = engine->GetNextScriptFunctionId();
  2672. if( objType->beh.factory )
  2673. engine->scriptFunctions[objType->beh.factory]->Release();
  2674. objType->beh.factory = funcId;
  2675. objType->beh.factories[0] = funcId;
  2676. returnType = asCDataType::CreateObjectHandle(objType, false);
  2677. module->AddScriptFunction(file->idx, funcId, objType->name, returnType, parameterTypes, inOutFlags, defaultArgs, false);
  2678. functions.PushLast(0);
  2679. asCCompiler compiler(engine);
  2680. compiler.CompileFactory(this, file, engine->scriptFunctions[funcId]);
  2681. engine->scriptFunctions[funcId]->AddRef();
  2682. // If the object is shared, then the factory must also be marked as shared
  2683. if( objType->flags & asOBJ_SHARED )
  2684. engine->scriptFunctions[funcId]->isShared = true;
  2685. }
  2686. int asCBuilder::RegisterEnum(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns)
  2687. {
  2688. // Is it a shared enum?
  2689. bool isShared = false;
  2690. asCObjectType *existingSharedType = 0;
  2691. asCScriptNode *tmp = node->firstChild;
  2692. if( tmp->nodeType == snIdentifier && file->TokenEquals(tmp->tokenPos, tmp->tokenLength, SHARED_TOKEN) )
  2693. {
  2694. isShared = true;
  2695. tmp = tmp->next;
  2696. }
  2697. // Grab the name of the enumeration
  2698. asCString name;
  2699. asASSERT(snDataType == tmp->nodeType);
  2700. asASSERT(snIdentifier == tmp->firstChild->nodeType);
  2701. name.Assign(&file->code[tmp->firstChild->tokenPos], tmp->firstChild->tokenLength);
  2702. if( isShared )
  2703. {
  2704. // Look for a pre-existing shared enum with the same signature
  2705. for( asUINT n = 0; n < engine->classTypes.GetLength(); n++ )
  2706. {
  2707. asCObjectType *o = engine->classTypes[n];
  2708. if( o &&
  2709. o->IsShared() &&
  2710. (o->flags & asOBJ_ENUM) &&
  2711. o->name == name &&
  2712. o->nameSpace == ns )
  2713. {
  2714. existingSharedType = o;
  2715. break;
  2716. }
  2717. }
  2718. }
  2719. // Check the name and add the enum
  2720. int r = CheckNameConflict(name.AddressOf(), tmp->firstChild, file, ns);
  2721. if( asSUCCESS == r )
  2722. {
  2723. asCObjectType *st;
  2724. if( existingSharedType )
  2725. st = existingSharedType;
  2726. else
  2727. {
  2728. st = asNEW(asCObjectType)(engine);
  2729. if( st == 0 )
  2730. return asOUT_OF_MEMORY;
  2731. st->flags = asOBJ_ENUM;
  2732. if( isShared )
  2733. st->flags |= asOBJ_SHARED;
  2734. st->size = 4;
  2735. st->name = name;
  2736. st->nameSpace = ns;
  2737. }
  2738. module->enumTypes.PushLast(st);
  2739. st->AddRef();
  2740. // TODO: cleanup: Should the enum type really be stored in the engine->classTypes?
  2741. // http://www.gamedev.net/topic/616912-c-header-file-shared-with-scripts/page__gopid__4895940
  2742. if( !existingSharedType )
  2743. engine->classTypes.PushLast(st);
  2744. // Store the location of this declaration for reference in name collisions
  2745. sClassDeclaration *decl = asNEW(sClassDeclaration);
  2746. if( decl == 0 )
  2747. return asOUT_OF_MEMORY;
  2748. decl->name = name;
  2749. decl->script = file;
  2750. decl->objType = st;
  2751. namedTypeDeclarations.PushLast(decl);
  2752. asCDataType type = CreateDataTypeFromNode(tmp, file, ns);
  2753. asASSERT(!type.IsReference());
  2754. // Register the enum values
  2755. tmp = tmp->next;
  2756. while( tmp )
  2757. {
  2758. asASSERT(snIdentifier == tmp->nodeType);
  2759. asCString name(&file->code[tmp->tokenPos], tmp->tokenLength);
  2760. if( existingSharedType )
  2761. {
  2762. // If this is a pre-existent shared enum, then just double check
  2763. // that the value is already defined in the original declaration
  2764. bool found = false;
  2765. for( size_t n = 0; n < st->enumValues.GetLength(); n++ )
  2766. if( st->enumValues[n]->name == name )
  2767. {
  2768. found = true;
  2769. break;
  2770. }
  2771. if( !found )
  2772. {
  2773. asCString str;
  2774. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, st->GetName());
  2775. WriteError(str, file, tmp);
  2776. break;
  2777. }
  2778. tmp = tmp->next;
  2779. if( tmp && tmp->nodeType == snAssignment )
  2780. tmp = tmp->next;
  2781. continue;
  2782. }
  2783. else
  2784. {
  2785. // Check for name conflict errors with other values in the enum
  2786. if( globVariables.GetFirst(ns, name, asCCompGlobVarType(type)) )
  2787. {
  2788. asCString str;
  2789. str.Format(TXT_NAME_CONFLICT_s_ALREADY_USED, name.AddressOf());
  2790. WriteError(str, file, tmp);
  2791. tmp = tmp->next;
  2792. if( tmp && tmp->nodeType == snAssignment )
  2793. tmp = tmp->next;
  2794. continue;
  2795. }
  2796. // Check for assignment
  2797. asCScriptNode *asnNode = tmp->next;
  2798. if( asnNode && snAssignment == asnNode->nodeType )
  2799. asnNode->DisconnectParent();
  2800. else
  2801. asnNode = 0;
  2802. // Create the global variable description so the enum value can be evaluated
  2803. sGlobalVariableDescription *gvar = asNEW(sGlobalVariableDescription);
  2804. if( gvar == 0 )
  2805. return asOUT_OF_MEMORY;
  2806. gvar->script = file;
  2807. gvar->idNode = 0;
  2808. gvar->nextNode = asnNode;
  2809. gvar->name = name;
  2810. gvar->datatype = type;
  2811. // No need to allocate space on the global memory stack since the values are stored in the asCObjectType
  2812. // Set the index to a negative to allow compiler to diferentiate from ordinary global var when compiling the initialization
  2813. gvar->index = -1;
  2814. gvar->isCompiled = false;
  2815. gvar->isPureConstant = true;
  2816. gvar->isEnumValue = true;
  2817. gvar->constantValue = 0xdeadbeef;
  2818. // Allocate dummy property so we can compile the value.
  2819. // This will be removed later on so we don't add it to the engine.
  2820. gvar->property = asNEW(asCGlobalProperty);
  2821. if( gvar->property == 0 )
  2822. return asOUT_OF_MEMORY;
  2823. gvar->property->name = name;
  2824. gvar->property->nameSpace = ns;
  2825. gvar->property->type = gvar->datatype;
  2826. gvar->property->id = 0;
  2827. globVariables.Put(gvar);
  2828. tmp = tmp->next;
  2829. }
  2830. }
  2831. }
  2832. node->Destroy(engine);
  2833. return r;
  2834. }
  2835. int asCBuilder::RegisterTypedef(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns)
  2836. {
  2837. // Get the native data type
  2838. asCScriptNode *tmp = node->firstChild;
  2839. asASSERT(NULL != tmp && snDataType == tmp->nodeType);
  2840. asCDataType dataType;
  2841. dataType.CreatePrimitive(tmp->tokenType, false);
  2842. dataType.SetTokenType(tmp->tokenType);
  2843. tmp = tmp->next;
  2844. // Grab the name of the typedef
  2845. asASSERT(NULL != tmp && NULL == tmp->next);
  2846. asCString name;
  2847. name.Assign(&file->code[tmp->tokenPos], tmp->tokenLength);
  2848. // If the name is not already in use add it
  2849. int r = CheckNameConflict(name.AddressOf(), tmp, file, ns);
  2850. asCObjectType *st = 0;
  2851. if( asSUCCESS == r )
  2852. {
  2853. // Create the new type
  2854. st = asNEW(asCObjectType)(engine);
  2855. if( st == 0 )
  2856. r = asOUT_OF_MEMORY;
  2857. }
  2858. if( asSUCCESS == r )
  2859. {
  2860. st->flags = asOBJ_TYPEDEF;
  2861. st->size = dataType.GetSizeInMemoryBytes();
  2862. st->name = name;
  2863. st->nameSpace = ns;
  2864. st->templateSubTypes.PushLast(dataType);
  2865. st->AddRef();
  2866. module->typeDefs.PushLast(st);
  2867. engine->classTypes.PushLast(st);
  2868. // Store the location of this declaration for reference in name collisions
  2869. sClassDeclaration *decl = asNEW(sClassDeclaration);
  2870. if( decl == 0 )
  2871. r = asOUT_OF_MEMORY;
  2872. else
  2873. {
  2874. decl->name = name;
  2875. decl->script = file;
  2876. decl->objType = st;
  2877. namedTypeDeclarations.PushLast(decl);
  2878. }
  2879. }
  2880. node->Destroy(engine);
  2881. return r;
  2882. }
  2883. void asCBuilder::GetParsedFunctionDetails(asCScriptNode *node, asCScriptCode *file, asCObjectType *objType, asCString &name, asCDataType &returnType, asCArray<asCString> &parameterNames, asCArray<asCDataType> &parameterTypes, asCArray<asETypeModifiers> &inOutFlags, asCArray<asCString *> &defaultArgs, bool &isConstMethod, bool &isConstructor, bool &isDestructor, bool &isPrivate, bool &isOverride, bool &isFinal, bool &isShared, asSNameSpace *implicitNamespace)
  2884. {
  2885. node = node->firstChild;
  2886. // Is the function a private class method?
  2887. isPrivate = false;
  2888. if( node->tokenType == ttPrivate )
  2889. {
  2890. isPrivate = true;
  2891. node = node->next;
  2892. }
  2893. // Is the function shared?
  2894. isShared = false;
  2895. if( node->tokenType == ttIdentifier && file->TokenEquals(node->tokenPos, node->tokenLength, SHARED_TOKEN) )
  2896. {
  2897. isShared = true;
  2898. node = node->next;
  2899. }
  2900. // Find the name
  2901. isConstructor = false;
  2902. isDestructor = false;
  2903. asCScriptNode *n = 0;
  2904. if( node->nodeType == snDataType )
  2905. n = node->next->next;
  2906. else
  2907. {
  2908. // If the first node is a ~ token, then we know it is a destructor
  2909. if( node->tokenType == ttBitNot )
  2910. {
  2911. n = node->next;
  2912. isDestructor = true;
  2913. }
  2914. else
  2915. {
  2916. n = node;
  2917. isConstructor = true;
  2918. }
  2919. }
  2920. name.Assign(&file->code[n->tokenPos], n->tokenLength);
  2921. // Initialize a script function object for registration
  2922. if( !isConstructor && !isDestructor )
  2923. {
  2924. returnType = CreateDataTypeFromNode(node, file, implicitNamespace);
  2925. returnType = ModifyDataTypeFromNode(returnType, node->next, file, 0, 0);
  2926. if( engine->ep.disallowValueAssignForRefType &&
  2927. returnType.GetObjectType() &&
  2928. (returnType.GetObjectType()->flags & asOBJ_REF) &&
  2929. !(returnType.GetObjectType()->flags & asOBJ_SCOPED) &&
  2930. !returnType.IsReference() &&
  2931. !returnType.IsObjectHandle() )
  2932. {
  2933. WriteError(TXT_REF_TYPE_CANT_BE_RETURNED_BY_VAL, file, node);
  2934. }
  2935. }
  2936. else
  2937. returnType = asCDataType::CreatePrimitive(ttVoid, false);
  2938. isConstMethod = false;
  2939. isFinal = false;
  2940. isOverride = false;
  2941. if( objType && n->next->next )
  2942. {
  2943. asCScriptNode *decorator = n->next->next;
  2944. // Is this a const method?
  2945. if( decorator->tokenType == ttConst )
  2946. {
  2947. isConstMethod = true;
  2948. decorator = decorator->next;
  2949. }
  2950. while( decorator )
  2951. {
  2952. if( decorator->tokenType == ttIdentifier && file->TokenEquals(decorator->tokenPos, decorator->tokenLength, FINAL_TOKEN) )
  2953. isFinal = true;
  2954. else if( decorator->tokenType == ttIdentifier && file->TokenEquals(decorator->tokenPos, decorator->tokenLength, OVERRIDE_TOKEN) )
  2955. isOverride = true;
  2956. decorator = decorator->next;
  2957. }
  2958. }
  2959. // Count the number of parameters
  2960. int count = 0;
  2961. asCScriptNode *c = n->next->firstChild;
  2962. while( c )
  2963. {
  2964. count++;
  2965. c = c->next->next;
  2966. if( c && c->nodeType == snIdentifier )
  2967. c = c->next;
  2968. if( c && c->nodeType == snExpression )
  2969. c = c->next;
  2970. }
  2971. // Get the parameter types
  2972. parameterNames.Allocate(count, false);
  2973. parameterTypes.Allocate(count, false);
  2974. inOutFlags.Allocate(count, false);
  2975. defaultArgs.Allocate(count, false);
  2976. n = n->next->firstChild;
  2977. while( n )
  2978. {
  2979. asETypeModifiers inOutFlag;
  2980. asCDataType type = CreateDataTypeFromNode(n, file, implicitNamespace);
  2981. type = ModifyDataTypeFromNode(type, n->next, file, &inOutFlag, 0);
  2982. if( engine->ep.disallowValueAssignForRefType &&
  2983. type.GetObjectType() &&
  2984. (type.GetObjectType()->flags & asOBJ_REF) &&
  2985. !(type.GetObjectType()->flags & asOBJ_SCOPED) &&
  2986. !type.IsReference() &&
  2987. !type.IsObjectHandle() )
  2988. {
  2989. WriteError(TXT_REF_TYPE_CANT_BE_PASSED_BY_VAL, file, node);
  2990. }
  2991. // Store the parameter type
  2992. parameterTypes.PushLast(type);
  2993. inOutFlags.PushLast(inOutFlag);
  2994. // Move to next parameter
  2995. n = n->next->next;
  2996. if( n && n->nodeType == snIdentifier )
  2997. {
  2998. asCString name;
  2999. name.Assign(&file->code[n->tokenPos], n->tokenLength);
  3000. parameterNames.PushLast(name);
  3001. n = n->next;
  3002. }
  3003. else
  3004. {
  3005. // No name was given for the parameter
  3006. parameterNames.PushLast(asCString());
  3007. }
  3008. if( n && n->nodeType == snExpression )
  3009. {
  3010. // Strip out white space and comments to better share the string
  3011. asCString *defaultArgStr = asNEW(asCString);
  3012. if( defaultArgStr )
  3013. *defaultArgStr = GetCleanExpressionString(n, file);
  3014. defaultArgs.PushLast(defaultArgStr);
  3015. n = n->next;
  3016. }
  3017. else
  3018. defaultArgs.PushLast(0);
  3019. }
  3020. }
  3021. #endif
  3022. asCString asCBuilder::GetCleanExpressionString(asCScriptNode *node, asCScriptCode *file)
  3023. {
  3024. asASSERT(node && node->nodeType == snExpression);
  3025. asCString str;
  3026. str.Assign(file->code + node->tokenPos, node->tokenLength);
  3027. asCString cleanStr;
  3028. for( asUINT n = 0; n < str.GetLength(); )
  3029. {
  3030. int len;
  3031. asETokenClass tok = engine->ParseToken(str.AddressOf() + n, str.GetLength() - n, &len);
  3032. if( tok != asTC_COMMENT && tok != asTC_WHITESPACE )
  3033. {
  3034. if( cleanStr.GetLength() ) cleanStr += " ";
  3035. cleanStr.Concatenate(str.AddressOf() + n, len);
  3036. }
  3037. n += len;
  3038. }
  3039. return cleanStr;
  3040. }
  3041. #ifndef AS_NO_COMPILER
  3042. int asCBuilder::RegisterScriptFunctionFromNode(asCScriptNode *node, asCScriptCode *file, asCObjectType *objType, bool isInterface, bool isGlobalFunction, asSNameSpace *ns, bool isExistingShared, bool isMixin)
  3043. {
  3044. asCString name;
  3045. asCDataType returnType;
  3046. asCArray<asCString> parameterNames;
  3047. asCArray<asCDataType> parameterTypes;
  3048. asCArray<asETypeModifiers> inOutFlags;
  3049. asCArray<asCString *> defaultArgs;
  3050. bool isConstMethod;
  3051. bool isOverride;
  3052. bool isFinal;
  3053. bool isConstructor;
  3054. bool isDestructor;
  3055. bool isPrivate;
  3056. bool isShared;
  3057. asASSERT( (objType && ns == 0) || isGlobalFunction );
  3058. // Set the default namespace
  3059. if( ns == 0 )
  3060. {
  3061. if( objType )
  3062. ns = objType->nameSpace;
  3063. else
  3064. ns = engine->nameSpaces[0];
  3065. }
  3066. GetParsedFunctionDetails(node, file, objType, name, returnType, parameterNames, parameterTypes, inOutFlags, defaultArgs, isConstMethod, isConstructor, isDestructor, isPrivate, isOverride, isFinal, isShared, ns);
  3067. return RegisterScriptFunction(node, file, objType, isInterface, isGlobalFunction, ns, isExistingShared, isMixin, name, returnType, parameterNames, parameterTypes, inOutFlags, defaultArgs, isConstMethod, isConstructor, isDestructor, isPrivate, isOverride, isFinal, isShared);
  3068. }
  3069. int asCBuilder::RegisterScriptFunction(asCScriptNode *node, asCScriptCode *file, asCObjectType *objType, bool isInterface, bool isGlobalFunction, asSNameSpace *ns, bool isExistingShared, bool isMixin, asCString &name, asCDataType &returnType, asCArray<asCString> &parameterNames, asCArray<asCDataType> &parameterTypes, asCArray<asETypeModifiers> &inOutFlags, asCArray<asCString *> &defaultArgs, bool isConstMethod, bool isConstructor, bool isDestructor, bool isPrivate, bool isOverride, bool isFinal, bool isShared)
  3070. {
  3071. // Determine default namespace if not specified
  3072. if( ns == 0 )
  3073. {
  3074. if( objType )
  3075. ns = objType->nameSpace;
  3076. else
  3077. ns = engine->nameSpaces[0];
  3078. }
  3079. if( isExistingShared )
  3080. {
  3081. asASSERT( objType );
  3082. // Should validate that the function really exists in the class/interface
  3083. bool found = false;
  3084. if( isConstructor || isDestructor )
  3085. {
  3086. // TODO: shared: Should check the existance of these too
  3087. found = true;
  3088. }
  3089. else
  3090. {
  3091. for( asUINT n = 0; n < objType->methods.GetLength(); n++ )
  3092. {
  3093. asCScriptFunction *func = engine->scriptFunctions[objType->methods[n]];
  3094. if( func->name == name &&
  3095. func->IsSignatureExceptNameEqual(returnType, parameterTypes, inOutFlags, objType, isConstMethod) )
  3096. {
  3097. found = true;
  3098. break;
  3099. }
  3100. }
  3101. }
  3102. if( !found )
  3103. {
  3104. asCString str;
  3105. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, objType->GetName());
  3106. WriteError(str, file, node);
  3107. }
  3108. node->Destroy(engine);
  3109. return 0;
  3110. }
  3111. // Check for name conflicts
  3112. if( !isConstructor && !isDestructor )
  3113. {
  3114. if( objType )
  3115. {
  3116. CheckNameConflictMember(objType, name.AddressOf(), node, file, false);
  3117. if( name == objType->name )
  3118. WriteError(TXT_METHOD_CANT_HAVE_NAME_OF_CLASS, file, node);
  3119. }
  3120. else
  3121. CheckNameConflict(name.AddressOf(), node, file, ns);
  3122. }
  3123. else
  3124. {
  3125. if( isMixin )
  3126. {
  3127. // Mixins cannot implement constructors/destructors
  3128. WriteError(TXT_MIXIN_CANNOT_HAVE_CONSTRUCTOR, file, node);
  3129. node->Destroy(engine);
  3130. return 0;
  3131. }
  3132. // Verify that the name of the constructor/destructor is the same as the class
  3133. if( name != objType->name )
  3134. WriteError(TXT_CONSTRUCTOR_NAME_ERROR, file, node);
  3135. if( isDestructor )
  3136. name = "~" + name;
  3137. }
  3138. isExistingShared = false;
  3139. int funcId = engine->GetNextScriptFunctionId();
  3140. if( !isInterface )
  3141. {
  3142. sFunctionDescription *func = asNEW(sFunctionDescription);
  3143. if( func == 0 )
  3144. return asOUT_OF_MEMORY;
  3145. functions.PushLast(func);
  3146. func->script = file;
  3147. func->node = node;
  3148. func->name = name;
  3149. func->objType = objType;
  3150. func->funcId = funcId;
  3151. func->isExistingShared = false;
  3152. func->paramNames = parameterNames;
  3153. if( isShared )
  3154. {
  3155. // Look for a pre-existing shared function with the same signature
  3156. for( asUINT n = 0; n < engine->scriptFunctions.GetLength(); n++ )
  3157. {
  3158. asCScriptFunction *f = engine->scriptFunctions[n];
  3159. if( f &&
  3160. f->isShared &&
  3161. f->name == name &&
  3162. f->nameSpace == ns &&
  3163. f->objectType == objType &&
  3164. f->IsSignatureExceptNameEqual(returnType, parameterTypes, inOutFlags, 0, false) )
  3165. {
  3166. funcId = func->funcId = f->id;
  3167. isExistingShared = func->isExistingShared = true;
  3168. break;
  3169. }
  3170. }
  3171. }
  3172. }
  3173. // Destructors may not have any parameters
  3174. if( isDestructor && parameterTypes.GetLength() > 0 )
  3175. WriteError(TXT_DESTRUCTOR_MAY_NOT_HAVE_PARM, file, node);
  3176. // If a function, class, or interface is shared then only shared types may be used in the signature
  3177. if( (objType && objType->IsShared()) || isShared )
  3178. {
  3179. asCObjectType *ot = returnType.GetObjectType();
  3180. if( ot && !ot->IsShared() )
  3181. {
  3182. asCString msg;
  3183. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, ot->name.AddressOf());
  3184. WriteError(msg, file, node);
  3185. }
  3186. for( asUINT p = 0; p < parameterTypes.GetLength(); ++p )
  3187. {
  3188. asCObjectType *ot = parameterTypes[p].GetObjectType();
  3189. if( ot && !ot->IsShared() )
  3190. {
  3191. asCString msg;
  3192. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, ot->name.AddressOf());
  3193. WriteError(msg, file, node);
  3194. }
  3195. }
  3196. }
  3197. // Check that the same function hasn't been registered already in the namespace
  3198. asCArray<int> funcs;
  3199. if( objType )
  3200. GetObjectMethodDescriptions(name.AddressOf(), objType, funcs, false);
  3201. else
  3202. GetFunctionDescriptions(name.AddressOf(), funcs, ns);
  3203. for( asUINT n = 0; n < funcs.GetLength(); ++n )
  3204. {
  3205. asCScriptFunction *func = GetFunctionDescription(funcs[n]);
  3206. if( func->IsSignatureExceptNameAndReturnTypeEqual(parameterTypes, inOutFlags, objType, isConstMethod) )
  3207. {
  3208. if( isMixin )
  3209. {
  3210. // Clean up the memory, as the function will not be registered
  3211. if( node )
  3212. node->Destroy(engine);
  3213. sFunctionDescription *func = functions.PopLast();
  3214. asDELETE(func, sFunctionDescription);
  3215. return 0;
  3216. }
  3217. WriteError(TXT_FUNCTION_ALREADY_EXIST, file, node);
  3218. break;
  3219. }
  3220. }
  3221. // Register the function
  3222. if( isExistingShared )
  3223. {
  3224. asCScriptFunction *f = engine->scriptFunctions[funcId];
  3225. module->AddScriptFunction(f);
  3226. // TODO: clean up: This should be done by AddScriptFunction() itself
  3227. module->globalFunctions.Put(f);
  3228. f->AddRef();
  3229. }
  3230. else
  3231. module->AddScriptFunction(file->idx, funcId, name, returnType, parameterTypes, inOutFlags, defaultArgs, isInterface, objType, isConstMethod, isGlobalFunction, isPrivate, isFinal, isOverride, isShared, ns);
  3232. // Make sure the default args are declared correctly
  3233. ValidateDefaultArgs(file, node, engine->scriptFunctions[funcId]);
  3234. if( objType )
  3235. {
  3236. asASSERT( !isExistingShared );
  3237. engine->scriptFunctions[funcId]->AddRef();
  3238. if( isConstructor )
  3239. {
  3240. int factoryId = engine->GetNextScriptFunctionId();
  3241. if( parameterTypes.GetLength() == 0 )
  3242. {
  3243. // Overload the default constructor
  3244. engine->scriptFunctions[objType->beh.construct]->Release();
  3245. objType->beh.construct = funcId;
  3246. objType->beh.constructors[0] = funcId;
  3247. // Register the default factory as well
  3248. engine->scriptFunctions[objType->beh.factory]->Release();
  3249. objType->beh.factory = factoryId;
  3250. objType->beh.factories[0] = factoryId;
  3251. }
  3252. else
  3253. {
  3254. objType->beh.constructors.PushLast(funcId);
  3255. // Register the factory as well
  3256. objType->beh.factories.PushLast(factoryId);
  3257. }
  3258. // We must copy the default arg strings to avoid deleting the same object multiple times
  3259. for( asUINT n = 0; n < defaultArgs.GetLength(); n++ )
  3260. if( defaultArgs[n] )
  3261. defaultArgs[n] = asNEW(asCString)(*defaultArgs[n]);
  3262. asCDataType dt = asCDataType::CreateObjectHandle(objType, false);
  3263. module->AddScriptFunction(file->idx, factoryId, name, dt, parameterTypes, inOutFlags, defaultArgs, false);
  3264. // If the object is shared, then the factory must also be marked as shared
  3265. if( objType->flags & asOBJ_SHARED )
  3266. engine->scriptFunctions[factoryId]->isShared = true;
  3267. // Add a dummy function to the builder so that it doesn't mix up the fund Ids
  3268. functions.PushLast(0);
  3269. // Compile the factory immediately
  3270. asCCompiler compiler(engine);
  3271. compiler.CompileFactory(this, file, engine->scriptFunctions[factoryId]);
  3272. engine->scriptFunctions[factoryId]->AddRef();
  3273. }
  3274. else if( isDestructor )
  3275. objType->beh.destruct = funcId;
  3276. else
  3277. {
  3278. // If the method is the assignment operator we need to replace the default implementation
  3279. asCScriptFunction *f = engine->scriptFunctions[funcId];
  3280. if( f->name == "opAssign" && f->parameterTypes.GetLength() == 1 &&
  3281. f->parameterTypes[0].GetObjectType() == f->objectType &&
  3282. (f->inOutFlags[0] & asTM_INREF) )
  3283. {
  3284. engine->scriptFunctions[objType->beh.copy]->Release();
  3285. objType->beh.copy = funcId;
  3286. f->AddRef();
  3287. }
  3288. objType->methods.PushLast(funcId);
  3289. }
  3290. }
  3291. // We need to delete the node already if this is an interface method
  3292. if( isInterface && node )
  3293. node->Destroy(engine);
  3294. return 0;
  3295. }
  3296. int asCBuilder::RegisterVirtualProperty(asCScriptNode *node, asCScriptCode *file, asCObjectType *objType, bool isInterface, bool isGlobalFunction, asSNameSpace *ns, bool isExistingShared)
  3297. {
  3298. if( engine->ep.propertyAccessorMode != 2 )
  3299. {
  3300. WriteError(TXT_PROPERTY_ACCESSOR_DISABLED, file, node);
  3301. node->Destroy(engine);
  3302. return 0;
  3303. }
  3304. asASSERT( (objType && ns == 0) || isGlobalFunction );
  3305. if( ns == 0 )
  3306. {
  3307. if( objType )
  3308. ns = objType->nameSpace;
  3309. else
  3310. ns = engine->nameSpaces[0];
  3311. }
  3312. bool isPrivate = false;
  3313. asCString emulatedName;
  3314. asCDataType emulatedType;
  3315. asCScriptNode *mainNode = node;
  3316. node = node->firstChild;
  3317. if( !isGlobalFunction && node->tokenType == ttPrivate )
  3318. {
  3319. isPrivate = true;
  3320. node = node->next;
  3321. }
  3322. emulatedType = CreateDataTypeFromNode(node, file, ns);
  3323. emulatedType = ModifyDataTypeFromNode(emulatedType, node->next, file, 0, 0);
  3324. node = node->next->next;
  3325. emulatedName.Assign(&file->code[node->tokenPos], node->tokenLength);
  3326. if( node->next == 0 )
  3327. WriteError(TXT_PROPERTY_WITHOUT_ACCESSOR, file, node);
  3328. node = node->next;
  3329. while( node )
  3330. {
  3331. asCScriptNode *next = node->next;
  3332. asCScriptNode *funcNode = 0;
  3333. bool success = false;
  3334. bool isConst = false;
  3335. bool isFinal = false;
  3336. bool isOverride = false;
  3337. asCDataType returnType;
  3338. asCArray<asCString> paramNames;
  3339. asCArray<asCDataType> paramTypes;
  3340. asCArray<asETypeModifiers> paramModifiers;
  3341. asCArray<asCString*> defaultArgs;
  3342. asCString name;
  3343. // TODO: getset: Allow private for individual property accessors
  3344. // TODO: getset: If the accessor uses its own name, then the property should be automatically declared
  3345. if( node->firstChild->nodeType == snIdentifier && file->TokenEquals(node->firstChild->tokenPos, node->firstChild->tokenLength, GET_TOKEN) )
  3346. {
  3347. funcNode = node->firstChild->next;
  3348. if( funcNode && funcNode->tokenType == ttConst )
  3349. {
  3350. isConst = true;
  3351. funcNode = funcNode->next;
  3352. }
  3353. while( funcNode && funcNode->nodeType != snStatementBlock )
  3354. {
  3355. if( funcNode->tokenType == ttIdentifier && file->TokenEquals(funcNode->tokenPos, funcNode->tokenLength, FINAL_TOKEN) )
  3356. isFinal = true;
  3357. else if( funcNode->tokenType == ttIdentifier && file->TokenEquals(funcNode->tokenPos, funcNode->tokenLength, OVERRIDE_TOKEN) )
  3358. isOverride = true;
  3359. funcNode = funcNode->next;
  3360. }
  3361. if( funcNode )
  3362. funcNode->DisconnectParent();
  3363. if( funcNode == 0 && (objType == 0 || !objType->IsInterface()) )
  3364. {
  3365. // TODO: getset: If no implementation is supplied the builder should provide an automatically generated implementation
  3366. // The compiler needs to be able to handle the different types, primitive, value type, and handle
  3367. // The code is also different for global property accessors
  3368. WriteError(TXT_PROPERTY_ACCESSOR_MUST_BE_IMPLEMENTED, file, node);
  3369. }
  3370. // Setup the signature for the get accessor method
  3371. returnType = emulatedType;
  3372. name = "get_" + emulatedName;
  3373. success = true;
  3374. }
  3375. else if( node->firstChild->nodeType == snIdentifier && file->TokenEquals(node->firstChild->tokenPos, node->firstChild->tokenLength, SET_TOKEN) )
  3376. {
  3377. funcNode = node->firstChild->next;
  3378. if( funcNode && funcNode->tokenType == ttConst )
  3379. {
  3380. isConst = true;
  3381. funcNode = funcNode->next;
  3382. }
  3383. while( funcNode && funcNode->nodeType != snStatementBlock )
  3384. {
  3385. if( funcNode->tokenType == ttIdentifier && file->TokenEquals(funcNode->tokenPos, funcNode->tokenLength, FINAL_TOKEN) )
  3386. isFinal = true;
  3387. else if( funcNode->tokenType == ttIdentifier && file->TokenEquals(funcNode->tokenPos, funcNode->tokenLength, OVERRIDE_TOKEN) )
  3388. isOverride = true;
  3389. funcNode = funcNode->next;
  3390. }
  3391. if( funcNode )
  3392. funcNode->DisconnectParent();
  3393. if( funcNode == 0 && (objType == 0 || !objType->IsInterface()) )
  3394. WriteError(TXT_PROPERTY_ACCESSOR_MUST_BE_IMPLEMENTED, file, node);
  3395. // Setup the signature for the set accessor method
  3396. returnType = asCDataType::CreatePrimitive(ttVoid, false);
  3397. paramModifiers.PushLast(asTM_NONE);
  3398. paramNames.PushLast("value");
  3399. paramTypes.PushLast(emulatedType);
  3400. defaultArgs.PushLast(0);
  3401. name = "set_" + emulatedName;
  3402. success = true;
  3403. }
  3404. else
  3405. WriteError(TXT_UNRECOGNIZED_VIRTUAL_PROPERTY_NODE, file, node);
  3406. if( success )
  3407. {
  3408. if( !isExistingShared )
  3409. RegisterScriptFunction(funcNode, file, objType, isInterface, isGlobalFunction, ns, false, false, name, returnType, paramNames, paramTypes, paramModifiers, defaultArgs, isConst, false, false, isPrivate, isOverride, isFinal, false);
  3410. else
  3411. {
  3412. // Free the funcNode as it won't be used
  3413. if( funcNode ) funcNode->Destroy(engine);
  3414. // Should validate that the function really exists in the class/interface
  3415. bool found = false;
  3416. for( asUINT n = 0; n < objType->methods.GetLength(); n++ )
  3417. {
  3418. asCScriptFunction *func = engine->scriptFunctions[objType->methods[n]];
  3419. if( func->name == name &&
  3420. func->IsSignatureExceptNameEqual(returnType, paramTypes, paramModifiers, objType, isConst) )
  3421. {
  3422. found = true;
  3423. break;
  3424. }
  3425. }
  3426. if( !found )
  3427. {
  3428. asCString str;
  3429. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, objType->GetName());
  3430. WriteError(str, file, node);
  3431. }
  3432. }
  3433. }
  3434. node = next;
  3435. };
  3436. mainNode->Destroy(engine);
  3437. return 0;
  3438. }
  3439. int asCBuilder::RegisterImportedFunction(int importID, asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns)
  3440. {
  3441. asCString name;
  3442. asCDataType returnType;
  3443. asCArray<asCString> parameterNames;
  3444. asCArray<asCDataType> parameterTypes;
  3445. asCArray<asETypeModifiers> inOutFlags;
  3446. asCArray<asCString *> defaultArgs;
  3447. bool isConstMethod, isOverride, isFinal, isConstructor, isDestructor, isPrivate, isShared;
  3448. if( ns == 0 )
  3449. ns = engine->nameSpaces[0];
  3450. GetParsedFunctionDetails(node->firstChild, file, 0, name, returnType, parameterNames, parameterTypes, inOutFlags, defaultArgs, isConstMethod, isConstructor, isDestructor, isPrivate, isOverride, isFinal, isShared, ns);
  3451. CheckNameConflict(name.AddressOf(), node, file, ns);
  3452. // Check that the same function hasn't been registered already in the namespace
  3453. asCArray<int> funcs;
  3454. GetFunctionDescriptions(name.AddressOf(), funcs, ns);
  3455. for( asUINT n = 0; n < funcs.GetLength(); ++n )
  3456. {
  3457. asCScriptFunction *func = GetFunctionDescription(funcs[n]);
  3458. if( func->IsSignatureExceptNameAndReturnTypeEqual(parameterTypes, inOutFlags, 0, false) )
  3459. {
  3460. WriteError(TXT_FUNCTION_ALREADY_EXIST, file, node);
  3461. break;
  3462. }
  3463. }
  3464. // Read the module name as well
  3465. asCScriptNode *nd = node->lastChild;
  3466. asASSERT( nd->nodeType == snConstant && nd->tokenType == ttStringConstant );
  3467. asCString moduleName;
  3468. moduleName.Assign(&file->code[nd->tokenPos+1], nd->tokenLength-2);
  3469. node->Destroy(engine);
  3470. // Register the function
  3471. module->AddImportedFunction(importID, name, returnType, parameterTypes, inOutFlags, defaultArgs, ns, moduleName);
  3472. return 0;
  3473. }
  3474. #endif
  3475. asCScriptFunction *asCBuilder::GetFunctionDescription(int id)
  3476. {
  3477. // TODO: import: This should be improved when the imported functions are removed
  3478. // Get the description from the engine
  3479. if( (id & FUNC_IMPORTED) == 0 )
  3480. return engine->scriptFunctions[id];
  3481. else
  3482. return engine->importedFunctions[id & ~FUNC_IMPORTED]->importedFunctionSignature;
  3483. }
  3484. void asCBuilder::GetFunctionDescriptions(const char *name, asCArray<int> &funcs, asSNameSpace *ns)
  3485. {
  3486. asUINT n;
  3487. const asCArray<unsigned int> &idxs = module->globalFunctions.GetIndexes(ns, name);
  3488. for( n = 0; n < idxs.GetLength(); n++ )
  3489. {
  3490. const asCScriptFunction *f = module->globalFunctions.Get(idxs[n]);
  3491. asASSERT( f->objectType == 0 );
  3492. funcs.PushLast(f->id);
  3493. }
  3494. // TODO: optimize: Linear search: This is probably not that critial. Also bindInformation will probably be removed in near future
  3495. for( n = 0; n < module->bindInformations.GetLength(); n++ )
  3496. {
  3497. if( module->bindInformations[n]->importedFunctionSignature->name == name )
  3498. funcs.PushLast(module->bindInformations[n]->importedFunctionSignature->id);
  3499. }
  3500. // TODO: optimize: Linear search. The registered global functions should be stored in a symbol table too
  3501. for( n = 0; n < engine->registeredGlobalFuncs.GetLength(); n++ )
  3502. {
  3503. asCScriptFunction *f = engine->registeredGlobalFuncs[n];
  3504. if( f &&
  3505. f->funcType == asFUNC_SYSTEM &&
  3506. f->objectType == 0 &&
  3507. f->nameSpace == ns &&
  3508. f->name == name )
  3509. {
  3510. // Verify if the module has access to the function
  3511. if( module->accessMask & f->accessMask )
  3512. {
  3513. funcs.PushLast(f->id);
  3514. }
  3515. }
  3516. }
  3517. }
  3518. void asCBuilder::GetObjectMethodDescriptions(const char *name, asCObjectType *objectType, asCArray<int> &methods, bool objIsConst, const asCString &scope)
  3519. {
  3520. if( scope != "" )
  3521. {
  3522. // Find the base class with the specified scope
  3523. while( objectType && objectType->name != scope )
  3524. objectType = objectType->derivedFrom;
  3525. // If the scope is not any of the base classes, then return no methods
  3526. if( objectType == 0 )
  3527. return;
  3528. }
  3529. // TODO: optimize: Improve linear search
  3530. if( objIsConst )
  3531. {
  3532. // Only add const methods to the list
  3533. for( asUINT n = 0; n < objectType->methods.GetLength(); n++ )
  3534. {
  3535. if( engine->scriptFunctions[objectType->methods[n]]->name == name &&
  3536. engine->scriptFunctions[objectType->methods[n]]->isReadOnly )
  3537. {
  3538. // When the scope is defined the returned methods should be the true methods, not the virtual method stubs
  3539. if( scope == "" )
  3540. methods.PushLast(engine->scriptFunctions[objectType->methods[n]]->id);
  3541. else
  3542. {
  3543. asCScriptFunction *virtFunc = engine->scriptFunctions[objectType->methods[n]];
  3544. asCScriptFunction *realFunc = objectType->virtualFunctionTable[virtFunc->vfTableIdx];
  3545. methods.PushLast(realFunc->id);
  3546. }
  3547. }
  3548. }
  3549. }
  3550. else
  3551. {
  3552. // TODO: Prefer non-const over const
  3553. for( asUINT n = 0; n < objectType->methods.GetLength(); n++ )
  3554. {
  3555. if( engine->scriptFunctions[objectType->methods[n]]->name == name )
  3556. {
  3557. // When the scope is defined the returned methods should be the true methods, not the virtual method stubs
  3558. if( scope == "" )
  3559. methods.PushLast(engine->scriptFunctions[objectType->methods[n]]->id);
  3560. else
  3561. {
  3562. asCScriptFunction *virtFunc = engine->scriptFunctions[objectType->methods[n]];
  3563. asCScriptFunction *realFunc = objectType->virtualFunctionTable[virtFunc->vfTableIdx];
  3564. methods.PushLast(realFunc->id);
  3565. }
  3566. }
  3567. }
  3568. }
  3569. }
  3570. void asCBuilder::WriteInfo(const asCString &scriptname, const asCString &message, int r, int c, bool pre)
  3571. {
  3572. // Need to store the pre message in a structure
  3573. if( pre )
  3574. {
  3575. preMessage.isSet = true;
  3576. preMessage.c = c;
  3577. preMessage.r = r;
  3578. preMessage.message = message;
  3579. preMessage.scriptname = scriptname;
  3580. }
  3581. else
  3582. {
  3583. preMessage.isSet = false;
  3584. engine->WriteMessage(scriptname.AddressOf(), r, c, asMSGTYPE_INFORMATION, message.AddressOf());
  3585. }
  3586. }
  3587. void asCBuilder::WriteInfo(const asCString &message, asCScriptCode *file, asCScriptNode *node)
  3588. {
  3589. int r = 0, c = 0;
  3590. if( node )
  3591. file->ConvertPosToRowCol(node->tokenPos, &r, &c);
  3592. WriteInfo(file->name, message, r, c, false);
  3593. }
  3594. void asCBuilder::WriteError(const asCString &message, asCScriptCode *file, asCScriptNode *node)
  3595. {
  3596. int r = 0, c = 0;
  3597. if( node && file )
  3598. file->ConvertPosToRowCol(node->tokenPos, &r, &c);
  3599. WriteError(file ? file->name : "", message, r, c);
  3600. }
  3601. void asCBuilder::WriteError(const asCString &scriptname, const asCString &message, int r, int c)
  3602. {
  3603. numErrors++;
  3604. // Need to pass the preMessage first
  3605. if( preMessage.isSet )
  3606. WriteInfo(preMessage.scriptname, preMessage.message, preMessage.r, preMessage.c, false);
  3607. engine->WriteMessage(scriptname.AddressOf(), r, c, asMSGTYPE_ERROR, message.AddressOf());
  3608. }
  3609. void asCBuilder::WriteWarning(const asCString &scriptname, const asCString &message, int r, int c)
  3610. {
  3611. if( engine->ep.compilerWarnings )
  3612. {
  3613. numWarnings++;
  3614. // Need to pass the preMessage first
  3615. if( preMessage.isSet )
  3616. WriteInfo(preMessage.scriptname, preMessage.message, preMessage.r, preMessage.c, false);
  3617. engine->WriteMessage(scriptname.AddressOf(), r, c, asMSGTYPE_WARNING, message.AddressOf());
  3618. }
  3619. }
  3620. asCString asCBuilder::GetScopeFromNode(asCScriptNode *node, asCScriptCode *script, asCScriptNode **next)
  3621. {
  3622. asCString scope;
  3623. asCScriptNode *sn = node;
  3624. if( sn->tokenType == ttScope )
  3625. {
  3626. scope = "::";
  3627. sn = sn->next;
  3628. }
  3629. while( sn && sn->next && sn->next->tokenType == ttScope )
  3630. {
  3631. asCString tmp;
  3632. tmp.Assign(&script->code[sn->tokenPos], sn->tokenLength);
  3633. if( scope != "" && scope != "::" )
  3634. scope += "::";
  3635. scope += tmp;
  3636. sn = sn->next->next;
  3637. }
  3638. if( next )
  3639. *next = sn;
  3640. return scope;
  3641. }
  3642. asSNameSpace *asCBuilder::GetNameSpaceFromNode(asCScriptNode *node, asCScriptCode *script, asSNameSpace *implicitNs, asCScriptNode **next)
  3643. {
  3644. asCString scope = GetScopeFromNode(node, script, next);
  3645. asSNameSpace *ns = implicitNs;
  3646. if( scope == "::" )
  3647. ns = engine->nameSpaces[0];
  3648. else if( scope != "" )
  3649. {
  3650. ns = engine->FindNameSpace(scope.AddressOf());
  3651. if( ns == 0 )
  3652. {
  3653. asCString msg;
  3654. msg.Format(TXT_NAMESPACE_s_DOESNT_EXIST, scope.AddressOf());
  3655. WriteError(msg, script, node);
  3656. }
  3657. }
  3658. return ns;
  3659. }
  3660. asSNameSpace *asCBuilder::GetParentNameSpace(asSNameSpace *ns)
  3661. {
  3662. if( ns == 0 ) return 0;
  3663. if( ns == engine->nameSpaces[0] ) return 0;
  3664. asCString scope = ns->name;
  3665. int pos = scope.FindLast("::");
  3666. if( pos >= 0 )
  3667. {
  3668. scope = scope.SubString(0, pos);
  3669. return engine->FindNameSpace(scope.AddressOf());
  3670. }
  3671. return engine->nameSpaces[0];
  3672. }
  3673. asCDataType asCBuilder::CreateDataTypeFromNode(asCScriptNode *node, asCScriptCode *file, asSNameSpace *implicitNamespace, bool acceptHandleForScope, asCObjectType *currentType)
  3674. {
  3675. asASSERT(node->nodeType == snDataType);
  3676. asCDataType dt;
  3677. asCScriptNode *n = node->firstChild;
  3678. bool isConst = false;
  3679. bool isImplicitHandle = false;
  3680. if( n->tokenType == ttConst )
  3681. {
  3682. isConst = true;
  3683. n = n->next;
  3684. }
  3685. // Determine namespace
  3686. asSNameSpace *ns = GetNameSpaceFromNode(n, file, implicitNamespace, &n);
  3687. if( ns == 0 )
  3688. {
  3689. // The namespace doesn't exist. Return a dummy type instead.
  3690. dt = asCDataType::CreatePrimitive(ttInt, false);
  3691. return dt;
  3692. }
  3693. if( n->tokenType == ttIdentifier )
  3694. {
  3695. bool found = false;
  3696. asCScriptNode *nameToken = n;
  3697. asCString str;
  3698. str.Assign(&file->code[n->tokenPos], n->tokenLength);
  3699. // Recursively search parent namespaces for matching type
  3700. while( ns && !found )
  3701. {
  3702. asCObjectType *ot = 0;
  3703. // If this is for a template type, then we must first determine if the
  3704. // identifier matches any of the template subtypes
  3705. if( currentType && (currentType->flags & asOBJ_TEMPLATE))
  3706. {
  3707. for( asUINT subtypeIndex = 0; subtypeIndex < currentType->templateSubTypes.GetLength(); subtypeIndex++)
  3708. {
  3709. if(str == currentType->templateSubTypes[subtypeIndex].GetObjectType()->name )
  3710. {
  3711. ot = currentType->templateSubTypes[subtypeIndex].GetObjectType();
  3712. break;
  3713. }
  3714. }
  3715. }
  3716. if( ot == 0 )
  3717. ot = GetObjectType(str.AddressOf(), ns);
  3718. if( ot == 0 && !module && currentType )
  3719. ot = GetObjectTypeFromTypesKnownByObject(str.AddressOf(), currentType);
  3720. if( ot )
  3721. {
  3722. found = true;
  3723. if( ot->flags & asOBJ_IMPLICIT_HANDLE )
  3724. isImplicitHandle = true;
  3725. // Make sure the module has access to the object type
  3726. if( !module || (module->accessMask & ot->accessMask) )
  3727. {
  3728. if(asOBJ_TYPEDEF == (ot->flags & asOBJ_TYPEDEF))
  3729. {
  3730. // TODO: typedef: A typedef should be considered different from the original type (though with implicit conversions between the two)
  3731. // Create primitive data type based on object flags
  3732. dt = ot->templateSubTypes[0];
  3733. dt.MakeReadOnly(isConst);
  3734. }
  3735. else
  3736. {
  3737. if( ot->flags & asOBJ_TEMPLATE )
  3738. {
  3739. // Check if the subtype is a type or the template's subtype
  3740. // if it is the template's subtype then this is the actual template type,
  3741. // orderwise it is a template instance.
  3742. // Only do this for application registered interface, as the
  3743. // scripts cannot implement templates.
  3744. // TODO: namespace: Use correct implicit namespace
  3745. asCArray<asCDataType> subTypes;
  3746. asUINT subtypeIndex;
  3747. while( n && n->next && n->next->nodeType == snDataType )
  3748. {
  3749. n = n->next;
  3750. asCDataType subType = CreateDataTypeFromNode(n, file, engine->nameSpaces[0], false, module ? 0 : ot);
  3751. subTypes.PushLast(subType);
  3752. if( subType.IsReadOnly() )
  3753. {
  3754. asCString msg;
  3755. msg.Format(TXT_TMPL_SUBTYPE_MUST_NOT_BE_READ_ONLY);
  3756. WriteError(msg, file, n);
  3757. // Return a dummy
  3758. return asCDataType::CreatePrimitive(ttInt, false);
  3759. }
  3760. }
  3761. if( subTypes.GetLength() != ot->templateSubTypes.GetLength() )
  3762. {
  3763. asCString msg;
  3764. msg.Format(TXT_TMPL_s_EXPECTS_d_SUBTYPES, ot->name.AddressOf(), int(ot->templateSubTypes.GetLength()));
  3765. WriteError(msg, file, nameToken);
  3766. // Return a dummy
  3767. return asCDataType::CreatePrimitive(ttInt, false);
  3768. }
  3769. asASSERT( subTypes.GetLength() == ot->templateSubTypes.GetLength() );
  3770. // Check if any of the given subtypes are different from the template's declared subtypes
  3771. bool isDifferent = false;
  3772. for( subtypeIndex = 0; subtypeIndex < subTypes.GetLength(); subtypeIndex++ )
  3773. {
  3774. if( subTypes[subtypeIndex].GetObjectType() != ot->templateSubTypes[subtypeIndex].GetObjectType() )
  3775. {
  3776. isDifferent = true;
  3777. break;
  3778. }
  3779. }
  3780. if( isDifferent )
  3781. {
  3782. // This is a template instance
  3783. // Need to find the correct object type
  3784. asCObjectType *otInstance = engine->GetTemplateInstanceType(ot, subTypes);
  3785. if( !otInstance )
  3786. {
  3787. asCString msg;
  3788. // TODO: Should name all subtypes
  3789. msg.Format(TXT_CANNOT_INSTANCIATE_TEMPLATE_s_WITH_s, ot->name.AddressOf(), subTypes[0].Format().AddressOf());
  3790. WriteError(msg, file, n);
  3791. }
  3792. ot = otInstance;
  3793. }
  3794. }
  3795. // Create object data type
  3796. if( ot )
  3797. dt = asCDataType::CreateObject(ot, isConst);
  3798. else
  3799. dt = asCDataType::CreatePrimitive(ttInt, isConst);
  3800. }
  3801. }
  3802. else
  3803. {
  3804. asCString msg;
  3805. msg.Format(TXT_TYPE_s_NOT_AVAILABLE_FOR_MODULE, (const char *)str.AddressOf());
  3806. WriteError(msg, file, n);
  3807. dt.SetTokenType(ttInt);
  3808. }
  3809. }
  3810. else if( ot == 0 )
  3811. {
  3812. // It can still be a function definition
  3813. asCScriptFunction *funcdef = GetFuncDef(str.AddressOf());
  3814. if( funcdef )
  3815. {
  3816. dt = asCDataType::CreateFuncDef(funcdef);
  3817. found = true;
  3818. }
  3819. }
  3820. if( !found )
  3821. {
  3822. // Try to find it in the parent namespace
  3823. ns = GetParentNameSpace(ns);
  3824. }
  3825. }
  3826. if( !found )
  3827. {
  3828. asCString msg;
  3829. msg.Format(TXT_IDENTIFIER_s_NOT_DATA_TYPE, (const char *)str.AddressOf());
  3830. WriteError(msg, file, n);
  3831. dt = asCDataType::CreatePrimitive(ttInt, isConst);
  3832. return dt;
  3833. }
  3834. }
  3835. else
  3836. {
  3837. // Create primitive data type
  3838. dt = asCDataType::CreatePrimitive(n->tokenType, isConst);
  3839. }
  3840. // Determine array dimensions and object handles
  3841. n = n->next;
  3842. while( n && (n->tokenType == ttOpenBracket || n->tokenType == ttHandle) )
  3843. {
  3844. if( n->tokenType == ttOpenBracket )
  3845. {
  3846. // Make sure the sub type can be instanciated
  3847. if( !dt.CanBeInstanciated() )
  3848. {
  3849. asCString str;
  3850. // TODO: Change to "Array sub type cannot be 'type'"
  3851. str.Format(TXT_DATA_TYPE_CANT_BE_s, dt.Format().AddressOf());
  3852. WriteError(str, file, n);
  3853. }
  3854. // Make the type an array (or multidimensional array)
  3855. if( dt.MakeArray(engine) < 0 )
  3856. {
  3857. WriteError(TXT_NO_DEFAULT_ARRAY_TYPE, file, n);
  3858. break;
  3859. }
  3860. }
  3861. else
  3862. {
  3863. // Make the type a handle
  3864. if( dt.MakeHandle(true, acceptHandleForScope) < 0 )
  3865. {
  3866. WriteError(TXT_OBJECT_HANDLE_NOT_SUPPORTED, file, n);
  3867. break;
  3868. }
  3869. }
  3870. n = n->next;
  3871. }
  3872. if( isImplicitHandle )
  3873. {
  3874. // Make the type a handle
  3875. if( dt.MakeHandle(true, acceptHandleForScope) < 0 )
  3876. WriteError(TXT_OBJECT_HANDLE_NOT_SUPPORTED, file, n);
  3877. }
  3878. return dt;
  3879. }
  3880. asCDataType asCBuilder::ModifyDataTypeFromNode(const asCDataType &type, asCScriptNode *node, asCScriptCode *file, asETypeModifiers *inOutFlags, bool *autoHandle)
  3881. {
  3882. asCDataType dt = type;
  3883. if( inOutFlags ) *inOutFlags = asTM_NONE;
  3884. // Is the argument sent by reference?
  3885. asCScriptNode *n = node->firstChild;
  3886. if( n && n->tokenType == ttAmp )
  3887. {
  3888. dt.MakeReference(true);
  3889. n = n->next;
  3890. if( n )
  3891. {
  3892. if( inOutFlags )
  3893. {
  3894. if( n->tokenType == ttIn )
  3895. *inOutFlags = asTM_INREF;
  3896. else if( n->tokenType == ttOut )
  3897. *inOutFlags = asTM_OUTREF;
  3898. else if( n->tokenType == ttInOut )
  3899. *inOutFlags = asTM_INOUTREF;
  3900. else
  3901. asASSERT(false);
  3902. }
  3903. n = n->next;
  3904. }
  3905. else
  3906. {
  3907. if( inOutFlags )
  3908. *inOutFlags = asTM_INOUTREF; // ttInOut
  3909. }
  3910. if( !engine->ep.allowUnsafeReferences &&
  3911. inOutFlags && *inOutFlags == asTM_INOUTREF )
  3912. {
  3913. // Verify that the base type support &inout parameter types
  3914. if( !dt.IsObject() || dt.IsObjectHandle() || !((dt.GetObjectType()->flags & asOBJ_NOCOUNT) || (dt.GetObjectType()->beh.addref && dt.GetObjectType()->beh.release)) )
  3915. WriteError(TXT_ONLY_OBJECTS_MAY_USE_REF_INOUT, file, node->firstChild);
  3916. }
  3917. }
  3918. if( autoHandle ) *autoHandle = false;
  3919. if( n && n->tokenType == ttPlus )
  3920. {
  3921. // Autohandles are not supported for types with NOCOUNT
  3922. if( dt.GetObjectType()->flags & asOBJ_NOCOUNT )
  3923. WriteError(TXT_AUTOHANDLE_CANNOT_BE_USED_FOR_NOCOUNT, file, node->firstChild);
  3924. if( autoHandle ) *autoHandle = true;
  3925. }
  3926. return dt;
  3927. }
  3928. asCObjectType *asCBuilder::GetObjectType(const char *type, asSNameSpace *ns)
  3929. {
  3930. asCObjectType *ot = engine->GetObjectType(type, ns);
  3931. if( !ot && module )
  3932. ot = module->GetObjectType(type, ns);
  3933. return ot;
  3934. }
  3935. // This function will return true if there are any types in the engine or module
  3936. // with the given name. The namespace is ignored in this verification.
  3937. bool asCBuilder::DoesTypeExist(const char *type)
  3938. {
  3939. asUINT n;
  3940. // TODO: optimize: Improve linear searches
  3941. // Check if it is a registered type
  3942. for( n = 0; n < engine->objectTypes.GetLength(); n++ )
  3943. if( engine->objectTypes[n] &&
  3944. engine->objectTypes[n]->name == type ) // TODO: template: Should we check the subtype in case of template instances?
  3945. return true;
  3946. for( n = 0; n < engine->registeredFuncDefs.GetLength(); n++ )
  3947. if( engine->registeredFuncDefs[n]->name == type )
  3948. return true;
  3949. // Check if it is a script type
  3950. if( module )
  3951. {
  3952. for( n = 0; n < module->classTypes.GetLength(); n++ )
  3953. if( module->classTypes[n]->name == type )
  3954. return true;
  3955. for( n = 0; n < module->enumTypes.GetLength(); n++ )
  3956. if( module->enumTypes[n]->name == type )
  3957. return true;
  3958. for( n = 0; n < module->typeDefs.GetLength(); n++ )
  3959. if( module->typeDefs[n]->name == type )
  3960. return true;
  3961. for( asUINT n = 0; n < module->funcDefs.GetLength(); n++ )
  3962. if( module->funcDefs[n]->name == type )
  3963. return true;
  3964. }
  3965. return false;
  3966. }
  3967. asCObjectType *asCBuilder::GetObjectTypeFromTypesKnownByObject(const char *type, asCObjectType *currentType)
  3968. {
  3969. if( currentType->name == type )
  3970. return currentType;
  3971. asUINT n;
  3972. for( n = 0; n < currentType->properties.GetLength(); n++ )
  3973. if( currentType->properties[n]->type.GetObjectType() &&
  3974. currentType->properties[n]->type.GetObjectType()->name == type )
  3975. return currentType->properties[n]->type.GetObjectType();
  3976. for( n = 0; n < currentType->methods.GetLength(); n++ )
  3977. {
  3978. asCScriptFunction *func = engine->scriptFunctions[currentType->methods[n]];
  3979. if( func->returnType.GetObjectType() &&
  3980. func->returnType.GetObjectType()->name == type )
  3981. return func->returnType.GetObjectType();
  3982. for( asUINT f = 0; f < func->parameterTypes.GetLength(); f++ )
  3983. if( func->parameterTypes[f].GetObjectType() &&
  3984. func->parameterTypes[f].GetObjectType()->name == type )
  3985. return func->parameterTypes[f].GetObjectType();
  3986. }
  3987. return 0;
  3988. }
  3989. asCScriptFunction *asCBuilder::GetFuncDef(const char *type)
  3990. {
  3991. for( asUINT n = 0; n < engine->registeredFuncDefs.GetLength(); n++ )
  3992. // TODO: access: Only return the definitions that the module has access to
  3993. if( engine->registeredFuncDefs[n]->name == type )
  3994. return engine->registeredFuncDefs[n];
  3995. if( module )
  3996. {
  3997. for( asUINT n = 0; n < module->funcDefs.GetLength(); n++ )
  3998. if( module->funcDefs[n]->name == type )
  3999. return module->funcDefs[n];
  4000. }
  4001. return 0;
  4002. }
  4003. #ifndef AS_NO_COMPILER
  4004. int asCBuilder::GetEnumValueFromObjectType(asCObjectType *objType, const char *name, asCDataType &outDt, asDWORD &outValue)
  4005. {
  4006. if( !objType || !(objType->flags & asOBJ_ENUM) )
  4007. return 0;
  4008. for( asUINT n = 0; n < objType->enumValues.GetLength(); ++n )
  4009. {
  4010. if( objType->enumValues[n]->name == name )
  4011. {
  4012. outDt = asCDataType::CreateObject(objType, true);
  4013. outValue = objType->enumValues[n]->value;
  4014. return 1;
  4015. }
  4016. }
  4017. return 0;
  4018. }
  4019. int asCBuilder::GetEnumValue(const char *name, asCDataType &outDt, asDWORD &outValue, asSNameSpace *ns)
  4020. {
  4021. bool found = false;
  4022. // Search all available enum types
  4023. asUINT t;
  4024. for( t = 0; t < engine->objectTypes.GetLength(); t++ )
  4025. {
  4026. asCObjectType *ot = engine->objectTypes[t];
  4027. if( ns != ot->nameSpace ) continue;
  4028. if( GetEnumValueFromObjectType(ot, name, outDt, outValue) )
  4029. {
  4030. if( !found )
  4031. found = true;
  4032. else
  4033. {
  4034. // Found more than one value in different enum types
  4035. return 2;
  4036. }
  4037. }
  4038. }
  4039. for( t = 0; t < module->enumTypes.GetLength(); t++ )
  4040. {
  4041. asCObjectType *ot = module->enumTypes[t];
  4042. if( ns != ot->nameSpace ) continue;
  4043. if( GetEnumValueFromObjectType(ot, name, outDt, outValue) )
  4044. {
  4045. if( !found )
  4046. found = true;
  4047. else
  4048. {
  4049. // Found more than one value in different enum types
  4050. return 2;
  4051. }
  4052. }
  4053. }
  4054. if( found )
  4055. return 1;
  4056. // Didn't find any value
  4057. return 0;
  4058. }
  4059. #endif // AS_NO_COMPILER
  4060. END_AS_NAMESPACE