as_builder.cpp 137 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773
  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 )
  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. for( asUINT i = 1; i < st->beh.operators.GetLength(); i += 2 )
  1317. engine->scriptFunctions[st->beh.operators[i]]->AddRef();
  1318. return 0;
  1319. }
  1320. int asCBuilder::RegisterInterface(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns)
  1321. {
  1322. asCScriptNode *n = node->firstChild;
  1323. asCString name(&file->code[n->tokenPos], n->tokenLength);
  1324. bool isShared = false;
  1325. if( name == SHARED_TOKEN )
  1326. {
  1327. isShared = true;
  1328. n = n->next;
  1329. name.Assign(&file->code[n->tokenPos], n->tokenLength);
  1330. }
  1331. int r, c;
  1332. file->ConvertPosToRowCol(n->tokenPos, &r, &c);
  1333. CheckNameConflict(name.AddressOf(), n, file, ns);
  1334. sClassDeclaration *decl = asNEW(sClassDeclaration);
  1335. if( decl == 0 )
  1336. {
  1337. node->Destroy(engine);
  1338. return asOUT_OF_MEMORY;
  1339. }
  1340. interfaceDeclarations.PushLast(decl);
  1341. decl->name = name;
  1342. decl->script = file;
  1343. decl->node = node;
  1344. // If this type is shared and there already exist another shared
  1345. // type of the same name, then that one should be used instead of
  1346. // creating a new one.
  1347. if( isShared )
  1348. {
  1349. for( asUINT n = 0; n < engine->classTypes.GetLength(); n++ )
  1350. {
  1351. asCObjectType *st = engine->classTypes[n];
  1352. if( st &&
  1353. st->IsShared() &&
  1354. st->name == name &&
  1355. st->nameSpace == ns &&
  1356. st->IsInterface() )
  1357. {
  1358. // We'll use the existing type
  1359. decl->isExistingShared = true;
  1360. decl->objType = st;
  1361. module->classTypes.PushLast(st);
  1362. st->AddRef();
  1363. return 0;
  1364. }
  1365. }
  1366. }
  1367. // Register the object type for the interface
  1368. asCObjectType *st = asNEW(asCObjectType)(engine);
  1369. if( st == 0 )
  1370. return asOUT_OF_MEMORY;
  1371. st->flags = asOBJ_REF | asOBJ_SCRIPT_OBJECT;
  1372. if( isShared )
  1373. st->flags |= asOBJ_SHARED;
  1374. st->size = 0; // Cannot be instanciated
  1375. st->name = name;
  1376. st->nameSpace = ns;
  1377. module->classTypes.PushLast(st);
  1378. engine->classTypes.PushLast(st);
  1379. st->AddRef();
  1380. decl->objType = st;
  1381. // Use the default script class behaviours
  1382. st->beh.construct = 0;
  1383. st->beh.addref = engine->scriptTypeBehaviours.beh.addref;
  1384. engine->scriptFunctions[st->beh.addref]->AddRef();
  1385. st->beh.release = engine->scriptTypeBehaviours.beh.release;
  1386. engine->scriptFunctions[st->beh.release]->AddRef();
  1387. st->beh.copy = 0;
  1388. return 0;
  1389. }
  1390. void asCBuilder::CompileGlobalVariables()
  1391. {
  1392. bool compileSucceeded = true;
  1393. // Store state of compilation (errors, warning, output)
  1394. int currNumErrors = numErrors;
  1395. int currNumWarnings = numWarnings;
  1396. // Backup the original message stream
  1397. bool msgCallback = engine->msgCallback;
  1398. asSSystemFunctionInterface msgCallbackFunc = engine->msgCallbackFunc;
  1399. void *msgCallbackObj = engine->msgCallbackObj;
  1400. // Set the new temporary message stream
  1401. asCOutputBuffer outBuffer;
  1402. engine->SetMessageCallback(asMETHOD(asCOutputBuffer, Callback), &outBuffer, asCALL_THISCALL);
  1403. asCOutputBuffer finalOutput;
  1404. asCScriptFunction *initFunc = 0;
  1405. asCSymbolTable<asCGlobalProperty> initOrder;
  1406. // We first try to compile all the primitive global variables, and only after that
  1407. // compile the non-primitive global variables. This permits the constructors
  1408. // for the complex types to use the already initialized variables of primitive
  1409. // type. Note, we currently don't know which global variables are used in the
  1410. // constructors, so we cannot guarantee that variables of complex types are
  1411. // initialized in the correct order, so we won't reorder those.
  1412. bool compilingPrimitives = true;
  1413. // Compile each global variable
  1414. while( compileSucceeded )
  1415. {
  1416. compileSucceeded = false;
  1417. int accumErrors = 0;
  1418. int accumWarnings = 0;
  1419. // Restore state of compilation
  1420. finalOutput.Clear();
  1421. asCSymbolTable<sGlobalVariableDescription>::iterator it = globVariables.List();
  1422. for( ; it; it++ )
  1423. {
  1424. sGlobalVariableDescription *gvar = *it;
  1425. if( gvar->isCompiled )
  1426. continue;
  1427. asCByteCode init(engine);
  1428. numWarnings = 0;
  1429. numErrors = 0;
  1430. outBuffer.Clear();
  1431. // Skip this for now if we're not compiling complex types yet
  1432. if( compilingPrimitives && !gvar->datatype.IsPrimitive() )
  1433. continue;
  1434. if( gvar->nextNode )
  1435. {
  1436. int r, c;
  1437. gvar->script->ConvertPosToRowCol(gvar->nextNode->tokenPos, &r, &c);
  1438. asCString str = gvar->datatype.Format();
  1439. str += " " + gvar->name;
  1440. str.Format(TXT_COMPILING_s, str.AddressOf());
  1441. WriteInfo(gvar->script->name, str, r, c, true);
  1442. }
  1443. if( gvar->isEnumValue )
  1444. {
  1445. int r;
  1446. if( gvar->nextNode )
  1447. {
  1448. asCCompiler comp(engine);
  1449. asCScriptFunction func(engine, module, asFUNC_DUMMY);
  1450. // Set the namespace that should be used during the compilation
  1451. func.nameSpace = gvar->datatype.GetObjectType()->nameSpace;
  1452. // Temporarily switch the type of the variable to int so it can be compiled properly
  1453. asCDataType saveType;
  1454. saveType = gvar->datatype;
  1455. gvar->datatype = asCDataType::CreatePrimitive(ttInt, true);
  1456. r = comp.CompileGlobalVariable(this, gvar->script, gvar->nextNode, gvar, &func);
  1457. gvar->datatype = saveType;
  1458. }
  1459. else
  1460. {
  1461. r = 0;
  1462. // When there is no assignment the value is the last + 1
  1463. int enumVal = 0;
  1464. asCSymbolTable<sGlobalVariableDescription>::iterator prev_it = it;
  1465. prev_it--;
  1466. if( prev_it )
  1467. {
  1468. sGlobalVariableDescription *gvar2 = *prev_it;
  1469. if(gvar2->datatype == gvar->datatype )
  1470. {
  1471. // The integer value is stored in the lower bytes
  1472. enumVal = (*(int*)&gvar2->constantValue) + 1;
  1473. if( !gvar2->isCompiled )
  1474. {
  1475. // TODO: Need to get the correct script position
  1476. int row, col;
  1477. gvar->script->ConvertPosToRowCol(0, &row, &col);
  1478. asCString str = gvar->datatype.Format();
  1479. str += " " + gvar->name;
  1480. str.Format(TXT_COMPILING_s, str.AddressOf());
  1481. WriteInfo(gvar->script->name, str, row, col, true);
  1482. str.Format(TXT_UNINITIALIZED_GLOBAL_VAR_s, gvar2->name.AddressOf());
  1483. WriteError(gvar->script->name, str, row, col);
  1484. r = -1;
  1485. }
  1486. }
  1487. }
  1488. // The integer value is stored in the lower bytes
  1489. *(int*)&gvar->constantValue = enumVal;
  1490. }
  1491. if( r >= 0 )
  1492. {
  1493. // Set the value as compiled
  1494. gvar->isCompiled = true;
  1495. compileSucceeded = true;
  1496. }
  1497. }
  1498. else
  1499. {
  1500. // Compile the global variable
  1501. initFunc = asNEW(asCScriptFunction)(engine, module, asFUNC_DUMMY);
  1502. if( initFunc == 0 )
  1503. {
  1504. // Out of memory
  1505. return;
  1506. }
  1507. // Set the namespace that should be used for this function
  1508. initFunc->nameSpace = gvar->property->nameSpace;
  1509. asCCompiler comp(engine);
  1510. int r = comp.CompileGlobalVariable(this, gvar->script, gvar->nextNode, gvar, initFunc);
  1511. if( r >= 0 )
  1512. {
  1513. // Compilation succeeded
  1514. gvar->isCompiled = true;
  1515. compileSucceeded = true;
  1516. }
  1517. else
  1518. {
  1519. // Compilation failed
  1520. asDELETE(initFunc, asCScriptFunction);
  1521. initFunc = 0;
  1522. }
  1523. }
  1524. if( gvar->isCompiled )
  1525. {
  1526. // Add warnings for this constant to the total build
  1527. if( numWarnings )
  1528. {
  1529. currNumWarnings += numWarnings;
  1530. if( msgCallback )
  1531. outBuffer.SendToCallback(engine, &msgCallbackFunc, msgCallbackObj);
  1532. }
  1533. // Determine order of variable initializations
  1534. if( gvar->property && !gvar->isEnumValue )
  1535. initOrder.Put(gvar->property);
  1536. // Does the function contain more than just a SUSPEND followed by a RET instruction?
  1537. if( initFunc && initFunc->byteCode.GetLength() > 2 )
  1538. {
  1539. // Create the init function for this variable
  1540. initFunc->id = engine->GetNextScriptFunctionId();
  1541. engine->SetScriptFunction(initFunc);
  1542. // Finalize the init function for this variable
  1543. initFunc->funcType = asFUNC_SCRIPT;
  1544. initFunc->returnType = asCDataType::CreatePrimitive(ttVoid, false);
  1545. initFunc->scriptSectionIdx = engine->GetScriptSectionNameIndex(gvar->script->name.AddressOf());
  1546. gvar->property->SetInitFunc(initFunc);
  1547. initFunc->Release();
  1548. initFunc = 0;
  1549. }
  1550. else if( initFunc )
  1551. {
  1552. // Destroy the function as it won't be used
  1553. asDELETE(initFunc, asCScriptFunction);
  1554. initFunc = 0;
  1555. }
  1556. // Convert enums to true enum values, so subsequent compilations can access it as an enum
  1557. if( gvar->isEnumValue )
  1558. {
  1559. asCObjectType *objectType = gvar->datatype.GetObjectType();
  1560. asASSERT(NULL != objectType);
  1561. asSEnumValue *e = asNEW(asSEnumValue);
  1562. if( e == 0 )
  1563. {
  1564. // Out of memory
  1565. numErrors++;
  1566. return;
  1567. }
  1568. e->name = gvar->name;
  1569. e->value = *(int*)&gvar->constantValue;
  1570. objectType->enumValues.PushLast(e);
  1571. }
  1572. }
  1573. else
  1574. {
  1575. // Add output to final output
  1576. finalOutput.Append(outBuffer);
  1577. accumErrors += numErrors;
  1578. accumWarnings += numWarnings;
  1579. }
  1580. preMessage.isSet = false;
  1581. }
  1582. if( !compileSucceeded )
  1583. {
  1584. if( compilingPrimitives )
  1585. {
  1586. // No more primitives could be compiled, so
  1587. // switch to compiling the complex variables
  1588. compilingPrimitives = false;
  1589. compileSucceeded = true;
  1590. }
  1591. else
  1592. {
  1593. // No more variables can be compiled
  1594. // Add errors and warnings to total build
  1595. currNumWarnings += accumWarnings;
  1596. currNumErrors += accumErrors;
  1597. if( msgCallback )
  1598. finalOutput.SendToCallback(engine, &msgCallbackFunc, msgCallbackObj);
  1599. }
  1600. }
  1601. }
  1602. // Restore states
  1603. engine->msgCallback = msgCallback;
  1604. engine->msgCallbackFunc = msgCallbackFunc;
  1605. engine->msgCallbackObj = msgCallbackObj;
  1606. numWarnings = currNumWarnings;
  1607. numErrors = currNumErrors;
  1608. // Set the correct order of initialization
  1609. if( numErrors == 0 )
  1610. {
  1611. // If the length of the arrays are not the same, then this is the compilation
  1612. // of a single variable, in which case the initialization order of the previous
  1613. // variables must be preserved.
  1614. if( module->scriptGlobals.GetSize() == initOrder.GetSize() )
  1615. module->scriptGlobals.SwapWith(initOrder);
  1616. }
  1617. // Delete the enum expressions
  1618. asCSymbolTableIterator<sGlobalVariableDescription> it = globVariables.List();
  1619. while( it )
  1620. {
  1621. sGlobalVariableDescription *gvar = *it;
  1622. if( gvar->isEnumValue )
  1623. {
  1624. // Remove from symboltable. This has to be done prior to freeing the memeory
  1625. globVariables.Erase(it.GetIndex());
  1626. // Destroy the gvar property
  1627. if( gvar->nextNode )
  1628. {
  1629. gvar->nextNode->Destroy(engine);
  1630. gvar->nextNode = 0;
  1631. }
  1632. if( gvar->property )
  1633. {
  1634. asDELETE(gvar->property, asCGlobalProperty);
  1635. gvar->property = 0;
  1636. }
  1637. asDELETE(gvar, sGlobalVariableDescription);
  1638. }
  1639. it++;
  1640. }
  1641. }
  1642. int asCBuilder::GetNamespaceAndNameFromNode(asCScriptNode *n, asCScriptCode *script, asSNameSpace *implicitNs, asSNameSpace *&outNs, asCString &outName)
  1643. {
  1644. asASSERT( n->nodeType == snIdentifier );
  1645. // Get the optional scope from the node
  1646. asSNameSpace *ns = GetNameSpaceFromNode(n->firstChild, script, implicitNs, 0);
  1647. if( ns == 0 )
  1648. return -1;
  1649. // Get the name
  1650. asCString name(&script->code[n->lastChild->tokenPos], n->lastChild->tokenLength);
  1651. outNs = ns;
  1652. outName = name;
  1653. return 0;
  1654. }
  1655. void asCBuilder::AddInterfaceFromMixinToClass(sClassDeclaration *decl, asCScriptNode *errNode, sMixinClass *mixin)
  1656. {
  1657. // Determine what interfaces that the mixin implements
  1658. asCScriptNode *node = mixin->node;
  1659. asASSERT(node->nodeType == snClass);
  1660. // Skip the name of the mixin
  1661. node = node->firstChild->next;
  1662. while( node && node->nodeType == snIdentifier )
  1663. {
  1664. bool ok = true;
  1665. asSNameSpace *ns;
  1666. asCString name;
  1667. if( GetNamespaceAndNameFromNode(node, mixin->script, mixin->ns, ns, name) < 0 )
  1668. ok = false;
  1669. else
  1670. {
  1671. // Find the object type for the interface
  1672. asCObjectType *objType = GetObjectType(name.AddressOf(), ns);
  1673. // Check that the object type is an interface
  1674. if( objType && objType->size == 0 && (objType->flags & asOBJ_SCRIPT_OBJECT) )
  1675. {
  1676. // Only add the interface if the class doesn't already implement it
  1677. if( !decl->objType->Implements(objType) )
  1678. AddInterfaceToClass(decl, errNode, objType);
  1679. }
  1680. else
  1681. {
  1682. WriteError(TXT_MIXIN_CLASS_CANNOT_INHERIT, mixin->script, node);
  1683. ok = false;
  1684. }
  1685. }
  1686. if( !ok )
  1687. {
  1688. // Remove this node so the error isn't reported again
  1689. asCScriptNode *delNode = node;
  1690. node = node->prev;
  1691. delNode->DisconnectParent();
  1692. delNode->Destroy(engine);
  1693. }
  1694. node = node->next;
  1695. }
  1696. }
  1697. void asCBuilder::AddInterfaceToClass(sClassDeclaration *decl, asCScriptNode *errNode, asCObjectType *intfType)
  1698. {
  1699. // A shared type may only implement from shared interfaces
  1700. if( decl->objType->IsShared() && !intfType->IsShared() )
  1701. {
  1702. asCString msg;
  1703. msg.Format(TXT_SHARED_CANNOT_IMPLEMENT_NON_SHARED_s, intfType->name.AddressOf());
  1704. WriteError(msg, decl->script, errNode);
  1705. return;
  1706. }
  1707. if( decl->isExistingShared )
  1708. {
  1709. // If the class is an existing shared class, then just check if the
  1710. // interface exists in the original declaration too
  1711. if( !decl->objType->Implements(intfType) )
  1712. {
  1713. asCString str;
  1714. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, decl->objType->GetName());
  1715. WriteError(str, decl->script, errNode);
  1716. return;
  1717. }
  1718. }
  1719. else
  1720. {
  1721. // If the interface is already in the class then don't add it again
  1722. if( decl->objType->Implements(intfType) )
  1723. return;
  1724. // Add the interface to the class
  1725. decl->objType->interfaces.PushLast(intfType);
  1726. // Add the inherited interfaces too
  1727. // For interfaces this will be done outside to handle out-of-order declarations
  1728. if( !decl->objType->IsInterface() )
  1729. {
  1730. for( asUINT n = 0; n < intfType->interfaces.GetLength(); n++ )
  1731. AddInterfaceToClass(decl, errNode, intfType->interfaces[n]);
  1732. }
  1733. }
  1734. }
  1735. void asCBuilder::CompileInterfaces()
  1736. {
  1737. asUINT n;
  1738. for( n = 0; n < interfaceDeclarations.GetLength(); n++ )
  1739. {
  1740. sClassDeclaration *intfDecl = interfaceDeclarations[n];
  1741. asCObjectType *intfType = intfDecl->objType;
  1742. asCScriptNode *node = intfDecl->node;
  1743. asASSERT(node && node->nodeType == snInterface);
  1744. node = node->firstChild;
  1745. // Skip the 'shared' keyword
  1746. if( intfType->IsShared() )
  1747. node = node->next;
  1748. // Skip the name
  1749. node = node->next;
  1750. // Verify the inherited interfaces
  1751. while( node && node->nodeType == snIdentifier )
  1752. {
  1753. asSNameSpace *ns;
  1754. asCString name;
  1755. if( GetNamespaceAndNameFromNode(node, intfDecl->script, intfType->nameSpace, ns, name) < 0 )
  1756. {
  1757. node = node->next;
  1758. continue;
  1759. }
  1760. // Find the object type for the interface
  1761. asCObjectType *objType = GetObjectType(name.AddressOf(), ns);
  1762. // Check that the object type is an interface
  1763. bool ok = true;
  1764. if( objType && objType->size == 0 && (objType->flags & asOBJ_SCRIPT_OBJECT) )
  1765. {
  1766. // Check that the implemented interface is shared if the base interface is shared
  1767. if( intfType->IsShared() && !objType->IsShared() )
  1768. {
  1769. asCString str;
  1770. str.Format(TXT_SHARED_CANNOT_IMPLEMENT_NON_SHARED_s, objType->GetName());
  1771. WriteError(str, intfDecl->script, node);
  1772. ok = false;
  1773. }
  1774. }
  1775. else
  1776. {
  1777. WriteError(TXT_INTERFACE_CAN_ONLY_IMPLEMENT_INTERFACE, intfDecl->script, node);
  1778. ok = false;
  1779. }
  1780. if( ok )
  1781. {
  1782. // Make sure none of the implemented interfaces implement from this one
  1783. asCObjectType *base = objType;
  1784. while( base != 0 )
  1785. {
  1786. if( base == intfType )
  1787. {
  1788. WriteError(TXT_CANNOT_IMPLEMENT_SELF, intfDecl->script, node);
  1789. ok = false;
  1790. break;
  1791. }
  1792. // At this point there is at most one implemented interface
  1793. if( base->interfaces.GetLength() )
  1794. base = base->interfaces[0];
  1795. else
  1796. break;
  1797. }
  1798. }
  1799. if( ok )
  1800. AddInterfaceToClass(intfDecl, node, objType);
  1801. // Remove the nodes so they aren't parsed again
  1802. asCScriptNode *delNode = node;
  1803. node = node->next;
  1804. delNode->DisconnectParent();
  1805. delNode->Destroy(engine);
  1806. }
  1807. }
  1808. // Order the interfaces with inheritances so that the inherited
  1809. // of inherited interfaces can be added properly
  1810. for( n = 0; n < interfaceDeclarations.GetLength(); n++ )
  1811. {
  1812. sClassDeclaration *intfDecl = interfaceDeclarations[n];
  1813. asCObjectType *intfType = intfDecl->objType;
  1814. if( intfType->interfaces.GetLength() == 0 ) continue;
  1815. // If any of the derived interfaces are found after this interface, then move this to the end of the list
  1816. for( asUINT m = n+1; m < interfaceDeclarations.GetLength(); m++ )
  1817. {
  1818. if( intfType->Implements(interfaceDeclarations[m]->objType) )
  1819. {
  1820. interfaceDeclarations.RemoveIndex(n);
  1821. interfaceDeclarations.PushLast(intfDecl);
  1822. // Decrease index so that we don't skip an entry
  1823. n--;
  1824. break;
  1825. }
  1826. }
  1827. }
  1828. // Now recursively add the additional inherited interfaces
  1829. for( n = 0; n < interfaceDeclarations.GetLength(); n++ )
  1830. {
  1831. sClassDeclaration *intfDecl = interfaceDeclarations[n];
  1832. asCObjectType *intfType = intfDecl->objType;
  1833. // As new interfaces will be added to the end of the list, all
  1834. // interfaces will be traversed the same as recursively
  1835. for( asUINT m = 0; m < intfType->interfaces.GetLength(); m++ )
  1836. {
  1837. asCObjectType *base = intfType->interfaces[m];
  1838. // Add any interfaces not already implemented
  1839. for( asUINT l = 0; l < base->interfaces.GetLength(); l++ )
  1840. AddInterfaceToClass(intfDecl, intfDecl->node, base->interfaces[l]);
  1841. // Add the methods from the implemented interface
  1842. for( asUINT m = 0; m < base->methods.GetLength(); m++ )
  1843. {
  1844. // If the derived interface implements the same method, then don't add the base interface' method
  1845. asCScriptFunction *baseFunc = GetFunctionDescription(base->methods[m]);
  1846. asCScriptFunction *derivedFunc = 0;
  1847. bool found = false;
  1848. for( asUINT d = 0; d < intfType->methods.GetLength(); d++ )
  1849. {
  1850. derivedFunc = GetFunctionDescription(intfType->methods[d]);
  1851. if( derivedFunc->IsSignatureEqual(baseFunc) )
  1852. {
  1853. found = true;
  1854. break;
  1855. }
  1856. }
  1857. if( !found )
  1858. {
  1859. // Add the method
  1860. intfType->methods.PushLast(baseFunc->id);
  1861. baseFunc->AddRef();
  1862. }
  1863. }
  1864. }
  1865. }
  1866. }
  1867. void asCBuilder::CompileClasses()
  1868. {
  1869. asUINT n;
  1870. asCArray<sClassDeclaration*> toValidate((int)classDeclarations.GetLength());
  1871. // Determine class inheritances and interfaces
  1872. for( n = 0; n < classDeclarations.GetLength(); n++ )
  1873. {
  1874. sClassDeclaration *decl = classDeclarations[n];
  1875. asCScriptCode *file = decl->script;
  1876. // Find the base class that this class inherits from
  1877. bool multipleInheritance = false;
  1878. asCScriptNode *node = decl->node->firstChild;
  1879. if( decl->objType->IsShared() )
  1880. {
  1881. // Skip the keyword 'shared'
  1882. asASSERT(node->tokenType == ttIdentifier);
  1883. node = node->next;
  1884. }
  1885. if( decl->objType->flags & asOBJ_NOINHERIT )
  1886. {
  1887. // skip the keyword 'final'
  1888. asASSERT(node->tokenType == ttIdentifier);
  1889. node = node->next;
  1890. }
  1891. // Skip the name of the class
  1892. asASSERT(node->tokenType == ttIdentifier);
  1893. node = node->next;
  1894. while( node && node->nodeType == snIdentifier )
  1895. {
  1896. asSNameSpace *ns;
  1897. asCString name;
  1898. if( GetNamespaceAndNameFromNode(node, file, decl->objType->nameSpace, ns, name) < 0 )
  1899. {
  1900. node = node->next;
  1901. continue;
  1902. }
  1903. // Find the object type for the interface
  1904. asCObjectType *objType = GetObjectType(name.AddressOf(), ns);
  1905. if( objType == 0 )
  1906. {
  1907. // Check if the name is a mixin class
  1908. sMixinClass *mixin = GetMixinClass(name.AddressOf(), ns);
  1909. if( !mixin )
  1910. {
  1911. asCString str;
  1912. str.Format(TXT_IDENTIFIER_s_NOT_DATA_TYPE, name.AddressOf());
  1913. WriteError(str, file, node);
  1914. }
  1915. else
  1916. AddInterfaceFromMixinToClass(decl, node, mixin);
  1917. }
  1918. else if( !(objType->flags & asOBJ_SCRIPT_OBJECT) ||
  1919. objType->flags & asOBJ_NOINHERIT )
  1920. {
  1921. // Either the class is not a script class or interface
  1922. // or the class has been declared as 'final'
  1923. asCString str;
  1924. str.Format(TXT_CANNOT_INHERIT_FROM_s_FINAL, objType->name.AddressOf());
  1925. WriteError(str, file, node);
  1926. }
  1927. else if( objType->size != 0 )
  1928. {
  1929. // The class inherits from another script class
  1930. if( !decl->isExistingShared && decl->objType->derivedFrom != 0 )
  1931. {
  1932. if( !multipleInheritance )
  1933. {
  1934. WriteError(TXT_CANNOT_INHERIT_FROM_MULTIPLE_CLASSES, file, node);
  1935. multipleInheritance = true;
  1936. }
  1937. }
  1938. else
  1939. {
  1940. // Make sure none of the base classes inherit from this one
  1941. asCObjectType *base = objType;
  1942. bool error = false;
  1943. while( base != 0 )
  1944. {
  1945. if( base == decl->objType )
  1946. {
  1947. WriteError(TXT_CANNOT_INHERIT_FROM_SELF, file, node);
  1948. error = true;
  1949. break;
  1950. }
  1951. base = base->derivedFrom;
  1952. }
  1953. if( !error )
  1954. {
  1955. // A shared type may only inherit from other shared types
  1956. if( (decl->objType->IsShared()) && !(objType->IsShared()) )
  1957. {
  1958. asCString msg;
  1959. msg.Format(TXT_SHARED_CANNOT_INHERIT_FROM_NON_SHARED_s, objType->name.AddressOf());
  1960. WriteError(msg, file, node);
  1961. error = true;
  1962. }
  1963. }
  1964. if( !error )
  1965. {
  1966. if( decl->isExistingShared )
  1967. {
  1968. // Verify that the base class is the same as the original shared type
  1969. if( decl->objType->derivedFrom != objType )
  1970. {
  1971. asCString str;
  1972. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, decl->objType->GetName());
  1973. WriteError(str, file, node);
  1974. }
  1975. }
  1976. else
  1977. {
  1978. // Set the base class
  1979. decl->objType->derivedFrom = objType;
  1980. objType->AddRef();
  1981. }
  1982. }
  1983. }
  1984. }
  1985. else
  1986. {
  1987. // The class implements an interface
  1988. AddInterfaceToClass(decl, node, objType);
  1989. }
  1990. node = node->next;
  1991. }
  1992. }
  1993. // Order class declarations so that base classes are compiled before derived classes.
  1994. // This will allow the derived classes to copy properties and methods in the next step.
  1995. for( n = 0; n < classDeclarations.GetLength(); n++ )
  1996. {
  1997. sClassDeclaration *decl = classDeclarations[n];
  1998. asCObjectType *derived = decl->objType;
  1999. asCObjectType *base = derived->derivedFrom;
  2000. if( base == 0 ) continue;
  2001. // If the base class is found after the derived class, then move the derived class to the end of the list
  2002. for( asUINT m = n+1; m < classDeclarations.GetLength(); m++ )
  2003. {
  2004. sClassDeclaration *declBase = classDeclarations[m];
  2005. if( base == declBase->objType )
  2006. {
  2007. classDeclarations.RemoveIndex(n);
  2008. classDeclarations.PushLast(decl);
  2009. // Decrease index so that we don't skip an entry
  2010. n--;
  2011. break;
  2012. }
  2013. }
  2014. }
  2015. // Go through each of the classes and register the object type descriptions
  2016. for( n = 0; n < classDeclarations.GetLength(); n++ )
  2017. {
  2018. sClassDeclaration *decl = classDeclarations[n];
  2019. if( decl->isExistingShared )
  2020. {
  2021. // Set the declaration as validated already, so that other
  2022. // types that contain this will accept this type
  2023. decl->validState = 1;
  2024. // We'll still validate the declaration to make sure nothing new is
  2025. // added to the shared class that wasn't there in the previous
  2026. // compilation. We do not care if something that is there in the previous
  2027. // declaration is not included in the new declaration though.
  2028. }
  2029. // Methods included from mixin classes should take precedence over inherited methods
  2030. IncludeMethodsFromMixins(decl);
  2031. // Add all properties and methods from the base class
  2032. if( !decl->isExistingShared && decl->objType->derivedFrom )
  2033. {
  2034. asCObjectType *baseType = decl->objType->derivedFrom;
  2035. // The derived class inherits all interfaces from the base class
  2036. for( unsigned int n = 0; n < baseType->interfaces.GetLength(); n++ )
  2037. {
  2038. if( !decl->objType->Implements(baseType->interfaces[n]) )
  2039. decl->objType->interfaces.PushLast(baseType->interfaces[n]);
  2040. }
  2041. // TODO: Need to check for name conflict with new class methods
  2042. // Copy properties from base class to derived class
  2043. for( asUINT p = 0; p < baseType->properties.GetLength(); p++ )
  2044. {
  2045. asCObjectProperty *prop = AddPropertyToClass(decl, baseType->properties[p]->name, baseType->properties[p]->type, baseType->properties[p]->isPrivate);
  2046. // The properties must maintain the same offset
  2047. asASSERT(prop && prop->byteOffset == baseType->properties[p]->byteOffset); UNUSED_VAR(prop);
  2048. }
  2049. // Copy methods from base class to derived class
  2050. for( asUINT m = 0; m < baseType->methods.GetLength(); m++ )
  2051. {
  2052. // If the derived class implements the same method, then don't add the base class' method
  2053. asCScriptFunction *baseFunc = GetFunctionDescription(baseType->methods[m]);
  2054. asCScriptFunction *derivedFunc = 0;
  2055. bool found = false;
  2056. for( asUINT d = 0; d < decl->objType->methods.GetLength(); d++ )
  2057. {
  2058. derivedFunc = GetFunctionDescription(decl->objType->methods[d]);
  2059. if( derivedFunc->IsSignatureEqual(baseFunc) )
  2060. {
  2061. if( baseFunc->IsFinal() )
  2062. {
  2063. asCString msg;
  2064. msg.Format(TXT_METHOD_CANNOT_OVERRIDE_s, baseFunc->GetDeclaration());
  2065. WriteError(msg, decl->script, decl->node);
  2066. }
  2067. // Move the function from the methods array to the virtualFunctionTable
  2068. decl->objType->methods.RemoveIndex(d);
  2069. decl->objType->virtualFunctionTable.PushLast(derivedFunc);
  2070. found = true;
  2071. break;
  2072. }
  2073. }
  2074. if( !found )
  2075. {
  2076. // Push the base class function on the virtual function table
  2077. decl->objType->virtualFunctionTable.PushLast(baseType->virtualFunctionTable[m]);
  2078. baseType->virtualFunctionTable[m]->AddRef();
  2079. }
  2080. decl->objType->methods.PushLast(baseType->methods[m]);
  2081. engine->scriptFunctions[baseType->methods[m]]->AddRef();
  2082. }
  2083. }
  2084. // Move this class' methods into the virtual function table
  2085. if( !decl->isExistingShared )
  2086. {
  2087. for( asUINT m = 0; m < decl->objType->methods.GetLength(); m++ )
  2088. {
  2089. asCScriptFunction *func = GetFunctionDescription(decl->objType->methods[m]);
  2090. if( func->funcType != asFUNC_VIRTUAL )
  2091. {
  2092. // Move the reference from the method list to the virtual function list
  2093. decl->objType->methods.RemoveIndex(m);
  2094. decl->objType->virtualFunctionTable.PushLast(func);
  2095. // Substitute the function description in the method list for a virtual method
  2096. // Make sure the methods are in the same order as the virtual function table
  2097. decl->objType->methods.PushLast(CreateVirtualFunction(func, (int)decl->objType->virtualFunctionTable.GetLength() - 1));
  2098. m--;
  2099. }
  2100. }
  2101. }
  2102. // Enumerate each of the declared properties
  2103. asCScriptNode *node = decl->node->firstChild->next;
  2104. if( decl->objType->IsShared() )
  2105. node = node->next;
  2106. if( decl->objType->flags & asOBJ_NOINHERIT )
  2107. node = node->next;
  2108. // Skip list of classes and interfaces
  2109. while( node && node->nodeType == snIdentifier )
  2110. node = node->next;
  2111. while( node )
  2112. {
  2113. if( node->nodeType == snDeclaration )
  2114. {
  2115. asCScriptNode *n = node->firstChild;
  2116. // Is the property declared as private?
  2117. bool isPrivate = false;
  2118. if( n && n->tokenType == ttPrivate )
  2119. {
  2120. isPrivate = true;
  2121. n = n->next;
  2122. }
  2123. // Determine the type of the property
  2124. asCScriptCode *file = decl->script;
  2125. asCDataType dt = CreateDataTypeFromNode(n, file, decl->objType->nameSpace);
  2126. if( decl->objType->IsShared() && dt.GetObjectType() && !dt.GetObjectType()->IsShared() )
  2127. {
  2128. asCString msg;
  2129. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, dt.GetObjectType()->name.AddressOf());
  2130. WriteError(msg, file, node);
  2131. }
  2132. if( dt.IsReadOnly() )
  2133. WriteError(TXT_PROPERTY_CANT_BE_CONST, file, node);
  2134. // Multiple properties can be declared separated by ,
  2135. n = n->next;
  2136. while( n )
  2137. {
  2138. asCString name(&file->code[n->tokenPos], n->tokenLength);
  2139. if( !decl->isExistingShared )
  2140. {
  2141. CheckNameConflictMember(decl->objType, name.AddressOf(), n, file, true);
  2142. AddPropertyToClass(decl, name, dt, isPrivate, file, n);
  2143. }
  2144. else
  2145. {
  2146. // Verify that the property exists in the original declaration
  2147. bool found = false;
  2148. for( asUINT p = 0; p < decl->objType->properties.GetLength(); p++ )
  2149. {
  2150. asCObjectProperty *prop = decl->objType->properties[p];
  2151. if( prop->isPrivate == isPrivate &&
  2152. prop->name == name &&
  2153. prop->type.IsEqualExceptRef(dt) )
  2154. {
  2155. found = true;
  2156. break;
  2157. }
  2158. }
  2159. if( !found )
  2160. {
  2161. asCString str;
  2162. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, decl->objType->GetName());
  2163. WriteError(str, file, n);
  2164. }
  2165. }
  2166. // Skip the initialization node
  2167. if( n->next && n->next->nodeType != snIdentifier )
  2168. n = n->next;
  2169. n = n->next;
  2170. }
  2171. }
  2172. else
  2173. asASSERT(false);
  2174. node = node->next;
  2175. }
  2176. // Add properties from included mixin classes that don't conflict with existing properties
  2177. IncludePropertiesFromMixins(decl);
  2178. if( !decl->isExistingShared )
  2179. toValidate.PushLast(decl);
  2180. }
  2181. // TODO: Warn if a method overrides a base method without marking it as 'override'.
  2182. // It must be possible to turn off this warning through engine property.
  2183. // TODO: A base class should be able to mark a method as 'abstract'. This will
  2184. // allow a base class to provide a partial implementation, but still force
  2185. // derived classes to implement specific methods.
  2186. // Verify that all interface methods are implemented in the classes
  2187. // We do this here so the base class' methods have already been inherited
  2188. for( n = 0; n < classDeclarations.GetLength(); n++ )
  2189. {
  2190. sClassDeclaration *decl = classDeclarations[n];
  2191. if( decl->isExistingShared ) continue;
  2192. asCArray<bool> overrideValidations(decl->objType->GetMethodCount());
  2193. for( asUINT k = 0; k < decl->objType->methods.GetLength(); k++ )
  2194. overrideValidations.PushLast( !static_cast<asCScriptFunction*>(decl->objType->GetMethodByIndex(k, false))->IsOverride() );
  2195. for( asUINT m = 0; m < decl->objType->interfaces.GetLength(); m++ )
  2196. {
  2197. asCObjectType *objType = decl->objType->interfaces[m];
  2198. for( asUINT i = 0; i < objType->methods.GetLength(); i++ )
  2199. {
  2200. // Only check the interface methods that was explicitly declared in this interface
  2201. // Methods that was inherited from other interfaces will be checked in those interfaces
  2202. if( objType != engine->scriptFunctions[objType->methods[i]]->objectType )
  2203. continue;
  2204. asUINT overrideIndex;
  2205. if( !DoesMethodExist(decl->objType, objType->methods[i], &overrideIndex) )
  2206. {
  2207. asCString str;
  2208. str.Format(TXT_MISSING_IMPLEMENTATION_OF_s,
  2209. engine->GetFunctionDeclaration(objType->methods[i]).AddressOf());
  2210. WriteError(str, decl->script, decl->node);
  2211. }
  2212. else
  2213. overrideValidations[overrideIndex] = true;
  2214. }
  2215. }
  2216. bool hasBaseClass = decl->objType->derivedFrom != 0;
  2217. for( asUINT j = 0; j < overrideValidations.GetLength(); j++ )
  2218. {
  2219. if( !overrideValidations[j] && (!hasBaseClass || !DoesMethodExist(decl->objType->derivedFrom, decl->objType->methods[j])) )
  2220. {
  2221. asCString msg;
  2222. msg.Format(TXT_METHOD_s_DOES_NOT_OVERRIDE, decl->objType->GetMethodByIndex(j, false)->GetDeclaration());
  2223. WriteError(msg, decl->script, decl->node);
  2224. }
  2225. }
  2226. }
  2227. // Verify that the declared structures are valid, e.g. that the structure
  2228. // doesn't contain a member of its own type directly or indirectly
  2229. while( toValidate.GetLength() > 0 )
  2230. {
  2231. asUINT numClasses = (asUINT)toValidate.GetLength();
  2232. asCArray<sClassDeclaration*> toValidateNext((int)toValidate.GetLength());
  2233. while( toValidate.GetLength() > 0 )
  2234. {
  2235. sClassDeclaration *decl = toValidate[toValidate.GetLength()-1];
  2236. int validState = 1;
  2237. for( asUINT n = 0; n < decl->objType->properties.GetLength(); n++ )
  2238. {
  2239. // A valid structure is one that uses only primitives or other valid objects
  2240. asCObjectProperty *prop = decl->objType->properties[n];
  2241. asCDataType dt = prop->type;
  2242. if( dt.IsTemplate() )
  2243. {
  2244. asCDataType sub = dt;
  2245. while( sub.IsTemplate() && !sub.IsObjectHandle() )
  2246. sub = sub.GetSubType();
  2247. dt = sub;
  2248. }
  2249. if( dt.IsObject() && !dt.IsObjectHandle() )
  2250. {
  2251. // Find the class declaration
  2252. sClassDeclaration *pdecl = 0;
  2253. for( asUINT p = 0; p < classDeclarations.GetLength(); p++ )
  2254. {
  2255. if( classDeclarations[p]->objType == dt.GetObjectType() )
  2256. {
  2257. pdecl = classDeclarations[p];
  2258. break;
  2259. }
  2260. }
  2261. if( pdecl )
  2262. {
  2263. if( pdecl->objType == decl->objType )
  2264. {
  2265. WriteError(TXT_ILLEGAL_MEMBER_TYPE, decl->script, decl->node);
  2266. validState = 2;
  2267. break;
  2268. }
  2269. else if( pdecl->validState != 1 )
  2270. {
  2271. validState = pdecl->validState;
  2272. break;
  2273. }
  2274. }
  2275. }
  2276. }
  2277. if( validState == 1 )
  2278. {
  2279. decl->validState = 1;
  2280. toValidate.PopLast();
  2281. }
  2282. else if( validState == 2 )
  2283. {
  2284. decl->validState = 2;
  2285. toValidate.PopLast();
  2286. }
  2287. else
  2288. {
  2289. toValidateNext.PushLast(toValidate.PopLast());
  2290. }
  2291. }
  2292. toValidate = toValidateNext;
  2293. toValidateNext.SetLength(0);
  2294. if( numClasses == toValidate.GetLength() )
  2295. {
  2296. WriteError(TXT_ILLEGAL_MEMBER_TYPE, toValidate[0]->script, toValidate[0]->node);
  2297. break;
  2298. }
  2299. }
  2300. if( numErrors > 0 ) return;
  2301. // Verify which script classes can really form circular references, and mark only those as garbage collected.
  2302. // TODO: runtime optimize: This algorithm can be further improved by checking the types that inherits from
  2303. // a base class. If the base class is not shared all the classes that derive from it
  2304. // are known at compile time, and can thus be checked for potential circular references too.
  2305. //
  2306. // Observe, that doing this would conflict with another potential future feature, which is to
  2307. // allow incremental builds, i.e. allow application to add or replace classes in an
  2308. // existing module. However, the applications that want to use that should use a special
  2309. // build flag to not finalize the module.
  2310. // Urho3D: disable garbage collection from script classes
  2311. /*
  2312. for( n = 0; n < classDeclarations.GetLength(); n++ )
  2313. {
  2314. sClassDeclaration *decl = classDeclarations[n];
  2315. // Existing shared classes won't be re-evaluated
  2316. if( decl->isExistingShared ) continue;
  2317. asCObjectType *ot = decl->objType;
  2318. // Is there some path in which this structure is involved in circular references?
  2319. bool gc = false;
  2320. for( asUINT p = 0; p < ot->properties.GetLength(); p++ )
  2321. {
  2322. asCDataType dt = ot->properties[p]->type;
  2323. if( !dt.IsObject() )
  2324. continue;
  2325. if( dt.IsObjectHandle() )
  2326. {
  2327. // If it is known that the handle can't be involved in a circular reference
  2328. // then this object doesn't need to be marked as garbage collected.
  2329. asCObjectType *prop = dt.GetObjectType();
  2330. if( prop->flags & asOBJ_SCRIPT_OBJECT )
  2331. {
  2332. // For script objects, treat non-final classes as if they can contain references
  2333. // as it is not known what derived classes might do. For final types, check all
  2334. // properties to determine if any of those can cause a circular reference.
  2335. if( prop->flags & asOBJ_NOINHERIT )
  2336. {
  2337. for( asUINT sp = 0; sp < prop->properties.GetLength(); sp++ )
  2338. {
  2339. asCDataType sdt = prop->properties[sp]->type;
  2340. if( sdt.IsObject() )
  2341. {
  2342. if( sdt.IsObjectHandle() )
  2343. {
  2344. // TODO: runtime optimize: If the handle is again to a final class, then we can recursively check if the circular reference can occur
  2345. if( sdt.GetObjectType()->flags & (asOBJ_SCRIPT_OBJECT | asOBJ_GC) )
  2346. {
  2347. gc = true;
  2348. break;
  2349. }
  2350. }
  2351. else if( sdt.GetObjectType()->flags & asOBJ_GC )
  2352. {
  2353. // TODO: runtime optimize: Just because the member type is a potential circle doesn't mean that this one is.
  2354. // Only if the object is of a type that can reference this type, either directly or indirectly
  2355. gc = true;
  2356. break;
  2357. }
  2358. }
  2359. }
  2360. if( gc )
  2361. break;
  2362. }
  2363. else
  2364. {
  2365. // Assume it is garbage collected as it is not known at compile time what might inherit from this type
  2366. gc = true;
  2367. break;
  2368. }
  2369. }
  2370. else if( prop->flags & asOBJ_GC )
  2371. {
  2372. // If a type is not a script object, adopt its GC flag
  2373. gc = true;
  2374. break;
  2375. }
  2376. }
  2377. else if( dt.GetObjectType()->flags & asOBJ_GC )
  2378. {
  2379. // TODO: runtime optimize: Just because the member type is a potential circle doesn't mean that this one is.
  2380. // Only if the object is of a type that can reference this type, either directly or indirectly
  2381. gc = true;
  2382. break;
  2383. }
  2384. }
  2385. // Update the flag in the object type
  2386. if( gc )
  2387. ot->flags |= asOBJ_GC;
  2388. else
  2389. ot->flags &= ~asOBJ_GC;
  2390. }
  2391. */
  2392. }
  2393. void asCBuilder::IncludeMethodsFromMixins(sClassDeclaration *decl)
  2394. {
  2395. asCScriptNode *node = decl->node->firstChild;
  2396. // Skip the 'final' and 'shared' keywords
  2397. if( decl->objType->IsShared() )
  2398. node = node->next;
  2399. if( decl->objType->flags & asOBJ_NOINHERIT )
  2400. node = node->next;
  2401. // Skip the name of the class
  2402. node = node->next;
  2403. // Find the included mixin classes
  2404. while( node && node->nodeType == snIdentifier )
  2405. {
  2406. asSNameSpace *ns;
  2407. asCString name;
  2408. if( GetNamespaceAndNameFromNode(node, decl->script, decl->objType->nameSpace, ns, name) < 0 )
  2409. {
  2410. node = node->next;
  2411. continue;
  2412. }
  2413. sMixinClass *mixin = GetMixinClass(name.AddressOf(), ns);
  2414. if( mixin )
  2415. {
  2416. // Find methods from mixin declaration
  2417. asCScriptNode *n = mixin->node->firstChild;
  2418. // Skip to the member declarations
  2419. // Possible keywords 'final' and 'shared' are removed in RegisterMixinClass so we don't need to worry about those here
  2420. while( n && n->nodeType == snIdentifier )
  2421. n = n->next;
  2422. // Add methods from the mixin that are not already existing in the class
  2423. while( n )
  2424. {
  2425. if( n->nodeType == snFunction )
  2426. {
  2427. // Instead of disconnecting the node, we need to clone it, otherwise other
  2428. // classes that include the same mixin will not see the methods
  2429. asCScriptNode *copy = n->CreateCopy(engine);
  2430. // Register the method, but only if it doesn't already exist in the class
  2431. RegisterScriptFunctionFromNode(copy, mixin->script, decl->objType, false, false, 0, false, true);
  2432. }
  2433. else if( n->nodeType == snVirtualProperty )
  2434. {
  2435. // TODO: mixin: Support virtual properties too
  2436. WriteError("The virtual property syntax is currently not supported for mixin classes", mixin->script, n);
  2437. //RegisterVirtualProperty(node, decl->script, decl->objType, false, false);
  2438. }
  2439. n = n->next;
  2440. }
  2441. }
  2442. node = node->next;
  2443. }
  2444. }
  2445. void asCBuilder::IncludePropertiesFromMixins(sClassDeclaration *decl)
  2446. {
  2447. asCScriptNode *node = decl->node->firstChild;
  2448. // Skip the 'final' and 'shared' keywords
  2449. if( decl->objType->IsShared() )
  2450. node = node->next;
  2451. if( decl->objType->flags & asOBJ_NOINHERIT )
  2452. node = node->next;
  2453. // Skip the name of the class
  2454. node = node->next;
  2455. // Find the included mixin classes
  2456. while( node && node->nodeType == snIdentifier )
  2457. {
  2458. asSNameSpace *ns;
  2459. asCString name;
  2460. if( GetNamespaceAndNameFromNode(node, decl->script, decl->objType->nameSpace, ns, name) < 0 )
  2461. {
  2462. node = node->next;
  2463. continue;
  2464. }
  2465. sMixinClass *mixin = GetMixinClass(name.AddressOf(), ns);
  2466. if( mixin )
  2467. {
  2468. // Find properties from mixin declaration
  2469. asCScriptNode *n = mixin->node->firstChild;
  2470. // Skip to the member declarations
  2471. // Possible keywords 'final' and 'shared' are removed in RegisterMixinClass so we don't need to worry about those here
  2472. while( n && n->nodeType == snIdentifier )
  2473. n = n->next;
  2474. // Add properties from the mixin that are not already existing in the class
  2475. while( n )
  2476. {
  2477. if( n->nodeType == snDeclaration )
  2478. {
  2479. asCScriptNode *n2 = n->firstChild;
  2480. bool isPrivate = false;
  2481. if( n2 && n2->tokenType == ttPrivate )
  2482. {
  2483. isPrivate = true;
  2484. n2 = n2->next;
  2485. }
  2486. asCScriptCode *file = mixin->script;
  2487. asCDataType dt = CreateDataTypeFromNode(n2, file, mixin->ns);
  2488. if( decl->objType->IsShared() && dt.GetObjectType() && !dt.GetObjectType()->IsShared() )
  2489. {
  2490. asCString msg;
  2491. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, dt.GetObjectType()->name.AddressOf());
  2492. WriteError(msg, file, n);
  2493. WriteInfo(TXT_WHILE_INCLUDING_MIXIN, decl->script, node);
  2494. }
  2495. if( dt.IsReadOnly() )
  2496. WriteError(TXT_PROPERTY_CANT_BE_CONST, file, n);
  2497. n2 = n2->next;
  2498. while( n2 )
  2499. {
  2500. asCString name(&file->code[n2->tokenPos], n2->tokenLength);
  2501. // Add the property only if it doesn't already exist in the class
  2502. bool exists = false;
  2503. for( asUINT p = 0; p < decl->objType->properties.GetLength(); p++ )
  2504. if( decl->objType->properties[p]->name == name )
  2505. {
  2506. exists = true;
  2507. break;
  2508. }
  2509. if( !exists )
  2510. {
  2511. if( !decl->isExistingShared )
  2512. {
  2513. // It must not conflict with the name of methods
  2514. int r = CheckNameConflictMember(decl->objType, name.AddressOf(), n2, file, true);
  2515. if( r < 0 )
  2516. WriteInfo(TXT_WHILE_INCLUDING_MIXIN, decl->script, node);
  2517. AddPropertyToClass(decl, name, dt, isPrivate, file, n2);
  2518. }
  2519. else
  2520. {
  2521. // Verify that the property exists in the original declaration
  2522. bool found = false;
  2523. for( asUINT p = 0; p < decl->objType->properties.GetLength(); p++ )
  2524. {
  2525. asCObjectProperty *prop = decl->objType->properties[p];
  2526. if( prop->isPrivate == isPrivate &&
  2527. prop->name == name &&
  2528. prop->type == dt )
  2529. {
  2530. found = true;
  2531. break;
  2532. }
  2533. }
  2534. if( !found )
  2535. {
  2536. asCString str;
  2537. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, decl->objType->GetName());
  2538. WriteError(str, decl->script, decl->node);
  2539. WriteInfo(TXT_WHILE_INCLUDING_MIXIN, decl->script, node);
  2540. }
  2541. }
  2542. }
  2543. // Skip the initialization expression
  2544. if( n2->next && n2->next->nodeType != snIdentifier )
  2545. n2 = n2->next;
  2546. n2 = n2->next;
  2547. }
  2548. }
  2549. n = n->next;
  2550. }
  2551. }
  2552. node = node->next;
  2553. }
  2554. }
  2555. int asCBuilder::CreateVirtualFunction(asCScriptFunction *func, int idx)
  2556. {
  2557. asCScriptFunction *vf = asNEW(asCScriptFunction)(engine, module, asFUNC_VIRTUAL);
  2558. if( vf == 0 )
  2559. return asOUT_OF_MEMORY;
  2560. vf->name = func->name;
  2561. vf->returnType = func->returnType;
  2562. vf->parameterTypes = func->parameterTypes;
  2563. vf->inOutFlags = func->inOutFlags;
  2564. vf->id = engine->GetNextScriptFunctionId();
  2565. vf->scriptSectionIdx = func->scriptSectionIdx;
  2566. vf->isReadOnly = func->isReadOnly;
  2567. vf->objectType = func->objectType;
  2568. vf->signatureId = func->signatureId;
  2569. vf->isPrivate = func->isPrivate;
  2570. vf->isFinal = func->isFinal;
  2571. vf->isOverride = func->isOverride;
  2572. vf->vfTableIdx = idx;
  2573. vf->defaultArgs = func->defaultArgs;
  2574. // Copy the default arg strings to avoid multiple deletes on the same object
  2575. for( asUINT n = 0; n < vf->defaultArgs.GetLength(); n++ )
  2576. if( vf->defaultArgs[n] )
  2577. vf->defaultArgs[n] = asNEW(asCString)(*vf->defaultArgs[n]);
  2578. module->AddScriptFunction(vf);
  2579. // Add a dummy to the builder so that it doesn't mix up function ids
  2580. functions.PushLast(0);
  2581. return vf->id;
  2582. }
  2583. asCObjectProperty *asCBuilder::AddPropertyToClass(sClassDeclaration *decl, const asCString &name, const asCDataType &dt, bool isPrivate, asCScriptCode *file, asCScriptNode *node)
  2584. {
  2585. // If the declaration node is not given, then
  2586. // this property is inherited from a base class
  2587. if( node )
  2588. {
  2589. // Check if the property is allowed
  2590. if( !dt.CanBeInstanciated() )
  2591. {
  2592. if( file && node )
  2593. {
  2594. asCString str;
  2595. str.Format(TXT_DATA_TYPE_CANT_BE_s, dt.Format().AddressOf());
  2596. WriteError(str, file, node);
  2597. }
  2598. return 0;
  2599. }
  2600. // Register the initialization expression (if any) to be compiled later
  2601. asCScriptNode *declNode = node;
  2602. asCScriptNode *initNode = 0;
  2603. if( node->next && node->next->nodeType != snIdentifier )
  2604. {
  2605. asASSERT( node->next->nodeType == snAssignment );
  2606. initNode = node->next;
  2607. }
  2608. sPropertyInitializer p(name, declNode, initNode, file);
  2609. decl->propInits.PushLast(p);
  2610. }
  2611. // Add the property to the object type
  2612. return decl->objType->AddPropertyToClass(name, dt, isPrivate);
  2613. }
  2614. bool asCBuilder::DoesMethodExist(asCObjectType *objType, int methodId, asUINT *methodIndex)
  2615. {
  2616. asCScriptFunction *method = GetFunctionDescription(methodId);
  2617. for( asUINT n = 0; n < objType->methods.GetLength(); n++ )
  2618. {
  2619. asCScriptFunction *m = GetFunctionDescription(objType->methods[n]);
  2620. if( m->name != method->name ) continue;
  2621. if( m->returnType != method->returnType ) continue;
  2622. if( m->isReadOnly != method->isReadOnly ) continue;
  2623. if( m->parameterTypes != method->parameterTypes ) continue;
  2624. if( m->inOutFlags != method->inOutFlags ) continue;
  2625. if( methodIndex )
  2626. *methodIndex = n;
  2627. return true;
  2628. }
  2629. return false;
  2630. }
  2631. void asCBuilder::AddDefaultConstructor(asCObjectType *objType, asCScriptCode *file)
  2632. {
  2633. int funcId = engine->GetNextScriptFunctionId();
  2634. asCDataType returnType = asCDataType::CreatePrimitive(ttVoid, false);
  2635. asCArray<asCDataType> parameterTypes;
  2636. asCArray<asETypeModifiers> inOutFlags;
  2637. asCArray<asCString *> defaultArgs;
  2638. // Add the script function
  2639. module->AddScriptFunction(file->idx, funcId, objType->name, returnType, parameterTypes, inOutFlags, defaultArgs, false, objType);
  2640. // Set it as default constructor
  2641. if( objType->beh.construct )
  2642. engine->scriptFunctions[objType->beh.construct]->Release();
  2643. objType->beh.construct = funcId;
  2644. objType->beh.constructors[0] = funcId;
  2645. engine->scriptFunctions[funcId]->AddRef();
  2646. // The bytecode for the default constructor will be generated
  2647. // only after the potential inheritance has been established
  2648. sFunctionDescription *func = asNEW(sFunctionDescription);
  2649. if( func == 0 )
  2650. {
  2651. // Out of memory
  2652. return;
  2653. }
  2654. functions.PushLast(func);
  2655. func->script = file;
  2656. func->node = 0;
  2657. func->name = objType->name;
  2658. func->objType = objType;
  2659. func->funcId = funcId;
  2660. func->isExistingShared = false;
  2661. // Add a default factory as well
  2662. funcId = engine->GetNextScriptFunctionId();
  2663. if( objType->beh.factory )
  2664. engine->scriptFunctions[objType->beh.factory]->Release();
  2665. objType->beh.factory = funcId;
  2666. objType->beh.factories[0] = funcId;
  2667. returnType = asCDataType::CreateObjectHandle(objType, false);
  2668. module->AddScriptFunction(file->idx, funcId, objType->name, returnType, parameterTypes, inOutFlags, defaultArgs, false);
  2669. functions.PushLast(0);
  2670. asCCompiler compiler(engine);
  2671. compiler.CompileFactory(this, file, engine->scriptFunctions[funcId]);
  2672. engine->scriptFunctions[funcId]->AddRef();
  2673. // If the object is shared, then the factory must also be marked as shared
  2674. if( objType->flags & asOBJ_SHARED )
  2675. engine->scriptFunctions[funcId]->isShared = true;
  2676. }
  2677. int asCBuilder::RegisterEnum(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns)
  2678. {
  2679. // Is it a shared enum?
  2680. bool isShared = false;
  2681. asCObjectType *existingSharedType = 0;
  2682. asCScriptNode *tmp = node->firstChild;
  2683. if( tmp->nodeType == snIdentifier && file->TokenEquals(tmp->tokenPos, tmp->tokenLength, SHARED_TOKEN) )
  2684. {
  2685. isShared = true;
  2686. tmp = tmp->next;
  2687. }
  2688. // Grab the name of the enumeration
  2689. asCString name;
  2690. asASSERT(snDataType == tmp->nodeType);
  2691. asASSERT(snIdentifier == tmp->firstChild->nodeType);
  2692. name.Assign(&file->code[tmp->firstChild->tokenPos], tmp->firstChild->tokenLength);
  2693. if( isShared )
  2694. {
  2695. // Look for a pre-existing shared enum with the same signature
  2696. for( asUINT n = 0; n < engine->classTypes.GetLength(); n++ )
  2697. {
  2698. asCObjectType *o = engine->classTypes[n];
  2699. if( o &&
  2700. o->IsShared() &&
  2701. (o->flags & asOBJ_ENUM) &&
  2702. o->name == name &&
  2703. o->nameSpace == ns )
  2704. {
  2705. existingSharedType = o;
  2706. break;
  2707. }
  2708. }
  2709. }
  2710. // Check the name and add the enum
  2711. int r = CheckNameConflict(name.AddressOf(), tmp->firstChild, file, ns);
  2712. if( asSUCCESS == r )
  2713. {
  2714. asCObjectType *st;
  2715. if( existingSharedType )
  2716. st = existingSharedType;
  2717. else
  2718. {
  2719. st = asNEW(asCObjectType)(engine);
  2720. if( st == 0 )
  2721. return asOUT_OF_MEMORY;
  2722. st->flags = asOBJ_ENUM;
  2723. if( isShared )
  2724. st->flags |= asOBJ_SHARED;
  2725. st->size = 4;
  2726. st->name = name;
  2727. st->nameSpace = ns;
  2728. }
  2729. module->enumTypes.PushLast(st);
  2730. st->AddRef();
  2731. // TODO: cleanup: Should the enum type really be stored in the engine->classTypes?
  2732. // http://www.gamedev.net/topic/616912-c-header-file-shared-with-scripts/page__gopid__4895940
  2733. if( !existingSharedType )
  2734. engine->classTypes.PushLast(st);
  2735. // Store the location of this declaration for reference in name collisions
  2736. sClassDeclaration *decl = asNEW(sClassDeclaration);
  2737. if( decl == 0 )
  2738. return asOUT_OF_MEMORY;
  2739. decl->name = name;
  2740. decl->script = file;
  2741. decl->objType = st;
  2742. namedTypeDeclarations.PushLast(decl);
  2743. asCDataType type = CreateDataTypeFromNode(tmp, file, ns);
  2744. asASSERT(!type.IsReference());
  2745. // Register the enum values
  2746. tmp = tmp->next;
  2747. while( tmp )
  2748. {
  2749. asASSERT(snIdentifier == tmp->nodeType);
  2750. asCString name(&file->code[tmp->tokenPos], tmp->tokenLength);
  2751. if( existingSharedType )
  2752. {
  2753. // If this is a pre-existent shared enum, then just double check
  2754. // that the value is already defined in the original declaration
  2755. bool found = false;
  2756. for( size_t n = 0; n < st->enumValues.GetLength(); n++ )
  2757. if( st->enumValues[n]->name == name )
  2758. {
  2759. found = true;
  2760. break;
  2761. }
  2762. if( !found )
  2763. {
  2764. asCString str;
  2765. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, st->GetName());
  2766. WriteError(str, file, tmp);
  2767. break;
  2768. }
  2769. tmp = tmp->next;
  2770. if( tmp && tmp->nodeType == snAssignment )
  2771. tmp = tmp->next;
  2772. continue;
  2773. }
  2774. else
  2775. {
  2776. // Check for name conflict errors with other values in the enum
  2777. if( globVariables.GetFirst(ns, name, asCCompGlobVarType(type)) )
  2778. {
  2779. asCString str;
  2780. str.Format(TXT_NAME_CONFLICT_s_ALREADY_USED, name.AddressOf());
  2781. WriteError(str, file, tmp);
  2782. tmp = tmp->next;
  2783. if( tmp && tmp->nodeType == snAssignment )
  2784. tmp = tmp->next;
  2785. continue;
  2786. }
  2787. // Check for assignment
  2788. asCScriptNode *asnNode = tmp->next;
  2789. if( asnNode && snAssignment == asnNode->nodeType )
  2790. asnNode->DisconnectParent();
  2791. else
  2792. asnNode = 0;
  2793. // Create the global variable description so the enum value can be evaluated
  2794. sGlobalVariableDescription *gvar = asNEW(sGlobalVariableDescription);
  2795. if( gvar == 0 )
  2796. return asOUT_OF_MEMORY;
  2797. gvar->script = file;
  2798. gvar->idNode = 0;
  2799. gvar->nextNode = asnNode;
  2800. gvar->name = name;
  2801. gvar->datatype = type;
  2802. // No need to allocate space on the global memory stack since the values are stored in the asCObjectType
  2803. gvar->index = 0;
  2804. gvar->isCompiled = false;
  2805. gvar->isPureConstant = true;
  2806. gvar->isEnumValue = true;
  2807. gvar->constantValue = 0xdeadbeef;
  2808. // Allocate dummy property so we can compile the value.
  2809. // This will be removed later on so we don't add it to the engine.
  2810. gvar->property = asNEW(asCGlobalProperty);
  2811. if( gvar->property == 0 )
  2812. return asOUT_OF_MEMORY;
  2813. gvar->property->name = name;
  2814. gvar->property->nameSpace = ns;
  2815. gvar->property->type = gvar->datatype;
  2816. gvar->property->id = 0;
  2817. globVariables.Put(gvar);
  2818. tmp = tmp->next;
  2819. }
  2820. }
  2821. }
  2822. node->Destroy(engine);
  2823. return r;
  2824. }
  2825. int asCBuilder::RegisterTypedef(asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns)
  2826. {
  2827. // Get the native data type
  2828. asCScriptNode *tmp = node->firstChild;
  2829. asASSERT(NULL != tmp && snDataType == tmp->nodeType);
  2830. asCDataType dataType;
  2831. dataType.CreatePrimitive(tmp->tokenType, false);
  2832. dataType.SetTokenType(tmp->tokenType);
  2833. tmp = tmp->next;
  2834. // Grab the name of the typedef
  2835. asASSERT(NULL != tmp && NULL == tmp->next);
  2836. asCString name;
  2837. name.Assign(&file->code[tmp->tokenPos], tmp->tokenLength);
  2838. // If the name is not already in use add it
  2839. int r = CheckNameConflict(name.AddressOf(), tmp, file, ns);
  2840. asCObjectType *st = 0;
  2841. if( asSUCCESS == r )
  2842. {
  2843. // Create the new type
  2844. st = asNEW(asCObjectType)(engine);
  2845. if( st == 0 )
  2846. r = asOUT_OF_MEMORY;
  2847. }
  2848. if( asSUCCESS == r )
  2849. {
  2850. st->flags = asOBJ_TYPEDEF;
  2851. st->size = dataType.GetSizeInMemoryBytes();
  2852. st->name = name;
  2853. st->nameSpace = ns;
  2854. st->templateSubTypes.PushLast(dataType);
  2855. st->AddRef();
  2856. module->typeDefs.PushLast(st);
  2857. engine->classTypes.PushLast(st);
  2858. // Store the location of this declaration for reference in name collisions
  2859. sClassDeclaration *decl = asNEW(sClassDeclaration);
  2860. if( decl == 0 )
  2861. r = asOUT_OF_MEMORY;
  2862. else
  2863. {
  2864. decl->name = name;
  2865. decl->script = file;
  2866. decl->objType = st;
  2867. namedTypeDeclarations.PushLast(decl);
  2868. }
  2869. }
  2870. node->Destroy(engine);
  2871. return r;
  2872. }
  2873. 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)
  2874. {
  2875. node = node->firstChild;
  2876. // Is the function a private class method?
  2877. isPrivate = false;
  2878. if( node->tokenType == ttPrivate )
  2879. {
  2880. isPrivate = true;
  2881. node = node->next;
  2882. }
  2883. // Is the function shared?
  2884. isShared = false;
  2885. if( node->tokenType == ttIdentifier && file->TokenEquals(node->tokenPos, node->tokenLength, SHARED_TOKEN) )
  2886. {
  2887. isShared = true;
  2888. node = node->next;
  2889. }
  2890. // Find the name
  2891. isConstructor = false;
  2892. isDestructor = false;
  2893. asCScriptNode *n = 0;
  2894. if( node->nodeType == snDataType )
  2895. n = node->next->next;
  2896. else
  2897. {
  2898. // If the first node is a ~ token, then we know it is a destructor
  2899. if( node->tokenType == ttBitNot )
  2900. {
  2901. n = node->next;
  2902. isDestructor = true;
  2903. }
  2904. else
  2905. {
  2906. n = node;
  2907. isConstructor = true;
  2908. }
  2909. }
  2910. name.Assign(&file->code[n->tokenPos], n->tokenLength);
  2911. // Initialize a script function object for registration
  2912. if( !isConstructor && !isDestructor )
  2913. {
  2914. returnType = CreateDataTypeFromNode(node, file, implicitNamespace);
  2915. returnType = ModifyDataTypeFromNode(returnType, node->next, file, 0, 0);
  2916. if( engine->ep.disallowValueAssignForRefType &&
  2917. returnType.GetObjectType() &&
  2918. (returnType.GetObjectType()->flags & asOBJ_REF) &&
  2919. !(returnType.GetObjectType()->flags & asOBJ_SCOPED) &&
  2920. !returnType.IsReference() &&
  2921. !returnType.IsObjectHandle() )
  2922. {
  2923. WriteError(TXT_REF_TYPE_CANT_BE_RETURNED_BY_VAL, file, node);
  2924. }
  2925. }
  2926. else
  2927. returnType = asCDataType::CreatePrimitive(ttVoid, false);
  2928. isConstMethod = false;
  2929. isFinal = false;
  2930. isOverride = false;
  2931. if( objType && n->next->next )
  2932. {
  2933. asCScriptNode *decorator = n->next->next;
  2934. // Is this a const method?
  2935. if( decorator->tokenType == ttConst )
  2936. {
  2937. isConstMethod = true;
  2938. decorator = decorator->next;
  2939. }
  2940. while( decorator )
  2941. {
  2942. if( decorator->tokenType == ttIdentifier && file->TokenEquals(decorator->tokenPos, decorator->tokenLength, FINAL_TOKEN) )
  2943. isFinal = true;
  2944. else if( decorator->tokenType == ttIdentifier && file->TokenEquals(decorator->tokenPos, decorator->tokenLength, OVERRIDE_TOKEN) )
  2945. isOverride = true;
  2946. decorator = decorator->next;
  2947. }
  2948. }
  2949. // Count the number of parameters
  2950. int count = 0;
  2951. asCScriptNode *c = n->next->firstChild;
  2952. while( c )
  2953. {
  2954. count++;
  2955. c = c->next->next;
  2956. if( c && c->nodeType == snIdentifier )
  2957. c = c->next;
  2958. if( c && c->nodeType == snExpression )
  2959. c = c->next;
  2960. }
  2961. // Get the parameter types
  2962. parameterNames.Allocate(count, false);
  2963. parameterTypes.Allocate(count, false);
  2964. inOutFlags.Allocate(count, false);
  2965. defaultArgs.Allocate(count, false);
  2966. n = n->next->firstChild;
  2967. while( n )
  2968. {
  2969. asETypeModifiers inOutFlag;
  2970. asCDataType type = CreateDataTypeFromNode(n, file, implicitNamespace);
  2971. type = ModifyDataTypeFromNode(type, n->next, file, &inOutFlag, 0);
  2972. if( engine->ep.disallowValueAssignForRefType &&
  2973. type.GetObjectType() &&
  2974. (type.GetObjectType()->flags & asOBJ_REF) &&
  2975. !(type.GetObjectType()->flags & asOBJ_SCOPED) &&
  2976. !type.IsReference() &&
  2977. !type.IsObjectHandle() )
  2978. {
  2979. WriteError(TXT_REF_TYPE_CANT_BE_PASSED_BY_VAL, file, node);
  2980. }
  2981. // Store the parameter type
  2982. parameterTypes.PushLast(type);
  2983. inOutFlags.PushLast(inOutFlag);
  2984. // Move to next parameter
  2985. n = n->next->next;
  2986. if( n && n->nodeType == snIdentifier )
  2987. {
  2988. asCString name;
  2989. name.Assign(&file->code[n->tokenPos], n->tokenLength);
  2990. parameterNames.PushLast(name);
  2991. n = n->next;
  2992. }
  2993. else
  2994. {
  2995. // No name was given for the parameter
  2996. parameterNames.PushLast(asCString());
  2997. }
  2998. if( n && n->nodeType == snExpression )
  2999. {
  3000. // Strip out white space and comments to better share the string
  3001. asCString *defaultArgStr = asNEW(asCString);
  3002. if( defaultArgStr )
  3003. *defaultArgStr = GetCleanExpressionString(n, file);
  3004. defaultArgs.PushLast(defaultArgStr);
  3005. n = n->next;
  3006. }
  3007. else
  3008. defaultArgs.PushLast(0);
  3009. }
  3010. }
  3011. #endif
  3012. asCString asCBuilder::GetCleanExpressionString(asCScriptNode *node, asCScriptCode *file)
  3013. {
  3014. asASSERT(node && node->nodeType == snExpression);
  3015. asCString str;
  3016. str.Assign(file->code + node->tokenPos, node->tokenLength);
  3017. asCString cleanStr;
  3018. for( asUINT n = 0; n < str.GetLength(); )
  3019. {
  3020. int len;
  3021. asETokenClass tok = engine->ParseToken(str.AddressOf() + n, str.GetLength() - n, &len);
  3022. if( tok != asTC_COMMENT && tok != asTC_WHITESPACE )
  3023. {
  3024. if( cleanStr.GetLength() ) cleanStr += " ";
  3025. cleanStr.Concatenate(str.AddressOf() + n, len);
  3026. }
  3027. n += len;
  3028. }
  3029. return cleanStr;
  3030. }
  3031. #ifndef AS_NO_COMPILER
  3032. int asCBuilder::RegisterScriptFunctionFromNode(asCScriptNode *node, asCScriptCode *file, asCObjectType *objType, bool isInterface, bool isGlobalFunction, asSNameSpace *ns, bool isExistingShared, bool isMixin)
  3033. {
  3034. asCString name;
  3035. asCDataType returnType;
  3036. asCArray<asCString> parameterNames;
  3037. asCArray<asCDataType> parameterTypes;
  3038. asCArray<asETypeModifiers> inOutFlags;
  3039. asCArray<asCString *> defaultArgs;
  3040. bool isConstMethod;
  3041. bool isOverride;
  3042. bool isFinal;
  3043. bool isConstructor;
  3044. bool isDestructor;
  3045. bool isPrivate;
  3046. bool isShared;
  3047. asASSERT( (objType && ns == 0) || isGlobalFunction );
  3048. // Set the default namespace
  3049. if( ns == 0 )
  3050. {
  3051. if( objType )
  3052. ns = objType->nameSpace;
  3053. else
  3054. ns = engine->nameSpaces[0];
  3055. }
  3056. GetParsedFunctionDetails(node, file, objType, name, returnType, parameterNames, parameterTypes, inOutFlags, defaultArgs, isConstMethod, isConstructor, isDestructor, isPrivate, isOverride, isFinal, isShared, ns);
  3057. return RegisterScriptFunction(node, file, objType, isInterface, isGlobalFunction, ns, isExistingShared, isMixin, name, returnType, parameterNames, parameterTypes, inOutFlags, defaultArgs, isConstMethod, isConstructor, isDestructor, isPrivate, isOverride, isFinal, isShared);
  3058. }
  3059. 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)
  3060. {
  3061. // Determine default namespace if not specified
  3062. if( ns == 0 )
  3063. {
  3064. if( objType )
  3065. ns = objType->nameSpace;
  3066. else
  3067. ns = engine->nameSpaces[0];
  3068. }
  3069. if( isExistingShared )
  3070. {
  3071. asASSERT( objType );
  3072. // Should validate that the function really exists in the class/interface
  3073. bool found = false;
  3074. if( isConstructor || isDestructor )
  3075. {
  3076. // TODO: shared: Should check the existance of these too
  3077. found = true;
  3078. }
  3079. else
  3080. {
  3081. for( asUINT n = 0; n < objType->methods.GetLength(); n++ )
  3082. {
  3083. asCScriptFunction *func = engine->scriptFunctions[objType->methods[n]];
  3084. if( func->name == name &&
  3085. func->IsSignatureExceptNameEqual(returnType, parameterTypes, inOutFlags, objType, isConstMethod) )
  3086. {
  3087. found = true;
  3088. break;
  3089. }
  3090. }
  3091. }
  3092. if( !found )
  3093. {
  3094. asCString str;
  3095. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, objType->GetName());
  3096. WriteError(str, file, node);
  3097. }
  3098. node->Destroy(engine);
  3099. return 0;
  3100. }
  3101. // Check for name conflicts
  3102. if( !isConstructor && !isDestructor )
  3103. {
  3104. if( objType )
  3105. {
  3106. CheckNameConflictMember(objType, name.AddressOf(), node, file, false);
  3107. if( name == objType->name )
  3108. WriteError(TXT_METHOD_CANT_HAVE_NAME_OF_CLASS, file, node);
  3109. }
  3110. else
  3111. CheckNameConflict(name.AddressOf(), node, file, ns);
  3112. }
  3113. else
  3114. {
  3115. if( isMixin )
  3116. {
  3117. // Mixins cannot implement constructors/destructors
  3118. WriteError(TXT_MIXIN_CANNOT_HAVE_CONSTRUCTOR, file, node);
  3119. node->Destroy(engine);
  3120. return 0;
  3121. }
  3122. // Verify that the name of the constructor/destructor is the same as the class
  3123. if( name != objType->name )
  3124. WriteError(TXT_CONSTRUCTOR_NAME_ERROR, file, node);
  3125. if( isDestructor )
  3126. name = "~" + name;
  3127. }
  3128. isExistingShared = false;
  3129. int funcId = engine->GetNextScriptFunctionId();
  3130. if( !isInterface )
  3131. {
  3132. sFunctionDescription *func = asNEW(sFunctionDescription);
  3133. if( func == 0 )
  3134. return asOUT_OF_MEMORY;
  3135. functions.PushLast(func);
  3136. func->script = file;
  3137. func->node = node;
  3138. func->name = name;
  3139. func->objType = objType;
  3140. func->funcId = funcId;
  3141. func->isExistingShared = false;
  3142. func->paramNames = parameterNames;
  3143. if( isShared )
  3144. {
  3145. // Look for a pre-existing shared function with the same signature
  3146. for( asUINT n = 0; n < engine->scriptFunctions.GetLength(); n++ )
  3147. {
  3148. asCScriptFunction *f = engine->scriptFunctions[n];
  3149. if( f &&
  3150. f->isShared &&
  3151. f->name == name &&
  3152. f->nameSpace == ns &&
  3153. f->objectType == objType &&
  3154. f->IsSignatureExceptNameEqual(returnType, parameterTypes, inOutFlags, 0, false) )
  3155. {
  3156. funcId = func->funcId = f->id;
  3157. isExistingShared = func->isExistingShared = true;
  3158. break;
  3159. }
  3160. }
  3161. }
  3162. }
  3163. // Destructors may not have any parameters
  3164. if( isDestructor && parameterTypes.GetLength() > 0 )
  3165. WriteError(TXT_DESTRUCTOR_MAY_NOT_HAVE_PARM, file, node);
  3166. // If a function, class, or interface is shared then only shared types may be used in the signature
  3167. if( (objType && objType->IsShared()) || isShared )
  3168. {
  3169. asCObjectType *ot = returnType.GetObjectType();
  3170. if( ot && !ot->IsShared() )
  3171. {
  3172. asCString msg;
  3173. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, ot->name.AddressOf());
  3174. WriteError(msg, file, node);
  3175. }
  3176. for( asUINT p = 0; p < parameterTypes.GetLength(); ++p )
  3177. {
  3178. asCObjectType *ot = parameterTypes[p].GetObjectType();
  3179. if( ot && !ot->IsShared() )
  3180. {
  3181. asCString msg;
  3182. msg.Format(TXT_SHARED_CANNOT_USE_NON_SHARED_TYPE_s, ot->name.AddressOf());
  3183. WriteError(msg, file, node);
  3184. }
  3185. }
  3186. }
  3187. // Check that the same function hasn't been registered already in the namespace
  3188. asCArray<int> funcs;
  3189. if( objType )
  3190. GetObjectMethodDescriptions(name.AddressOf(), objType, funcs, false);
  3191. else
  3192. GetFunctionDescriptions(name.AddressOf(), funcs, ns);
  3193. for( asUINT n = 0; n < funcs.GetLength(); ++n )
  3194. {
  3195. asCScriptFunction *func = GetFunctionDescription(funcs[n]);
  3196. if( func->IsSignatureExceptNameAndReturnTypeEqual(parameterTypes, inOutFlags, objType, isConstMethod) )
  3197. {
  3198. if( isMixin )
  3199. {
  3200. // Clean up the memory, as the function will not be registered
  3201. if( node )
  3202. node->Destroy(engine);
  3203. sFunctionDescription *func = functions.PopLast();
  3204. asDELETE(func, sFunctionDescription);
  3205. return 0;
  3206. }
  3207. WriteError(TXT_FUNCTION_ALREADY_EXIST, file, node);
  3208. break;
  3209. }
  3210. }
  3211. // Register the function
  3212. if( isExistingShared )
  3213. {
  3214. asCScriptFunction *f = engine->scriptFunctions[funcId];
  3215. module->AddScriptFunction(f);
  3216. // TODO: clean up: This should be done by AddScriptFunction() itself
  3217. module->globalFunctions.Put(f);
  3218. f->AddRef();
  3219. }
  3220. else
  3221. module->AddScriptFunction(file->idx, funcId, name, returnType, parameterTypes, inOutFlags, defaultArgs, isInterface, objType, isConstMethod, isGlobalFunction, isPrivate, isFinal, isOverride, isShared, ns);
  3222. // Make sure the default args are declared correctly
  3223. ValidateDefaultArgs(file, node, engine->scriptFunctions[funcId]);
  3224. if( objType )
  3225. {
  3226. asASSERT( !isExistingShared );
  3227. engine->scriptFunctions[funcId]->AddRef();
  3228. if( isConstructor )
  3229. {
  3230. int factoryId = engine->GetNextScriptFunctionId();
  3231. if( parameterTypes.GetLength() == 0 )
  3232. {
  3233. // Overload the default constructor
  3234. engine->scriptFunctions[objType->beh.construct]->Release();
  3235. objType->beh.construct = funcId;
  3236. objType->beh.constructors[0] = funcId;
  3237. // Register the default factory as well
  3238. engine->scriptFunctions[objType->beh.factory]->Release();
  3239. objType->beh.factory = factoryId;
  3240. objType->beh.factories[0] = factoryId;
  3241. }
  3242. else
  3243. {
  3244. objType->beh.constructors.PushLast(funcId);
  3245. // Register the factory as well
  3246. objType->beh.factories.PushLast(factoryId);
  3247. }
  3248. // We must copy the default arg strings to avoid deleting the same object multiple times
  3249. for( asUINT n = 0; n < defaultArgs.GetLength(); n++ )
  3250. if( defaultArgs[n] )
  3251. defaultArgs[n] = asNEW(asCString)(*defaultArgs[n]);
  3252. asCDataType dt = asCDataType::CreateObjectHandle(objType, false);
  3253. module->AddScriptFunction(file->idx, factoryId, name, dt, parameterTypes, inOutFlags, defaultArgs, false);
  3254. // If the object is shared, then the factory must also be marked as shared
  3255. if( objType->flags & asOBJ_SHARED )
  3256. engine->scriptFunctions[factoryId]->isShared = true;
  3257. // Add a dummy function to the builder so that it doesn't mix up the fund Ids
  3258. functions.PushLast(0);
  3259. // Compile the factory immediately
  3260. asCCompiler compiler(engine);
  3261. compiler.CompileFactory(this, file, engine->scriptFunctions[factoryId]);
  3262. engine->scriptFunctions[factoryId]->AddRef();
  3263. }
  3264. else if( isDestructor )
  3265. objType->beh.destruct = funcId;
  3266. else
  3267. {
  3268. // If the method is the assignment operator we need to replace the default implementation
  3269. asCScriptFunction *f = engine->scriptFunctions[funcId];
  3270. if( f->name == "opAssign" && f->parameterTypes.GetLength() == 1 &&
  3271. f->parameterTypes[0].GetObjectType() == f->objectType &&
  3272. (f->inOutFlags[0] & asTM_INREF) )
  3273. {
  3274. engine->scriptFunctions[objType->beh.copy]->Release();
  3275. objType->beh.copy = funcId;
  3276. f->AddRef();
  3277. }
  3278. objType->methods.PushLast(funcId);
  3279. }
  3280. }
  3281. // We need to delete the node already if this is an interface method
  3282. if( isInterface && node )
  3283. node->Destroy(engine);
  3284. return 0;
  3285. }
  3286. int asCBuilder::RegisterVirtualProperty(asCScriptNode *node, asCScriptCode *file, asCObjectType *objType, bool isInterface, bool isGlobalFunction, asSNameSpace *ns, bool isExistingShared)
  3287. {
  3288. if( engine->ep.propertyAccessorMode != 2 )
  3289. {
  3290. WriteError(TXT_PROPERTY_ACCESSOR_DISABLED, file, node);
  3291. node->Destroy(engine);
  3292. return 0;
  3293. }
  3294. asASSERT( (objType && ns == 0) || isGlobalFunction );
  3295. if( ns == 0 )
  3296. {
  3297. if( objType )
  3298. ns = objType->nameSpace;
  3299. else
  3300. ns = engine->nameSpaces[0];
  3301. }
  3302. bool isPrivate = false;
  3303. asCString emulatedName;
  3304. asCDataType emulatedType;
  3305. asCScriptNode *mainNode = node;
  3306. node = node->firstChild;
  3307. if( !isGlobalFunction && node->tokenType == ttPrivate )
  3308. {
  3309. isPrivate = true;
  3310. node = node->next;
  3311. }
  3312. emulatedType = CreateDataTypeFromNode(node, file, ns);
  3313. emulatedType = ModifyDataTypeFromNode(emulatedType, node->next, file, 0, 0);
  3314. node = node->next->next;
  3315. emulatedName.Assign(&file->code[node->tokenPos], node->tokenLength);
  3316. if( node->next == 0 )
  3317. WriteError(TXT_PROPERTY_WITHOUT_ACCESSOR, file, node);
  3318. node = node->next;
  3319. while( node )
  3320. {
  3321. asCScriptNode *next = node->next;
  3322. asCScriptNode *funcNode = 0;
  3323. bool success = false;
  3324. bool isConst = false;
  3325. bool isFinal = false;
  3326. bool isOverride = false;
  3327. asCDataType returnType;
  3328. asCArray<asCString> paramNames;
  3329. asCArray<asCDataType> paramTypes;
  3330. asCArray<asETypeModifiers> paramModifiers;
  3331. asCArray<asCString*> defaultArgs;
  3332. asCString name;
  3333. // TODO: getset: Allow private for individual property accessors
  3334. // TODO: getset: If the accessor uses its own name, then the property should be automatically declared
  3335. if( node->firstChild->nodeType == snIdentifier && file->TokenEquals(node->firstChild->tokenPos, node->firstChild->tokenLength, GET_TOKEN) )
  3336. {
  3337. funcNode = node->firstChild->next;
  3338. if( funcNode && funcNode->tokenType == ttConst )
  3339. {
  3340. isConst = true;
  3341. funcNode = funcNode->next;
  3342. }
  3343. while( funcNode && funcNode->nodeType != snStatementBlock )
  3344. {
  3345. if( funcNode->tokenType == ttIdentifier && file->TokenEquals(funcNode->tokenPos, funcNode->tokenLength, FINAL_TOKEN) )
  3346. isFinal = true;
  3347. else if( funcNode->tokenType == ttIdentifier && file->TokenEquals(funcNode->tokenPos, funcNode->tokenLength, OVERRIDE_TOKEN) )
  3348. isOverride = true;
  3349. funcNode = funcNode->next;
  3350. }
  3351. if( funcNode )
  3352. funcNode->DisconnectParent();
  3353. if( funcNode == 0 && (objType == 0 || !objType->IsInterface()) )
  3354. {
  3355. // TODO: getset: If no implementation is supplied the builder should provide an automatically generated implementation
  3356. // The compiler needs to be able to handle the different types, primitive, value type, and handle
  3357. // The code is also different for global property accessors
  3358. WriteError(TXT_PROPERTY_ACCESSOR_MUST_BE_IMPLEMENTED, file, node);
  3359. }
  3360. // Setup the signature for the get accessor method
  3361. returnType = emulatedType;
  3362. name = "get_" + emulatedName;
  3363. success = true;
  3364. }
  3365. else if( node->firstChild->nodeType == snIdentifier && file->TokenEquals(node->firstChild->tokenPos, node->firstChild->tokenLength, SET_TOKEN) )
  3366. {
  3367. funcNode = node->firstChild->next;
  3368. if( funcNode && funcNode->tokenType == ttConst )
  3369. {
  3370. isConst = true;
  3371. funcNode = funcNode->next;
  3372. }
  3373. while( funcNode && funcNode->nodeType != snStatementBlock )
  3374. {
  3375. if( funcNode->tokenType == ttIdentifier && file->TokenEquals(funcNode->tokenPos, funcNode->tokenLength, FINAL_TOKEN) )
  3376. isFinal = true;
  3377. else if( funcNode->tokenType == ttIdentifier && file->TokenEquals(funcNode->tokenPos, funcNode->tokenLength, OVERRIDE_TOKEN) )
  3378. isOverride = true;
  3379. funcNode = funcNode->next;
  3380. }
  3381. if( funcNode )
  3382. funcNode->DisconnectParent();
  3383. if( funcNode == 0 && (objType == 0 || !objType->IsInterface()) )
  3384. WriteError(TXT_PROPERTY_ACCESSOR_MUST_BE_IMPLEMENTED, file, node);
  3385. // Setup the signature for the set accessor method
  3386. returnType = asCDataType::CreatePrimitive(ttVoid, false);
  3387. paramModifiers.PushLast(asTM_NONE);
  3388. paramNames.PushLast("value");
  3389. paramTypes.PushLast(emulatedType);
  3390. defaultArgs.PushLast(0);
  3391. name = "set_" + emulatedName;
  3392. success = true;
  3393. }
  3394. else
  3395. WriteError(TXT_UNRECOGNIZED_VIRTUAL_PROPERTY_NODE, file, node);
  3396. if( success )
  3397. {
  3398. if( !isExistingShared )
  3399. RegisterScriptFunction(funcNode, file, objType, isInterface, isGlobalFunction, ns, false, false, name, returnType, paramNames, paramTypes, paramModifiers, defaultArgs, isConst, false, false, isPrivate, isOverride, isFinal, false);
  3400. else
  3401. {
  3402. // Should validate that the function really exists in the class/interface
  3403. bool found = false;
  3404. for( asUINT n = 0; n < objType->methods.GetLength(); n++ )
  3405. {
  3406. asCScriptFunction *func = engine->scriptFunctions[objType->methods[n]];
  3407. if( func->name == name &&
  3408. func->IsSignatureExceptNameEqual(returnType, paramTypes, paramModifiers, objType, isConst) )
  3409. {
  3410. found = true;
  3411. break;
  3412. }
  3413. }
  3414. if( !found )
  3415. {
  3416. asCString str;
  3417. str.Format(TXT_SHARED_s_DOESNT_MATCH_ORIGINAL, objType->GetName());
  3418. WriteError(str, file, node);
  3419. }
  3420. }
  3421. }
  3422. node = next;
  3423. };
  3424. mainNode->Destroy(engine);
  3425. return 0;
  3426. }
  3427. int asCBuilder::RegisterImportedFunction(int importID, asCScriptNode *node, asCScriptCode *file, asSNameSpace *ns)
  3428. {
  3429. asCString name;
  3430. asCDataType returnType;
  3431. asCArray<asCString> parameterNames;
  3432. asCArray<asCDataType> parameterTypes;
  3433. asCArray<asETypeModifiers> inOutFlags;
  3434. asCArray<asCString *> defaultArgs;
  3435. bool isConstMethod, isOverride, isFinal, isConstructor, isDestructor, isPrivate, isShared;
  3436. if( ns == 0 )
  3437. ns = engine->nameSpaces[0];
  3438. GetParsedFunctionDetails(node->firstChild, file, 0, name, returnType, parameterNames, parameterTypes, inOutFlags, defaultArgs, isConstMethod, isConstructor, isDestructor, isPrivate, isOverride, isFinal, isShared, ns);
  3439. CheckNameConflict(name.AddressOf(), node, file, ns);
  3440. // Check that the same function hasn't been registered already in the namespace
  3441. asCArray<int> funcs;
  3442. GetFunctionDescriptions(name.AddressOf(), funcs, ns);
  3443. for( asUINT n = 0; n < funcs.GetLength(); ++n )
  3444. {
  3445. asCScriptFunction *func = GetFunctionDescription(funcs[n]);
  3446. if( func->IsSignatureExceptNameAndReturnTypeEqual(parameterTypes, inOutFlags, 0, false) )
  3447. {
  3448. WriteError(TXT_FUNCTION_ALREADY_EXIST, file, node);
  3449. break;
  3450. }
  3451. }
  3452. // Read the module name as well
  3453. asCScriptNode *nd = node->lastChild;
  3454. asASSERT( nd->nodeType == snConstant && nd->tokenType == ttStringConstant );
  3455. asCString moduleName;
  3456. moduleName.Assign(&file->code[nd->tokenPos+1], nd->tokenLength-2);
  3457. node->Destroy(engine);
  3458. // Register the function
  3459. module->AddImportedFunction(importID, name, returnType, parameterTypes, inOutFlags, defaultArgs, ns, moduleName);
  3460. return 0;
  3461. }
  3462. #endif
  3463. asCScriptFunction *asCBuilder::GetFunctionDescription(int id)
  3464. {
  3465. // TODO: import: This should be improved when the imported functions are removed
  3466. // Get the description from the engine
  3467. if( (id & FUNC_IMPORTED) == 0 )
  3468. return engine->scriptFunctions[id];
  3469. else
  3470. return engine->importedFunctions[id & ~FUNC_IMPORTED]->importedFunctionSignature;
  3471. }
  3472. void asCBuilder::GetFunctionDescriptions(const char *name, asCArray<int> &funcs, asSNameSpace *ns)
  3473. {
  3474. asUINT n;
  3475. const asCArray<unsigned int> &idxs = module->globalFunctions.GetIndexes(ns, name);
  3476. for( n = 0; n < idxs.GetLength(); n++ )
  3477. {
  3478. const asCScriptFunction *f = module->globalFunctions.Get(idxs[n]);
  3479. asASSERT( f->objectType == 0 );
  3480. funcs.PushLast(f->id);
  3481. }
  3482. // TODO: optimize: Linear search: This is probably not that critial. Also bindInformation will probably be removed in near future
  3483. for( n = 0; n < module->bindInformations.GetLength(); n++ )
  3484. {
  3485. if( module->bindInformations[n]->importedFunctionSignature->name == name )
  3486. funcs.PushLast(module->bindInformations[n]->importedFunctionSignature->id);
  3487. }
  3488. // TODO: optimize: Linear search. The registered global functions should be stored in a symbol table too
  3489. for( n = 0; n < engine->registeredGlobalFuncs.GetLength(); n++ )
  3490. {
  3491. asCScriptFunction *f = engine->registeredGlobalFuncs[n];
  3492. if( f &&
  3493. f->funcType == asFUNC_SYSTEM &&
  3494. f->objectType == 0 &&
  3495. f->nameSpace == ns &&
  3496. f->name == name )
  3497. {
  3498. // Verify if the module has access to the function
  3499. if( module->accessMask & f->accessMask )
  3500. {
  3501. funcs.PushLast(f->id);
  3502. }
  3503. }
  3504. }
  3505. }
  3506. void asCBuilder::GetObjectMethodDescriptions(const char *name, asCObjectType *objectType, asCArray<int> &methods, bool objIsConst, const asCString &scope)
  3507. {
  3508. if( scope != "" )
  3509. {
  3510. // Find the base class with the specified scope
  3511. while( objectType && objectType->name != scope )
  3512. objectType = objectType->derivedFrom;
  3513. // If the scope is not any of the base classes, then return no methods
  3514. if( objectType == 0 )
  3515. return;
  3516. }
  3517. // TODO: optimize: Improve linear search
  3518. if( objIsConst )
  3519. {
  3520. // Only add const methods to the list
  3521. for( asUINT n = 0; n < objectType->methods.GetLength(); n++ )
  3522. {
  3523. if( engine->scriptFunctions[objectType->methods[n]]->name == name &&
  3524. engine->scriptFunctions[objectType->methods[n]]->isReadOnly )
  3525. {
  3526. // When the scope is defined the returned methods should be the true methods, not the virtual method stubs
  3527. if( scope == "" )
  3528. methods.PushLast(engine->scriptFunctions[objectType->methods[n]]->id);
  3529. else
  3530. {
  3531. asCScriptFunction *virtFunc = engine->scriptFunctions[objectType->methods[n]];
  3532. asCScriptFunction *realFunc = objectType->virtualFunctionTable[virtFunc->vfTableIdx];
  3533. methods.PushLast(realFunc->id);
  3534. }
  3535. }
  3536. }
  3537. }
  3538. else
  3539. {
  3540. // TODO: Prefer non-const over const
  3541. for( asUINT n = 0; n < objectType->methods.GetLength(); n++ )
  3542. {
  3543. if( engine->scriptFunctions[objectType->methods[n]]->name == name )
  3544. {
  3545. // When the scope is defined the returned methods should be the true methods, not the virtual method stubs
  3546. if( scope == "" )
  3547. methods.PushLast(engine->scriptFunctions[objectType->methods[n]]->id);
  3548. else
  3549. {
  3550. asCScriptFunction *virtFunc = engine->scriptFunctions[objectType->methods[n]];
  3551. asCScriptFunction *realFunc = objectType->virtualFunctionTable[virtFunc->vfTableIdx];
  3552. methods.PushLast(realFunc->id);
  3553. }
  3554. }
  3555. }
  3556. }
  3557. }
  3558. void asCBuilder::WriteInfo(const asCString &scriptname, const asCString &message, int r, int c, bool pre)
  3559. {
  3560. // Need to store the pre message in a structure
  3561. if( pre )
  3562. {
  3563. preMessage.isSet = true;
  3564. preMessage.c = c;
  3565. preMessage.r = r;
  3566. preMessage.message = message;
  3567. preMessage.scriptname = scriptname;
  3568. }
  3569. else
  3570. {
  3571. preMessage.isSet = false;
  3572. engine->WriteMessage(scriptname.AddressOf(), r, c, asMSGTYPE_INFORMATION, message.AddressOf());
  3573. }
  3574. }
  3575. void asCBuilder::WriteInfo(const asCString &message, asCScriptCode *file, asCScriptNode *node)
  3576. {
  3577. int r = 0, c = 0;
  3578. if( node )
  3579. file->ConvertPosToRowCol(node->tokenPos, &r, &c);
  3580. WriteInfo(file->name, message, r, c, false);
  3581. }
  3582. void asCBuilder::WriteError(const asCString &message, asCScriptCode *file, asCScriptNode *node)
  3583. {
  3584. int r = 0, c = 0;
  3585. if( node && file )
  3586. file->ConvertPosToRowCol(node->tokenPos, &r, &c);
  3587. WriteError(file ? file->name : "", message, r, c);
  3588. }
  3589. void asCBuilder::WriteError(const asCString &scriptname, const asCString &message, int r, int c)
  3590. {
  3591. numErrors++;
  3592. // Need to pass the preMessage first
  3593. if( preMessage.isSet )
  3594. WriteInfo(preMessage.scriptname, preMessage.message, preMessage.r, preMessage.c, false);
  3595. engine->WriteMessage(scriptname.AddressOf(), r, c, asMSGTYPE_ERROR, message.AddressOf());
  3596. }
  3597. void asCBuilder::WriteWarning(const asCString &scriptname, const asCString &message, int r, int c)
  3598. {
  3599. if( engine->ep.compilerWarnings )
  3600. {
  3601. numWarnings++;
  3602. // Need to pass the preMessage first
  3603. if( preMessage.isSet )
  3604. WriteInfo(preMessage.scriptname, preMessage.message, preMessage.r, preMessage.c, false);
  3605. engine->WriteMessage(scriptname.AddressOf(), r, c, asMSGTYPE_WARNING, message.AddressOf());
  3606. }
  3607. }
  3608. asCString asCBuilder::GetScopeFromNode(asCScriptNode *node, asCScriptCode *script, asCScriptNode **next)
  3609. {
  3610. asCString scope;
  3611. asCScriptNode *sn = node;
  3612. if( sn->tokenType == ttScope )
  3613. {
  3614. scope = "::";
  3615. sn = sn->next;
  3616. }
  3617. while( sn && sn->next && sn->next->tokenType == ttScope )
  3618. {
  3619. asCString tmp;
  3620. tmp.Assign(&script->code[sn->tokenPos], sn->tokenLength);
  3621. if( scope != "" && scope != "::" )
  3622. scope += "::";
  3623. scope += tmp;
  3624. sn = sn->next->next;
  3625. }
  3626. if( next )
  3627. *next = sn;
  3628. return scope;
  3629. }
  3630. asSNameSpace *asCBuilder::GetNameSpaceFromNode(asCScriptNode *node, asCScriptCode *script, asSNameSpace *implicitNs, asCScriptNode **next)
  3631. {
  3632. asCString scope = GetScopeFromNode(node, script, next);
  3633. asSNameSpace *ns = implicitNs;
  3634. if( scope == "::" )
  3635. ns = engine->nameSpaces[0];
  3636. else if( scope != "" )
  3637. {
  3638. ns = engine->FindNameSpace(scope.AddressOf());
  3639. if( ns == 0 )
  3640. {
  3641. asCString msg;
  3642. msg.Format(TXT_NAMESPACE_s_DOESNT_EXIST, scope.AddressOf());
  3643. WriteError(msg, script, node);
  3644. }
  3645. }
  3646. return ns;
  3647. }
  3648. asSNameSpace *asCBuilder::GetParentNameSpace(asSNameSpace *ns)
  3649. {
  3650. if( ns == 0 ) return 0;
  3651. if( ns == engine->nameSpaces[0] ) return 0;
  3652. asCString scope = ns->name;
  3653. int pos = scope.FindLast("::");
  3654. if( pos >= 0 )
  3655. {
  3656. scope = scope.SubString(0, pos);
  3657. return engine->FindNameSpace(scope.AddressOf());
  3658. }
  3659. return engine->nameSpaces[0];
  3660. }
  3661. asCDataType asCBuilder::CreateDataTypeFromNode(asCScriptNode *node, asCScriptCode *file, asSNameSpace *implicitNamespace, bool acceptHandleForScope, asCObjectType *currentType)
  3662. {
  3663. asASSERT(node->nodeType == snDataType);
  3664. asCDataType dt;
  3665. asCScriptNode *n = node->firstChild;
  3666. bool isConst = false;
  3667. bool isImplicitHandle = false;
  3668. if( n->tokenType == ttConst )
  3669. {
  3670. isConst = true;
  3671. n = n->next;
  3672. }
  3673. // Determine namespace
  3674. asSNameSpace *ns = GetNameSpaceFromNode(n, file, implicitNamespace, &n);
  3675. if( ns == 0 )
  3676. {
  3677. // The namespace doesn't exist. Return a dummy type instead.
  3678. dt = asCDataType::CreatePrimitive(ttInt, false);
  3679. return dt;
  3680. }
  3681. if( n->tokenType == ttIdentifier )
  3682. {
  3683. bool found = false;
  3684. asCScriptNode *nameToken = n;
  3685. asCString str;
  3686. str.Assign(&file->code[n->tokenPos], n->tokenLength);
  3687. // Recursively search parent namespaces for matching type
  3688. while( ns && !found )
  3689. {
  3690. asCObjectType *ot = 0;
  3691. // If this is for a template type, then we must first determine if the
  3692. // identifier matches any of the template subtypes
  3693. if( currentType && (currentType->flags & asOBJ_TEMPLATE))
  3694. {
  3695. for( asUINT subtypeIndex = 0; subtypeIndex < currentType->templateSubTypes.GetLength(); subtypeIndex++)
  3696. {
  3697. if(str == currentType->templateSubTypes[subtypeIndex].GetObjectType()->name )
  3698. {
  3699. ot = currentType->templateSubTypes[subtypeIndex].GetObjectType();
  3700. break;
  3701. }
  3702. }
  3703. }
  3704. if( ot == 0 )
  3705. ot = GetObjectType(str.AddressOf(), ns);
  3706. if( ot == 0 && !module && currentType )
  3707. ot = GetObjectTypeFromTypesKnownByObject(str.AddressOf(), currentType);
  3708. if( ot )
  3709. {
  3710. found = true;
  3711. if( ot->flags & asOBJ_IMPLICIT_HANDLE )
  3712. isImplicitHandle = true;
  3713. // Make sure the module has access to the object type
  3714. if( !module || (module->accessMask & ot->accessMask) )
  3715. {
  3716. if(asOBJ_TYPEDEF == (ot->flags & asOBJ_TYPEDEF))
  3717. {
  3718. // TODO: typedef: A typedef should be considered different from the original type (though with implicit conversions between the two)
  3719. // Create primitive data type based on object flags
  3720. dt = ot->templateSubTypes[0];
  3721. dt.MakeReadOnly(isConst);
  3722. }
  3723. else
  3724. {
  3725. if( ot->flags & asOBJ_TEMPLATE )
  3726. {
  3727. // Check if the subtype is a type or the template's subtype
  3728. // if it is the template's subtype then this is the actual template type,
  3729. // orderwise it is a template instance.
  3730. // Only do this for application registered interface, as the
  3731. // scripts cannot implement templates.
  3732. // TODO: namespace: Use correct implicit namespace
  3733. asCArray<asCDataType> subTypes;
  3734. asUINT subtypeIndex;
  3735. while( n && n->next && n->next->nodeType == snDataType )
  3736. {
  3737. n = n->next;
  3738. asCDataType subType = CreateDataTypeFromNode(n, file, engine->nameSpaces[0], false, module ? 0 : ot);
  3739. subTypes.PushLast(subType);
  3740. }
  3741. if( subTypes.GetLength() != ot->templateSubTypes.GetLength() )
  3742. {
  3743. asCString msg;
  3744. msg.Format(TXT_TMPL_s_EXPECTS_d_SUBTYPES, ot->name.AddressOf(), int(ot->templateSubTypes.GetLength()));
  3745. WriteError(msg, file, nameToken);
  3746. // Return a dummy
  3747. return asCDataType::CreatePrimitive(ttInt, false);
  3748. }
  3749. asASSERT( subTypes.GetLength() == ot->templateSubTypes.GetLength() );
  3750. // Check if any of the given subtypes are different from the template's declared subtypes
  3751. bool isDifferent = false;
  3752. for( subtypeIndex = 0; subtypeIndex < subTypes.GetLength(); subtypeIndex++ )
  3753. {
  3754. if( subTypes[subtypeIndex].GetObjectType() != ot->templateSubTypes[subtypeIndex].GetObjectType() )
  3755. {
  3756. isDifferent = true;
  3757. break;
  3758. }
  3759. }
  3760. if( isDifferent )
  3761. {
  3762. // This is a template instance
  3763. // Need to find the correct object type
  3764. asCObjectType *otInstance = engine->GetTemplateInstanceType(ot, subTypes);
  3765. if( !otInstance )
  3766. {
  3767. asCString msg;
  3768. // TODO: Should name all subtypes
  3769. msg.Format(TXT_CANNOT_INSTANCIATE_TEMPLATE_s_WITH_s, ot->name.AddressOf(), subTypes[0].Format().AddressOf());
  3770. WriteError(msg, file, n);
  3771. }
  3772. ot = otInstance;
  3773. }
  3774. }
  3775. // Create object data type
  3776. if( ot )
  3777. dt = asCDataType::CreateObject(ot, isConst);
  3778. else
  3779. dt = asCDataType::CreatePrimitive(ttInt, isConst);
  3780. }
  3781. }
  3782. else
  3783. {
  3784. asCString msg;
  3785. msg.Format(TXT_TYPE_s_NOT_AVAILABLE_FOR_MODULE, (const char *)str.AddressOf());
  3786. WriteError(msg, file, n);
  3787. dt.SetTokenType(ttInt);
  3788. }
  3789. }
  3790. else if( ot == 0 )
  3791. {
  3792. // It can still be a function definition
  3793. asCScriptFunction *funcdef = GetFuncDef(str.AddressOf());
  3794. if( funcdef )
  3795. {
  3796. dt = asCDataType::CreateFuncDef(funcdef);
  3797. found = true;
  3798. }
  3799. }
  3800. if( !found )
  3801. {
  3802. // Try to find it in the parent namespace
  3803. ns = GetParentNameSpace(ns);
  3804. }
  3805. }
  3806. if( !found )
  3807. {
  3808. asCString msg;
  3809. msg.Format(TXT_IDENTIFIER_s_NOT_DATA_TYPE, (const char *)str.AddressOf());
  3810. WriteError(msg, file, n);
  3811. dt = asCDataType::CreatePrimitive(ttInt, isConst);
  3812. return dt;
  3813. }
  3814. }
  3815. else
  3816. {
  3817. // Create primitive data type
  3818. dt = asCDataType::CreatePrimitive(n->tokenType, isConst);
  3819. }
  3820. // Determine array dimensions and object handles
  3821. n = n->next;
  3822. while( n && (n->tokenType == ttOpenBracket || n->tokenType == ttHandle) )
  3823. {
  3824. if( n->tokenType == ttOpenBracket )
  3825. {
  3826. // Make sure the sub type can be instanciated
  3827. if( !dt.CanBeInstanciated() )
  3828. {
  3829. asCString str;
  3830. // TODO: Change to "Array sub type cannot be 'type'"
  3831. str.Format(TXT_DATA_TYPE_CANT_BE_s, dt.Format().AddressOf());
  3832. WriteError(str, file, n);
  3833. }
  3834. // Make the type an array (or multidimensional array)
  3835. if( dt.MakeArray(engine) < 0 )
  3836. {
  3837. WriteError(TXT_NO_DEFAULT_ARRAY_TYPE, file, n);
  3838. break;
  3839. }
  3840. }
  3841. else
  3842. {
  3843. // Make the type a handle
  3844. if( dt.MakeHandle(true, acceptHandleForScope) < 0 )
  3845. {
  3846. WriteError(TXT_OBJECT_HANDLE_NOT_SUPPORTED, file, n);
  3847. break;
  3848. }
  3849. }
  3850. n = n->next;
  3851. }
  3852. if( isImplicitHandle )
  3853. {
  3854. // Make the type a handle
  3855. if( dt.MakeHandle(true, acceptHandleForScope) < 0 )
  3856. WriteError(TXT_OBJECT_HANDLE_NOT_SUPPORTED, file, n);
  3857. }
  3858. return dt;
  3859. }
  3860. asCDataType asCBuilder::ModifyDataTypeFromNode(const asCDataType &type, asCScriptNode *node, asCScriptCode *file, asETypeModifiers *inOutFlags, bool *autoHandle)
  3861. {
  3862. asCDataType dt = type;
  3863. if( inOutFlags ) *inOutFlags = asTM_NONE;
  3864. // Is the argument sent by reference?
  3865. asCScriptNode *n = node->firstChild;
  3866. if( n && n->tokenType == ttAmp )
  3867. {
  3868. dt.MakeReference(true);
  3869. n = n->next;
  3870. if( n )
  3871. {
  3872. if( inOutFlags )
  3873. {
  3874. if( n->tokenType == ttIn )
  3875. *inOutFlags = asTM_INREF;
  3876. else if( n->tokenType == ttOut )
  3877. *inOutFlags = asTM_OUTREF;
  3878. else if( n->tokenType == ttInOut )
  3879. *inOutFlags = asTM_INOUTREF;
  3880. else
  3881. asASSERT(false);
  3882. }
  3883. n = n->next;
  3884. }
  3885. else
  3886. {
  3887. if( inOutFlags )
  3888. *inOutFlags = asTM_INOUTREF; // ttInOut
  3889. }
  3890. if( !engine->ep.allowUnsafeReferences &&
  3891. inOutFlags && *inOutFlags == asTM_INOUTREF )
  3892. {
  3893. // Verify that the base type support &inout parameter types
  3894. if( !dt.IsObject() || dt.IsObjectHandle() || !((dt.GetObjectType()->flags & asOBJ_NOCOUNT) || (dt.GetObjectType()->beh.addref && dt.GetObjectType()->beh.release)) )
  3895. WriteError(TXT_ONLY_OBJECTS_MAY_USE_REF_INOUT, file, node->firstChild);
  3896. }
  3897. }
  3898. if( autoHandle ) *autoHandle = false;
  3899. if( n && n->tokenType == ttPlus )
  3900. {
  3901. // Autohandles are not supported for types with NOCOUNT
  3902. if( dt.GetObjectType()->flags & asOBJ_NOCOUNT )
  3903. WriteError(TXT_AUTOHANDLE_CANNOT_BE_USED_FOR_NOCOUNT, file, node->firstChild);
  3904. if( autoHandle ) *autoHandle = true;
  3905. }
  3906. return dt;
  3907. }
  3908. asCObjectType *asCBuilder::GetObjectType(const char *type, asSNameSpace *ns)
  3909. {
  3910. asCObjectType *ot = engine->GetObjectType(type, ns);
  3911. if( !ot && module )
  3912. ot = module->GetObjectType(type, ns);
  3913. return ot;
  3914. }
  3915. // This function will return true if there are any types in the engine or module
  3916. // with the given name. The namespace is ignored in this verification.
  3917. bool asCBuilder::DoesTypeExist(const char *type)
  3918. {
  3919. asUINT n;
  3920. // TODO: optimize: Improve linear searches
  3921. // Check if it is a registered type
  3922. for( n = 0; n < engine->objectTypes.GetLength(); n++ )
  3923. if( engine->objectTypes[n] &&
  3924. engine->objectTypes[n]->name == type ) // TODO: template: Should we check the subtype in case of template instances?
  3925. return true;
  3926. for( n = 0; n < engine->registeredFuncDefs.GetLength(); n++ )
  3927. if( engine->registeredFuncDefs[n]->name == type )
  3928. return true;
  3929. // Check if it is a script type
  3930. if( module )
  3931. {
  3932. for( n = 0; n < module->classTypes.GetLength(); n++ )
  3933. if( module->classTypes[n]->name == type )
  3934. return true;
  3935. for( n = 0; n < module->enumTypes.GetLength(); n++ )
  3936. if( module->enumTypes[n]->name == type )
  3937. return true;
  3938. for( n = 0; n < module->typeDefs.GetLength(); n++ )
  3939. if( module->typeDefs[n]->name == type )
  3940. return true;
  3941. for( asUINT n = 0; n < module->funcDefs.GetLength(); n++ )
  3942. if( module->funcDefs[n]->name == type )
  3943. return true;
  3944. }
  3945. return false;
  3946. }
  3947. asCObjectType *asCBuilder::GetObjectTypeFromTypesKnownByObject(const char *type, asCObjectType *currentType)
  3948. {
  3949. if( currentType->name == type )
  3950. return currentType;
  3951. asUINT n;
  3952. for( n = 0; n < currentType->properties.GetLength(); n++ )
  3953. if( currentType->properties[n]->type.GetObjectType() &&
  3954. currentType->properties[n]->type.GetObjectType()->name == type )
  3955. return currentType->properties[n]->type.GetObjectType();
  3956. for( n = 0; n < currentType->methods.GetLength(); n++ )
  3957. {
  3958. asCScriptFunction *func = engine->scriptFunctions[currentType->methods[n]];
  3959. if( func->returnType.GetObjectType() &&
  3960. func->returnType.GetObjectType()->name == type )
  3961. return func->returnType.GetObjectType();
  3962. for( asUINT f = 0; f < func->parameterTypes.GetLength(); f++ )
  3963. if( func->parameterTypes[f].GetObjectType() &&
  3964. func->parameterTypes[f].GetObjectType()->name == type )
  3965. return func->parameterTypes[f].GetObjectType();
  3966. }
  3967. return 0;
  3968. }
  3969. asCScriptFunction *asCBuilder::GetFuncDef(const char *type)
  3970. {
  3971. for( asUINT n = 0; n < engine->registeredFuncDefs.GetLength(); n++ )
  3972. // TODO: access: Only return the definitions that the module has access to
  3973. if( engine->registeredFuncDefs[n]->name == type )
  3974. return engine->registeredFuncDefs[n];
  3975. if( module )
  3976. {
  3977. for( asUINT n = 0; n < module->funcDefs.GetLength(); n++ )
  3978. if( module->funcDefs[n]->name == type )
  3979. return module->funcDefs[n];
  3980. }
  3981. return 0;
  3982. }
  3983. #ifndef AS_NO_COMPILER
  3984. int asCBuilder::GetEnumValueFromObjectType(asCObjectType *objType, const char *name, asCDataType &outDt, asDWORD &outValue)
  3985. {
  3986. if( !objType || !(objType->flags & asOBJ_ENUM) )
  3987. return 0;
  3988. for( asUINT n = 0; n < objType->enumValues.GetLength(); ++n )
  3989. {
  3990. if( objType->enumValues[n]->name == name )
  3991. {
  3992. outDt = asCDataType::CreateObject(objType, true);
  3993. outValue = objType->enumValues[n]->value;
  3994. return 1;
  3995. }
  3996. }
  3997. return 0;
  3998. }
  3999. int asCBuilder::GetEnumValue(const char *name, asCDataType &outDt, asDWORD &outValue, asSNameSpace *ns)
  4000. {
  4001. bool found = false;
  4002. // Search all available enum types
  4003. asUINT t;
  4004. for( t = 0; t < engine->objectTypes.GetLength(); t++ )
  4005. {
  4006. asCObjectType *ot = engine->objectTypes[t];
  4007. if( ns != ot->nameSpace ) continue;
  4008. if( GetEnumValueFromObjectType(ot, name, outDt, outValue) )
  4009. {
  4010. if( !found )
  4011. found = true;
  4012. else
  4013. {
  4014. // Found more than one value in different enum types
  4015. return 2;
  4016. }
  4017. }
  4018. }
  4019. for( t = 0; t < module->enumTypes.GetLength(); t++ )
  4020. {
  4021. asCObjectType *ot = module->enumTypes[t];
  4022. if( ns != ot->nameSpace ) continue;
  4023. if( GetEnumValueFromObjectType(ot, name, outDt, outValue) )
  4024. {
  4025. if( !found )
  4026. found = true;
  4027. else
  4028. {
  4029. // Found more than one value in different enum types
  4030. return 2;
  4031. }
  4032. }
  4033. }
  4034. if( found )
  4035. return 1;
  4036. // Didn't find any value
  4037. return 0;
  4038. }
  4039. #endif // AS_NO_COMPILER
  4040. END_AS_NAMESPACE