sqcompiler.cpp 111 KB

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