as_builder.cpp 139 KB

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