sqcompiler.cpp 116 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513
  1. /*
  2. see copyright notice in squirrel.h
  3. */
  4. #include "sqpcheader.h"
  5. #ifndef NO_COMPILER
  6. #include <stdarg.h>
  7. #include <setjmp.h>
  8. #include "sqopcodes.h"
  9. #include "sqstring.h"
  10. #include "sqfuncproto.h"
  11. #include "sqcompiler.h"
  12. #include "sqfuncstate.h"
  13. #include "sqlexer.h"
  14. #include "sqvm.h"
  15. #include "sqtable.h"
  16. enum
  17. {
  18. eFunctionType_global = 1,
  19. eFunctionType_local,
  20. eFunctionType_lambda,
  21. eFunctionType_member,
  22. eFunctionType_anonymous
  23. };
  24. #define EXPR 1
  25. #define OBJECT 2
  26. #define BASE 3
  27. #define LOCAL 4
  28. #define OUTER 5
  29. #define EXPR_STATEMENT 6 //we start from statement state
  30. struct SQExpState
  31. {
  32. SQInteger etype; /* expr. type; one of EXPR, OBJECT, BASE, OUTER, LOCAL or EXPR_STATEMENT */
  33. SQInteger epos; /* expr. location on stack; -1 for OBJECT and BASE */
  34. bool donot_get; /* signal not to deref the next value */
  35. };
  36. #define MAX_COMPILER_ERROR_LEN 256
  37. struct SQScope
  38. {
  39. SQInt32 stacksize;
  40. SQInt16 outers;
  41. SQInt16 nested;
  42. };
  43. #define BEGIN_SCOPE() SQScope __oldscope__ = _scope; \
  44. ++_scope.nested; \
  45. _scope.outers = (SQInt16)_fs->_outers; \
  46. _scope.stacksize = (SQInt32)_fs->GetStackSize();\
  47. _scope_types.push_back(SQTable::Create(_ss(_vm),0)); \
  48. _scope_consts.push_back(SQTable::Create(_ss(_vm),0));
  49. #define RESOLVE_OUTERS() if(_fs->GetStackSize() != _scope.stacksize) { \
  50. if(_fs->CountOuters(_scope.stacksize)) { \
  51. _fs->AddInstruction(_OP_CLOSE,0,_scope.stacksize); \
  52. } \
  53. }
  54. #define END_SCOPE_NO_CLOSE() { if(_fs->GetStackSize() != _scope.stacksize) { \
  55. _fs->SetStackSize(_scope.stacksize); \
  56. } \
  57. _scope = __oldscope__; \
  58. _scope_types.pop_back();\
  59. _scope_consts.pop_back();\
  60. }
  61. #define END_SCOPE() { SQInteger oldouters = _fs->_outers;\
  62. if(_fs->GetStackSize() != _scope.stacksize) { \
  63. _fs->SetStackSize(_scope.stacksize); \
  64. if(oldouters != _fs->_outers) { \
  65. _fs->AddInstruction(_OP_CLOSE,0,_scope.stacksize); \
  66. } \
  67. } \
  68. _scope = __oldscope__; \
  69. }
  70. #define BEGIN_BREAKBLE_BLOCK() SQInteger __nbreaks__=_fs->_unresolvedbreaks.size(); \
  71. SQInteger __ncontinues__=_fs->_unresolvedcontinues.size(); \
  72. _fs->_breaktargets.push_back(0);_fs->_continuetargets.push_back(0);
  73. #define END_BREAKBLE_BLOCK(continue_target) {__nbreaks__=_fs->_unresolvedbreaks.size()-__nbreaks__; \
  74. __ncontinues__=_fs->_unresolvedcontinues.size()-__ncontinues__; \
  75. if(__ncontinues__>0)ResolveContinues(_fs,__ncontinues__,continue_target); \
  76. if(__nbreaks__>0)ResolveBreaks(_fs,__nbreaks__); \
  77. _fs->_breaktargets.pop_back();_fs->_continuetargets.pop_back();}
  78. #define CASE_TK_LOCAL_CHAR_TYPES \
  79. case TK_LOCAL_STRING_T: \
  80. case TK_LOCAL_CHAR_T: \
  81. case TK_LOCAL_WCHAR_T
  82. #define CASE_TK_LOCAL_INT_TYPES \
  83. case TK_LOCAL_INT8_T: \
  84. case TK_LOCAL_INT16_T: \
  85. case TK_LOCAL_INT32_T: \
  86. case TK_LOCAL_INT64_T: \
  87. case TK_LOCAL_INT_T: \
  88. case TK_LOCAL_UINT8_T: \
  89. case TK_LOCAL_UINT16_T: \
  90. case TK_LOCAL_UINT32_T: \
  91. case TK_LOCAL_UINT64_T: \
  92. case TK_LOCAL_UINT_T: \
  93. case TK_LOCAL_SIZE_T: \
  94. case TK_LOCAL_SSIZE_T
  95. #define CASE_TK_LOCAL_FLOAT_TYPES \
  96. case TK_LOCAL_FLOAT_T: \
  97. case TK_LOCAL_DOUBLE_T: \
  98. case TK_LOCAL_LONG_DOUBLE_T
  99. #define CASE_TK_NUMBER_TYPES \
  100. CASE_TK_LOCAL_FLOAT_TYPES: \
  101. CASE_TK_LOCAL_INT_TYPES: \
  102. case TK_LOCAL_NUMBER_T
  103. #define CASE_CONST_TYPES \
  104. CASE_TK_LOCAL_CHAR_TYPES: \
  105. CASE_TK_NUMBER_TYPES: \
  106. case TK_LOCAL_BOOL_T: \
  107. case TK_LOCAL_VOIDPTR_T
  108. #define CASE_TK_LOCAL_TYPES \
  109. CASE_CONST_TYPES: \
  110. case TK_LOCAL_TABLE_T: \
  111. case TK_LOCAL_ANY_T: \
  112. case TK_LOCAL_ARRAY_T: \
  113. case TK_VOID: \
  114. case TK_LOCAL_WEAKREF_T
  115. #define CASE_TK_INTEGER \
  116. case TK_INTEGER: \
  117. case TK_UNSIGNED_INTEGER: \
  118. case TK_SHORT_INTEGER: \
  119. case TK_UNSIGNED_SHORT_INTEGER: \
  120. case TK_LONG_INTEGER: \
  121. case TK_UNSIGNED_LONG_INTEGER: \
  122. case TK_LONG_LONG_INTEGER: \
  123. case TK_UNSIGNED_LONG_LONG_INTEGER
  124. static SQInteger compilerReadFunc(SQUserPointer fp)
  125. {
  126. SQInteger c = fgetc((FILE *)fp);
  127. if(c == EOF)
  128. {
  129. return 0;
  130. }
  131. return c;
  132. }
  133. class SQCompiler
  134. {
  135. public:
  136. SQCompiler(SQVM *v, SQLEXREADFUNC rg, SQUserPointer up, const SQChar* sourcename,
  137. bool raiseerror, bool lineinfo, bool show_warnings, SQInteger max_nested_includes)
  138. {
  139. _vm=v;
  140. _lex.Init(_ss(v), rg, up,ThrowError,this);
  141. _sourcename = SQString::Create(_ss(v), sourcename);
  142. _lineinfo = lineinfo;
  143. _raiseerror = raiseerror;
  144. _show_warnings = show_warnings;
  145. _scope.outers = 0;
  146. _scope.stacksize = 0;
  147. _scope.nested = 0;
  148. _compilererror = NULL;
  149. _globals = SQTable::Create(_ss(_vm),0);
  150. _type_names = SQTable::Create(_ss(_vm),0);
  151. _extern_names = SQTable::Create(_ss(_vm),0);
  152. _max_nested_includes = max_nested_includes;
  153. _nested_includes_count = 0;
  154. _is_parsing_extern = false;
  155. _ifdef_exclude = 0;
  156. _ifdef_line = 0;
  157. _inside_ifdef = 0;
  158. squilu_lib_path = NULL;
  159. }
  160. ~SQCompiler()
  161. {
  162. _table(_globals)->Finalize();
  163. _globals.Null();
  164. }
  165. static void ThrowError(void *ud, const SQChar *s)
  166. {
  167. SQCompiler *c = (SQCompiler *)ud;
  168. c->Error(_SC("%s"), s);
  169. }
  170. void Error(const SQChar *s, ...) __attribute__((format(printf, 2, 3)))
  171. {
  172. va_list vl;
  173. va_start(vl, s);
  174. scvsprintf(error_buf, sizeof(error_buf), s, vl);
  175. va_end(vl);
  176. _compilererror = error_buf;
  177. longjmp(_errorjmp,1);
  178. }
  179. void Warning(const SQChar *s, ...) __attribute__((format(printf, 2, 3)))
  180. {
  181. if(!_show_warnings) return;
  182. va_list vl;
  183. va_start(vl, s);
  184. scvfprintf(stderr, s, vl);
  185. va_end(vl);
  186. }
  187. void ErrorNameAlreadyDeclared(const SQObject &name)
  188. {
  189. //Error(_SC("Name '%s' already declared"), _stringval(name));
  190. }
  191. bool CheckNameIsType(const SQObject &name)
  192. {
  193. for(int i=_scope.nested-1; i >= 0; --i)
  194. {
  195. if(_table(_scope_types[i])->Exists(name)) return true;
  196. }
  197. return _table(_type_names)->Exists(name);
  198. }
  199. bool CheckTypeName(const SQObject &name, bool addIfNotExists=false)
  200. {
  201. bool found = CheckNameIsType(name);
  202. if(addIfNotExists && !found)
  203. {
  204. SQObjectPtr oname = name, otrue = true;
  205. _table(_type_names)->NewSlot(oname, otrue);
  206. }
  207. return found;
  208. }
  209. bool TypesGet(const SQObjectPtr &key,SQObjectPtr &val)
  210. {
  211. for(int i=_scope.nested-1; i >= 0; --i)
  212. {
  213. if(_table(_scope_types[i])->Get(key,val)) return true;
  214. }
  215. return _table(_type_names)->NewSlot(key,val);
  216. }
  217. bool TypesNewSlot(const SQObjectPtr &key, const SQObjectPtr &val)
  218. {
  219. if(_scope.nested) return _table(_scope_types[_scope.nested-1])->NewSlot(key,val);
  220. return _table(_type_names)->NewSlot(key,val);
  221. }
  222. SQInteger CheckExternName(const SQObject &name, bool addIfNotExists=false)
  223. {
  224. SQObjectPtr orefcount;
  225. int found = _table(_extern_names)->Get(name, orefcount);
  226. if(addIfNotExists && !found)
  227. {
  228. SQObjectPtr oname = name;
  229. _integer(orefcount) = 1; //1 means only declared, 2 declared and assigned
  230. _table(_extern_names)->NewSlot(oname, orefcount);
  231. _table(_globals)->NewSlot(oname, orefcount);
  232. }
  233. return found ? _integer(orefcount) : 0;
  234. }
  235. SQInteger ExternNameSetRefCount(const SQObject &name)
  236. {
  237. SQInteger ref_count = CheckExternName(name);
  238. if(ref_count == 1)
  239. {
  240. SQObjectPtr orefcount;
  241. _integer(orefcount) = ref_count = 2;
  242. _table(_extern_names)->Set(name, orefcount);
  243. }
  244. return ref_count;
  245. }
  246. void AddGlobalName(const SQObject &name)
  247. {
  248. SQObjectPtr oname = name, otrue = true;
  249. _table(_globals)->NewSlot(oname, otrue);
  250. }
  251. void CheckGlobalName(const SQObject &name, bool addIfNotExists=false, bool checkLocals=true)
  252. {
  253. const SQChar *found = NULL;
  254. if(CheckExternName(name))
  255. {
  256. found = _SC("extern");
  257. }
  258. else if(_table(_globals)->Exists(name))
  259. {
  260. found = _SC("global");
  261. }
  262. if(found)
  263. {
  264. if(checkLocals) Error(_SC("%s '%s' already declared"), found, _stringval(name));
  265. else Warning(_SC("%s:%d:%d warning %s '%s' already declared will be shadowed\n"),
  266. _stringval(_sourcename), (int)_lex.data->currentline, (int)_lex.data->currentcolumn,
  267. found, _stringval(name));
  268. }
  269. else if(checkLocals) CheckLocalNameScope(name, -1, false);
  270. if(addIfNotExists)
  271. {
  272. AddGlobalName(name);
  273. }
  274. }
  275. void CheckLocalNameScope(const SQObject &name, SQInteger scope, bool checkGlobals=true)
  276. {
  277. SQInteger found = _fs->GetLocalVariable(name);
  278. if(found >= 0)
  279. {
  280. SQLocalVarInfo &lvi = _fs->_vlocals[found];
  281. if(lvi._scope == scope)
  282. Error(_SC("local '%s' already declared"), _stringval(name));
  283. else
  284. Warning(_SC("%s:%d:%d warning local '%s' already declared will be shadowed\n"),
  285. _stringval(_sourcename), (int)_lex.data->currentline, (int)_lex.data->currentcolumn, _stringval(name));
  286. }
  287. else
  288. {
  289. found = _fs->FindOuterVariable(name);
  290. if(found >= 0) Warning(_SC("%s:%d:%d warning outer variable '%s' already declared will be shadowed\n"),
  291. _stringval(_sourcename), (int)_lex.data->currentline, (int)_lex.data->currentcolumn, _stringval(name));
  292. }
  293. if(checkGlobals) CheckGlobalName(name, false, false);
  294. SQObjectPtr strongid = name;
  295. CheckConstsExists(strongid);
  296. }
  297. bool IsConstant(const SQObject &name,SQObject &e)
  298. {
  299. SQObjectPtr val;
  300. if(ConstsGet(name, val))
  301. {
  302. e = val;
  303. return true;
  304. }
  305. return false;
  306. }
  307. SQInteger ExpressionConstant(SQObject id)
  308. {
  309. SQObject constant;
  310. SQInteger epos = 0;
  311. if(IsConstant(id, constant))
  312. {
  313. /* Handle named constant */
  314. SQObjectPtr constval;
  315. SQObject constid;
  316. if(sq_type(constant) == OT_TABLE)
  317. {
  318. Expect('.');
  319. constid = Expect(TK_IDENTIFIER);
  320. if(!_table(constant)->Get(constid, constval))
  321. {
  322. constval.Null();
  323. Error(_SC("invalid constant [%s.%s]"), _stringval(id), _stringval(constid));
  324. }
  325. }
  326. else
  327. {
  328. constval = constant;
  329. }
  330. epos = _fs->PushTarget();
  331. /* generate direct or literal function depending on size */
  332. SQObjectType ctype = sq_type(constval);
  333. switch(ctype)
  334. {
  335. case OT_INTEGER:
  336. EmitLoadConstInt(_integer(constval),epos);
  337. break;
  338. case OT_FLOAT:
  339. EmitLoadConstFloat(_float(constval),epos);
  340. break;
  341. default:
  342. _fs->AddInstruction(_OP_LOAD,epos,_fs->GetConstant(constval));
  343. break;
  344. }
  345. }
  346. else
  347. {
  348. Error(_SC("invalid constant [%s]"), _stringval(id));
  349. }
  350. return epos;
  351. }
  352. void CheckConstsExists(const SQObjectPtr &key)
  353. {
  354. int found = -1;
  355. for(int i=_scope.nested-1; i >= 0; --i)
  356. {
  357. if(_table(_scope_consts[i])->Exists(key))
  358. {
  359. found = i+1;
  360. break;
  361. }
  362. }
  363. if(found < 0 && _table(_ss(_vm)->_consts)->Exists(key)) found = 0;
  364. if(found == _scope.nested)
  365. {
  366. Error(_SC("constant '%s' already exists\n"), _stringval(key));
  367. }
  368. if(found >= 0) Warning(_SC("%s:%d:%d warning an already defined constant '%s' will be shadowed\n"),
  369. _stringval(_sourcename), (int)_lex.data->currentline, (int)_lex.data->currentcolumn, _stringval(key));
  370. }
  371. bool ConstsGet(const SQObjectPtr &key,SQObjectPtr &val)
  372. {
  373. for(int i=_scope.nested-1; i >= 0; --i)
  374. {
  375. if(_table(_scope_consts[i])->Get(key,val)) return true;
  376. }
  377. return _table(_ss(_vm)->_consts)->Get(key,val);
  378. }
  379. void CompileTimeCheckConstsGet(const SQObjectPtr &key,SQObjectPtr &val)
  380. {
  381. if(!ConstsGet(key, val))
  382. {
  383. Error(_SC("compile time checked constant fail \"%s\""), _stringval(key));
  384. }
  385. }
  386. bool ConstsNewSlot(const SQObjectPtr &key, const SQObjectPtr &val)
  387. {
  388. if(_scope.nested) return _table(_scope_consts[_scope.nested-1])->NewSlot(key,val);
  389. return _table(_ss(_vm)->_consts)->NewSlot(key,val);
  390. }
  391. void Lex(bool dontThrowIntegerOverflow=false)
  392. {
  393. _token = _lex.Lex(dontThrowIntegerOverflow);
  394. }
  395. SQObjectPtr GetTokenObject(SQInteger tok, bool doLex=true)
  396. {
  397. SQObjectPtr ret;
  398. switch(tok)
  399. {
  400. case TK_IDENTIFIER:
  401. ret = _fs->CreateString(_lex.data->svalue);
  402. break;
  403. case TK_STRING_LITERAL:
  404. ret = _fs->CreateString(_lex.data->svalue,_lex.data->longstr.size()-1);
  405. break;
  406. CASE_TK_INTEGER:
  407. ret = SQObjectPtr(_lex.data->nvalue);
  408. break;
  409. case TK_FLOAT:
  410. ret = SQObjectPtr(_lex.data->fvalue);
  411. break;
  412. default:
  413. ret = _fs->CreateString(_lex.GetTokenName(_token));
  414. }
  415. if(doLex) Lex();
  416. return ret;
  417. }
  418. void ErrorIfNotToken(SQInteger tok)
  419. {
  420. if(_token != tok)
  421. {
  422. if(((_token == TK_CONSTRUCTOR) || (_token == TK_DESTRUCTOR)) && tok == TK_IDENTIFIER)
  423. {
  424. //do nothing
  425. }
  426. else
  427. {
  428. const SQChar *etypename;
  429. if(tok > 255)
  430. {
  431. switch(tok)
  432. {
  433. case TK_IDENTIFIER:
  434. etypename = _SC("IDENTIFIER");
  435. break;
  436. case TK_STRING_LITERAL:
  437. etypename = _SC("STRING_LITERAL");
  438. break;
  439. CASE_TK_INTEGER:
  440. etypename = _SC("INTEGER");
  441. break;
  442. case TK_FLOAT:
  443. etypename = _SC("FLOAT");
  444. break;
  445. default:
  446. etypename = _lex.Tok2Str(tok);
  447. }
  448. Error(_SC("expected '%s'"), etypename);
  449. }
  450. Error(_SC("expected '%c'"), (int)tok);
  451. }
  452. }
  453. }
  454. SQObject Expect(SQInteger tok, bool doLex=true)
  455. {
  456. ErrorIfNotToken(tok);
  457. return GetTokenObject(tok, doLex);
  458. }
  459. SQObject ExpectTypeToken()
  460. {
  461. switch(_token)
  462. {
  463. CASE_TK_LOCAL_TYPES:
  464. return GetTokenObject(_token);
  465. case TK_IDENTIFIER:
  466. break;
  467. default:
  468. ErrorIfNotToken(TK_IDENTIFIER);
  469. }
  470. return GetTokenObject(TK_IDENTIFIER);
  471. }
  472. bool IsEndOfStatement()
  473. {
  474. return ((_lex.data->prevtoken == _SC('\n')) || (_token == SQUIRREL_EOB) || (_token == _SC('}')) || (_token == _SC(';')));
  475. }
  476. void OptionalSemicolon()
  477. {
  478. if(_token == _SC(';'))
  479. {
  480. Lex();
  481. return;
  482. }
  483. if(!IsEndOfStatement())
  484. {
  485. Error(_SC("end of statement expected (; or lf) found (%d)"), (int)_token);
  486. }
  487. }
  488. void MoveIfCurrentTargetIsLocal()
  489. {
  490. SQInteger trg = _fs->TopTarget();
  491. if(_fs->IsLocal(trg))
  492. {
  493. trg = _fs->PopTarget(); //pops the target and moves it
  494. _fs->AddInstruction(_OP_MOVE, _fs->PushTarget(), trg);
  495. }
  496. }
  497. void Pragma()
  498. {
  499. SQInteger line = _lex.data->currentline;
  500. SQInteger column = _lex.data->currentcolumn;
  501. Lex();
  502. if(_token == TK_ELSE)
  503. {
  504. if(!_inside_ifdef) Error(_SC("'#else' without '#ifdef'"));
  505. Lex();
  506. //if we were not been excluding we start excluding
  507. if(_ifdef_exclude == 0) ++_ifdef_exclude;
  508. else if(_ifdef_exclude == 1) --_ifdef_exclude;
  509. return;
  510. }
  511. SQObject id = Expect(TK_IDENTIFIER);
  512. if(scstrcmp(_stringval(id), _SC("include")) == 0)
  513. {
  514. #if SQ_ENABLE_INCLUDES
  515. SQInteger nested_count = _nested_includes_count + 1;
  516. if((_max_nested_includes <= 0) || (nested_count > _max_nested_includes))
  517. {
  518. Error(_SC("Error: too many nested includes %d %s\n"), (int)nested_count, _stringval(id));
  519. }
  520. //C/C++ system includes we do not use it in SquiLu
  521. if(_ifdef_exclude && (_token == _SC('<')))
  522. {
  523. while(_token > 0)
  524. {
  525. if(_token == _SC('>'))
  526. {
  527. Lex();
  528. return;
  529. }
  530. Lex();
  531. }
  532. return;
  533. }
  534. //do not call Lex() since next token can try search for id defined in the include
  535. //and then go global instead of local, we'll call it after including
  536. id = Expect(TK_STRING_LITERAL, false);
  537. if(_ifdef_exclude)
  538. {
  539. Lex();
  540. return;
  541. }
  542. //Warning(_SC("%s:%d:%d warning pragma include %s\n"),
  543. // _stringval(_sourcename), line, column, _stringval(id));
  544. const SQChar *lib_path = NULL;
  545. //first try the filename alone
  546. FILE *fp = scfopen(_stringval(id), "r");
  547. while(!fp)
  548. {
  549. //now if we have an environment path let's try it
  550. if(!lib_path)
  551. {
  552. if(!squilu_lib_path) squilu_lib_path = _vm->GetIncludePath();
  553. lib_path = squilu_lib_path;
  554. if(!lib_path) break;
  555. }
  556. while (*lib_path == *SQUILU_PATH_SEP) lib_path++; /* skip separators */
  557. if (*lib_path == '\0') break; /* no more templates */
  558. const SQChar *l = scstrchr(lib_path, *SQUILU_PATH_SEP); /* find next separator */
  559. if (l == NULL) l = lib_path + scstrlen(lib_path);
  560. size_t path_len = l - lib_path;
  561. SQChar file_path_name[SQUILU_MAX_PATH];
  562. if(path_len < sizeof(file_path_name)) //enough room to work ?
  563. {
  564. scsprintf(file_path_name, sizeof(file_path_name), "%s", lib_path);
  565. scsprintf(file_path_name + path_len, sizeof(file_path_name) - path_len,
  566. "%s%s", SQUILU_DIRSEP, _stringval(id));
  567. //printf("file_path_name = %s\n", file_path_name);
  568. fp = scfopen(file_path_name, "r");
  569. lib_path += path_len; //move the pointer to the next path
  570. }
  571. }
  572. if(fp != NULL)
  573. {
  574. //increment nested count
  575. ++_nested_includes_count;
  576. //save current source file and lex state
  577. SQUserPointer saved_up = _lex._up; //current userpointer
  578. SQLEXREADFUNC saved_readf = _lex._readf; //current readfunction
  579. SQInteger saved_line = _lex.data->currentline;
  580. SQInteger saved_column = _lex.data->currentcolumn;
  581. SQInteger saved_curdata = _lex.data->currdata;
  582. SQInteger saved_prevtoken = _lex.data->prevtoken;
  583. SQInteger saved_token = _token;
  584. SQInteger saved__inside_ifdef = _inside_ifdef;
  585. SQObjectPtr saved_source_name = _sourcename;
  586. //set new source file
  587. _fs->_sourcename = id;
  588. _sourcename = id;
  589. _lex.ResetReader(compilerReadFunc, fp, 1);
  590. _inside_ifdef = 0;
  591. //compile the include file
  592. Lex();
  593. while(_token > 0)
  594. {
  595. Statement();
  596. if(_lex.data->prevtoken != _SC('}') && _lex.data->prevtoken != _SC(';')) OptionalSemicolon();
  597. }
  598. //close file
  599. fclose(fp);
  600. if(_inside_ifdef) Error(_SC("unterminated #ifdef starting on line %d"), (int)_ifdef_line);
  601. //restore saved source file and lex state
  602. _fs->_sourcename = saved_source_name;
  603. _sourcename = saved_source_name;
  604. _token = saved_token;
  605. _lex.data->currdata = saved_curdata;
  606. _lex.data->prevtoken = saved_prevtoken;
  607. _lex.data->currentcolumn = saved_column;
  608. _lex.data->currentline = saved_line;
  609. _lex._readf = saved_readf;
  610. _lex._up = saved_up;
  611. --_nested_includes_count;
  612. _inside_ifdef = saved__inside_ifdef;
  613. //done let's continue working
  614. //Now we do the Lex() call skiped before compile the include file
  615. Lex();
  616. }
  617. else
  618. {
  619. Error(_SC("Error: opening include file %s\n"), _stringval(id));
  620. }
  621. #else
  622. Error(_SC("Error: includes are not enabled\n"));
  623. #endif
  624. }
  625. else if(scstrcmp(_stringval(id), _SC("endif")) == 0)
  626. {
  627. if(!_inside_ifdef) Error(_SC("'#endif' without '#ifdef'"));
  628. if(_ifdef_exclude) --_ifdef_exclude;
  629. --_inside_ifdef;
  630. }
  631. else if((scstrcmp(_stringval(id), _SC("ifdef")) == 0)
  632. || (scstrcmp(_stringval(id), _SC("ifndef")) == 0))
  633. {
  634. ++_inside_ifdef;
  635. bool isIfndef = _stringval(id)[2] == _SC('n');
  636. id = Expect(TK_IDENTIFIER);
  637. if(_ifdef_exclude) ++_ifdef_exclude;
  638. else
  639. {
  640. _ifdef_line = line;
  641. bool isDefined = _vm->IsDefined(_stringval(id));
  642. if(isIfndef) isDefined = !isDefined;
  643. _ifdef_exclude = (isDefined ? 0 : 1);
  644. }
  645. }
  646. else if(scstrcmp(_stringval(id), _SC("define")) == 0)
  647. {
  648. id = Expect(TK_IDENTIFIER);
  649. if(_ifdef_exclude == 0)
  650. {
  651. if(_vm->IsDefined(_stringval(id)))
  652. Warning(_SC("%s:%d:%d warning '%s' redefined\n"),
  653. _stringval(_sourcename), (int)line, (int)column, _stringval(id));
  654. _vm->AddDefined(_stringval(id));
  655. }
  656. }
  657. else if(scstrcmp(_stringval(id), _SC("undef")) == 0)
  658. {
  659. id = Expect(TK_IDENTIFIER);
  660. if(_ifdef_exclude == 0) _vm->RemoveDefined(_stringval(id));
  661. }
  662. else
  663. {
  664. _lex.data->currentline = line;
  665. Error(_SC("Error: unknown pragma %s\n"), _stringval(id));
  666. }
  667. }
  668. bool Compile(SQObjectPtr &o)
  669. {
  670. _debugline = 1;
  671. _debugop = 0;
  672. SQFuncState funcstate(_ss(_vm), NULL,ThrowError,this);
  673. funcstate._name = SQString::Create(_ss(_vm), _SC("main"));
  674. _fs = &funcstate;
  675. SQObject strTemp = _fs->CreateString(_SC("this"));
  676. if(_fs->AddParameter(strTemp, _scope.nested+1) < 0)
  677. ErrorNameAlreadyDeclared(strTemp);
  678. strTemp = _fs->CreateString(_SC("vargv"));
  679. if(_fs->AddParameter(strTemp, _scope.nested+1) < 0)
  680. ErrorNameAlreadyDeclared(strTemp);
  681. _fs->_varparams = true;
  682. _fs->_sourcename = _sourcename;
  683. SQInteger stacksize = _fs->GetStackSize();
  684. if(setjmp(_errorjmp) == 0)
  685. {
  686. Lex();
  687. while(_token > 0)
  688. {
  689. Statement();
  690. if(_lex.data->prevtoken != _SC('}') && _lex.data->prevtoken != _SC(';')) OptionalSemicolon();
  691. }
  692. if(_inside_ifdef) Error(_SC("unterminated #ifdef starting on line %d"), (int)_ifdef_line);
  693. _fs->SetStackSize(stacksize);
  694. _fs->AddLineInfos(_lex.data->currentline, _lineinfo, true);
  695. _fs->AddInstruction(_OP_RETURN, 0xFF);
  696. _fs->SetStackSize(0);
  697. o =_fs->BuildProto();
  698. #ifdef _DEBUG_DUMP
  699. _fs->Dump(_funcproto(o));
  700. #endif
  701. }
  702. else
  703. {
  704. if(_raiseerror && _ss(_vm)->_compilererrorhandler)
  705. {
  706. _ss(_vm)->_compilererrorhandler(_vm, _compilererror, sq_type(_sourcename) == OT_STRING?_stringval(_sourcename):_SC("unknown"),
  707. _lex.data->currentline, _lex.data->currentcolumn);
  708. }
  709. _vm->_lasterror = SQString::Create(_ss(_vm), _compilererror, -1);
  710. _vm->_lasterror_line = _lex.data->currentline;
  711. _vm->_lasterror_column = _lex.data->currentcolumn;
  712. return false;
  713. }
  714. return true;
  715. }
  716. void Statements()
  717. {
  718. while(_token != _SC('}') && _token != TK_DEFAULT && _token != TK_CASE)
  719. {
  720. Statement();
  721. if(_lex.data->prevtoken != _SC('}') && _lex.data->prevtoken != _SC(';')) OptionalSemicolon();
  722. }
  723. }
  724. void Statement(bool closeframe = true)
  725. {
  726. _es.etype = EXPR_STATEMENT;
  727. SQObject id;
  728. _fs->AddLineInfos(_lex.data->currentline, _lineinfo);
  729. while(_ifdef_exclude && (_token != TK_PRAGMA))
  730. {
  731. Lex(true); //dontThrowIntegerOverflow for when in 32bits parsing 64bits integer inside excluded ifdef
  732. if(_token <= 0) Error(_SC("'#endif' expected to close '#ifdef' started at %d"), (int)_ifdef_line);
  733. }
  734. start_again:
  735. switch(_token)
  736. {
  737. case _SC(';'):
  738. Lex();
  739. break;
  740. case TK_IF:
  741. IfStatement();
  742. break;
  743. case TK_WHILE:
  744. WhileStatement();
  745. break;
  746. case TK_DO:
  747. DoWhileStatement();
  748. break;
  749. case TK_FOR:
  750. ForStatement();
  751. break;
  752. case TK_FOREACH:
  753. ForEachStatement();
  754. break;
  755. case TK_SWITCH:
  756. SwitchStatement();
  757. break;
  758. case TK_LOCAL:
  759. //case TK_CONST:
  760. CASE_TK_LOCAL_TYPES:
  761. LocalDeclStatement();
  762. break;
  763. case TK_RETURN:
  764. case TK_YIELD:
  765. {
  766. SQOpcode op;
  767. if(_token == TK_RETURN)
  768. {
  769. op = _OP_RETURN;
  770. }
  771. else
  772. {
  773. op = _OP_YIELD;
  774. _fs->_bgenerator = true;
  775. }
  776. Lex();
  777. if(!IsEndOfStatement())
  778. {
  779. SQInteger retexp = _fs->GetCurrentPos()+1;
  780. CommaExpr(true);
  781. if(op == _OP_RETURN && _fs->_traps > 0)
  782. _fs->AddInstruction(_OP_POPTRAP, _fs->_traps, 0);
  783. _fs->_returnexp = retexp;
  784. _fs->AddInstruction(op, 1, _fs->PopTarget(),_fs->GetStackSize());
  785. }
  786. else
  787. {
  788. if(op == _OP_RETURN && _fs->_traps > 0)
  789. _fs->AddInstruction(_OP_POPTRAP, _fs->_traps ,0);
  790. _fs->_returnexp = -1;
  791. _fs->AddInstruction(op, 0xFF,0,_fs->GetStackSize());
  792. }
  793. break;
  794. }
  795. case TK_GOTO:
  796. {
  797. //error if outside any function
  798. //if(!_fs->_parent) Error(_SC("'goto' has to be in a function block"));
  799. Lex(); //ignore for now
  800. id = Expect(TK_IDENTIFIER);
  801. SQGotoLabelsInfo info;
  802. info.name = id;
  803. info.line = _lex.data->currentline; //need to get line number here
  804. info.traps = _fs->_traps;
  805. info.nested = _scope.nested;
  806. //Expect(_SC(';'));
  807. if(info.traps) _fs->AddInstruction(_OP_NOP, 0, 0); //for _OP_POPTRAP
  808. RESOLVE_OUTERS();
  809. _fs->AddInstruction(_OP_JMP, 0, -1234);
  810. //instruction pos
  811. info.pos = _fs->GetCurrentPos();
  812. _fs->_unresolvedgotos.push_back(info);
  813. }
  814. break;
  815. case TK_BREAK:
  816. if(_fs->_breaktargets.size() <= 0)Error(_SC("'break' has to be in a loop block"));
  817. if(_fs->_breaktargets.top() > 0)
  818. {
  819. _fs->AddInstruction(_OP_POPTRAP, _fs->_breaktargets.top(), 0);
  820. }
  821. RESOLVE_OUTERS();
  822. _fs->AddInstruction(_OP_JMP, 0, -1234);
  823. _fs->_unresolvedbreaks.push_back(_fs->GetCurrentPos());
  824. Lex();
  825. break;
  826. case TK_CONTINUE:
  827. if(_fs->_continuetargets.size() <= 0)Error(_SC("'continue' has to be in a loop block"));
  828. if(_fs->_continuetargets.top() > 0)
  829. {
  830. _fs->AddInstruction(_OP_POPTRAP, _fs->_continuetargets.top(), 0);
  831. }
  832. RESOLVE_OUTERS();
  833. _fs->AddInstruction(_OP_JMP, 0, -1234);
  834. _fs->_unresolvedcontinues.push_back(_fs->GetCurrentPos());
  835. Lex();
  836. break;
  837. case TK_FUNCTION:
  838. FunctionStatement();
  839. break;
  840. case TK_CLASS:
  841. case TK_STRUCT:
  842. case TK_INTERFACE:
  843. ClassStatement();
  844. break;
  845. case TK_ENUM:
  846. EnumStatement();
  847. break;
  848. case _SC('{'):
  849. {
  850. BEGIN_SCOPE();
  851. Lex();
  852. Statements();
  853. Expect(_SC('}'));
  854. if(closeframe)
  855. {
  856. END_SCOPE();
  857. }
  858. else
  859. {
  860. END_SCOPE_NO_CLOSE();
  861. }
  862. }
  863. break;
  864. case TK_TRY:
  865. TryCatchStatement();
  866. break;
  867. case TK_THROW:
  868. Lex();
  869. CommaExpr();
  870. _fs->AddInstruction(_OP_THROW, _fs->PopTarget());
  871. break;
  872. case TK_CONST:
  873. {
  874. Lex();
  875. if(_token == _SC('$'))
  876. {
  877. //string const
  878. Lex();
  879. id = Expect(TK_IDENTIFIER);
  880. SQObjectPtr strongid = id;
  881. CheckLocalNameScope(id, _scope.nested);
  882. //CheckConstsExists(strongid);
  883. OptionalSemicolon();
  884. ConstsNewSlot(strongid,SQObjectPtr(id));
  885. break;
  886. }
  887. ////C/C++ type declaration using local types;
  888. switch(_token){
  889. CASE_CONST_TYPES:
  890. Lex(); //ignore for now
  891. break;
  892. }
  893. if(_token == TK_IDENTIFIER)
  894. {
  895. id = _fs->CreateString(_lex.data->svalue);
  896. if(CheckTypeName(id)) //C/C++ type declaration;
  897. {
  898. goto start_again;
  899. }
  900. Lex();
  901. }
  902. else id = Expect(TK_IDENTIFIER);
  903. if(_token == _SC(':'))
  904. {
  905. //type specifier like typescript
  906. Lex();
  907. ExpectTypeToken(); //ignore for now
  908. }
  909. Expect(_SC('='));
  910. SQObjectPtr strongid = id;
  911. CheckLocalNameScope(id, _scope.nested);
  912. //CheckConstsExists(strongid);
  913. SQObject val = ExpectScalar();
  914. OptionalSemicolon();
  915. ConstsNewSlot(strongid,SQObjectPtr(val));
  916. }
  917. break;
  918. case TK_INLINE: //accept and ignore
  919. case TK_CONSTEXPR: //accept and ignore
  920. case TK_FRIEND:
  921. case TK_VOLATILE:
  922. Lex();
  923. goto start_again;
  924. case TK_STATIC:
  925. if(_scope.nested)
  926. {
  927. Warning(_SC("%s:%d:%d warning static cualifier is ignored\n"),
  928. _stringval(_sourcename), (int)_lex.data->currentline, (int)_lex.data->currentcolumn);
  929. }
  930. Lex(); //ignore it only to allow run some C/C++ code
  931. goto start_again;
  932. case TK_DECLARE: //parse as extern
  933. case TK_EXTERN:
  934. ExternDeclStatement();
  935. break;
  936. case TK_TYPEDEF:
  937. {
  938. Lex();
  939. SQObject type_val = ExpectTypeToken();
  940. id = ExpectTypeToken();
  941. SQObjectPtr strongid = id;
  942. CheckLocalNameScope(id, _scope.nested);
  943. //Expect(_SC(';'));
  944. TypesNewSlot(strongid,SQObjectPtr(type_val));
  945. if(_token == _SC('[')) //fixed size array
  946. {
  947. Lex();
  948. Expect(TK_INTEGER);
  949. Expect(_SC(']'));
  950. }
  951. }
  952. break;
  953. case TK_USING:
  954. {
  955. Lex();
  956. id = Expect(TK_IDENTIFIER);
  957. Expect('=');
  958. SQObjectPtr strongid = id;
  959. CheckLocalNameScope(id, _scope.nested);
  960. SQObject type_val = ExpectTypeToken();
  961. //Expect(_SC(';'));
  962. TypesNewSlot(strongid,SQObjectPtr(type_val));
  963. }
  964. break;
  965. case TK_PRAGMA:
  966. Pragma();
  967. break;
  968. case TK_UNSAFE:
  969. Lex(); //ignore for now
  970. goto start_again;
  971. case TK_TEMPLATE:
  972. TemplateStatement();
  973. break;
  974. case TK_IDENTIFIER:
  975. {
  976. id = _fs->CreateString(_lex.data->svalue);
  977. SQInteger lhtk = _lex.LookaheadLex();
  978. if(lhtk == _SC(':'))
  979. {
  980. //if(!_fs->_parent) Error(_SC("'label' has to be inside a function block"));
  981. if(!_fs->AddGotoTarget(id, _lex.data->currentline, _fs->_traps, _scope.nested))
  982. {
  983. Error(_SC("Label already declared"));
  984. }
  985. Lex(); //eat ':'
  986. Lex();
  987. break;
  988. }
  989. if(CheckTypeName(id)) //C/C++ type declaration;
  990. {
  991. if(lhtk != _SC('.'))
  992. {
  993. LocalDeclStatement();
  994. break;
  995. }
  996. }
  997. }
  998. default:
  999. CommaExpr();
  1000. _fs->DiscardTarget();
  1001. /*
  1002. //Fagiano says that this is not a bug
  1003. //and with this modification the stack grow by one lement all the time
  1004. if(_token == TK_IDENTIFIER){
  1005. CommaExpr();
  1006. if(_token == TK_IDENTIFIER){
  1007. Error(_SC(" '=' expected near '%s'"), _lex.data->svalue);
  1008. }
  1009. }
  1010. */
  1011. //_fs->PopTarget();
  1012. break;
  1013. }
  1014. _fs->SnoozeOpt();
  1015. }
  1016. void EmitDerefOp(SQOpcode op)
  1017. {
  1018. SQInteger val = _fs->PopTarget();
  1019. SQInteger key = _fs->PopTarget();
  1020. SQInteger src = _fs->PopTarget();
  1021. _fs->AddInstruction(op,_fs->PushTarget(),src,key,val);
  1022. }
  1023. void Emit2ArgsOP(SQOpcode op, SQInteger p3 = 0)
  1024. {
  1025. SQInteger p2 = _fs->PopTarget(); //src in OP_GET
  1026. SQInteger p1 = _fs->PopTarget(); //key in OP_GET
  1027. _fs->AddInstruction(op,_fs->PushTarget(), p1, p2, p3);
  1028. }
  1029. void EmitCompoundArith(SQInteger tok, SQInteger etype, SQInteger pos)
  1030. {
  1031. /* Generate code depending on the expression type */
  1032. switch(etype)
  1033. {
  1034. case LOCAL:
  1035. {
  1036. SQOpcode op = ChooseArithOpByToken(tok);
  1037. SQInteger p3 = 0;
  1038. SQInteger p2 = _fs->PopTarget(); //src in OP_GET
  1039. SQInteger p1 = _fs->PopTarget(); //key in OP_GET
  1040. _fs->PushTarget(p1);
  1041. //EmitCompArithLocal(tok, p1, p1, p2);
  1042. if(op == _OP_BITW)
  1043. {
  1044. p3 = ChooseBitwOpByToken(tok);
  1045. }
  1046. _fs->AddInstruction(op,p1, p2, p1, p3);
  1047. _fs->SnoozeOpt(); //FIX: stop optimizer in retargeting opcode
  1048. }
  1049. break;
  1050. case OBJECT:
  1051. case BASE:
  1052. {
  1053. SQInteger val = _fs->PopTarget();
  1054. SQInteger key = _fs->PopTarget();
  1055. SQInteger src = _fs->PopTarget();
  1056. /* _OP_COMPARITH mixes dest obj and source val in the arg1 */
  1057. _fs->AddInstruction(_OP_COMPARITH, _fs->PushTarget(), (src<<16)|val, key, ChooseCompArithCharByToken(tok));
  1058. }
  1059. break;
  1060. case OUTER:
  1061. {
  1062. SQInteger val = _fs->TopTarget();
  1063. SQInteger tmp = _fs->PushTarget();
  1064. _fs->AddInstruction(_OP_GETOUTER, tmp, pos);
  1065. _fs->AddInstruction(ChooseArithOpByToken(tok), tmp, val, tmp, 0);
  1066. _fs->PopTarget();
  1067. _fs->PopTarget();
  1068. _fs->AddInstruction(_OP_SETOUTER, _fs->PushTarget(), pos, tmp);
  1069. }
  1070. break;
  1071. }
  1072. }
  1073. void CommaExpr(bool warningAssign=false)
  1074. {
  1075. for(Expression(warningAssign); _token == ','; _fs->PopTarget(), Lex(), CommaExpr(warningAssign));
  1076. }
  1077. void ErrorIfConst()
  1078. {
  1079. SQLocalVarInfo &vsrc = _fs->_vlocals[_fs->TopTarget()];
  1080. //printf("%d %d %d %d %s\n", __LINE__, vsrc._scope, vsrc._type, vsrc._pos, vsrc._name._unVal.pString ? _stringval(vsrc._name) : "?");
  1081. if(vsrc._type & _VAR_CONST) Error(_SC("can't assign to a const variable"));
  1082. }
  1083. void Expression(bool warningAssign=false)
  1084. {
  1085. SQExpState es = _es;
  1086. _es.etype = EXPR;
  1087. _es.epos = -1;
  1088. _es.donot_get = false;
  1089. SQObject id;
  1090. if((_token == TK_IDENTIFIER) && (es.etype == EXPR_STATEMENT))
  1091. {
  1092. id = _fs->CreateString(_lex.data->svalue);
  1093. }
  1094. //else id = {}; //old compilers do not allow this
  1095. else id._type = OT_NULL; //segfault without it with gcc -O3
  1096. LogicalOrExp();
  1097. switch(_token)
  1098. {
  1099. case _SC('='):
  1100. case TK_NEWSLOT:
  1101. case TK_MINUSEQ:
  1102. case TK_PLUSEQ:
  1103. case TK_MULEQ:
  1104. case TK_DIVEQ:
  1105. case TK_MODEQ:
  1106. case TK_BIT_XOR_EQ:
  1107. case TK_BIT_AND_EQ:
  1108. case TK_BIT_OR_EQ:
  1109. case TK_BIT_SHIFT_LEFT_EQ:
  1110. case TK_BIT_SHIFT_RIGHT_EQ:
  1111. {
  1112. SQInteger op = _token;
  1113. SQInteger ds = _es.etype;
  1114. SQInteger pos = _es.epos;
  1115. if(ds == EXPR) Error(_SC("can't assign expression"));
  1116. else if(ds == BASE) Error(_SC("'base' cannot be modified"));
  1117. Lex();
  1118. Expression();
  1119. switch(op)
  1120. {
  1121. case TK_NEWSLOT:
  1122. if(ds == OBJECT || ds == BASE)
  1123. {
  1124. EmitDerefOp(_OP_NEWSLOT);
  1125. if((_es.epos == -1) && (es.etype == EXPR_STATEMENT)
  1126. && (sq_type(id) == OT_STRING) ) AddGlobalName(id);
  1127. }
  1128. else //if _derefstate != DEREF_NO_DEREF && DEREF_FIELD so is the index of a local
  1129. Error(_SC("can't 'create' a local slot"));
  1130. break;
  1131. case _SC('='): //ASSIGN
  1132. if(warningAssign) Warning(_SC("%s:%d:%d warning making assignment, maybe it's not what you want\n"),
  1133. _stringval(_sourcename), (int)_lex.data->currentline, (int)_lex.data->currentcolumn);
  1134. switch(ds)
  1135. {
  1136. case LOCAL:
  1137. {
  1138. SQInteger src = _fs->PopTarget();
  1139. SQInteger dst = _fs->TopTarget();
  1140. _fs->AddInstruction(_OP_MOVE, dst, src);
  1141. }
  1142. break;
  1143. case OBJECT:
  1144. case BASE:
  1145. EmitDerefOp(_OP_SET);
  1146. break;
  1147. case OUTER:
  1148. {
  1149. SQInteger src = _fs->PopTarget();
  1150. SQInteger dst = _fs->PushTarget();
  1151. _fs->AddInstruction(_OP_SETOUTER, dst, pos, src);
  1152. }
  1153. }
  1154. break;
  1155. case TK_MINUSEQ:
  1156. case TK_PLUSEQ:
  1157. case TK_MULEQ:
  1158. case TK_DIVEQ:
  1159. case TK_MODEQ:
  1160. case TK_BIT_XOR_EQ:
  1161. case TK_BIT_AND_EQ:
  1162. case TK_BIT_OR_EQ:
  1163. case TK_BIT_SHIFT_LEFT_EQ:
  1164. case TK_BIT_SHIFT_RIGHT_EQ:
  1165. EmitCompoundArith(op, ds, pos);
  1166. break;
  1167. }
  1168. }
  1169. break;
  1170. case _SC('?'):
  1171. {
  1172. Lex();
  1173. _fs->AddInstruction(_OP_JZ, _fs->PopTarget());
  1174. SQInteger jzpos = _fs->GetCurrentPos();
  1175. SQInteger trg = _fs->PushTarget();
  1176. Expression();
  1177. SQInteger first_exp = _fs->PopTarget();
  1178. if(trg != first_exp) _fs->AddInstruction(_OP_MOVE, trg, first_exp);
  1179. SQInteger endfirstexp = _fs->GetCurrentPos();
  1180. _fs->AddInstruction(_OP_JMP, 0, 0);
  1181. Expect(_SC(':'));
  1182. SQInteger jmppos = _fs->GetCurrentPos();
  1183. Expression();
  1184. SQInteger second_exp = _fs->PopTarget();
  1185. if(trg != second_exp) _fs->AddInstruction(_OP_MOVE, trg, second_exp);
  1186. _fs->SetInstructionParam(jmppos, 1, _fs->GetCurrentPos() - jmppos);
  1187. _fs->SetInstructionParam(jzpos, 1, endfirstexp - jzpos + 1);
  1188. _fs->SnoozeOpt();
  1189. }
  1190. break;
  1191. }
  1192. _es = es;
  1193. }
  1194. template<typename T> void INVOKE_EXP(T f)
  1195. {
  1196. SQExpState es = _es;
  1197. _es.etype = EXPR;
  1198. _es.epos = -1;
  1199. _es.donot_get = false;
  1200. (this->*f)();
  1201. _es = es;
  1202. }
  1203. template<typename T> void BIN_EXP(SQOpcode op, T f,SQInteger op3 = 0)
  1204. {
  1205. Lex();
  1206. INVOKE_EXP(f);
  1207. SQInteger op1 = _fs->PopTarget();
  1208. SQInteger op2 = _fs->PopTarget();
  1209. _fs->AddInstruction(op, _fs->PushTarget(), op1, op2, op3);
  1210. _es.etype = EXPR;
  1211. }
  1212. void LogicalOrExp()
  1213. {
  1214. LogicalAndExp();
  1215. for(;;) if(_token == TK_OR)
  1216. {
  1217. SQInteger first_exp = _fs->PopTarget();
  1218. SQInteger trg = _fs->PushTarget();
  1219. _fs->AddInstruction(_OP_OR, trg, 0, first_exp, 0);
  1220. SQInteger jpos = _fs->GetCurrentPos();
  1221. if(trg != first_exp) _fs->AddInstruction(_OP_MOVE, trg, first_exp);
  1222. Lex();
  1223. INVOKE_EXP(&SQCompiler::LogicalOrExp);
  1224. _fs->SnoozeOpt();
  1225. SQInteger second_exp = _fs->PopTarget();
  1226. if(trg != second_exp) _fs->AddInstruction(_OP_MOVE, trg, second_exp);
  1227. _fs->SnoozeOpt();
  1228. _fs->SetInstructionParam(jpos, 1, (_fs->GetCurrentPos() - jpos));
  1229. _es.etype = EXPR;
  1230. break;
  1231. }
  1232. else return;
  1233. }
  1234. void LogicalAndExp()
  1235. {
  1236. BitwiseOrExp();
  1237. for(;;) switch(_token)
  1238. {
  1239. case TK_AND:
  1240. {
  1241. SQInteger first_exp = _fs->PopTarget();
  1242. SQInteger trg = _fs->PushTarget();
  1243. _fs->AddInstruction(_OP_AND, trg, 0, first_exp, 0);
  1244. SQInteger jpos = _fs->GetCurrentPos();
  1245. if(trg != first_exp) _fs->AddInstruction(_OP_MOVE, trg, first_exp);
  1246. Lex();
  1247. INVOKE_EXP(&SQCompiler::LogicalAndExp);
  1248. _fs->SnoozeOpt();
  1249. SQInteger second_exp = _fs->PopTarget();
  1250. if(trg != second_exp) _fs->AddInstruction(_OP_MOVE, trg, second_exp);
  1251. _fs->SnoozeOpt();
  1252. _fs->SetInstructionParam(jpos, 1, (_fs->GetCurrentPos() - jpos));
  1253. _es.etype = EXPR;
  1254. break;
  1255. }
  1256. default:
  1257. return;
  1258. }
  1259. }
  1260. void BitwiseOrExp()
  1261. {
  1262. BitwiseXorExp();
  1263. for(;;) if(_token == _SC('|'))
  1264. {
  1265. BIN_EXP(_OP_BITW, &SQCompiler::BitwiseXorExp,BW_OR);
  1266. }
  1267. else return;
  1268. }
  1269. void BitwiseXorExp()
  1270. {
  1271. BitwiseAndExp();
  1272. for(;;) if(_token == _SC('^'))
  1273. {
  1274. BIN_EXP(_OP_BITW, &SQCompiler::BitwiseAndExp,BW_XOR);
  1275. }
  1276. else return;
  1277. }
  1278. void BitwiseAndExp()
  1279. {
  1280. EqExp();
  1281. for(;;) if(_token == _SC('&'))
  1282. {
  1283. BIN_EXP(_OP_BITW, &SQCompiler::EqExp,BW_AND);
  1284. }
  1285. else return;
  1286. }
  1287. void EqExp()
  1288. {
  1289. CompExp();
  1290. for(;;) switch(_token)
  1291. {
  1292. case TK_EQ:
  1293. BIN_EXP(_OP_EQ, &SQCompiler::CompExp);
  1294. break;
  1295. case TK_EQ_IDENTITY :
  1296. BIN_EXP(_OP_EQI, &SQCompiler::CompExp);
  1297. break;
  1298. case TK_NE:
  1299. BIN_EXP(_OP_NE, &SQCompiler::CompExp);
  1300. break;
  1301. case TK_NE_IDENTITY:
  1302. BIN_EXP(_OP_NEI, &SQCompiler::CompExp);
  1303. break;
  1304. case TK_3WAYSCMP:
  1305. BIN_EXP(_OP_CMP, &SQCompiler::CompExp,CMP_3W);
  1306. break;
  1307. default:
  1308. return;
  1309. }
  1310. }
  1311. void CompExp()
  1312. {
  1313. ShiftExp();
  1314. for(;;) switch(_token)
  1315. {
  1316. case _SC('>'):
  1317. BIN_EXP(_OP_CMP, &SQCompiler::ShiftExp,CMP_G);
  1318. break;
  1319. case _SC('<'):
  1320. BIN_EXP(_OP_CMP, &SQCompiler::ShiftExp,CMP_L);
  1321. break;
  1322. case TK_GE:
  1323. BIN_EXP(_OP_CMP, &SQCompiler::ShiftExp,CMP_GE);
  1324. break;
  1325. case TK_LE:
  1326. BIN_EXP(_OP_CMP, &SQCompiler::ShiftExp,CMP_LE);
  1327. break;
  1328. case TK_IN:
  1329. BIN_EXP(_OP_EXISTS, &SQCompiler::ShiftExp);
  1330. break;
  1331. case TK_INSTANCEOF:
  1332. BIN_EXP(_OP_INSTANCEOF, &SQCompiler::ShiftExp);
  1333. break;
  1334. default:
  1335. return;
  1336. }
  1337. }
  1338. void ShiftExp()
  1339. {
  1340. PlusExp();
  1341. for(;;) switch(_token)
  1342. {
  1343. case TK_USHIFTR:
  1344. BIN_EXP(_OP_BITW, &SQCompiler::PlusExp,BW_USHIFTR);
  1345. break;
  1346. case TK_SHIFTL:
  1347. BIN_EXP(_OP_BITW, &SQCompiler::PlusExp,BW_SHIFTL);
  1348. break;
  1349. case TK_SHIFTR:
  1350. BIN_EXP(_OP_BITW, &SQCompiler::PlusExp,BW_SHIFTR);
  1351. break;
  1352. default:
  1353. return;
  1354. }
  1355. }
  1356. SQOpcode ChooseArithOpByToken(SQInteger tok)
  1357. {
  1358. switch(tok)
  1359. {
  1360. case TK_PLUSEQ:
  1361. case _SC('+'):
  1362. return _OP_ADD;
  1363. case TK_MINUSEQ:
  1364. case _SC('-'):
  1365. return _OP_SUB;
  1366. case TK_MULEQ:
  1367. case _SC('*'):
  1368. return _OP_MUL;
  1369. case TK_DIVEQ:
  1370. case _SC('/'):
  1371. return _OP_DIV;
  1372. case TK_MODEQ:
  1373. case _SC('%'):
  1374. return _OP_MOD;
  1375. case TK_BIT_XOR_EQ:
  1376. case TK_BIT_AND_EQ:
  1377. case TK_BIT_OR_EQ:
  1378. case TK_BIT_SHIFT_LEFT_EQ:
  1379. case TK_BIT_SHIFT_RIGHT_EQ:
  1380. return _OP_BITW;
  1381. default:
  1382. assert(0);
  1383. }
  1384. return _OP_ADD;
  1385. }
  1386. BitWiseOP ChooseBitwOpByToken(SQInteger tok)
  1387. {
  1388. switch(tok)
  1389. {
  1390. case TK_BIT_XOR_EQ:
  1391. return BW_XOR;
  1392. case TK_BIT_AND_EQ:
  1393. return BW_AND;
  1394. case TK_BIT_OR_EQ:
  1395. return BW_OR;
  1396. case TK_BIT_SHIFT_LEFT_EQ:
  1397. return BW_SHIFTL;
  1398. case TK_BIT_SHIFT_RIGHT_EQ:
  1399. return BW_SHIFTR;
  1400. default:
  1401. Error(_SC("unknown bitwise token"));
  1402. }
  1403. return BW_AND;
  1404. }
  1405. SQInteger ChooseCompArithCharByToken(SQInteger tok)
  1406. {
  1407. SQInteger oper;
  1408. switch(tok)
  1409. {
  1410. case TK_MINUSEQ:
  1411. oper = _SC('-');
  1412. break;
  1413. case TK_PLUSEQ:
  1414. oper = _SC('+');
  1415. break;
  1416. case TK_MULEQ:
  1417. oper = _SC('*');
  1418. break;
  1419. case TK_DIVEQ:
  1420. oper = _SC('/');
  1421. break;
  1422. case TK_MODEQ:
  1423. oper = _SC('%');
  1424. break;
  1425. default:
  1426. oper = 0; //shut up compiler
  1427. assert(0);
  1428. break;
  1429. };
  1430. return oper;
  1431. }
  1432. void PlusExp()
  1433. {
  1434. MultExp();
  1435. for(;;) switch(_token)
  1436. {
  1437. case _SC('+'):
  1438. case _SC('-'):
  1439. BIN_EXP(ChooseArithOpByToken(_token), &SQCompiler::MultExp);
  1440. break;
  1441. default:
  1442. return;
  1443. }
  1444. }
  1445. void MultExp()
  1446. {
  1447. PrefixedExpr();
  1448. for(;;) switch(_token)
  1449. {
  1450. case _SC('*'):
  1451. case _SC('/'):
  1452. case _SC('%'):
  1453. BIN_EXP(ChooseArithOpByToken(_token), &SQCompiler::PrefixedExpr);
  1454. break;
  1455. default:
  1456. return;
  1457. }
  1458. }
  1459. //if 'pos' != -1 the previous variable is a local variable
  1460. void PrefixedExpr()
  1461. {
  1462. SQInteger pos = Factor();
  1463. for(;;)
  1464. {
  1465. switch(_token)
  1466. {
  1467. case TK_DOUBLE_COLON: //C++ style namespace
  1468. if(IsEndOfStatement()) return;
  1469. //else fall trough
  1470. case _SC('.'):
  1471. pos = -1;
  1472. Lex();
  1473. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(Expect(TK_IDENTIFIER)));
  1474. if(_es.etype==BASE)
  1475. {
  1476. Emit2ArgsOP(_OP_GET);
  1477. pos = _fs->TopTarget();
  1478. _es.etype = EXPR;
  1479. _es.epos = pos;
  1480. }
  1481. else
  1482. {
  1483. if(NeedGet())
  1484. {
  1485. Emit2ArgsOP(_OP_GET);
  1486. }
  1487. _es.etype = OBJECT;
  1488. }
  1489. break;
  1490. case _SC('['):
  1491. if(_lex.data->prevtoken == _SC('\n')) Error(_SC("cannot breake deref/or comma needed after [exp]=exp slot declaration"));
  1492. Lex();
  1493. Expression();
  1494. Expect(_SC(']'));
  1495. pos = -1;
  1496. if(_es.etype==BASE)
  1497. {
  1498. Emit2ArgsOP(_OP_GET);
  1499. pos = _fs->TopTarget();
  1500. _es.etype = EXPR;
  1501. _es.epos = pos;
  1502. }
  1503. else
  1504. {
  1505. if(NeedGet())
  1506. {
  1507. Emit2ArgsOP(_OP_GET);
  1508. }
  1509. _es.etype = OBJECT;
  1510. }
  1511. break;
  1512. case TK_MINUSMINUS:
  1513. case TK_PLUSPLUS:
  1514. {
  1515. if(IsEndOfStatement()) return;
  1516. SQInteger diff = (_token==TK_MINUSMINUS) ? -1 : 1;
  1517. Lex();
  1518. switch(_es.etype)
  1519. {
  1520. case EXPR:
  1521. Error(_SC("can't '++' or '--' an expression"));
  1522. break;
  1523. case OBJECT:
  1524. case BASE:
  1525. if(_es.donot_get == true)
  1526. {
  1527. Error(_SC("can't '++' or '--' an expression")); //mmh dor this make sense?
  1528. break;
  1529. }
  1530. Emit2ArgsOP(_OP_PINC, diff);
  1531. break;
  1532. case LOCAL:
  1533. {
  1534. SQInteger src = _fs->PopTarget();
  1535. _fs->AddInstruction(_OP_PINCL, _fs->PushTarget(), src, 0, diff);
  1536. }
  1537. break;
  1538. case OUTER:
  1539. {
  1540. SQInteger tmp1 = _fs->PushTarget();
  1541. SQInteger tmp2 = _fs->PushTarget();
  1542. _fs->AddInstruction(_OP_GETOUTER, tmp2, _es.epos);
  1543. _fs->AddInstruction(_OP_PINCL, tmp1, tmp2, 0, diff);
  1544. _fs->AddInstruction(_OP_SETOUTER, tmp2, _es.epos, tmp2);
  1545. _fs->PopTarget();
  1546. }
  1547. }
  1548. }
  1549. return;
  1550. case _SC('('):
  1551. switch(_es.etype)
  1552. {
  1553. case OBJECT:
  1554. {
  1555. SQInteger key = _fs->PopTarget(); /* location of the key */
  1556. SQInteger table = _fs->PopTarget(); /* location of the object */
  1557. SQInteger closure = _fs->PushTarget(); /* location for the closure */
  1558. SQInteger ttarget = _fs->PushTarget(); /* location for 'this' pointer */
  1559. _fs->AddInstruction(_OP_PREPCALL, closure, key, table, ttarget);
  1560. }
  1561. break;
  1562. case BASE:
  1563. //Emit2ArgsOP(_OP_GET);
  1564. _fs->AddInstruction(_OP_MOVE, _fs->PushTarget(), 0);
  1565. break;
  1566. case OUTER:
  1567. _fs->AddInstruction(_OP_GETOUTER, _fs->PushTarget(), _es.epos);
  1568. _fs->AddInstruction(_OP_MOVE, _fs->PushTarget(), 0);
  1569. break;
  1570. default:
  1571. _fs->AddInstruction(_OP_MOVE, _fs->PushTarget(), 0);
  1572. }
  1573. _es.etype = EXPR;
  1574. Lex();
  1575. FunctionCallArgs();
  1576. break;
  1577. case TK_AS:
  1578. {
  1579. Lex();
  1580. ExpectTypeToken(); //ignore for now
  1581. }
  1582. default:
  1583. return;
  1584. }
  1585. }
  1586. }
  1587. SQInteger Factor()
  1588. {
  1589. _es.etype = EXPR;
  1590. bool compileTimeCheckedConstant = false;
  1591. switch(_token)
  1592. {
  1593. case TK_STRING_LITERAL:
  1594. {
  1595. SQInteger lhtk = _lex.LookaheadLex();
  1596. if(lhtk == TK_STRING_LITERAL) //C/C++ two consecutive strings
  1597. {
  1598. SQCharBuf buf;
  1599. //save the current string
  1600. buf.append(_lex.data->svalue,_lex.data->longstr.size()-1);
  1601. while(lhtk == TK_STRING_LITERAL)
  1602. {
  1603. Lex(); //get lookahead token
  1604. buf.append(_lex.data->svalue,_lex.data->longstr.size()-1);
  1605. lhtk = _lex.LookaheadLex();
  1606. }
  1607. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(
  1608. _fs->CreateString(buf.data(),buf.size())));
  1609. }
  1610. else
  1611. {
  1612. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(
  1613. _fs->CreateString(_lex.data->svalue,_lex.data->longstr.size()-1)));
  1614. }
  1615. Lex();
  1616. }
  1617. break;
  1618. case TK_BASE:
  1619. Lex();
  1620. _fs->AddInstruction(_OP_GETBASE, _fs->PushTarget());
  1621. _es.etype = BASE;
  1622. _es.epos = _fs->TopTarget();
  1623. return (_es.epos);
  1624. case _SC('$'): //compile time checked constant
  1625. Lex();
  1626. ErrorIfNotToken(TK_IDENTIFIER);
  1627. compileTimeCheckedConstant = true;
  1628. //fallthrough to TK_IDENTIFIER
  1629. case TK_IDENTIFIER:
  1630. case TK_CONSTRUCTOR:
  1631. case TK_DESTRUCTOR:
  1632. case TK_THIS:
  1633. {
  1634. SQObject id;
  1635. SQObject constant;
  1636. switch(_token)
  1637. {
  1638. case TK_IDENTIFIER:
  1639. id = _fs->CreateString(_lex.data->svalue);
  1640. if(compileTimeCheckedConstant)
  1641. {
  1642. SQObjectPtr val;
  1643. CompileTimeCheckConstsGet(id, val);
  1644. }
  1645. break;
  1646. case TK_THIS:
  1647. id = _fs->CreateString(_SC("this"), 4);
  1648. break;
  1649. case TK_CONSTRUCTOR:
  1650. id = _fs->CreateString(_SC("constructor"), 11);
  1651. break;
  1652. case TK_DESTRUCTOR:
  1653. id = _fs->CreateString(_SC("destructor"), 10);
  1654. break;
  1655. }
  1656. SQInteger pos = -1;
  1657. Lex();
  1658. if((pos = _fs->GetLocalVariable(id)) != -1)
  1659. {
  1660. /* Handle a local variable (includes 'this') */
  1661. _fs->PushTarget(pos);
  1662. _es.etype = LOCAL;
  1663. _es.epos = pos;
  1664. }
  1665. else if((pos = _fs->GetOuterVariable(id)) != -1)
  1666. {
  1667. /* Handle a free var */
  1668. if(NeedGet())
  1669. {
  1670. _es.epos = _fs->PushTarget();
  1671. _fs->AddInstruction(_OP_GETOUTER, _es.epos, pos);
  1672. /* _es.etype = EXPR; already default value */
  1673. }
  1674. else
  1675. {
  1676. _es.etype = OUTER;
  1677. _es.epos = pos;
  1678. }
  1679. }
  1680. else if(IsConstant(id, constant))
  1681. {
  1682. /* Handle named constant */
  1683. SQObjectPtr constval;
  1684. SQObject constid;
  1685. if(sq_type(constant) == OT_TABLE)
  1686. {
  1687. Expect('.');
  1688. constid = Expect(TK_IDENTIFIER);
  1689. if(!_table(constant)->Get(constid, constval))
  1690. {
  1691. constval.Null();
  1692. Error(_SC("invalid constant [%s.%s]"), _stringval(id), _stringval(constid));
  1693. }
  1694. }
  1695. else
  1696. {
  1697. constval = constant;
  1698. }
  1699. _es.epos = _fs->PushTarget();
  1700. /* generate direct or literal function depending on size */
  1701. SQObjectType ctype = sq_type(constval);
  1702. switch(ctype)
  1703. {
  1704. case OT_INTEGER:
  1705. EmitLoadConstInt(_integer(constval),_es.epos);
  1706. break;
  1707. case OT_FLOAT:
  1708. EmitLoadConstFloat(_float(constval),_es.epos);
  1709. break;
  1710. case OT_BOOL:
  1711. _fs->AddInstruction(_OP_LOADBOOL, _es.epos, _integer(constval));
  1712. break;
  1713. default:
  1714. _fs->AddInstruction(_OP_LOAD,_es.epos,_fs->GetConstant(constval));
  1715. break;
  1716. }
  1717. _es.etype = EXPR;
  1718. }
  1719. else
  1720. {
  1721. /* Handle a non-local variable, aka a field. Push the 'this' pointer on
  1722. * the virtual stack (always found in offset 0, so no instruction needs to
  1723. * be generated), and push the key next. Generate an _OP_LOAD instruction
  1724. * for the latter. If we are not using the variable as a dref expr, generate
  1725. * the _OP_GET instruction.
  1726. */
  1727. if(CheckNameIsType(id)) EatTemplateInitialization();
  1728. _fs->PushTarget(0);
  1729. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(id));
  1730. if(NeedGet())
  1731. {
  1732. Emit2ArgsOP(_OP_GET);
  1733. }
  1734. _es.etype = OBJECT;
  1735. }
  1736. return _es.epos;
  1737. }
  1738. break;
  1739. case TK_DOUBLE_COLON: // "::"
  1740. _fs->AddInstruction(_OP_LOADROOT, _fs->PushTarget());
  1741. _es.etype = OBJECT;
  1742. _token = _SC('.'); /* hack: drop into PrefixExpr, case '.'*/
  1743. _es.epos = -1;
  1744. return _es.epos;
  1745. case TK_NULL:
  1746. _fs->AddInstruction(_OP_LOADNULLS, _fs->PushTarget(),1);
  1747. Lex();
  1748. break;
  1749. CASE_TK_INTEGER:
  1750. EmitLoadConstInt(_lex.data->nvalue,-1);
  1751. Lex();
  1752. break;
  1753. case TK_FLOAT:
  1754. EmitLoadConstFloat(_lex.data->fvalue,-1);
  1755. Lex();
  1756. break;
  1757. case TK_TRUE:
  1758. case TK_FALSE:
  1759. _fs->AddInstruction(_OP_LOADBOOL, _fs->PushTarget(),_token == TK_TRUE?1:0);
  1760. Lex();
  1761. break;
  1762. case _SC('['):
  1763. {
  1764. _fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(),0,0,NOT_ARRAY);
  1765. SQInteger apos = _fs->GetCurrentPos(),key = 0;
  1766. Lex();
  1767. while(_token != _SC(']'))
  1768. {
  1769. Expression();
  1770. if(_token == _SC(',')) Lex();
  1771. SQInteger val = _fs->PopTarget();
  1772. SQInteger array = _fs->TopTarget();
  1773. _fs->AddInstruction(_OP_APPENDARRAY, array, val, AAT_STACK);
  1774. key++;
  1775. }
  1776. _fs->SetInstructionParam(apos, 1, key);
  1777. Lex();
  1778. }
  1779. break;
  1780. case _SC('{'):
  1781. _fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(),0,NOT_TABLE);
  1782. Lex();
  1783. ParseTableOrClass(_SC(','),_SC('}'));
  1784. break;
  1785. case TK_FUNCTION:
  1786. FunctionExp(_token);
  1787. break;
  1788. case _SC('@'):
  1789. FunctionExp(_token,true);
  1790. break;
  1791. case TK_STRUCT:
  1792. case TK_CLASS:
  1793. case TK_INTERFACE:
  1794. Lex();
  1795. ClassExp(NULL);
  1796. break;
  1797. case _SC('-'):
  1798. Lex();
  1799. switch(_token)
  1800. {
  1801. CASE_TK_INTEGER:
  1802. EmitLoadConstInt(-_lex.data->nvalue,-1);
  1803. Lex();
  1804. break;
  1805. case TK_FLOAT:
  1806. EmitLoadConstFloat(-_lex.data->fvalue,-1);
  1807. Lex();
  1808. break;
  1809. default:
  1810. UnaryOP(_OP_NEG);
  1811. }
  1812. break;
  1813. case _SC('!'):
  1814. Lex();
  1815. UnaryOP(_OP_NOT);
  1816. break;
  1817. case _SC('~'):
  1818. Lex();
  1819. bool isInteger;
  1820. switch(_token)
  1821. {
  1822. CASE_TK_INTEGER:
  1823. isInteger = true;
  1824. default:
  1825. isInteger = false;
  1826. }
  1827. if(isInteger)
  1828. {
  1829. EmitLoadConstInt(~_lex.data->nvalue,-1);
  1830. Lex();
  1831. break;
  1832. }
  1833. UnaryOP(_OP_BWNOT);
  1834. break;
  1835. case TK_TYPEOF :
  1836. Lex() ;
  1837. UnaryOP(_OP_TYPEOF);
  1838. break;
  1839. case TK_RESUME :
  1840. Lex();
  1841. UnaryOP(_OP_RESUME);
  1842. break;
  1843. case TK_CLONE :
  1844. Lex();
  1845. UnaryOP(_OP_CLONE);
  1846. break;
  1847. case TK_RAWCALL:
  1848. Lex();
  1849. Expect('(');
  1850. FunctionCallArgs(true);
  1851. break;
  1852. case TK_MINUSMINUS :
  1853. case TK_PLUSPLUS :
  1854. PrefixIncDec(_token);
  1855. break;
  1856. case TK_DELETE :
  1857. DeleteExpr();
  1858. break;
  1859. case _SC('('):
  1860. Lex();
  1861. if(_token == TK_IDENTIFIER)
  1862. {
  1863. //check C/C++ cast
  1864. SQObject id = _fs->CreateString(_lex.data->svalue);
  1865. if(CheckTypeName(id)) //C/C++ type declaration;
  1866. {
  1867. SQInteger lhtk = _lex.LookaheadLex();
  1868. if(lhtk == _SC(')'))
  1869. {
  1870. Lex(); //eat TK_IDENTIFIER
  1871. Lex(); //eat ')'
  1872. CommaExpr();
  1873. break;
  1874. }
  1875. }
  1876. }
  1877. CommaExpr();
  1878. Expect(_SC(')'));
  1879. break;
  1880. case TK___LINE__:
  1881. EmitLoadConstInt(_lex.data->currentline,-1);
  1882. Lex();
  1883. break;
  1884. case TK___FILE__:
  1885. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(_sourcename));
  1886. Lex();
  1887. break;
  1888. case TK___FUNCTION__:
  1889. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(_fs->_name));
  1890. Lex();
  1891. break;
  1892. case TK_IGNORE:
  1893. //Warning("Keyword ignored \"%s\" at line %d:%d\n", _lex.Tok2Str(_token),
  1894. // _lex.data->currentline, _lex.data->currentcolumn);
  1895. Lex();
  1896. return Factor();
  1897. default:
  1898. Error(_SC("expression expected"));
  1899. }
  1900. _es.etype = EXPR;
  1901. return -1;
  1902. }
  1903. void EmitLoadConstInt(SQInteger value,SQInteger target)
  1904. {
  1905. if(target < 0)
  1906. {
  1907. target = _fs->PushTarget();
  1908. }
  1909. //with the line bellow we get wrong result for -1
  1910. //if(value <= INT_MAX && value > INT_MIN) { //does it fit in 32 bits?
  1911. if((value & (~((SQInteger)0xFFFFFFFF))) == 0) //does it fit in 32 bits?
  1912. {
  1913. _fs->AddInstruction(_OP_LOADINT, target,value);
  1914. }
  1915. else
  1916. {
  1917. _fs->AddInstruction(_OP_LOAD, target, _fs->GetNumericConstant(value));
  1918. }
  1919. }
  1920. void EmitLoadConstFloat(SQFloat value,SQInteger target)
  1921. {
  1922. if(target < 0)
  1923. {
  1924. target = _fs->PushTarget();
  1925. }
  1926. SQFloat32 f32 = value;
  1927. if(f32 == value) //same value no overflow/underflow/infinity
  1928. {
  1929. _fs->AddInstruction(_OP_LOADFLOAT, target,*((SQInt32 *)&f32));
  1930. }
  1931. else _fs->AddInstruction(_OP_LOAD, target, _fs->GetNumericConstant(value));
  1932. }
  1933. void UnaryOP(SQOpcode op)
  1934. {
  1935. PrefixedExpr();
  1936. SQInteger src = _fs->PopTarget();
  1937. _fs->AddInstruction(op, _fs->PushTarget(), src);
  1938. }
  1939. bool NeedGet()
  1940. {
  1941. switch(_token)
  1942. {
  1943. case _SC('='):
  1944. case _SC('('):
  1945. case TK_NEWSLOT:
  1946. case TK_MODEQ:
  1947. case TK_MULEQ:
  1948. case TK_DIVEQ:
  1949. case TK_MINUSEQ:
  1950. case TK_PLUSEQ:
  1951. case TK_BIT_XOR_EQ:
  1952. case TK_BIT_AND_EQ:
  1953. case TK_BIT_OR_EQ:
  1954. case TK_BIT_SHIFT_LEFT_EQ:
  1955. case TK_BIT_SHIFT_RIGHT_EQ:
  1956. return false;
  1957. case TK_PLUSPLUS:
  1958. case TK_MINUSMINUS:
  1959. if (!IsEndOfStatement())
  1960. {
  1961. return false;
  1962. }
  1963. break;
  1964. }
  1965. return (!_es.donot_get || ( _es.donot_get && (_token == _SC('.') || _token == _SC('[') || _token == TK_DOUBLE_COLON)));
  1966. }
  1967. void FunctionCallArgs(bool rawcall = false)
  1968. {
  1969. SQInteger nargs = 1;//this
  1970. while(_token != _SC(')'))
  1971. {
  1972. Expression();
  1973. MoveIfCurrentTargetIsLocal();
  1974. nargs++;
  1975. if(_token == _SC(','))
  1976. {
  1977. Lex();
  1978. if(_token == ')') Error(_SC("expression expected, found ')'"));
  1979. }
  1980. }
  1981. Lex();
  1982. if (rawcall)
  1983. {
  1984. if (nargs < 3) Error(_SC("rawcall requires at least 2 parameters (callee and this)"));
  1985. nargs -= 2; //removes callee and this from count
  1986. }
  1987. for(SQInteger i = 0; i < (nargs - 1); i++) _fs->PopTarget();
  1988. SQInteger stackbase = _fs->PopTarget();
  1989. SQInteger closure = _fs->PopTarget();
  1990. SQInteger target = _fs->PushTarget();
  1991. assert(target >= -1);
  1992. assert(target < 255);
  1993. /*
  1994. const char *fname = _stringval(_fs->_name);
  1995. SQObjectPtr optr = _fs->_functions[closure];
  1996. SQFunctionProto *f = _funcproto(optr);
  1997. for(int i=0; i < f->_nparameters; ++i)
  1998. {
  1999. printf("Func %s params %d %d\n", _stringval(f->_name), i, (int)_integer(f->_parameters_type[i]));
  2000. }
  2001. */
  2002. _fs->AddInstruction(_OP_CALL, target, closure, stackbase, nargs);
  2003. }
  2004. void AddClassMemberExists(SQObjectPtr &member_names, SQObject &name)
  2005. {
  2006. SQObjectPtr oname = name, otrue = true;
  2007. _table(member_names)->NewSlot(oname, otrue);
  2008. }
  2009. void CheckClassMemberExists(SQObjectPtr &member_names, SQObject &name, bool addIfNotExists=true)
  2010. {
  2011. if(_table(member_names)->Exists(name))
  2012. {
  2013. Error(_SC("class already has a member named: %s"), _stringval(name));
  2014. }
  2015. if(addIfNotExists) AddClassMemberExists(member_names, name);
  2016. }
  2017. void CheckClassMemberExists(SQObjectPtr &member_names, const SQChar *name)
  2018. {
  2019. SQObject oname = _fs->CreateString(name);
  2020. CheckClassMemberExists(member_names, oname);
  2021. }
  2022. void ParseTableOrClass(SQInteger separator,SQInteger terminator, SQObjectPtr *class_name=NULL)
  2023. {
  2024. SQObjectPtr member_names;
  2025. SQInteger saved_tok, tpos = _fs->GetCurrentPos(),nkeys = 0;
  2026. SQObject type_name, obj_id;
  2027. bool isClass = separator == ';'; //hack recognizes a table/class from the separator
  2028. if(isClass)
  2029. {
  2030. member_names = SQTable::Create(_ss(_vm),0);
  2031. }
  2032. int addClassMember = 0;
  2033. while(_token != terminator)
  2034. {
  2035. bool hasattrs = false;
  2036. bool isstatic = false;
  2037. bool cppDestructor = false;
  2038. //bool isvirtual = false;
  2039. //bool isprivate = false;
  2040. bool compileTimeCheckedConstant = false;
  2041. const SQChar *membertypename = 0;
  2042. SQInteger member_type_token = 0;
  2043. //check if is an attribute
  2044. if(isClass)
  2045. {
  2046. if(_token == TK_ATTR_OPEN)
  2047. {
  2048. _fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(),0,NOT_TABLE);
  2049. Lex();
  2050. ParseTableOrClass(',',TK_ATTR_CLOSE);
  2051. hasattrs = true;
  2052. }
  2053. if(_token == TK_STATIC)
  2054. {
  2055. isstatic = true;
  2056. Lex();
  2057. }
  2058. if(_token == TK_VIRTUAL)
  2059. {
  2060. //isvirtual = true;
  2061. Lex();
  2062. }
  2063. else if(_token == TK_PUBLIC)
  2064. {
  2065. Lex();
  2066. if(_token == _SC(':')) Lex();
  2067. }
  2068. else if(_token == TK_PRIVATE)
  2069. {
  2070. //isprivate = true;
  2071. Lex();
  2072. if(_token == _SC(':')) Lex();
  2073. }
  2074. else if(_token == TK_PROTECTED)
  2075. {
  2076. //isprivate = true;
  2077. Lex();
  2078. if(_token == _SC(':')) Lex();
  2079. }
  2080. else if(_token == TK_INLINE)
  2081. {
  2082. Lex();
  2083. }
  2084. else if(_token == TK_CONST)
  2085. {
  2086. Lex();
  2087. }
  2088. else if(_token == TK_TEMPLATE)
  2089. {
  2090. TemplateStatement();
  2091. }
  2092. }
  2093. member_has_type:
  2094. switch(_token)
  2095. {
  2096. case TK_FUNCTION:
  2097. case TK_CONSTRUCTOR:
  2098. case TK_DESTRUCTOR:
  2099. {
  2100. saved_tok = _token;
  2101. Lex();
  2102. obj_id = saved_tok == TK_FUNCTION ? Expect(TK_IDENTIFIER) :
  2103. _fs->CreateString(saved_tok == TK_CONSTRUCTOR ? _SC("constructor") : _SC("destructor"));
  2104. if(sq_type(member_names) == OT_TABLE) CheckClassMemberExists(member_names, obj_id);
  2105. else Error(_SC("unexpected error in class declaration"));
  2106. Expect(_SC('('));
  2107. function_params_decl:
  2108. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(obj_id));
  2109. CreateFunction(obj_id, eFunctionType_member);
  2110. _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, 0);
  2111. }
  2112. break;
  2113. case _SC('['):
  2114. Lex();
  2115. CommaExpr();
  2116. Expect(_SC(']'));
  2117. Expect(_SC('='));
  2118. Expression();
  2119. break;
  2120. case _SC('$'): //compile time checked constant
  2121. Lex();
  2122. ErrorIfNotToken(TK_IDENTIFIER);
  2123. compileTimeCheckedConstant = true;
  2124. //fallthrough to TK_IDENTIFIER
  2125. case TK_STRING_LITERAL: //JSON
  2126. if(isClass)
  2127. {
  2128. Error(_SC("unexpected string literal in class declaration"));
  2129. }
  2130. case TK_IDENTIFIER: //JSON
  2131. {
  2132. obj_id = GetTokenObject(_token);
  2133. if(compileTimeCheckedConstant)
  2134. {
  2135. SQObjectPtr val;
  2136. CompileTimeCheckConstsGet(obj_id, val);
  2137. obj_id = val;
  2138. }
  2139. SQInteger next_token = _SC('=');
  2140. if(isClass)
  2141. {
  2142. CheckClassMemberExists(member_names, obj_id, false);
  2143. addClassMember = 0;
  2144. EatTemplateInitialization();
  2145. switch(_token)
  2146. {
  2147. case _SC('('): //C/C++ style function declaration
  2148. Lex();
  2149. if(class_name)
  2150. {
  2151. //printf("ClassMember %d : %s : %s\n", (int)cppDestructor, _stringval(*class_name), _stringval(obj_id));
  2152. if(memcmp(_stringval(*class_name), _stringval(obj_id), _string(*class_name)->_len) == 0)
  2153. {
  2154. //C++ style constructor/destructor declaration
  2155. obj_id = _fs->CreateString(cppDestructor ? _SC("destructor") : _SC("constructor"));
  2156. cppDestructor = false;
  2157. }
  2158. }
  2159. AddClassMemberExists(member_names, obj_id);
  2160. goto function_params_decl;
  2161. case _SC(':'): //typescript field with type annotation
  2162. if(membertypename)
  2163. {
  2164. Error(_SC("member type already declared before %s"), _stringval(obj_id));
  2165. }
  2166. Lex();
  2167. type_name = ExpectTypeToken();
  2168. addClassMember = 1;
  2169. break;
  2170. case _SC(','):
  2171. ++addClassMember;
  2172. case _SC(';'): //member variable declaration without explicit initialization
  2173. Lex();
  2174. ++addClassMember;
  2175. break;
  2176. case TK_IDENTIFIER: //if 2 identifier found the first should be a type
  2177. if(CheckNameIsType(obj_id)) //Struct/Class/Typedef names
  2178. {
  2179. membertypename = _stringval(obj_id);
  2180. goto member_has_type;
  2181. }
  2182. }
  2183. if(addClassMember)
  2184. {
  2185. AddClassMemberExists(member_names, obj_id);
  2186. if(_token != _SC('='))
  2187. {
  2188. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(obj_id));
  2189. if(member_type_token) GetVarTypeDeclaration(member_type_token, _fs->PushTarget());
  2190. else _fs->AddInstruction(_OP_LOADNULLS, _fs->PushTarget(), 1);
  2191. break;
  2192. }
  2193. }
  2194. }
  2195. if(_token == _SC(':'))
  2196. {
  2197. next_token = _token;
  2198. }
  2199. Expect(next_token);
  2200. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(obj_id));
  2201. Expression();
  2202. break;
  2203. }
  2204. CASE_TK_LOCAL_TYPES: //class member variables;
  2205. case TK_LOCAL:
  2206. if(isClass)
  2207. {
  2208. member_type_token = _token;
  2209. membertypename = _lex.GetTokenName(_token);
  2210. Lex();
  2211. goto member_has_type;
  2212. }
  2213. case _SC('~'): //C++ style destructor declaration
  2214. if(isClass)
  2215. {
  2216. cppDestructor = true;
  2217. Lex();
  2218. goto member_has_type;
  2219. }
  2220. case TK_CONSTEXPR:
  2221. if(isClass)
  2222. {
  2223. Lex();
  2224. continue;
  2225. }
  2226. //else fallthrough
  2227. default :
  2228. ErrorIfNotToken(TK_IDENTIFIER);
  2229. }
  2230. if(_token == separator) Lex();//optional comma/semicolon
  2231. nkeys++;
  2232. SQInteger val = _fs->PopTarget();
  2233. SQInteger key = _fs->PopTarget();
  2234. SQInteger attrs = hasattrs ? _fs->PopTarget():-1;
  2235. assert((hasattrs && (attrs == key-1)) || !hasattrs);
  2236. (void)attrs; // UNUSED
  2237. unsigned char flags = (hasattrs?NEW_SLOT_ATTRIBUTES_FLAG:0)|(isstatic?NEW_SLOT_STATIC_FLAG:0);
  2238. SQInteger table = _fs->TopTarget(); //<<BECAUSE OF THIS NO COMMON EMIT FUNC IS POSSIBLE
  2239. if(isClass)
  2240. {
  2241. _fs->AddInstruction(_OP_NEWSLOTA, flags, table, key, val); //this for classes only as it invokes _newmember
  2242. if(addClassMember > 1)
  2243. {
  2244. addClassMember = 0;
  2245. goto member_has_type;
  2246. }
  2247. }
  2248. else
  2249. {
  2250. _fs->AddInstruction(_OP_NEWSLOT, 0xFF, table, key, val);
  2251. }
  2252. }
  2253. if(separator == _SC(',')) //hack recognizes a table from the separator
  2254. _fs->SetInstructionParam(tpos, 1, nkeys);
  2255. Lex();
  2256. }
  2257. void ExternDeclStatement()
  2258. {
  2259. _is_parsing_extern = true;
  2260. Lex();
  2261. LocalDeclStatement();
  2262. _is_parsing_extern = false;
  2263. }
  2264. void EatTemplateInitialization()
  2265. {
  2266. //C++/Java template instantiation
  2267. if(_token == _SC('<'))
  2268. {
  2269. int nested = 1;
  2270. Lex();
  2271. while(nested > 0)
  2272. {
  2273. ExpectTypeToken();
  2274. switch(_token)
  2275. {
  2276. case ',': break;
  2277. case '<': ++nested; break;
  2278. case '>': --nested; break;
  2279. default:
  2280. Error(_SC("template instantiation declaration unexpected token"));
  2281. }
  2282. Lex();
  2283. }
  2284. }
  2285. }
  2286. SQInteger GetVarTypeDeclaration(SQInteger declType, SQInteger dest=-1)
  2287. {
  2288. bool doAddInstruction = (dest >= 0);
  2289. switch(declType)
  2290. {
  2291. CASE_TK_LOCAL_CHAR_TYPES:
  2292. if(doAddInstruction) _fs->AddInstruction(_OP_LOADNULLS, dest,1);
  2293. declType = _VAR_STRING;
  2294. break;
  2295. case TK_LOCAL_BOOL_T:
  2296. //default value false
  2297. if(doAddInstruction) _fs->AddInstruction(_OP_LOADBOOL, dest,0);
  2298. declType = _VAR_BOOL;
  2299. break;
  2300. case TK_LOCAL_TABLE_T:
  2301. if(doAddInstruction) _fs->AddInstruction(_OP_LOADNULLS, dest,1);
  2302. declType = _VAR_TABLE;
  2303. break;
  2304. case TK_LOCAL_ARRAY_T:
  2305. if(doAddInstruction) _fs->AddInstruction(_OP_LOADNULLS, dest,1);
  2306. declType = _VAR_ARRAY;
  2307. break;
  2308. CASE_TK_LOCAL_INT_TYPES:
  2309. //default value 0
  2310. if(doAddInstruction) _fs->AddInstruction(_OP_LOADINT, dest,0);
  2311. declType = _VAR_INTEGER;
  2312. break;
  2313. CASE_TK_LOCAL_FLOAT_TYPES:
  2314. case TK_LOCAL_NUMBER_T: //start numbers as floats
  2315. //default value 0.0
  2316. if(doAddInstruction)
  2317. {
  2318. SQFloat value = 0.0;
  2319. EmitLoadConstFloat(value, dest);
  2320. }
  2321. declType = _VAR_FLOAT;
  2322. break;
  2323. //case TK_LOCAL:
  2324. default:
  2325. //default value null
  2326. if(doAddInstruction) _fs->AddInstruction(_OP_LOADNULLS, dest,1);
  2327. declType = _VAR_ANY;
  2328. }
  2329. return declType;
  2330. }
  2331. #define CHECK_REF_DECLARATION(tk) \
  2332. if(tk == _SC('&')){is_reference_declaration = true;Lex();}\
  2333. else if(tk == _SC('*')){is_pointer_declaration = true;Lex();}
  2334. void LocalDeclStatement()
  2335. {
  2336. SQObject varname;
  2337. SQObject type_name = GetTokenObject(_token, false);
  2338. //SQChar *param_type_name;
  2339. bool is_void_declaration = _token == TK_VOID;
  2340. bool is_const_declaration = _token == TK_CONST;
  2341. bool is_reference_declaration = false;
  2342. bool is_pointer_declaration = false;
  2343. //bool is_instance_declaration = _token == TK_IDENTIFIER;
  2344. SQInteger declType = _token;
  2345. Lex();
  2346. EatTemplateInitialization();
  2347. if( _token == TK_FUNCTION)
  2348. {
  2349. Lex();
  2350. varname = Expect(TK_IDENTIFIER);
  2351. CheckLocalNameScope(varname, _scope.nested);
  2352. Expect(_SC('('));
  2353. function_params_decl:
  2354. #if 1
  2355. //doing this way works but prevents garbage collection when doing multiple reloads on the same vm
  2356. //the following is an attempt to allow local declared functions be called recursivelly
  2357. SQInteger old_pos = _fs->GetCurrentPos(); //save current instructions position
  2358. if(_fs->PushLocalVariable(varname, _scope.nested, _VAR_CLOSURE) < 0) //add function name to find it as outer var if needed
  2359. ErrorNameAlreadyDeclared(varname);
  2360. if(sq_type(type_name) == OT_STRING) _fs->AddParameterTypeName(type_name);
  2361. CreateFunction(varname, eFunctionType_local, declType);
  2362. if(_is_parsing_extern)
  2363. {
  2364. if(_token == _SC(';')) //to parse thinscript
  2365. {
  2366. //Expect(_SC(';'));
  2367. CheckExternName(varname, true);
  2368. return;
  2369. }
  2370. else _is_parsing_extern = false;
  2371. }
  2372. _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, 0);
  2373. //rellocate any stack operation (default parameters & _OP_Closure)
  2374. for(int i=old_pos+1, curr_pos = _fs->GetCurrentPos(); i <= curr_pos; ++i)
  2375. {
  2376. SQInstruction & inst = _fs->GetInstruction(i);
  2377. //printf("%d: %s\n", inst.op, SQGetOpName(inst.op));
  2378. if(inst.op == _OP_CLOSURE) _fs->SetInstructionParam(i, 0, inst._arg0 -1);
  2379. }
  2380. _fs->PopTarget();
  2381. #else
  2382. CreateFunction(varname,eFunctionType::local);
  2383. _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, 0);
  2384. _fs->PopTarget();
  2385. if( _fs->PushLocalVariable(varname, _scope.nested, _VAR_CLOSURE) < 0)
  2386. ErrorNameAlreadyDeclared(varname);;
  2387. #endif
  2388. return;
  2389. }
  2390. do
  2391. {
  2392. //param_type_name = NULL;
  2393. CHECK_REF_DECLARATION(_token);
  2394. varname = Expect(TK_IDENTIFIER);
  2395. if(CheckNameIsType(varname))
  2396. {
  2397. //ignore custom types for now
  2398. //param_type_name = _stringval(varname);
  2399. declType = _VAR_ANY;
  2400. CHECK_REF_DECLARATION(_token);
  2401. varname = Expect(TK_IDENTIFIER);
  2402. }
  2403. CheckLocalNameScope(varname, _scope.nested);
  2404. EatTemplateInitialization();
  2405. if(_token == _SC('('))
  2406. {
  2407. declType = GetVarTypeDeclaration(declType);
  2408. //C/C++ style function declaration
  2409. Lex();
  2410. goto function_params_decl;
  2411. }
  2412. else if(_token == _SC(':'))
  2413. {
  2414. //type specifier like typescript
  2415. Lex();
  2416. declType = _token;
  2417. type_name = ExpectTypeToken(); //ignore for now
  2418. }
  2419. if(is_void_declaration && !is_pointer_declaration)
  2420. {
  2421. Error(_SC("void type is invalid here"));
  2422. }
  2423. else if(_token == _SC('='))
  2424. {
  2425. if(_is_parsing_extern)
  2426. {
  2427. Error(_SC("can not make assignment in external declarations"));
  2428. }
  2429. Lex();
  2430. Expression();
  2431. SQInteger src = _fs->PopTarget();
  2432. SQInteger dest = _fs->PushTarget();
  2433. if(dest != src) _fs->AddInstruction(_OP_MOVE, dest, src);
  2434. declType = GetVarTypeDeclaration(declType);
  2435. }
  2436. else if(is_const_declaration || is_reference_declaration)
  2437. Error(_SC("const/reference '%s' need an initializer"), _stringval(varname));
  2438. else
  2439. {
  2440. //check_param_type:
  2441. if(!_is_parsing_extern)
  2442. {
  2443. SQInteger dest = _fs->PushTarget();
  2444. declType = GetVarTypeDeclaration(declType, dest);
  2445. }
  2446. }
  2447. if(_is_parsing_extern)
  2448. {
  2449. if(CheckExternName(varname, true))
  2450. {
  2451. Error(_SC("extern %s already declared"), _stringval(varname));
  2452. }
  2453. }
  2454. else
  2455. {
  2456. _fs->PopTarget();
  2457. if(_fs->PushLocalVariable(varname, _scope.nested, (is_const_declaration ? _VAR_CONST : declType)
  2458. | (is_reference_declaration ? _VAR_REFERENCE : 0)
  2459. | (is_pointer_declaration ? _VAR_POINTER : 0)
  2460. ) < 0) ErrorNameAlreadyDeclared(varname);
  2461. if(sq_type(type_name) == OT_STRING) _fs->AddParameterTypeName(type_name);
  2462. }
  2463. if(_token == _SC(',')) Lex();
  2464. else break;
  2465. }
  2466. while(1);
  2467. }
  2468. void IfBlock()
  2469. {
  2470. if (_token == _SC('{'))
  2471. {
  2472. BEGIN_SCOPE();
  2473. Lex();
  2474. Statements();
  2475. Expect(_SC('}'));
  2476. if (true)
  2477. {
  2478. END_SCOPE();
  2479. }
  2480. else
  2481. {
  2482. END_SCOPE_NO_CLOSE();
  2483. }
  2484. }
  2485. else
  2486. {
  2487. //BEGIN_SCOPE();
  2488. Statement();
  2489. if (_lex.data->prevtoken != _SC('}') && _lex.data->prevtoken != _SC(';')) OptionalSemicolon();
  2490. //END_SCOPE();
  2491. }
  2492. }
  2493. void IfStatement()
  2494. {
  2495. SQInteger jmppos;
  2496. bool haselse = false;
  2497. Lex();
  2498. Expect(_SC('('));
  2499. CommaExpr(true);
  2500. Expect(_SC(')'));
  2501. _fs->AddInstruction(_OP_JZ, _fs->PopTarget());
  2502. SQInteger jnepos = _fs->GetCurrentPos();
  2503. IfBlock();
  2504. //there is a situation where the if statement has a statement enclosed by {}
  2505. //and after the closing "}" there is no newline or semicolom
  2506. //it's a valid construction but the compiler was complaining about it
  2507. //for now added "&& _token != TK_IDENTIFIER" to the check after "Statement()" call
  2508. /*
  2509. local color = "blue";
  2510. if(color == "yellow"){
  2511. print(color);
  2512. } print("Waht color is it ?");
  2513. */
  2514. SQInteger endifblock = _fs->GetCurrentPos();
  2515. if(_token == TK_ELSE)
  2516. {
  2517. haselse = true;
  2518. BEGIN_SCOPE();
  2519. _fs->AddInstruction(_OP_JMP);
  2520. jmppos = _fs->GetCurrentPos();
  2521. Lex();
  2522. Statement();
  2523. if(_token != TK_IDENTIFIER) OptionalSemicolon();
  2524. END_SCOPE();
  2525. _fs->SetInstructionParam(jmppos, 1, _fs->GetCurrentPos() - jmppos);
  2526. }
  2527. _fs->SetInstructionParam(jnepos, 1, endifblock - jnepos + (haselse?1:0));
  2528. }
  2529. void WhileStatement()
  2530. {
  2531. SQInteger jzpos, jmppos;
  2532. jmppos = _fs->GetCurrentPos();
  2533. Lex();
  2534. Expect(_SC('('));
  2535. CommaExpr(true);
  2536. Expect(_SC(')'));
  2537. BEGIN_BREAKBLE_BLOCK();
  2538. _fs->AddInstruction(_OP_JZ, _fs->PopTarget());
  2539. jzpos = _fs->GetCurrentPos();
  2540. BEGIN_SCOPE();
  2541. Statement();
  2542. END_SCOPE();
  2543. _fs->AddInstruction(_OP_JMP, 0, jmppos - _fs->GetCurrentPos() - 1);
  2544. _fs->SetInstructionParam(jzpos, 1, _fs->GetCurrentPos() - jzpos);
  2545. END_BREAKBLE_BLOCK(jmppos);
  2546. }
  2547. void DoWhileStatement()
  2548. {
  2549. Lex();
  2550. SQInteger jmptrg = _fs->GetCurrentPos();
  2551. BEGIN_BREAKBLE_BLOCK()
  2552. BEGIN_SCOPE();
  2553. Statement();
  2554. END_SCOPE();
  2555. //fix proposed by frosch to correct line number info in stack dumps
  2556. _fs->AddLineInfos(_lex.data->currentline, _lineinfo, true);
  2557. Expect(TK_WHILE);
  2558. SQInteger continuetrg = _fs->GetCurrentPos();
  2559. Expect(_SC('('));
  2560. CommaExpr(true);
  2561. Expect(_SC(')'));
  2562. _fs->AddInstruction(_OP_JZ, _fs->PopTarget(), 1);
  2563. _fs->AddInstruction(_OP_JMP, 0, jmptrg - _fs->GetCurrentPos() - 1);
  2564. END_BREAKBLE_BLOCK(continuetrg);
  2565. }
  2566. void ForStatement()
  2567. {
  2568. Lex();
  2569. BEGIN_SCOPE();
  2570. Expect(_SC('('));
  2571. switch(_token)
  2572. {
  2573. case TK_IDENTIFIER:
  2574. {
  2575. SQObject id = _fs->CreateString(_lex.data->svalue);
  2576. if(!CheckTypeName(id))
  2577. {
  2578. SQInteger lhtk = _lex.LookaheadLex();
  2579. if(lhtk == TK_IDENTIFIER) Error(_SC("unknown type specifier"));
  2580. goto lbl_commaexpr;//not a C/C++ type declaration;
  2581. }
  2582. }
  2583. //ignore custom types for now
  2584. //fallthrough as local declaration
  2585. CASE_TK_LOCAL_TYPES:
  2586. case TK_LOCAL:
  2587. LocalDeclStatement();
  2588. break;
  2589. default:
  2590. lbl_commaexpr:
  2591. if(_token != _SC(';'))
  2592. {
  2593. CommaExpr();
  2594. _fs->PopTarget();
  2595. }
  2596. }
  2597. Expect(_SC(';'));
  2598. _fs->SnoozeOpt();
  2599. SQInteger jmppos = _fs->GetCurrentPos();
  2600. SQInteger jzpos = -1;
  2601. if(_token != _SC(';'))
  2602. {
  2603. CommaExpr();
  2604. _fs->AddInstruction(_OP_JZ, _fs->PopTarget());
  2605. jzpos = _fs->GetCurrentPos();
  2606. }
  2607. Expect(_SC(';'));
  2608. _fs->SnoozeOpt();
  2609. SQInteger expstart = _fs->GetCurrentPos() + 1;
  2610. if(_token != _SC(')'))
  2611. {
  2612. CommaExpr();
  2613. _fs->PopTarget();
  2614. }
  2615. Expect(_SC(')'));
  2616. _fs->SnoozeOpt();
  2617. SQInteger expend = _fs->GetCurrentPos();
  2618. SQInteger expsize = (expend - expstart) + 1;
  2619. SQInstructionVec exp;
  2620. if(expsize > 0)
  2621. {
  2622. for(SQInteger i = 0; i < expsize; i++)
  2623. exp.push_back(_fs->GetInstruction(expstart + i));
  2624. _fs->PopInstructions(expsize);
  2625. }
  2626. BEGIN_BREAKBLE_BLOCK()
  2627. Statement();
  2628. SQInteger continuetrg = _fs->GetCurrentPos();
  2629. if(expsize > 0)
  2630. {
  2631. for(SQInteger i = 0; i < expsize; i++)
  2632. _fs->AddInstruction(exp[i]);
  2633. }
  2634. _fs->AddInstruction(_OP_JMP, 0, jmppos - _fs->GetCurrentPos() - 1, 0);
  2635. if(jzpos> 0) _fs->SetInstructionParam(jzpos, 1, _fs->GetCurrentPos() - jzpos);
  2636. END_BREAKBLE_BLOCK(continuetrg);
  2637. END_SCOPE();
  2638. }
  2639. void ForEachStatement()
  2640. {
  2641. SQObject idxname, valname;
  2642. Lex();
  2643. Expect(_SC('('));
  2644. valname = Expect(TK_IDENTIFIER);
  2645. if(_token == _SC(','))
  2646. {
  2647. idxname = valname;
  2648. Lex();
  2649. valname = Expect(TK_IDENTIFIER);
  2650. }
  2651. else
  2652. {
  2653. idxname = _fs->CreateString(_SC("@INDEX@"));
  2654. }
  2655. Expect(TK_IN);
  2656. //save the stack size
  2657. BEGIN_SCOPE();
  2658. //put the table in the stack(evaluate the table expression)
  2659. Expression();
  2660. Expect(_SC(')'));
  2661. SQInteger container = _fs->TopTarget();
  2662. //push the index local var
  2663. SQInteger indexpos = _fs->PushLocalVariable(idxname, _scope.nested);
  2664. if(indexpos < 0) ErrorNameAlreadyDeclared(idxname);
  2665. _fs->AddInstruction(_OP_LOADNULLS, indexpos,1);
  2666. //push the value local var
  2667. SQInteger valuepos = _fs->PushLocalVariable(valname, _scope.nested);
  2668. if(valuepos < 0) ErrorNameAlreadyDeclared(valname);
  2669. _fs->AddInstruction(_OP_LOADNULLS, valuepos,1);
  2670. //push reference index
  2671. SQObject strIter = _fs->CreateString(_SC("@ITERATOR@"));
  2672. SQInteger itrpos = _fs->PushLocalVariable(strIter, _scope.nested); //use invalid id to make it inaccessible
  2673. if(itrpos < 0) ErrorNameAlreadyDeclared(strIter);
  2674. _fs->AddInstruction(_OP_LOADNULLS, itrpos,1);
  2675. SQInteger jmppos = _fs->GetCurrentPos();
  2676. _fs->AddInstruction(_OP_FOREACH, container, 0, indexpos);
  2677. SQInteger foreachpos = _fs->GetCurrentPos();
  2678. _fs->AddInstruction(_OP_POSTFOREACH, container, 0, indexpos);
  2679. //generate the statement code
  2680. BEGIN_BREAKBLE_BLOCK()
  2681. Statement();
  2682. _fs->AddInstruction(_OP_JMP, 0, jmppos - _fs->GetCurrentPos() - 1);
  2683. _fs->SetInstructionParam(foreachpos, 1, _fs->GetCurrentPos() - foreachpos);
  2684. _fs->SetInstructionParam(foreachpos + 1, 1, _fs->GetCurrentPos() - foreachpos);
  2685. END_BREAKBLE_BLOCK(foreachpos - 1);
  2686. //restore the local variable stack(remove index,val and ref idx)
  2687. _fs->PopTarget();
  2688. END_SCOPE();
  2689. }
  2690. void SwitchStatement()
  2691. {
  2692. Lex();
  2693. Expect(_SC('('));
  2694. CommaExpr(true);
  2695. Expect(_SC(')'));
  2696. Expect(_SC('{'));
  2697. SQInteger expr = _fs->TopTarget();
  2698. bool bfirst = true;
  2699. SQInteger tonextcondjmp = -1;
  2700. SQInteger skipcondjmp = -1;
  2701. SQInteger __nbreaks__ = _fs->_unresolvedbreaks.size();
  2702. _fs->_breaktargets.push_back(0);
  2703. while(_token == TK_CASE)
  2704. {
  2705. if(!bfirst)
  2706. {
  2707. _fs->AddInstruction(_OP_JMP, 0, 0);
  2708. skipcondjmp = _fs->GetCurrentPos();
  2709. _fs->SetInstructionParam(tonextcondjmp, 1, _fs->GetCurrentPos() - tonextcondjmp);
  2710. }
  2711. //condition
  2712. Lex();
  2713. ExpressionScalar() /*Expression()*/;
  2714. Expect(_SC(':'));
  2715. SQInteger trg = _fs->PopTarget();
  2716. SQInteger eqtarget = trg;
  2717. bool local = _fs->IsLocal(trg);
  2718. if(local)
  2719. {
  2720. eqtarget = _fs->PushTarget(); //we need to allocate a extra reg
  2721. }
  2722. _fs->AddInstruction(_OP_EQ, eqtarget, trg, expr);
  2723. _fs->AddInstruction(_OP_JZ, eqtarget, 0);
  2724. if(local)
  2725. {
  2726. _fs->PopTarget();
  2727. }
  2728. //end condition
  2729. if(skipcondjmp != -1)
  2730. {
  2731. _fs->SetInstructionParam(skipcondjmp, 1, (_fs->GetCurrentPos() - skipcondjmp));
  2732. }
  2733. tonextcondjmp = _fs->GetCurrentPos();
  2734. BEGIN_SCOPE();
  2735. Statements();
  2736. END_SCOPE();
  2737. bfirst = false;
  2738. }
  2739. if(tonextcondjmp != -1)
  2740. _fs->SetInstructionParam(tonextcondjmp, 1, _fs->GetCurrentPos() - tonextcondjmp);
  2741. if(_token == TK_DEFAULT)
  2742. {
  2743. Lex();
  2744. Expect(_SC(':'));
  2745. BEGIN_SCOPE();
  2746. Statements();
  2747. END_SCOPE();
  2748. }
  2749. Expect(_SC('}'));
  2750. _fs->PopTarget();
  2751. __nbreaks__ = _fs->_unresolvedbreaks.size() - __nbreaks__;
  2752. if(__nbreaks__ > 0)ResolveBreaks(_fs, __nbreaks__);
  2753. _fs->_breaktargets.pop_back();
  2754. }
  2755. void TemplateStatement()
  2756. {
  2757. Lex(); //ignore for now
  2758. Expect(_SC('<'));
  2759. int nest_count = 1;
  2760. while(_token > 0 && nest_count > 0)
  2761. {
  2762. Lex();
  2763. switch(_token)
  2764. {
  2765. case _SC('>'):
  2766. --nest_count;
  2767. break;
  2768. case _SC('<'):
  2769. nest_count++;
  2770. }
  2771. }
  2772. if(nest_count == 0) Lex(); //last '>' ignore for now
  2773. }
  2774. void FunctionStatement()
  2775. {
  2776. SQObject id;
  2777. Lex();
  2778. id = Expect(TK_IDENTIFIER);
  2779. _fs->PushTarget(0);
  2780. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(id));
  2781. if(_token == TK_DOUBLE_COLON) Emit2ArgsOP(_OP_GET);
  2782. else CheckGlobalName(id, true);
  2783. while(_token == TK_DOUBLE_COLON)
  2784. {
  2785. Lex();
  2786. id = Expect(TK_IDENTIFIER);
  2787. //todo check if class function already exists
  2788. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(id));
  2789. if(_token == TK_DOUBLE_COLON) Emit2ArgsOP(_OP_GET);
  2790. }
  2791. Expect(_SC('('));
  2792. CreateFunction(id, eFunctionType_global);
  2793. _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, 0);
  2794. EmitDerefOp(_OP_NEWSLOT);
  2795. _fs->PopTarget();
  2796. }
  2797. void ClassStatement()
  2798. {
  2799. SQExpState es;
  2800. SQObjectPtr class_name;
  2801. Lex();
  2802. if(_token == TK_IDENTIFIER)
  2803. {
  2804. SQInteger lhtk = _lex.LookaheadLex();
  2805. switch(lhtk)
  2806. {
  2807. case TK_DOUBLE_COLON: //C++ style namespace
  2808. case _SC('.'):
  2809. break;
  2810. default:
  2811. class_name = SQString::Create(_ss(_vm), _lex.data->svalue);
  2812. CheckGlobalName(class_name, true);
  2813. CheckTypeName(class_name, true); //to allow C/C++ style instance declarations
  2814. }
  2815. }
  2816. es = _es;
  2817. _es.donot_get = true;
  2818. PrefixedExpr();
  2819. if(_token == _SC(';')) //class forward declaration
  2820. {
  2821. //return;
  2822. }
  2823. if(_es.etype == EXPR)
  2824. {
  2825. Error(_SC("invalid class name"));
  2826. }
  2827. else if(_es.etype == OBJECT || _es.etype == BASE)
  2828. {
  2829. ClassExp(&class_name);
  2830. EmitDerefOp(_OP_NEWSLOT);
  2831. _fs->PopTarget();
  2832. }
  2833. else
  2834. {
  2835. Error(_SC("cannot create a class in a local with the syntax(class <local>)"));
  2836. }
  2837. _es = es;
  2838. }
  2839. SQObject ExpectScalar()
  2840. {
  2841. SQObject val;
  2842. val._type = OT_NULL;
  2843. val._unVal.nInteger = 0; //shut up GCC 4.x
  2844. switch(_token)
  2845. {
  2846. CASE_TK_INTEGER:
  2847. val._type = OT_INTEGER;
  2848. val._unVal.nInteger = _lex.data->nvalue;
  2849. break;
  2850. case TK_FLOAT:
  2851. val._type = OT_FLOAT;
  2852. val._unVal.fFloat = _lex.data->fvalue;
  2853. break;
  2854. case TK_STRING_LITERAL:
  2855. val = _fs->CreateString(_lex.data->svalue,_lex.data->longstr.size()-1);
  2856. break;
  2857. case TK_TRUE:
  2858. case TK_FALSE:
  2859. val._type = OT_BOOL;
  2860. val._unVal.nInteger = _token == TK_TRUE ? 1 : 0;
  2861. break;
  2862. case '-':
  2863. Lex();
  2864. switch(_token)
  2865. {
  2866. CASE_TK_INTEGER:
  2867. val._type = OT_INTEGER;
  2868. val._unVal.nInteger = -_lex.data->nvalue;
  2869. break;
  2870. case TK_FLOAT:
  2871. val._type = OT_FLOAT;
  2872. val._unVal.fFloat = -_lex.data->fvalue;
  2873. break;
  2874. default:
  2875. Error(_SC("scalar expected : integer, float"));
  2876. }
  2877. break;
  2878. default:
  2879. Error(_SC("scalar expected : integer, float or string"));
  2880. }
  2881. Lex();
  2882. return val;
  2883. }
  2884. SQInteger ExpressionScalar()
  2885. {
  2886. SQInteger tk_type = _token;
  2887. switch(_token)
  2888. {
  2889. CASE_TK_INTEGER:
  2890. EmitLoadConstInt(_lex.data->nvalue,-1);
  2891. break;
  2892. case TK_FLOAT:
  2893. EmitLoadConstFloat(_lex.data->fvalue,-1);
  2894. break;
  2895. case TK_STRING_LITERAL:
  2896. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(_fs->CreateString(_lex.data->svalue,_lex.data->longstr.size()-1)));
  2897. break;
  2898. case TK_IDENTIFIER:
  2899. {
  2900. SQObject id = _fs->CreateString(_lex.data->svalue);
  2901. Lex();
  2902. ExpressionConstant(id);
  2903. return tk_type;
  2904. }
  2905. break;
  2906. case '-':
  2907. Lex();
  2908. tk_type = _token;
  2909. switch(_token)
  2910. {
  2911. CASE_TK_INTEGER:
  2912. EmitLoadConstInt(-_lex.data->nvalue,-1);
  2913. break;
  2914. case TK_FLOAT:
  2915. EmitLoadConstFloat(-_lex.data->fvalue,-1);
  2916. break;
  2917. default:
  2918. Error(_SC("scalar expected : integer, float"));
  2919. }
  2920. break;
  2921. default:
  2922. goto error;
  2923. }
  2924. Lex();
  2925. return tk_type;
  2926. error:
  2927. Error(_SC("constant or scalar expected : integer, float or string"));
  2928. return 0;
  2929. }
  2930. void EnumStatement()
  2931. {
  2932. Lex();
  2933. SQObject id = Expect(TK_IDENTIFIER);
  2934. Expect(_SC('{'));
  2935. //CheckLocalNameScope(id, _scope.nested);
  2936. SQObjectPtr strongid = id;
  2937. CheckLocalNameScope(id, _scope.nested);
  2938. TypesNewSlot(strongid,strongid);
  2939. SQObject table = _fs->CreateTable();
  2940. //_fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(),0,NOT_TABLE);
  2941. SQInteger nval = 0;
  2942. while(_token != _SC('}'))
  2943. {
  2944. SQObject key = Expect(TK_IDENTIFIER);
  2945. SQObject val;
  2946. if(_token == _SC('='))
  2947. {
  2948. Lex();
  2949. val = ExpectScalar();
  2950. if(sq_type(val) == OT_INTEGER) nval = _integer(val)+1;
  2951. }
  2952. else
  2953. {
  2954. val._type = OT_INTEGER;
  2955. val._unVal.nInteger = nval++;
  2956. }
  2957. //SQInteger table = _fs->TopTarget(); //<<BECAUSE OF THIS NO COMMON EMIT FUNC IS POSSIBLE
  2958. //_fs->AddInstruction(_OP_NEWSLOT, 0xFF, table, key, val);
  2959. _table(table)->NewSlot(SQObjectPtr(key),SQObjectPtr(val));
  2960. if(_token == ',') Lex();
  2961. }
  2962. ConstsNewSlot(SQObjectPtr(strongid),SQObjectPtr(table));
  2963. strongid.Null();
  2964. Lex();
  2965. }
  2966. void TryCatchStatement()
  2967. {
  2968. SQObject exid;
  2969. Lex();
  2970. _fs->AddInstruction(_OP_PUSHTRAP,0,0);
  2971. _fs->_traps++;
  2972. if(_fs->_breaktargets.size()) _fs->_breaktargets.top()++;
  2973. if(_fs->_continuetargets.size()) _fs->_continuetargets.top()++;
  2974. SQInteger trappos = _fs->GetCurrentPos();
  2975. {
  2976. BEGIN_SCOPE();
  2977. Statement();
  2978. END_SCOPE();
  2979. }
  2980. _fs->_traps--;
  2981. _fs->AddInstruction(_OP_POPTRAP, 1, 0);
  2982. if(_fs->_breaktargets.size()) _fs->_breaktargets.top()--;
  2983. if(_fs->_continuetargets.size()) _fs->_continuetargets.top()--;
  2984. _fs->AddInstruction(_OP_JMP, 0, 0);
  2985. SQInteger jmppos = _fs->GetCurrentPos();
  2986. _fs->SetInstructionParam(trappos, 1, (_fs->GetCurrentPos() - trappos));
  2987. Expect(TK_CATCH);
  2988. Expect(_SC('('));
  2989. exid = Expect(TK_IDENTIFIER);
  2990. if(CheckTypeName(exid)) //C/C++ type declaration;
  2991. {
  2992. //for now just accept the type and do nothing with it
  2993. exid = Expect(TK_IDENTIFIER);
  2994. }
  2995. Expect(_SC(')'));
  2996. {
  2997. BEGIN_SCOPE();
  2998. SQInteger ex_target = _fs->PushLocalVariable(exid, _scope.nested);
  2999. if(ex_target < 0) ErrorNameAlreadyDeclared(exid);
  3000. _fs->SetInstructionParam(trappos, 0, ex_target);
  3001. Statement();
  3002. _fs->SetInstructionParams(jmppos, 0, (_fs->GetCurrentPos() - jmppos), 0);
  3003. END_SCOPE();
  3004. }
  3005. }
  3006. void FunctionExp(SQInteger ftype,bool lambda = false)
  3007. {
  3008. Lex();
  3009. Expect(_SC('('));
  3010. SQObjectPtr dummy;
  3011. CreateFunction(dummy, lambda ? eFunctionType_lambda : eFunctionType_anonymous);
  3012. _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, ftype == TK_FUNCTION?0:1);
  3013. }
  3014. void ClassExp(SQObjectPtr *class_name)
  3015. {
  3016. SQInteger base = -1;
  3017. SQInteger attrs = -1;
  3018. bool hasInheritance = false;
  3019. switch(_token)
  3020. {
  3021. case _SC(':'): //C++ style class derivation
  3022. case TK_EXTENDS: //squirrel style class derivation
  3023. Lex();
  3024. hasInheritance = true;
  3025. switch(_token)
  3026. {
  3027. case TK_PRIVATE:
  3028. case TK_PROTECTED:
  3029. case TK_PUBLIC:
  3030. Lex(); //ignore, accepted only to compile a subset of C++
  3031. }
  3032. }
  3033. if(hasInheritance)
  3034. {
  3035. Expression();
  3036. base = _fs->TopTarget();
  3037. }
  3038. if(_token == TK_ATTR_OPEN)
  3039. {
  3040. Lex();
  3041. _fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(),0,NOT_TABLE);
  3042. ParseTableOrClass(_SC(','),TK_ATTR_CLOSE);
  3043. attrs = _fs->TopTarget();
  3044. }
  3045. Expect(_SC('{'));
  3046. if(attrs != -1) _fs->PopTarget();
  3047. if(base != -1) _fs->PopTarget();
  3048. _fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(), base, attrs,NOT_CLASS);
  3049. ParseTableOrClass(_SC(';'),_SC('}'), class_name);
  3050. }
  3051. void DeleteExpr()
  3052. {
  3053. SQExpState es;
  3054. Lex();
  3055. es = _es;
  3056. _es.donot_get = true;
  3057. PrefixedExpr();
  3058. if(_es.etype==EXPR) Error(_SC("can't delete an expression"));
  3059. if(_es.etype==OBJECT || _es.etype==BASE)
  3060. {
  3061. Emit2ArgsOP(_OP_DELETE);
  3062. }
  3063. else
  3064. {
  3065. Error(_SC("cannot delete an (outer) local"));
  3066. }
  3067. _es = es;
  3068. }
  3069. void PrefixIncDec(SQInteger token)
  3070. {
  3071. SQExpState es;
  3072. SQInteger diff = (token==TK_MINUSMINUS) ? -1 : 1;
  3073. Lex();
  3074. es = _es;
  3075. _es.donot_get = true;
  3076. PrefixedExpr();
  3077. if(_es.etype==EXPR)
  3078. {
  3079. Error(_SC("can't '++' or '--' an expression"));
  3080. }
  3081. else if(_es.etype==OBJECT || _es.etype==BASE)
  3082. {
  3083. Emit2ArgsOP(_OP_INC, diff);
  3084. }
  3085. else if(_es.etype==LOCAL)
  3086. {
  3087. SQInteger src = _fs->TopTarget();
  3088. _fs->AddInstruction(_OP_INCL, src, src, 0, diff);
  3089. }
  3090. else if(_es.etype==OUTER)
  3091. {
  3092. SQInteger tmp = _fs->PushTarget();
  3093. _fs->AddInstruction(_OP_GETOUTER, tmp, _es.epos);
  3094. _fs->AddInstruction(_OP_INCL, tmp, tmp, 0, diff);
  3095. _fs->AddInstruction(_OP_SETOUTER, tmp, _es.epos, tmp);
  3096. }
  3097. _es = es;
  3098. }
  3099. void CreateFunction(SQObject &name, int ftype, int fdeclType=0)
  3100. {
  3101. SQFuncState *funcstate = _fs->PushChildState(_ss(_vm));
  3102. funcstate->_name = name;
  3103. SQObject paramname, type_name;
  3104. SQObject strThis = _fs->CreateString(_SC("this"));
  3105. if(funcstate->AddParameter(strThis, _scope.nested+1) < 0)
  3106. ErrorNameAlreadyDeclared(strThis);
  3107. funcstate->_sourcename = _sourcename;
  3108. SQInteger defparams = 0;
  3109. bool is_reference_declaration = 0;
  3110. bool is_pointer_declaration = false;
  3111. const SQChar *param_type_name = 0;
  3112. bool isVoid = false;
  3113. if(fdeclType)
  3114. {
  3115. funcstate->SetReturnTypeName(SQGetVarTypeName(fdeclType));
  3116. }
  3117. while(_token!=_SC(')'))
  3118. {
  3119. if(isVoid)
  3120. {
  3121. Error(_SC("void type is invalid here"));
  3122. }
  3123. is_reference_declaration = 0; //reset is_reference_declaration
  3124. param_type_name = 0; //rest for each parameter
  3125. if(_token == TK_VOID)
  3126. {
  3127. isVoid = true;
  3128. Lex();
  3129. continue;
  3130. }
  3131. if(_token == TK_VARPARAMS)
  3132. {
  3133. if(defparams > 0) Error(_SC("function with default parameters cannot have variable number of parameters"));
  3134. SQObject strVargv = _fs->CreateString(_SC("vargv"));
  3135. if(funcstate->AddParameter(strVargv, _scope.nested+1) < 0)
  3136. ErrorNameAlreadyDeclared(strVargv);
  3137. funcstate->_varparams = true;
  3138. Lex();
  3139. if(_token != _SC(')')) Error(_SC("expected ')'"));
  3140. break;
  3141. }
  3142. else
  3143. {
  3144. if(_token == TK_CONST) Lex(); //C/C++ const cualifiers for now
  3145. switch(_token)
  3146. {
  3147. CASE_TK_LOCAL_TYPES: //accept C/C++ type parameter declarations
  3148. param_type_name = _lex.GetTokenName(_token);
  3149. Lex();
  3150. }
  3151. CHECK_REF_DECLARATION(_token);
  3152. paramname = Expect(TK_IDENTIFIER);
  3153. if(CheckNameIsType(paramname))
  3154. {
  3155. //ignore custom types for now
  3156. param_type_name = _stringval(paramname);
  3157. CHECK_REF_DECLARATION(_token);
  3158. EatTemplateInitialization();
  3159. paramname = Expect(TK_IDENTIFIER);
  3160. }
  3161. if(funcstate->AddParameter(paramname, _scope.nested+1, is_reference_declaration ? _VAR_REFERENCE :
  3162. (is_pointer_declaration ? _VAR_POINTER : _VAR_ANY)) < 0)
  3163. ErrorNameAlreadyDeclared(paramname);
  3164. if(param_type_name)
  3165. {
  3166. funcstate->AddParameterTypeName(param_type_name);
  3167. }
  3168. default_value:
  3169. if(_token == _SC('='))
  3170. {
  3171. if(is_reference_declaration) Error(_SC("parameter passed by reference can't have default value"));
  3172. Lex();
  3173. if(_token == _SC('[') || _token == _SC('{')) Error(_SC("default parameter with array/table values not supported"));
  3174. Expression();
  3175. //stack_offset to compensate for local functions been relocated to allow recursion
  3176. funcstate->AddDefaultParam(_fs->TopTarget());
  3177. defparams++;
  3178. }
  3179. else if(_token == _SC(':'))
  3180. {
  3181. //param type specifier like typescript
  3182. if(param_type_name)
  3183. {
  3184. Error(_SC("parameter type already declared before %s"), _stringval(paramname));
  3185. }
  3186. Lex();
  3187. type_name = ExpectTypeToken();
  3188. funcstate->AddParameterTypeName(type_name);
  3189. //printf("%d %s\n", __LINE__, _stringval(type_name));
  3190. if(_token == _SC('=')) goto default_value; //default value
  3191. }
  3192. else
  3193. {
  3194. if(defparams > 0) Error(_SC("expected '='"));
  3195. }
  3196. if(_token == _SC(',')) Lex();
  3197. else if(_token != _SC(')')) Error(_SC("expected ')' or ','"));
  3198. }
  3199. }
  3200. Expect(_SC(')'));
  3201. switch(_token)
  3202. {
  3203. case _SC(':'):
  3204. {
  3205. //return type specifier like typescript
  3206. Lex();
  3207. type_name = ExpectTypeToken();
  3208. funcstate->_return_type = type_name;
  3209. //printf("%d %s\n", __LINE__, _stringval(type_name));
  3210. }
  3211. break;
  3212. case TK_CONST:
  3213. case TK_NOEXCEPT:
  3214. case TK_VOLATILE:
  3215. Lex(); //accept and ignore
  3216. break;
  3217. case TK_IDENTIFIER:
  3218. if(ftype == eFunctionType_member)
  3219. {
  3220. if( (scstrcmp(_lex.data->svalue, _SC("final")) == 0) ||
  3221. (scstrcmp(_lex.data->svalue, _SC("override")) == 0))
  3222. {
  3223. Lex(); //accept but ignore then
  3224. }
  3225. }
  3226. }
  3227. for(SQInteger n = 0; n < defparams; n++)
  3228. {
  3229. _fs->PopTarget();
  3230. }
  3231. if(_is_parsing_extern)
  3232. {
  3233. if(_token == _SC(';')) //to parse thinscript
  3234. {
  3235. _fs->PopChildState();
  3236. return;
  3237. }
  3238. else _is_parsing_extern = false;
  3239. }
  3240. SQFuncState *currchunk = _fs;
  3241. _fs = funcstate;
  3242. if(ftype == eFunctionType_lambda)
  3243. {
  3244. Expression();
  3245. _fs->AddInstruction(_OP_RETURN, 1, _fs->PopTarget());
  3246. }
  3247. else
  3248. {
  3249. Statement(false);
  3250. }
  3251. ResolveGotos();
  3252. funcstate->AddLineInfos(_lex.data->prevtoken == _SC('\n')?_lex.data->lasttokenline:_lex.data->currentline, _lineinfo, true);
  3253. funcstate->AddInstruction(_OP_RETURN, -1);
  3254. funcstate->SetStackSize(0);
  3255. SQFunctionProto *func = funcstate->BuildProto();
  3256. #ifdef _DEBUG_DUMP
  3257. funcstate->Dump(func);
  3258. #endif
  3259. _fs = currchunk;
  3260. _fs->_functions.push_back(func);
  3261. _fs->PopChildState();
  3262. }
  3263. void AdjustGotoInstruction(const SQGotoLabelsInfo &goto_info, const SQGotoLabelsInfo &label)
  3264. {
  3265. SQInteger target_pos = label.pos;
  3266. SQInteger jump_pos = target_pos - goto_info.pos;
  3267. //set the jmp instruction
  3268. SQInteger poptraps = goto_info.traps - label.traps;
  3269. SQInt32 ioffset = 1;
  3270. while(poptraps)
  3271. {
  3272. SQInstruction &i_op_poptrap = _fs->GetInstruction(goto_info.pos-ioffset);
  3273. if(i_op_poptrap.op != _OP_NOP)
  3274. {
  3275. if(ioffset < 2)
  3276. {
  3277. ++ioffset;
  3278. continue;
  3279. }
  3280. Error(_SC("Compiler: This should not happen i_op_poptrap.op != _OP_NOP"));
  3281. }
  3282. //printf("poptraps for %s = %d : %d\n", _stringval(label.name), (int)poptraps, (int)i_op_poptrap._arg0);
  3283. i_op_poptrap.op = _OP_POPTRAP;
  3284. i_op_poptrap._arg0 = poptraps;
  3285. break;
  3286. }
  3287. _fs->SetInstructionParams(goto_info.pos, 0, jump_pos, 0);
  3288. }
  3289. void ResolveGotos()
  3290. {
  3291. //first we walk through the labels and when we come back
  3292. //nested labels we remove then because we only allow
  3293. //goto/joump out of blocks/scopes
  3294. SQInt16 last_nested = -1;
  3295. for(SQUnsignedInteger idxlabel = 0; idxlabel < _fs->_gototargets.size(); ++idxlabel)
  3296. {
  3297. SQGotoLabelsInfo &label = _fs->_gototargets[idxlabel];
  3298. SQUnsignedInteger resolved = 0;
  3299. for(SQUnsignedInteger idxGoto = 0; idxGoto < _fs->_unresolvedgotos.size(); ++idxGoto)
  3300. {
  3301. SQGotoLabelsInfo &goto_info = _fs->_unresolvedgotos[idxGoto];
  3302. if(_string(label.name) == _string(goto_info.name))
  3303. {
  3304. if(label.nested > goto_info.nested)
  3305. {
  3306. _lex.data->currentline = goto_info.line;
  3307. Error(_SC("Goto can not jump inside nested block/scope '%s'"), _stringval(goto_info.name));
  3308. }
  3309. AdjustGotoInstruction(goto_info, label);
  3310. //we dcrease idxGoto here to compensate the removal inside the for loop
  3311. _fs->_unresolvedgotos.remove(idxGoto--);
  3312. ++resolved;
  3313. }
  3314. }
  3315. if(!resolved)
  3316. {
  3317. //if a label isn't resolved we have an unused label
  3318. _lex.data->currentline = label.line;
  3319. Error(_SC("Label not resolved at this point '%s'"), _stringval(label.name));
  3320. }
  3321. if(label.nested < last_nested)
  3322. {
  3323. //remove any previous nested label to prevent goto/jump inside blocks/scopes
  3324. SQUnsignedInteger i = idxlabel - 1;
  3325. for(; i > 0; --i)
  3326. {
  3327. if(_fs->_gototargets[i].nested <= label.nested) break;
  3328. _fs->_gototargets.remove(i);
  3329. //we decrease the index idxlabel here due to remove before
  3330. //the current idxlabel
  3331. --idxlabel;
  3332. }
  3333. }
  3334. last_nested = label.nested;
  3335. }
  3336. if(_fs->_unresolvedgotos.size())
  3337. {
  3338. //if we still have any unresolved goto it's an error, let's show the first
  3339. SQGotoLabelsInfo &goto_info = _fs->_unresolvedgotos[0];
  3340. _lex.data->currentline = goto_info.line;
  3341. Error(_SC("Goto can not jump to undeclared label '%s'"), _stringval(goto_info.name));
  3342. }
  3343. }
  3344. void ResolveBreaks(SQFuncState *funcstate, SQInteger ntoresolve)
  3345. {
  3346. while(ntoresolve > 0)
  3347. {
  3348. SQInteger pos = funcstate->_unresolvedbreaks.back();
  3349. funcstate->_unresolvedbreaks.pop_back();
  3350. //set the jmp instruction
  3351. funcstate->SetInstructionParams(pos, 0, funcstate->GetCurrentPos() - pos, 0);
  3352. ntoresolve--;
  3353. }
  3354. }
  3355. void ResolveContinues(SQFuncState *funcstate, SQInteger ntoresolve, SQInteger targetpos)
  3356. {
  3357. while(ntoresolve > 0)
  3358. {
  3359. SQInteger pos = funcstate->_unresolvedcontinues.back();
  3360. funcstate->_unresolvedcontinues.pop_back();
  3361. //set the jmp instruction
  3362. funcstate->SetInstructionParams(pos, 0, targetpos - pos, 0);
  3363. ntoresolve--;
  3364. }
  3365. }
  3366. private:
  3367. SQInteger _token;
  3368. SQFuncState *_fs;
  3369. SQObjectPtr _sourcename;
  3370. SQLexer _lex;
  3371. bool _lineinfo;
  3372. bool _raiseerror;
  3373. bool _show_warnings;
  3374. bool _is_parsing_extern;
  3375. SQInteger _debugline;
  3376. SQInteger _debugop;
  3377. SQExpState _es;
  3378. SQScope _scope;
  3379. SQChar *_compilererror;
  3380. jmp_buf _errorjmp;
  3381. SQVM *_vm;
  3382. SQObjectPtrVec _scope_consts;
  3383. SQObjectPtrVec _scope_types;
  3384. SQObjectPtr _globals;
  3385. SQObjectPtr _type_names; //to allow C/C++ style instance declarations
  3386. SQObjectPtr _extern_names; //to allow C/C++ style extern declarations
  3387. SQChar error_buf[MAX_COMPILER_ERROR_LEN];
  3388. SQInteger _max_nested_includes, _nested_includes_count;
  3389. SQInteger _ifdef_exclude, _ifdef_line, _inside_ifdef;
  3390. const SQChar *squilu_lib_path;
  3391. };
  3392. bool Compile(SQVM *vm,SQLEXREADFUNC rg, SQUserPointer up, const SQChar *sourcename, SQObjectPtr &out,
  3393. bool raiseerror, bool lineinfo, bool show_warnings, SQInteger max_nested_includes)
  3394. {
  3395. SQCompiler p(vm, rg, up, sourcename, raiseerror, lineinfo, show_warnings, max_nested_includes);
  3396. return p.Compile(out);
  3397. }
  3398. #endif