2
0

as_builder.cpp 140 KB

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