sqcompiler.cpp 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851
  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. #define EXPR 1
  17. #define OBJECT 2
  18. #define BASE 3
  19. #define LOCAL 4
  20. #define OUTER 5
  21. struct SQExpState {
  22. SQInteger etype; /* expr. type; one of EXPR, OBJECT, BASE, OUTER or LOCAL */
  23. SQInteger epos; /* expr. location on stack; -1 for OBJECT and BASE */
  24. bool donot_get; /* signal not to deref the next value */
  25. };
  26. struct SQScope {
  27. SQInteger outers;
  28. SQInteger stacksize;
  29. SQInteger nested;
  30. };
  31. #define BEGIN_SCOPE() SQScope __oldscope__ = _scope; \
  32. ++_scope.nested; \
  33. _scope.outers = _fs->_outers; \
  34. _scope.stacksize = _fs->GetStackSize();\
  35. _scope_consts.push_back(SQTable::Create(_ss(_vm),0));
  36. #define RESOLVE_OUTERS() if(_fs->GetStackSize() != _scope.stacksize) { \
  37. if(_fs->CountOuters(_scope.stacksize)) { \
  38. _fs->AddInstruction(_OP_CLOSE,0,_scope.stacksize); \
  39. } \
  40. }
  41. #define END_SCOPE_NO_CLOSE() { if(_fs->GetStackSize() != _scope.stacksize) { \
  42. _fs->SetStackSize(_scope.stacksize); \
  43. } \
  44. _scope = __oldscope__; \
  45. _scope_consts.pop_back();\
  46. }
  47. #define END_SCOPE() { SQInteger oldouters = _fs->_outers;\
  48. if(_fs->GetStackSize() != _scope.stacksize) { \
  49. _fs->SetStackSize(_scope.stacksize); \
  50. if(oldouters != _fs->_outers) { \
  51. _fs->AddInstruction(_OP_CLOSE,0,_scope.stacksize); \
  52. } \
  53. } \
  54. _scope = __oldscope__; \
  55. }
  56. #define BEGIN_BREAKBLE_BLOCK() SQInteger __nbreaks__=_fs->_unresolvedbreaks.size(); \
  57. SQInteger __ncontinues__=_fs->_unresolvedcontinues.size(); \
  58. _fs->_breaktargets.push_back(0);_fs->_continuetargets.push_back(0);
  59. #define END_BREAKBLE_BLOCK(continue_target) {__nbreaks__=_fs->_unresolvedbreaks.size()-__nbreaks__; \
  60. __ncontinues__=_fs->_unresolvedcontinues.size()-__ncontinues__; \
  61. if(__ncontinues__>0)ResolveContinues(_fs,__ncontinues__,continue_target); \
  62. if(__nbreaks__>0)ResolveBreaks(_fs,__nbreaks__); \
  63. _fs->_breaktargets.pop_back();_fs->_continuetargets.pop_back();}
  64. class SQCompiler
  65. {
  66. public:
  67. SQCompiler(SQVM *v, SQLEXREADFUNC rg, SQUserPointer up, const SQChar* sourcename,
  68. bool raiseerror, bool lineinfo, bool show_warnings)
  69. {
  70. _vm=v;
  71. _lex.Init(_ss(v), rg, up,ThrowError,this);
  72. _sourcename = SQString::Create(_ss(v), sourcename);
  73. _lineinfo = lineinfo;_raiseerror = raiseerror;
  74. _show_warnings = show_warnings;
  75. _scope.outers = 0;
  76. _scope.stacksize = 0;
  77. _scope.nested = 0;
  78. compilererror = NULL;
  79. _globals = SQTable::Create(_ss(_vm),0);
  80. }
  81. ~SQCompiler(){
  82. _table(_globals)->Finalize();
  83. _globals.Null();
  84. }
  85. static void ThrowError(void *ud, const SQChar *s) {
  86. SQCompiler *c = (SQCompiler *)ud;
  87. c->Error(s);
  88. }
  89. void Error(const SQChar *s, ...)
  90. {
  91. static SQChar temp[256];
  92. va_list vl;
  93. va_start(vl, s);
  94. scvsprintf(temp, s, vl);
  95. va_end(vl);
  96. compilererror = temp;
  97. longjmp(_errorjmp,1);
  98. }
  99. void Warning(const SQChar *s, ...)
  100. {
  101. if(!_show_warnings) return;
  102. va_list vl;
  103. va_start(vl, s);
  104. scvfprintf(stderr, s, vl);
  105. va_end(vl);
  106. }
  107. void CheckGlobalName(const SQObject &name, bool addIfNotExists=false, bool checkLocals=true){
  108. if(_table(_globals)->Exists(name)){
  109. if(checkLocals) Error(_SC("global '%s' already declared"), _stringval(name));
  110. else Warning(_SC("WARNING: %s:%d:%d global '%s' already declared will be shadowed\n"),
  111. _stringval(_sourcename), _lex._currentline, _lex._currentcolumn, _stringval(name));
  112. }
  113. else if(checkLocals) CheckLocalNameScope(name, -1, false);
  114. if(addIfNotExists) {
  115. SQObjectPtr oname = name, otrue = true;
  116. _table(_globals)->NewSlot(oname, otrue);
  117. }
  118. }
  119. void CheckLocalNameScope(const SQObject &name, SQInteger scope, bool checkGlobals=true){
  120. SQInteger found = _fs->GetLocalVariable(name);
  121. if(found >= 0){
  122. SQLocalVarInfo &lvi = _fs->_vlocals[found];
  123. if(lvi._scope == scope)
  124. Error(_SC("local '%s' already declared"), _stringval(name));
  125. else
  126. Warning(_SC("WARNING: %s:%d:%d local '%s' already declared will be shadowed\n"),
  127. _stringval(_sourcename), _lex._currentline, _lex._currentcolumn, _stringval(name));
  128. }
  129. else
  130. {
  131. found = _fs->FindOuterVariable(name);
  132. if(found >= 0) Warning(_SC("WARNING: %s:%d:%d outer variable '%s' already declared will be shadowed\n"),
  133. _stringval(_sourcename), _lex._currentline, _lex._currentcolumn, _stringval(name));
  134. }
  135. if(checkGlobals) CheckGlobalName(name, false, false);
  136. }
  137. bool IsConstant(const SQObject &name,SQObject &e){
  138. SQObjectPtr val;
  139. for(int i=_scope.nested-1; i >= 0; --i){
  140. if(_table(_scope_consts[i])->Get(name,val)) {
  141. e = val;
  142. return true;
  143. }
  144. }
  145. if(_table(_ss(_vm)->_consts)->Get(name,val)) {
  146. e = val;
  147. return true;
  148. }
  149. return false;
  150. }
  151. void CheckConstsExists(const SQObjectPtr &key){
  152. int found = -1;
  153. for(int i=_scope.nested-1; i >= 0; --i){
  154. if(_table(_scope_consts[i])->Exists(key)) {
  155. found = i+1;
  156. break;
  157. }
  158. }
  159. if(found < 0 && _table(_ss(_vm)->_consts)->Exists(key)) found = 0;
  160. if(found == _scope.nested) {
  161. Error(_SC("constant '%s' already exists\n"), _stringval(key));
  162. }
  163. if(found >= 0) Warning(_SC("WARNING: %s:%d:%d an already defined constant '%s' will be shadowed\n"),
  164. _stringval(_sourcename), _lex._currentline, _lex._currentcolumn, _stringval(key));
  165. }
  166. bool ConstsGet(const SQObjectPtr &key,SQObjectPtr &val){
  167. for(int i=_scope.nested-1; i >= 0; --i){
  168. if(_table(_scope_consts[i])->Get(key,val)) return true;
  169. }
  170. return _table(_ss(_vm)->_consts)->Get(key,val);
  171. }
  172. bool ConstsNewSlot(const SQObjectPtr &key, const SQObjectPtr &val){
  173. if(_scope.nested) return _table(_scope_consts[_scope.nested-1])->NewSlot(key,val);
  174. return _table(_ss(_vm)->_consts)->NewSlot(key,val);
  175. }
  176. void Lex(){ _token = _lex.Lex();}
  177. SQObjectPtr GetTokenObject(SQInteger tok)
  178. {
  179. SQObjectPtr ret;
  180. switch(tok)
  181. {
  182. case TK_IDENTIFIER:
  183. ret = _fs->CreateString(_lex._svalue);
  184. break;
  185. case TK_STRING_LITERAL:
  186. ret = _fs->CreateString(_lex._svalue,_lex._longstr.size()-1);
  187. break;
  188. case TK_INTEGER:
  189. ret = SQObjectPtr(_lex._nvalue);
  190. break;
  191. case TK_FLOAT:
  192. ret = SQObjectPtr(_lex._fvalue);
  193. break;
  194. }
  195. Lex();
  196. return ret;
  197. }
  198. void ErrorIfNotToken(SQInteger tok){
  199. if(_token != tok) {
  200. if(((_token == TK_CONSTRUCTOR) || (_token == TK_DESTRUCTOR)) && tok == TK_IDENTIFIER) {
  201. //do nothing
  202. }
  203. else {
  204. const SQChar *etypename;
  205. if(tok > 255) {
  206. switch(tok)
  207. {
  208. case TK_IDENTIFIER:
  209. etypename = _SC("IDENTIFIER");
  210. break;
  211. case TK_STRING_LITERAL:
  212. etypename = _SC("STRING_LITERAL");
  213. break;
  214. case TK_INTEGER:
  215. etypename = _SC("INTEGER");
  216. break;
  217. case TK_FLOAT:
  218. etypename = _SC("FLOAT");
  219. break;
  220. default:
  221. etypename = _lex.Tok2Str(tok);
  222. }
  223. Error(_SC("expected '%s'"), etypename);
  224. }
  225. Error(_SC("expected '%c'"), tok);
  226. }
  227. }
  228. }
  229. SQObject Expect(SQInteger tok)
  230. {
  231. ErrorIfNotToken(tok);
  232. return GetTokenObject(tok);
  233. }
  234. bool IsEndOfStatement() { return ((_lex._prevtoken == _SC('\n')) || (_token == SQUIRREL_EOB) || (_token == _SC('}')) || (_token == _SC(';'))); }
  235. void OptionalSemicolon()
  236. {
  237. if(_token == _SC(';')) { Lex(); return; }
  238. if(!IsEndOfStatement()) {
  239. Error(_SC("end of statement expected (; or lf) found (%d)"), _token);
  240. }
  241. }
  242. void MoveIfCurrentTargetIsLocal() {
  243. SQInteger trg = _fs->TopTarget();
  244. if(_fs->IsLocal(trg)) {
  245. trg = _fs->PopTarget(); //no pops the target and move it
  246. _fs->AddInstruction(_OP_MOVE, _fs->PushTarget(), trg);
  247. }
  248. }
  249. bool Compile(SQObjectPtr &o)
  250. {
  251. _debugline = 1;
  252. _debugop = 0;
  253. SQFuncState funcstate(_ss(_vm), NULL,ThrowError,this);
  254. funcstate._name = SQString::Create(_ss(_vm), _SC("main"));
  255. _fs = &funcstate;
  256. _fs->AddParameter(_fs->CreateString(_SC("this")), _scope.nested+1);
  257. _fs->AddParameter(_fs->CreateString(_SC("vargv")), _scope.nested+1);
  258. _fs->_varparams = true;
  259. _fs->_sourcename = _sourcename;
  260. SQInteger stacksize = _fs->GetStackSize();
  261. if(setjmp(_errorjmp) == 0) {
  262. Lex();
  263. while(_token > 0){
  264. Statement();
  265. if(_lex._prevtoken != _SC('}') && _lex._prevtoken != _SC(';')) OptionalSemicolon();
  266. }
  267. _fs->SetStackSize(stacksize);
  268. _fs->AddLineInfos(_lex._currentline, _lineinfo, true);
  269. _fs->AddInstruction(_OP_RETURN, 0xFF);
  270. _fs->SetStackSize(0);
  271. o =_fs->BuildProto();
  272. #ifdef _DEBUG_DUMP
  273. _fs->Dump(_funcproto(o));
  274. #endif
  275. }
  276. else {
  277. if(_raiseerror && _ss(_vm)->_compilererrorhandler) {
  278. _ss(_vm)->_compilererrorhandler(_vm, compilererror, type(_sourcename) == OT_STRING?_stringval(_sourcename):_SC("unknown"),
  279. _lex._currentline, _lex._currentcolumn);
  280. }
  281. _vm->_lasterror = SQString::Create(_ss(_vm), compilererror, -1);
  282. return false;
  283. }
  284. return true;
  285. }
  286. void Statements()
  287. {
  288. while(_token != _SC('}') && _token != TK_DEFAULT && _token != TK_CASE) {
  289. Statement();
  290. if(_lex._prevtoken != _SC('}') && _lex._prevtoken != _SC(';')) OptionalSemicolon();
  291. }
  292. }
  293. void Statement(bool closeframe = true)
  294. {
  295. _fs->AddLineInfos(_lex._currentline, _lineinfo);
  296. switch(_token){
  297. case _SC(';'): Lex(); break;
  298. case TK_IF: IfStatement(); break;
  299. case TK_WHILE: WhileStatement(); break;
  300. case TK_DO: DoWhileStatement(); break;
  301. case TK_FOR: ForStatement(); break;
  302. case TK_FOREACH: ForEachStatement(); break;
  303. case TK_SWITCH: SwitchStatement(); break;
  304. case TK_LOCAL_CHAR_T:
  305. case TK_LOCAL_WCHAR_T:
  306. case TK_LOCAL_BOOL_T:
  307. case TK_LOCAL_TABLE_T:
  308. case TK_LOCAL_ARRAY_T:
  309. case TK_LOCAL_INT8_T:
  310. case TK_LOCAL_INT16_T:
  311. case TK_LOCAL_INT32_T:
  312. case TK_LOCAL_INT64_T:
  313. case TK_LOCAL_INT_T:
  314. case TK_LOCAL_UINT8_T:
  315. case TK_LOCAL_UINT16_T:
  316. case TK_LOCAL_UINT32_T:
  317. case TK_LOCAL_UINT64_T:
  318. case TK_LOCAL_UINT_T:
  319. case TK_LOCAL_FLOAT_T:
  320. case TK_LOCAL_DOUBLE_T:
  321. case TK_LOCAL_LONG_DOUBLE_T:
  322. //case TK_CONST:
  323. case TK_LOCAL: LocalDeclStatement(); break;
  324. case TK_RETURN:
  325. case TK_YIELD: {
  326. SQOpcode op;
  327. if(_token == TK_RETURN) {
  328. op = _OP_RETURN;
  329. }
  330. else {
  331. op = _OP_YIELD;
  332. _fs->_bgenerator = true;
  333. }
  334. Lex();
  335. if(!IsEndOfStatement()) {
  336. SQInteger retexp = _fs->GetCurrentPos()+1;
  337. CommaExpr(true);
  338. if(op == _OP_RETURN && _fs->_traps > 0)
  339. _fs->AddInstruction(_OP_POPTRAP, _fs->_traps, 0);
  340. _fs->_returnexp = retexp;
  341. _fs->AddInstruction(op, 1, _fs->PopTarget(),_fs->GetStackSize());
  342. }
  343. else{
  344. if(op == _OP_RETURN && _fs->_traps > 0)
  345. _fs->AddInstruction(_OP_POPTRAP, _fs->_traps ,0);
  346. _fs->_returnexp = -1;
  347. _fs->AddInstruction(op, 0xFF,0,_fs->GetStackSize());
  348. }
  349. break;}
  350. case TK_BREAK:
  351. if(_fs->_breaktargets.size() <= 0)Error(_SC("'break' has to be in a loop block"));
  352. if(_fs->_breaktargets.top() > 0){
  353. _fs->AddInstruction(_OP_POPTRAP, _fs->_breaktargets.top(), 0);
  354. }
  355. RESOLVE_OUTERS();
  356. _fs->AddInstruction(_OP_JMP, 0, -1234);
  357. _fs->_unresolvedbreaks.push_back(_fs->GetCurrentPos());
  358. Lex();
  359. break;
  360. case TK_CONTINUE:
  361. if(_fs->_continuetargets.size() <= 0)Error(_SC("'continue' has to be in a loop block"));
  362. if(_fs->_continuetargets.top() > 0) {
  363. _fs->AddInstruction(_OP_POPTRAP, _fs->_continuetargets.top(), 0);
  364. }
  365. RESOLVE_OUTERS();
  366. _fs->AddInstruction(_OP_JMP, 0, -1234);
  367. _fs->_unresolvedcontinues.push_back(_fs->GetCurrentPos());
  368. Lex();
  369. break;
  370. case TK_FUNCTION:
  371. FunctionStatement();
  372. break;
  373. case TK_CLASS:
  374. ClassStatement();
  375. break;
  376. case TK_ENUM:
  377. EnumStatement();
  378. break;
  379. case _SC('{'):{
  380. BEGIN_SCOPE();
  381. Lex();
  382. Statements();
  383. Expect(_SC('}'));
  384. if(closeframe) {
  385. END_SCOPE();
  386. }
  387. else {
  388. END_SCOPE_NO_CLOSE();
  389. }
  390. }
  391. break;
  392. case TK_TRY:
  393. TryCatchStatement();
  394. break;
  395. case TK_THROW:
  396. Lex();
  397. CommaExpr();
  398. _fs->AddInstruction(_OP_THROW, _fs->PopTarget());
  399. break;
  400. case TK_CONST:
  401. {
  402. Lex();
  403. SQObject id = Expect(TK_IDENTIFIER);
  404. Expect('=');
  405. SQObjectPtr strongid = id;
  406. CheckLocalNameScope(id, _scope.nested);
  407. CheckConstsExists(strongid);
  408. SQObject val = ExpectScalar();
  409. OptionalSemicolon();
  410. ConstsNewSlot(strongid,SQObjectPtr(val));
  411. strongid.Null();
  412. }
  413. break;
  414. default:
  415. CommaExpr();
  416. _fs->DiscardTarget();
  417. /*
  418. //Fagiano says that this is not a bug
  419. //and with this modification stack grow by one lement all the time
  420. if(_token == TK_IDENTIFIER){
  421. CommaExpr();
  422. if(_token == TK_IDENTIFIER){
  423. Error(_SC(" '=' expected near '%s'"), _lex._svalue);
  424. }
  425. }
  426. */
  427. //_fs->PopTarget();
  428. break;
  429. }
  430. _fs->SnoozeOpt();
  431. }
  432. void EmitDerefOp(SQOpcode op)
  433. {
  434. SQInteger val = _fs->PopTarget();
  435. SQInteger key = _fs->PopTarget();
  436. SQInteger src = _fs->PopTarget();
  437. _fs->AddInstruction(op,_fs->PushTarget(),src,key,val);
  438. }
  439. void Emit2ArgsOP(SQOpcode op, SQInteger p3 = 0)
  440. {
  441. SQInteger p2 = _fs->PopTarget(); //src in OP_GET
  442. SQInteger p1 = _fs->PopTarget(); //key in OP_GET
  443. _fs->AddInstruction(op,_fs->PushTarget(), p1, p2, p3);
  444. }
  445. void EmitCompoundArith(SQInteger tok, SQInteger etype, SQInteger pos)
  446. {
  447. /* Generate code depending on the expression type */
  448. switch(etype) {
  449. case LOCAL:{
  450. SQInteger p2 = _fs->PopTarget(); //src in OP_GET
  451. SQInteger p1 = _fs->PopTarget(); //key in OP_GET
  452. _fs->PushTarget(p1);
  453. //EmitCompArithLocal(tok, p1, p1, p2);
  454. _fs->AddInstruction(ChooseArithOpByToken(tok),p1, p2, p1, 0);
  455. }
  456. break;
  457. case OBJECT:
  458. case BASE:
  459. {
  460. SQInteger val = _fs->PopTarget();
  461. SQInteger key = _fs->PopTarget();
  462. SQInteger src = _fs->PopTarget();
  463. /* _OP_COMPARITH mixes dest obj and source val in the arg1 */
  464. _fs->AddInstruction(_OP_COMPARITH, _fs->PushTarget(), (src<<16)|val, key, ChooseCompArithCharByToken(tok));
  465. }
  466. break;
  467. case OUTER:
  468. {
  469. SQInteger val = _fs->TopTarget();
  470. SQInteger tmp = _fs->PushTarget();
  471. _fs->AddInstruction(_OP_GETOUTER, tmp, pos);
  472. _fs->AddInstruction(ChooseArithOpByToken(tok), tmp, val, tmp, 0);
  473. _fs->AddInstruction(_OP_SETOUTER, tmp, pos, tmp);
  474. }
  475. break;
  476. }
  477. }
  478. void CommaExpr(bool warningAssign=false)
  479. {
  480. for(Expression(warningAssign);_token == ',';_fs->PopTarget(), Lex(), CommaExpr(warningAssign));
  481. }
  482. void ErrorIfConst(){
  483. SQLocalVarInfo &vsrc = _fs->_vlocals[_fs->TopTarget()];
  484. //printf("%d %d %d %d %s\n", __LINE__, vsrc._scope, vsrc._type, vsrc._pos, vsrc._name._unVal.pString ? _stringval(vsrc._name) : "?");
  485. if(vsrc._type & _VAR_CONST) Error(_SC("can't assign to a const variable"));
  486. }
  487. void Expression(bool warningAssign=false)
  488. {
  489. SQExpState es = _es;
  490. _es.etype = EXPR;
  491. _es.epos = -1;
  492. _es.donot_get = false;
  493. LogicalOrExp();
  494. switch(_token) {
  495. case _SC('='):
  496. case TK_NEWSLOT:
  497. case TK_MINUSEQ:
  498. case TK_PLUSEQ:
  499. case TK_MULEQ:
  500. case TK_DIVEQ:
  501. case TK_MODEQ:{
  502. SQInteger op = _token;
  503. SQInteger ds = _es.etype;
  504. SQInteger pos = _es.epos;
  505. if(ds == EXPR) Error(_SC("can't assign expression"));
  506. else if(ds == BASE) Error(_SC("'base' cannot be modified"));
  507. Lex(); Expression();
  508. switch(op){
  509. case TK_NEWSLOT:
  510. if(ds == OBJECT || ds == BASE)
  511. EmitDerefOp(_OP_NEWSLOT);
  512. else //if _derefstate != DEREF_NO_DEREF && DEREF_FIELD so is the index of a local
  513. Error(_SC("can't 'create' a local slot"));
  514. break;
  515. case _SC('='): //ASSIGN
  516. if(warningAssign) Warning(_SC("WARNING: making assignment at line %d:%d maybe is not what you want\n"),
  517. _lex._currentline, _lex._currentcolumn);
  518. switch(ds) {
  519. case LOCAL:
  520. {
  521. SQInteger src = _fs->PopTarget();
  522. SQInteger dst = _fs->TopTarget();
  523. _fs->AddInstruction(_OP_MOVE, dst, src);
  524. }
  525. break;
  526. case OBJECT:
  527. case BASE:
  528. EmitDerefOp(_OP_SET);
  529. break;
  530. case OUTER:
  531. {
  532. SQInteger src = _fs->PopTarget();
  533. SQInteger dst = _fs->PushTarget();
  534. _fs->AddInstruction(_OP_SETOUTER, dst, pos, src);
  535. }
  536. }
  537. break;
  538. case TK_MINUSEQ:
  539. case TK_PLUSEQ:
  540. case TK_MULEQ:
  541. case TK_DIVEQ:
  542. case TK_MODEQ:
  543. EmitCompoundArith(op, ds, pos);
  544. break;
  545. }
  546. }
  547. break;
  548. case _SC('?'): {
  549. Lex();
  550. _fs->AddInstruction(_OP_JZ, _fs->PopTarget());
  551. SQInteger jzpos = _fs->GetCurrentPos();
  552. SQInteger trg = _fs->PushTarget();
  553. Expression();
  554. SQInteger first_exp = _fs->PopTarget();
  555. if(trg != first_exp) _fs->AddInstruction(_OP_MOVE, trg, first_exp);
  556. SQInteger endfirstexp = _fs->GetCurrentPos();
  557. _fs->AddInstruction(_OP_JMP, 0, 0);
  558. Expect(_SC(':'));
  559. SQInteger jmppos = _fs->GetCurrentPos();
  560. Expression();
  561. SQInteger second_exp = _fs->PopTarget();
  562. if(trg != second_exp) _fs->AddInstruction(_OP_MOVE, trg, second_exp);
  563. _fs->SetIntructionParam(jmppos, 1, _fs->GetCurrentPos() - jmppos);
  564. _fs->SetIntructionParam(jzpos, 1, endfirstexp - jzpos + 1);
  565. _fs->SnoozeOpt();
  566. }
  567. break;
  568. }
  569. _es = es;
  570. }
  571. template<typename T> void BIN_EXP(SQOpcode op, T f,SQInteger op3 = 0)
  572. {
  573. Lex(); (this->*f)();
  574. SQInteger op1 = _fs->PopTarget();SQInteger op2 = _fs->PopTarget();
  575. _fs->AddInstruction(op, _fs->PushTarget(), op1, op2, op3);
  576. }
  577. void LogicalOrExp()
  578. {
  579. LogicalAndExp();
  580. for(;;) if(_token == TK_OR) {
  581. SQInteger first_exp = _fs->PopTarget();
  582. SQInteger trg = _fs->PushTarget();
  583. _fs->AddInstruction(_OP_OR, trg, 0, first_exp, 0);
  584. SQInteger jpos = _fs->GetCurrentPos();
  585. if(trg != first_exp) _fs->AddInstruction(_OP_MOVE, trg, first_exp);
  586. Lex(); LogicalOrExp();
  587. _fs->SnoozeOpt();
  588. SQInteger second_exp = _fs->PopTarget();
  589. if(trg != second_exp) _fs->AddInstruction(_OP_MOVE, trg, second_exp);
  590. _fs->SnoozeOpt();
  591. _fs->SetIntructionParam(jpos, 1, (_fs->GetCurrentPos() - jpos));
  592. break;
  593. }else return;
  594. }
  595. void LogicalAndExp()
  596. {
  597. BitwiseOrExp();
  598. for(;;) switch(_token) {
  599. case TK_AND: {
  600. SQInteger first_exp = _fs->PopTarget();
  601. SQInteger trg = _fs->PushTarget();
  602. _fs->AddInstruction(_OP_AND, trg, 0, first_exp, 0);
  603. SQInteger jpos = _fs->GetCurrentPos();
  604. if(trg != first_exp) _fs->AddInstruction(_OP_MOVE, trg, first_exp);
  605. Lex(); LogicalAndExp();
  606. _fs->SnoozeOpt();
  607. SQInteger second_exp = _fs->PopTarget();
  608. if(trg != second_exp) _fs->AddInstruction(_OP_MOVE, trg, second_exp);
  609. _fs->SnoozeOpt();
  610. _fs->SetIntructionParam(jpos, 1, (_fs->GetCurrentPos() - jpos));
  611. break;
  612. }
  613. default:
  614. return;
  615. }
  616. }
  617. void BitwiseOrExp()
  618. {
  619. BitwiseXorExp();
  620. for(;;) if(_token == _SC('|'))
  621. {BIN_EXP(_OP_BITW, &SQCompiler::BitwiseXorExp,BW_OR);
  622. }else return;
  623. }
  624. void BitwiseXorExp()
  625. {
  626. BitwiseAndExp();
  627. for(;;) if(_token == _SC('^'))
  628. {BIN_EXP(_OP_BITW, &SQCompiler::BitwiseAndExp,BW_XOR);
  629. }else return;
  630. }
  631. void BitwiseAndExp()
  632. {
  633. EqExp();
  634. for(;;) if(_token == _SC('&'))
  635. {BIN_EXP(_OP_BITW, &SQCompiler::EqExp,BW_AND);
  636. }else return;
  637. }
  638. void EqExp()
  639. {
  640. CompExp();
  641. for(;;) switch(_token) {
  642. case TK_EQ: BIN_EXP(_OP_EQ, &SQCompiler::CompExp); break;
  643. case TK_NE: BIN_EXP(_OP_NE, &SQCompiler::CompExp); break;
  644. case TK_3WAYSCMP: BIN_EXP(_OP_CMP, &SQCompiler::CompExp,CMP_3W); break;
  645. default: return;
  646. }
  647. }
  648. void CompExp()
  649. {
  650. ShiftExp();
  651. for(;;) switch(_token) {
  652. case _SC('>'): BIN_EXP(_OP_CMP, &SQCompiler::ShiftExp,CMP_G); break;
  653. case _SC('<'): BIN_EXP(_OP_CMP, &SQCompiler::ShiftExp,CMP_L); break;
  654. case TK_GE: BIN_EXP(_OP_CMP, &SQCompiler::ShiftExp,CMP_GE); break;
  655. case TK_LE: BIN_EXP(_OP_CMP, &SQCompiler::ShiftExp,CMP_LE); break;
  656. case TK_IN: BIN_EXP(_OP_EXISTS, &SQCompiler::ShiftExp); break;
  657. case TK_INSTANCEOF: BIN_EXP(_OP_INSTANCEOF, &SQCompiler::ShiftExp); break;
  658. default: return;
  659. }
  660. }
  661. void ShiftExp()
  662. {
  663. PlusExp();
  664. for(;;) switch(_token) {
  665. case TK_USHIFTR: BIN_EXP(_OP_BITW, &SQCompiler::PlusExp,BW_USHIFTR); break;
  666. case TK_SHIFTL: BIN_EXP(_OP_BITW, &SQCompiler::PlusExp,BW_SHIFTL); break;
  667. case TK_SHIFTR: BIN_EXP(_OP_BITW, &SQCompiler::PlusExp,BW_SHIFTR); break;
  668. default: return;
  669. }
  670. }
  671. SQOpcode ChooseArithOpByToken(SQInteger tok)
  672. {
  673. switch(tok) {
  674. case TK_PLUSEQ: case '+': return _OP_ADD;
  675. case TK_MINUSEQ: case '-': return _OP_SUB;
  676. case TK_MULEQ: case '*': return _OP_MUL;
  677. case TK_DIVEQ: case '/': return _OP_DIV;
  678. case TK_MODEQ: case '%': return _OP_MOD;
  679. default: assert(0);
  680. }
  681. return _OP_ADD;
  682. }
  683. SQInteger ChooseCompArithCharByToken(SQInteger tok)
  684. {
  685. SQInteger oper;
  686. switch(tok){
  687. case TK_MINUSEQ: oper = '-'; break;
  688. case TK_PLUSEQ: oper = '+'; break;
  689. case TK_MULEQ: oper = '*'; break;
  690. case TK_DIVEQ: oper = '/'; break;
  691. case TK_MODEQ: oper = '%'; break;
  692. default: oper = 0; //shut up compiler
  693. assert(0); break;
  694. };
  695. return oper;
  696. }
  697. void PlusExp()
  698. {
  699. MultExp();
  700. for(;;) switch(_token) {
  701. case _SC('+'): case _SC('-'):
  702. BIN_EXP(ChooseArithOpByToken(_token), &SQCompiler::MultExp); break;
  703. default: return;
  704. }
  705. }
  706. void MultExp()
  707. {
  708. PrefixedExpr();
  709. for(;;) switch(_token) {
  710. case _SC('*'): case _SC('/'): case _SC('%'):
  711. BIN_EXP(ChooseArithOpByToken(_token), &SQCompiler::PrefixedExpr); break;
  712. default: return;
  713. }
  714. }
  715. //if 'pos' != -1 the previous variable is a local variable
  716. void PrefixedExpr()
  717. {
  718. SQInteger pos = Factor();
  719. for(;;) {
  720. switch(_token) {
  721. case _SC('.'):
  722. pos = -1;
  723. Lex();
  724. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(Expect(TK_IDENTIFIER)));
  725. if(_es.etype==BASE) {
  726. Emit2ArgsOP(_OP_GET);
  727. pos = _fs->TopTarget();
  728. _es.etype = EXPR;
  729. _es.epos = pos;
  730. }
  731. else {
  732. if(NeedGet()) {
  733. Emit2ArgsOP(_OP_GET);
  734. }
  735. _es.etype = OBJECT;
  736. }
  737. break;
  738. case _SC('['):
  739. if(_lex._prevtoken == _SC('\n')) Error(_SC("cannot brake deref/or comma needed after [exp]=exp slot declaration"));
  740. Lex(); Expression(); Expect(_SC(']'));
  741. pos = -1;
  742. if(_es.etype==BASE) {
  743. Emit2ArgsOP(_OP_GET);
  744. pos = _fs->TopTarget();
  745. _es.etype = EXPR;
  746. _es.epos = pos;
  747. }
  748. else {
  749. if(NeedGet()) {
  750. Emit2ArgsOP(_OP_GET);
  751. }
  752. _es.etype = OBJECT;
  753. }
  754. break;
  755. case TK_MINUSMINUS:
  756. case TK_PLUSPLUS:
  757. {
  758. if(IsEndOfStatement()) return;
  759. SQInteger diff = (_token==TK_MINUSMINUS) ? -1 : 1;
  760. Lex();
  761. switch(_es.etype)
  762. {
  763. case EXPR: Error(_SC("can't '++' or '--' an expression")); break;
  764. case OBJECT:
  765. case BASE:
  766. Emit2ArgsOP(_OP_PINC, diff);
  767. break;
  768. case LOCAL: {
  769. SQInteger src = _fs->PopTarget();
  770. _fs->AddInstruction(_OP_PINCL, _fs->PushTarget(), src, 0, diff);
  771. }
  772. break;
  773. case OUTER: {
  774. SQInteger tmp1 = _fs->PushTarget();
  775. SQInteger tmp2 = _fs->PushTarget();
  776. _fs->AddInstruction(_OP_GETOUTER, tmp2, _es.epos);
  777. _fs->AddInstruction(_OP_PINCL, tmp1, tmp2, 0, diff);
  778. _fs->AddInstruction(_OP_SETOUTER, tmp2, _es.epos, tmp2);
  779. _fs->PopTarget();
  780. }
  781. }
  782. }
  783. return;
  784. break;
  785. case _SC('('):
  786. switch(_es.etype) {
  787. case OBJECT: {
  788. SQInteger key = _fs->PopTarget(); /* location of the key */
  789. SQInteger table = _fs->PopTarget(); /* location of the object */
  790. SQInteger closure = _fs->PushTarget(); /* location for the closure */
  791. SQInteger ttarget = _fs->PushTarget(); /* location for 'this' pointer */
  792. _fs->AddInstruction(_OP_PREPCALL, closure, key, table, ttarget);
  793. }
  794. break;
  795. case BASE:
  796. //Emit2ArgsOP(_OP_GET);
  797. _fs->AddInstruction(_OP_MOVE, _fs->PushTarget(), 0);
  798. break;
  799. case OUTER:
  800. _fs->AddInstruction(_OP_GETOUTER, _fs->PushTarget(), _es.epos);
  801. _fs->AddInstruction(_OP_MOVE, _fs->PushTarget(), 0);
  802. break;
  803. default:
  804. _fs->AddInstruction(_OP_MOVE, _fs->PushTarget(), 0);
  805. }
  806. _es.etype = EXPR;
  807. Lex();
  808. FunctionCallArgs();
  809. break;
  810. default: return;
  811. }
  812. }
  813. }
  814. SQInteger Factor()
  815. {
  816. _es.etype = EXPR;
  817. switch(_token)
  818. {
  819. case TK_STRING_LITERAL:
  820. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(_fs->CreateString(_lex._svalue,_lex._longstr.size()-1)));
  821. Lex();
  822. break;
  823. case TK_BASE:
  824. Lex();
  825. _fs->AddInstruction(_OP_GETBASE, _fs->PushTarget());
  826. _es.etype = BASE;
  827. _es.epos = _fs->TopTarget();
  828. return (_es.epos);
  829. break;
  830. case TK_IDENTIFIER:
  831. case TK_CONSTRUCTOR:
  832. case TK_DESTRUCTOR:
  833. case TK_THIS:{
  834. SQObject id;
  835. SQObject constant;
  836. switch(_token) {
  837. case TK_IDENTIFIER: id = _fs->CreateString(_lex._svalue); break;
  838. case TK_THIS: id = _fs->CreateString(_SC("this"), 4); break;
  839. case TK_CONSTRUCTOR: id = _fs->CreateString(_SC("constructor"), 11); break;
  840. case TK_DESTRUCTOR: id = _fs->CreateString(_SC("destructor"), 10); break;
  841. }
  842. SQInteger pos = -1;
  843. Lex();
  844. if((pos = _fs->GetLocalVariable(id)) != -1) {
  845. /* Handle a local variable (includes 'this') */
  846. _fs->PushTarget(pos);
  847. _es.etype = LOCAL;
  848. _es.epos = pos;
  849. }
  850. else if((pos = _fs->GetOuterVariable(id)) != -1) {
  851. /* Handle a free var */
  852. if(NeedGet()) {
  853. _es.epos = _fs->PushTarget();
  854. _fs->AddInstruction(_OP_GETOUTER, _es.epos, pos);
  855. /* _es.etype = EXPR; already default value */
  856. }
  857. else {
  858. _es.etype = OUTER;
  859. _es.epos = pos;
  860. }
  861. }
  862. else if(IsConstant(id, constant)) {
  863. /* Handle named constant */
  864. SQObjectPtr constval;
  865. SQObject constid;
  866. if(type(constant) == OT_TABLE) {
  867. Expect('.');
  868. constid = Expect(TK_IDENTIFIER);
  869. if(!_table(constant)->Get(constid, constval)) {
  870. constval.Null();
  871. Error(_SC("invalid constant [%s.%s]"), _stringval(id), _stringval(constid));
  872. }
  873. }
  874. else {
  875. constval = constant;
  876. }
  877. _es.epos = _fs->PushTarget();
  878. /* generate direct or literal function depending on size */
  879. SQObjectType ctype = type(constval);
  880. switch(ctype) {
  881. case OT_INTEGER: EmitLoadConstInt(_integer(constval),_es.epos); break;
  882. case OT_FLOAT: EmitLoadConstFloat(_float(constval),_es.epos); break;
  883. default: _fs->AddInstruction(_OP_LOAD,_es.epos,_fs->GetConstant(constval)); break;
  884. }
  885. _es.etype = EXPR;
  886. }
  887. else {
  888. /* Handle a non-local variable, aka a field. Push the 'this' pointer on
  889. * the virtual stack (always found in offset 0, so no instruction needs to
  890. * be generated), and push the key next. Generate an _OP_LOAD instruction
  891. * for the latter. If we are not using the variable as a dref expr, generate
  892. * the _OP_GET instruction.
  893. */
  894. _fs->PushTarget(0);
  895. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(id));
  896. if(NeedGet()) {
  897. Emit2ArgsOP(_OP_GET);
  898. }
  899. _es.etype = OBJECT;
  900. }
  901. return _es.epos;
  902. }
  903. break;
  904. case TK_DOUBLE_COLON: // "::"
  905. _fs->AddInstruction(_OP_LOADROOT, _fs->PushTarget());
  906. _es.etype = OBJECT;
  907. _token = _SC('.'); /* hack: drop into PrefixExpr, case '.'*/
  908. _es.epos = -1;
  909. return _es.epos;
  910. break;
  911. case TK_NULL:
  912. _fs->AddInstruction(_OP_LOADNULLS, _fs->PushTarget(),1);
  913. Lex();
  914. break;
  915. case TK_INTEGER: EmitLoadConstInt(_lex._nvalue,-1); Lex(); break;
  916. case TK_FLOAT: EmitLoadConstFloat(_lex._fvalue,-1); Lex(); break;
  917. case TK_TRUE: case TK_FALSE:
  918. _fs->AddInstruction(_OP_LOADBOOL, _fs->PushTarget(),_token == TK_TRUE?1:0);
  919. Lex();
  920. break;
  921. case _SC('['): {
  922. _fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(),0,0,NOT_ARRAY);
  923. SQInteger apos = _fs->GetCurrentPos(),key = 0;
  924. Lex();
  925. while(_token != _SC(']')) {
  926. Expression();
  927. if(_token == _SC(',')) Lex();
  928. SQInteger val = _fs->PopTarget();
  929. SQInteger array = _fs->TopTarget();
  930. _fs->AddInstruction(_OP_APPENDARRAY, array, val, AAT_STACK);
  931. key++;
  932. }
  933. _fs->SetIntructionParam(apos, 1, key);
  934. Lex();
  935. }
  936. break;
  937. case _SC('{'):
  938. _fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(),0,NOT_TABLE);
  939. Lex();ParseTableOrClass(_SC(','),_SC('}'));
  940. break;
  941. case TK_FUNCTION: FunctionExp(_token);break;
  942. case _SC('@'): FunctionExp(_token,true);break;
  943. case TK_CLASS: Lex(); ClassExp();break;
  944. case _SC('-'):
  945. Lex();
  946. switch(_token) {
  947. case TK_INTEGER: EmitLoadConstInt(-_lex._nvalue,-1); Lex(); break;
  948. case TK_FLOAT: EmitLoadConstFloat(-_lex._fvalue,-1); Lex(); break;
  949. default: UnaryOP(_OP_NEG);
  950. }
  951. break;
  952. case _SC('!'): Lex(); UnaryOP(_OP_NOT); break;
  953. case _SC('~'):
  954. Lex();
  955. if(_token == TK_INTEGER) { EmitLoadConstInt(~_lex._nvalue,-1); Lex(); break; }
  956. UnaryOP(_OP_BWNOT);
  957. break;
  958. case TK_TYPEOF : Lex() ;UnaryOP(_OP_TYPEOF); break;
  959. case TK_RESUME : Lex(); UnaryOP(_OP_RESUME); break;
  960. case TK_CLONE : Lex(); UnaryOP(_OP_CLONE); break;
  961. case TK_MINUSMINUS :
  962. case TK_PLUSPLUS :PrefixIncDec(_token); break;
  963. case TK_DELETE : DeleteExpr(); break;
  964. case _SC('('): Lex(); CommaExpr(); Expect(_SC(')'));
  965. break;
  966. case TK___LINE__: EmitLoadConstInt(_lex._currentline,-1); Lex(); break;
  967. case TK___FILE__:
  968. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(_sourcename));
  969. Lex();
  970. break;
  971. case TK___FUNCTION__:
  972. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(_fs->_name));
  973. Lex();
  974. break;
  975. case TK_IGNORE:
  976. //Warning("Keyword ignored \"%s\" at line %d:%d\n", _lex.Tok2Str(_token),
  977. // _lex._currentline, _lex._currentcolumn);
  978. Lex(); Factor();
  979. break;
  980. default: Error(_SC("expression expected"));
  981. }
  982. return -1;
  983. }
  984. void EmitLoadConstInt(SQInteger value,SQInteger target)
  985. {
  986. if(target < 0) {
  987. target = _fs->PushTarget();
  988. }
  989. if((value & (~((SQInteger)0xFFFFFFFF))) == 0) { //does it fit in 32 bits?
  990. _fs->AddInstruction(_OP_LOADINT, target,value);
  991. }
  992. else {
  993. _fs->AddInstruction(_OP_LOAD, target, _fs->GetNumericConstant(value));
  994. }
  995. }
  996. void EmitLoadConstFloat(SQFloat value,SQInteger target)
  997. {
  998. if(target < 0) {
  999. target = _fs->PushTarget();
  1000. }
  1001. if(sizeof(SQFloat) == sizeof(SQInt32)) {
  1002. _fs->AddInstruction(_OP_LOADFLOAT, target,*((SQInt32 *)&value));
  1003. }
  1004. else {
  1005. _fs->AddInstruction(_OP_LOAD, target, _fs->GetNumericConstant(value));
  1006. }
  1007. }
  1008. void UnaryOP(SQOpcode op)
  1009. {
  1010. PrefixedExpr();
  1011. SQInteger src = _fs->PopTarget();
  1012. _fs->AddInstruction(op, _fs->PushTarget(), src);
  1013. }
  1014. bool NeedGet()
  1015. {
  1016. switch(_token) {
  1017. case _SC('='): case _SC('('): case TK_NEWSLOT: case TK_MODEQ: case TK_MULEQ:
  1018. case TK_DIVEQ: case TK_MINUSEQ: case TK_PLUSEQ: case TK_PLUSPLUS: case TK_MINUSMINUS:
  1019. return false;
  1020. }
  1021. return (!_es.donot_get || ( _es.donot_get && (_token == _SC('.') || _token == _SC('['))));
  1022. }
  1023. void FunctionCallArgs()
  1024. {
  1025. SQInteger nargs = 1;//this
  1026. while(_token != _SC(')')) {
  1027. Expression();
  1028. MoveIfCurrentTargetIsLocal();
  1029. nargs++;
  1030. if(_token == _SC(',')){
  1031. Lex();
  1032. if(_token == ')') Error(_SC("expression expected, found ')'"));
  1033. }
  1034. }
  1035. Lex();
  1036. for(SQInteger i = 0; i < (nargs - 1); i++) _fs->PopTarget();
  1037. SQInteger stackbase = _fs->PopTarget();
  1038. SQInteger closure = _fs->PopTarget();
  1039. _fs->AddInstruction(_OP_CALL, _fs->PushTarget(), closure, stackbase, nargs);
  1040. }
  1041. void ParseTableOrClass(SQInteger separator,SQInteger terminator)
  1042. {
  1043. SQInteger tpos = _fs->GetCurrentPos(),nkeys = 0;
  1044. SQObject type_name;
  1045. bool isClass = separator == ';'; //hack recognizes a table/class from the separator
  1046. while(_token != terminator) {
  1047. bool hasattrs = false;
  1048. bool isstatic = false;
  1049. bool isprivate = false;
  1050. //check if is an attribute
  1051. if(isClass) {
  1052. if(_token == TK_ATTR_OPEN) {
  1053. _fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(),0,NOT_TABLE); Lex();
  1054. ParseTableOrClass(',',TK_ATTR_CLOSE);
  1055. hasattrs = true;
  1056. }
  1057. if(_token == TK_STATIC) {
  1058. isstatic = true;
  1059. Lex();
  1060. }
  1061. else if(_token == TK_PUBLIC) {
  1062. Lex();
  1063. }
  1064. else if(_token == TK_PRIVATE) {
  1065. isprivate = true;
  1066. Lex();
  1067. }
  1068. }
  1069. switch(_token) {
  1070. case TK_FUNCTION:
  1071. case TK_CONSTRUCTOR:
  1072. case TK_DESTRUCTOR:{
  1073. SQInteger tk = _token;
  1074. Lex();
  1075. SQObject id = tk == TK_FUNCTION ? Expect(TK_IDENTIFIER) :
  1076. _fs->CreateString(tk == TK_CONSTRUCTOR ? _SC("constructor") : _SC("destructor"));
  1077. Expect(_SC('('));
  1078. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(id));
  1079. CreateFunction(id);
  1080. _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, 0);
  1081. }
  1082. break;
  1083. case _SC('['):
  1084. Lex(); CommaExpr(); Expect(_SC(']'));
  1085. Expect(_SC('=')); Expression();
  1086. break;
  1087. case TK_STRING_LITERAL: //JSON
  1088. case TK_IDENTIFIER: {//JSON
  1089. SQObjectPtr obj = GetTokenObject(_token);
  1090. SQInteger next_token = _SC('=');
  1091. if(_token == _SC(':')){
  1092. if(isClass){
  1093. //class field with type annotation
  1094. Lex();
  1095. type_name = Expect(TK_IDENTIFIER);
  1096. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(obj));
  1097. _fs->AddInstruction(_OP_LOADNULLS, _fs->PushTarget(), 1);
  1098. break;
  1099. }
  1100. else
  1101. {
  1102. next_token = _token;
  1103. }
  1104. }
  1105. Expect(next_token);
  1106. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(obj));
  1107. Expression();
  1108. break;
  1109. }
  1110. default :
  1111. ErrorIfNotToken(TK_IDENTIFIER);
  1112. }
  1113. if(_token == separator) Lex();//optional comma/semicolon
  1114. nkeys++;
  1115. SQInteger val = _fs->PopTarget();
  1116. SQInteger key = _fs->PopTarget();
  1117. SQInteger attrs = hasattrs ? _fs->PopTarget():-1;
  1118. assert((hasattrs && (attrs == key-1)) || !hasattrs);
  1119. unsigned char flags = (hasattrs?NEW_SLOT_ATTRIBUTES_FLAG:0)|(isstatic?NEW_SLOT_STATIC_FLAG:0);
  1120. SQInteger table = _fs->TopTarget(); //<<BECAUSE OF THIS NO COMMON EMIT FUNC IS POSSIBLE
  1121. if(isClass) {
  1122. _fs->AddInstruction(_OP_NEWSLOTA, flags, table, key, val); //this for classes only as it invokes _newmember
  1123. }
  1124. else {
  1125. _fs->AddInstruction(_OP_NEWSLOT, 0xFF, table, key, val);
  1126. }
  1127. }
  1128. if(separator == _SC(',')) //hack recognizes a table from the separator
  1129. _fs->SetIntructionParam(tpos, 1, nkeys);
  1130. Lex();
  1131. }
  1132. void LocalDeclStatement()
  1133. {
  1134. SQObject varname;
  1135. bool is_const_declaration = _token == TK_CONST;
  1136. bool is_reference_declaration = false;
  1137. SQInteger declType = _token;
  1138. Lex();
  1139. if( _token == TK_FUNCTION) {
  1140. Lex();
  1141. varname = Expect(TK_IDENTIFIER);
  1142. CheckLocalNameScope(varname, _scope.nested);
  1143. Expect(_SC('('));
  1144. #if 1 //doing this way works but prevents garbage collection when doing multiple reloads on the same vm
  1145. //the following is an attempt to allow local declared functions be called recursivelly
  1146. SQInteger old_pos = _fs->GetCurrentPos(); //save current instructions position
  1147. _fs->PushLocalVariable(varname, _scope.nested, _VAR_CLOSURE); //add function name to find it as outer var if needed
  1148. //-1 to compensate default parameters when relocating
  1149. CreateFunction(varname,false, -1);
  1150. _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, 0);
  1151. //rellocate any stack operation (default parameters & _OP_Closure)
  1152. for(int i=old_pos+1, curr_pos = _fs->GetCurrentPos(); i <= curr_pos; ++i){
  1153. SQInstruction & inst = _fs->GetInstruction(i);
  1154. _fs->SetIntructionParam(i, 0, inst._arg0 -1);
  1155. }
  1156. _fs->PopTarget();
  1157. #else
  1158. CreateFunction(varname,false);
  1159. _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, 0);
  1160. _fs->PopTarget();
  1161. _fs->PushLocalVariable(varname, _scope.nested, _VAR_CLOSURE);
  1162. #endif
  1163. return;
  1164. }
  1165. do {
  1166. if(_token == _SC('&')){
  1167. is_reference_declaration = true;
  1168. Lex();
  1169. }
  1170. varname = Expect(TK_IDENTIFIER);
  1171. CheckLocalNameScope(varname, _scope.nested);
  1172. if(_token == _SC('=')) {
  1173. Lex(); Expression();
  1174. SQInteger src = _fs->PopTarget();
  1175. SQInteger dest = _fs->PushTarget();
  1176. if(dest != src) _fs->AddInstruction(_OP_MOVE, dest, src);
  1177. declType = _VAR_ANY;
  1178. }
  1179. else if(is_const_declaration || is_reference_declaration)
  1180. Error(_SC("const/reference '%s' need an initializer"), _stringval(varname));
  1181. else{
  1182. SQInteger dest = _fs->PushTarget();
  1183. switch(declType){
  1184. case TK_LOCAL_CHAR_T:
  1185. case TK_LOCAL_WCHAR_T:
  1186. _fs->AddInstruction(_OP_LOADNULLS, dest,1);
  1187. declType = _VAR_STRING;
  1188. break;
  1189. case TK_LOCAL_BOOL_T:
  1190. //default value false
  1191. _fs->AddInstruction(_OP_LOADBOOL, dest,0);
  1192. declType = _VAR_BOOL;
  1193. break;
  1194. case TK_LOCAL_TABLE_T:
  1195. _fs->AddInstruction(_OP_LOADNULLS, dest,1);
  1196. declType = _VAR_TABLE;
  1197. break;
  1198. case TK_LOCAL_ARRAY_T:
  1199. _fs->AddInstruction(_OP_LOADNULLS, dest,1);
  1200. declType = _VAR_ARRAY;
  1201. break;
  1202. case TK_LOCAL_INT8_T:
  1203. case TK_LOCAL_INT16_T:
  1204. case TK_LOCAL_INT32_T:
  1205. case TK_LOCAL_INT64_T:
  1206. case TK_LOCAL_INT_T:
  1207. case TK_LOCAL_UINT8_T:
  1208. case TK_LOCAL_UINT16_T:
  1209. case TK_LOCAL_UINT32_T:
  1210. case TK_LOCAL_UINT64_T:
  1211. case TK_LOCAL_UINT_T:
  1212. //default value 0
  1213. _fs->AddInstruction(_OP_LOADINT, dest,0);
  1214. declType = _VAR_INTEGER;
  1215. break;
  1216. case TK_LOCAL_FLOAT_T:
  1217. case TK_LOCAL_DOUBLE_T:
  1218. case TK_LOCAL_LONG_DOUBLE_T:
  1219. //default value 0.0
  1220. //_OP_LOADFLOAT is only valid when SQFloat size == SQInt32 size
  1221. _fs->AddInstruction(_OP_LOADINT, dest,0);
  1222. declType = _VAR_FLOAT;
  1223. break;
  1224. //case TK_LOCAL:
  1225. default:
  1226. //default value null
  1227. _fs->AddInstruction(_OP_LOADNULLS, dest,1);
  1228. declType = _VAR_ANY;
  1229. }
  1230. }
  1231. _fs->PopTarget();
  1232. _fs->PushLocalVariable(varname, _scope.nested, (is_const_declaration ? _VAR_CONST : declType)
  1233. | (is_reference_declaration ? _VAR_REFERENCE : 0));
  1234. if(_token == _SC(',')) Lex(); else break;
  1235. } while(1);
  1236. }
  1237. void IfStatement()
  1238. {
  1239. SQInteger jmppos;
  1240. bool haselse = false;
  1241. Lex(); Expect(_SC('(')); CommaExpr(true); Expect(_SC(')'));
  1242. _fs->AddInstruction(_OP_JZ, _fs->PopTarget());
  1243. SQInteger jnepos = _fs->GetCurrentPos();
  1244. BEGIN_SCOPE();
  1245. //there is a situation where the if statement has a statement enclosed by {}
  1246. //and after the closing "}" there is no newline or semicolom
  1247. //it's a valid construction but the compiler was complaining about it
  1248. //for now added "&& _token != TK_IDENTIFIER" to the check after "Statement()" call
  1249. /*
  1250. local color = "blue";
  1251. if(color == "yellow"){
  1252. print(color);
  1253. } print("Waht color is it ?");
  1254. */
  1255. Statement();
  1256. //
  1257. if(_token != _SC('}') && _token != TK_ELSE && _token != TK_IDENTIFIER) OptionalSemicolon();
  1258. END_SCOPE();
  1259. SQInteger endifblock = _fs->GetCurrentPos();
  1260. if(_token == TK_ELSE){
  1261. haselse = true;
  1262. BEGIN_SCOPE();
  1263. _fs->AddInstruction(_OP_JMP);
  1264. jmppos = _fs->GetCurrentPos();
  1265. Lex();
  1266. Statement(); if(_token != TK_IDENTIFIER) OptionalSemicolon();
  1267. END_SCOPE();
  1268. _fs->SetIntructionParam(jmppos, 1, _fs->GetCurrentPos() - jmppos);
  1269. }
  1270. _fs->SetIntructionParam(jnepos, 1, endifblock - jnepos + (haselse?1:0));
  1271. }
  1272. void WhileStatement()
  1273. {
  1274. SQInteger jzpos, jmppos;
  1275. jmppos = _fs->GetCurrentPos();
  1276. Lex(); Expect(_SC('(')); CommaExpr(true); Expect(_SC(')'));
  1277. BEGIN_BREAKBLE_BLOCK();
  1278. _fs->AddInstruction(_OP_JZ, _fs->PopTarget());
  1279. jzpos = _fs->GetCurrentPos();
  1280. BEGIN_SCOPE();
  1281. Statement();
  1282. END_SCOPE();
  1283. _fs->AddInstruction(_OP_JMP, 0, jmppos - _fs->GetCurrentPos() - 1);
  1284. _fs->SetIntructionParam(jzpos, 1, _fs->GetCurrentPos() - jzpos);
  1285. END_BREAKBLE_BLOCK(jmppos);
  1286. }
  1287. void DoWhileStatement()
  1288. {
  1289. Lex();
  1290. SQInteger jmptrg = _fs->GetCurrentPos();
  1291. BEGIN_BREAKBLE_BLOCK()
  1292. BEGIN_SCOPE();
  1293. Statement();
  1294. END_SCOPE();
  1295. //fix proposed by frosch to correct line number info in stack dumps
  1296. _fs->AddLineInfos(_lex._currentline, _lineinfo, true);
  1297. Expect(TK_WHILE);
  1298. SQInteger continuetrg = _fs->GetCurrentPos();
  1299. Expect(_SC('(')); CommaExpr(true); Expect(_SC(')'));
  1300. _fs->AddInstruction(_OP_JZ, _fs->PopTarget(), 1);
  1301. _fs->AddInstruction(_OP_JMP, 0, jmptrg - _fs->GetCurrentPos() - 1);
  1302. END_BREAKBLE_BLOCK(continuetrg);
  1303. }
  1304. void ForStatement()
  1305. {
  1306. Lex();
  1307. BEGIN_SCOPE();
  1308. Expect(_SC('('));
  1309. switch(_token){
  1310. case TK_LOCAL_CHAR_T:
  1311. case TK_LOCAL_WCHAR_T:
  1312. case TK_LOCAL_BOOL_T:
  1313. case TK_LOCAL_TABLE_T:
  1314. case TK_LOCAL_ARRAY_T:
  1315. case TK_LOCAL_INT8_T:
  1316. case TK_LOCAL_INT16_T:
  1317. case TK_LOCAL_INT32_T:
  1318. case TK_LOCAL_INT64_T:
  1319. case TK_LOCAL_INT_T:
  1320. case TK_LOCAL_UINT8_T:
  1321. case TK_LOCAL_UINT16_T:
  1322. case TK_LOCAL_UINT32_T:
  1323. case TK_LOCAL_UINT64_T:
  1324. case TK_LOCAL_UINT_T:
  1325. case TK_LOCAL_FLOAT_T:
  1326. case TK_LOCAL_DOUBLE_T:
  1327. case TK_LOCAL_LONG_DOUBLE_T:
  1328. case TK_LOCAL:
  1329. LocalDeclStatement();
  1330. break;
  1331. default:
  1332. if(_token != _SC(';')){
  1333. CommaExpr();
  1334. _fs->PopTarget();
  1335. }
  1336. }
  1337. Expect(_SC(';'));
  1338. _fs->SnoozeOpt();
  1339. SQInteger jmppos = _fs->GetCurrentPos();
  1340. SQInteger jzpos = -1;
  1341. if(_token != _SC(';')) { CommaExpr(); _fs->AddInstruction(_OP_JZ, _fs->PopTarget()); jzpos = _fs->GetCurrentPos(); }
  1342. Expect(_SC(';'));
  1343. _fs->SnoozeOpt();
  1344. SQInteger expstart = _fs->GetCurrentPos() + 1;
  1345. if(_token != _SC(')')) {
  1346. CommaExpr();
  1347. _fs->PopTarget();
  1348. }
  1349. Expect(_SC(')'));
  1350. _fs->SnoozeOpt();
  1351. SQInteger expend = _fs->GetCurrentPos();
  1352. SQInteger expsize = (expend - expstart) + 1;
  1353. SQInstructionVec exp;
  1354. if(expsize > 0) {
  1355. for(SQInteger i = 0; i < expsize; i++)
  1356. exp.push_back(_fs->GetInstruction(expstart + i));
  1357. _fs->PopInstructions(expsize);
  1358. }
  1359. BEGIN_BREAKBLE_BLOCK()
  1360. Statement();
  1361. SQInteger continuetrg = _fs->GetCurrentPos();
  1362. if(expsize > 0) {
  1363. for(SQInteger i = 0; i < expsize; i++)
  1364. _fs->AddInstruction(exp[i]);
  1365. }
  1366. _fs->AddInstruction(_OP_JMP, 0, jmppos - _fs->GetCurrentPos() - 1, 0);
  1367. if(jzpos> 0) _fs->SetIntructionParam(jzpos, 1, _fs->GetCurrentPos() - jzpos);
  1368. END_SCOPE();
  1369. END_BREAKBLE_BLOCK(continuetrg);
  1370. }
  1371. void ForEachStatement()
  1372. {
  1373. SQObject idxname, valname;
  1374. Lex(); Expect(_SC('(')); valname = Expect(TK_IDENTIFIER);
  1375. if(_token == _SC(',')) {
  1376. idxname = valname;
  1377. Lex(); valname = Expect(TK_IDENTIFIER);
  1378. }
  1379. else{
  1380. idxname = _fs->CreateString(_SC("@INDEX@"));
  1381. }
  1382. Expect(TK_IN);
  1383. //save the stack size
  1384. BEGIN_SCOPE();
  1385. //put the table in the stack(evaluate the table expression)
  1386. Expression(); Expect(_SC(')'));
  1387. SQInteger container = _fs->TopTarget();
  1388. //push the index local var
  1389. SQInteger indexpos = _fs->PushLocalVariable(idxname, _scope.nested);
  1390. _fs->AddInstruction(_OP_LOADNULLS, indexpos,1);
  1391. //push the value local var
  1392. SQInteger valuepos = _fs->PushLocalVariable(valname, _scope.nested);
  1393. _fs->AddInstruction(_OP_LOADNULLS, valuepos,1);
  1394. //push reference index
  1395. SQInteger itrpos = _fs->PushLocalVariable(_fs->CreateString(_SC("@ITERATOR@")), _scope.nested); //use invalid id to make it inaccessible
  1396. _fs->AddInstruction(_OP_LOADNULLS, itrpos,1);
  1397. SQInteger jmppos = _fs->GetCurrentPos();
  1398. _fs->AddInstruction(_OP_FOREACH, container, 0, indexpos);
  1399. SQInteger foreachpos = _fs->GetCurrentPos();
  1400. _fs->AddInstruction(_OP_POSTFOREACH, container, 0, indexpos);
  1401. //generate the statement code
  1402. BEGIN_BREAKBLE_BLOCK()
  1403. Statement();
  1404. _fs->AddInstruction(_OP_JMP, 0, jmppos - _fs->GetCurrentPos() - 1);
  1405. _fs->SetIntructionParam(foreachpos, 1, _fs->GetCurrentPos() - foreachpos);
  1406. _fs->SetIntructionParam(foreachpos + 1, 1, _fs->GetCurrentPos() - foreachpos);
  1407. END_BREAKBLE_BLOCK(foreachpos - 1);
  1408. //restore the local variable stack(remove index,val and ref idx)
  1409. _fs->PopTarget();
  1410. END_SCOPE();
  1411. }
  1412. void SwitchStatement()
  1413. {
  1414. Lex(); Expect(_SC('(')); CommaExpr(true); Expect(_SC(')'));
  1415. Expect(_SC('{'));
  1416. SQInteger expr = _fs->TopTarget();
  1417. bool bfirst = true;
  1418. SQInteger tonextcondjmp = -1;
  1419. SQInteger skipcondjmp = -1;
  1420. SQInteger __nbreaks__ = _fs->_unresolvedbreaks.size();
  1421. _fs->_breaktargets.push_back(0);
  1422. while(_token == TK_CASE) {
  1423. if(!bfirst) {
  1424. _fs->AddInstruction(_OP_JMP, 0, 0);
  1425. skipcondjmp = _fs->GetCurrentPos();
  1426. _fs->SetIntructionParam(tonextcondjmp, 1, _fs->GetCurrentPos() - tonextcondjmp);
  1427. }
  1428. //condition
  1429. Lex(); Expression(); Expect(_SC(':'));
  1430. SQInteger trg = _fs->PopTarget();
  1431. _fs->AddInstruction(_OP_EQ, trg, trg, expr);
  1432. _fs->AddInstruction(_OP_JZ, trg, 0);
  1433. //end condition
  1434. if(skipcondjmp != -1) {
  1435. _fs->SetIntructionParam(skipcondjmp, 1, (_fs->GetCurrentPos() - skipcondjmp));
  1436. }
  1437. tonextcondjmp = _fs->GetCurrentPos();
  1438. BEGIN_SCOPE();
  1439. Statements();
  1440. END_SCOPE();
  1441. bfirst = false;
  1442. }
  1443. if(tonextcondjmp != -1)
  1444. _fs->SetIntructionParam(tonextcondjmp, 1, _fs->GetCurrentPos() - tonextcondjmp);
  1445. if(_token == TK_DEFAULT) {
  1446. Lex(); Expect(_SC(':'));
  1447. BEGIN_SCOPE();
  1448. Statements();
  1449. END_SCOPE();
  1450. }
  1451. Expect(_SC('}'));
  1452. _fs->PopTarget();
  1453. __nbreaks__ = _fs->_unresolvedbreaks.size() - __nbreaks__;
  1454. if(__nbreaks__ > 0)ResolveBreaks(_fs, __nbreaks__);
  1455. _fs->_breaktargets.pop_back();
  1456. }
  1457. void FunctionStatement()
  1458. {
  1459. SQObject id;
  1460. Lex(); id = Expect(TK_IDENTIFIER);
  1461. _fs->PushTarget(0);
  1462. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(id));
  1463. if(_token == TK_DOUBLE_COLON) Emit2ArgsOP(_OP_GET);
  1464. else CheckGlobalName(id, true);
  1465. while(_token == TK_DOUBLE_COLON) {
  1466. Lex();
  1467. id = Expect(TK_IDENTIFIER);
  1468. //todo check if class function already exists
  1469. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(id));
  1470. if(_token == TK_DOUBLE_COLON) Emit2ArgsOP(_OP_GET);
  1471. }
  1472. Expect(_SC('('));
  1473. CreateFunction(id);
  1474. _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, 0);
  1475. EmitDerefOp(_OP_NEWSLOT);
  1476. _fs->PopTarget();
  1477. }
  1478. void ClassStatement()
  1479. {
  1480. SQExpState es;
  1481. Lex();
  1482. if(_token == TK_IDENTIFIER) {
  1483. SQObjectPtr str = SQString::Create(_ss(_vm), _lex._svalue);
  1484. CheckGlobalName(str, true);
  1485. }
  1486. es = _es;
  1487. _es.donot_get = true;
  1488. PrefixedExpr();
  1489. if(_es.etype == EXPR) {
  1490. Error(_SC("invalid class name"));
  1491. }
  1492. else if(_es.etype == OBJECT || _es.etype == BASE) {
  1493. ClassExp();
  1494. EmitDerefOp(_OP_NEWSLOT);
  1495. _fs->PopTarget();
  1496. }
  1497. else {
  1498. Error(_SC("cannot create a class in a local with the syntax(class <local>)"));
  1499. }
  1500. _es = es;
  1501. }
  1502. SQObject ExpectScalar()
  1503. {
  1504. SQObject val;
  1505. val._type = OT_NULL; val._unVal.nInteger = 0; //shut up GCC 4.x
  1506. switch(_token) {
  1507. case TK_INTEGER:
  1508. val._type = OT_INTEGER;
  1509. val._unVal.nInteger = _lex._nvalue;
  1510. break;
  1511. case TK_FLOAT:
  1512. val._type = OT_FLOAT;
  1513. val._unVal.fFloat = _lex._fvalue;
  1514. break;
  1515. case TK_STRING_LITERAL:
  1516. val = _fs->CreateString(_lex._svalue,_lex._longstr.size()-1);
  1517. break;
  1518. case '-':
  1519. Lex();
  1520. switch(_token)
  1521. {
  1522. case TK_INTEGER:
  1523. val._type = OT_INTEGER;
  1524. val._unVal.nInteger = -_lex._nvalue;
  1525. break;
  1526. case TK_FLOAT:
  1527. val._type = OT_FLOAT;
  1528. val._unVal.fFloat = -_lex._fvalue;
  1529. break;
  1530. default:
  1531. Error(_SC("scalar expected : integer,float"));
  1532. }
  1533. break;
  1534. default:
  1535. Error(_SC("scalar expected : integer,float or string"));
  1536. }
  1537. Lex();
  1538. return val;
  1539. }
  1540. void EnumStatement()
  1541. {
  1542. Lex();
  1543. SQObject id = Expect(TK_IDENTIFIER);
  1544. Expect(_SC('{'));
  1545. //CheckLocalNameScope(id, _scope.nested);
  1546. SQObjectPtr strongid = id;
  1547. CheckLocalNameScope(id, _scope.nested);
  1548. CheckConstsExists(strongid);
  1549. SQObject table = _fs->CreateTable();
  1550. //_fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(),0,NOT_TABLE);
  1551. SQInteger nval = 0;
  1552. while(_token != _SC('}')) {
  1553. SQObject key = Expect(TK_IDENTIFIER);
  1554. SQObject val;
  1555. if(_token == _SC('=')) {
  1556. Lex();
  1557. val = ExpectScalar();
  1558. }
  1559. else {
  1560. val._type = OT_INTEGER;
  1561. val._unVal.nInteger = nval++;
  1562. }
  1563. //SQInteger table = _fs->TopTarget(); //<<BECAUSE OF THIS NO COMMON EMIT FUNC IS POSSIBLE
  1564. //_fs->AddInstruction(_OP_NEWSLOT, 0xFF, table, key, val);
  1565. _table(table)->NewSlot(SQObjectPtr(key),SQObjectPtr(val));
  1566. if(_token == ',') Lex();
  1567. }
  1568. ConstsNewSlot(SQObjectPtr(strongid),SQObjectPtr(table));
  1569. strongid.Null();
  1570. Lex();
  1571. }
  1572. void TryCatchStatement()
  1573. {
  1574. SQObject exid;
  1575. Lex();
  1576. _fs->AddInstruction(_OP_PUSHTRAP,0,0);
  1577. _fs->_traps++;
  1578. if(_fs->_breaktargets.size()) _fs->_breaktargets.top()++;
  1579. if(_fs->_continuetargets.size()) _fs->_continuetargets.top()++;
  1580. SQInteger trappos = _fs->GetCurrentPos();
  1581. {
  1582. BEGIN_SCOPE();
  1583. Statement();
  1584. END_SCOPE();
  1585. }
  1586. _fs->_traps--;
  1587. _fs->AddInstruction(_OP_POPTRAP, 1, 0);
  1588. if(_fs->_breaktargets.size()) _fs->_breaktargets.top()--;
  1589. if(_fs->_continuetargets.size()) _fs->_continuetargets.top()--;
  1590. _fs->AddInstruction(_OP_JMP, 0, 0);
  1591. SQInteger jmppos = _fs->GetCurrentPos();
  1592. _fs->SetIntructionParam(trappos, 1, (_fs->GetCurrentPos() - trappos));
  1593. Expect(TK_CATCH); Expect(_SC('(')); exid = Expect(TK_IDENTIFIER); Expect(_SC(')'));
  1594. {
  1595. BEGIN_SCOPE();
  1596. SQInteger ex_target = _fs->PushLocalVariable(exid, _scope.nested);
  1597. _fs->SetIntructionParam(trappos, 0, ex_target);
  1598. Statement();
  1599. _fs->SetIntructionParams(jmppos, 0, (_fs->GetCurrentPos() - jmppos), 0);
  1600. END_SCOPE();
  1601. }
  1602. }
  1603. void FunctionExp(SQInteger ftype,bool lambda = false)
  1604. {
  1605. Lex(); Expect(_SC('('));
  1606. SQObjectPtr dummy;
  1607. CreateFunction(dummy,lambda);
  1608. _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, ftype == TK_FUNCTION?0:1);
  1609. }
  1610. void ClassExp()
  1611. {
  1612. SQInteger base = -1;
  1613. SQInteger attrs = -1;
  1614. if(_token == TK_EXTENDS) {
  1615. Lex(); Expression();
  1616. base = _fs->TopTarget();
  1617. }
  1618. if(_token == TK_ATTR_OPEN) {
  1619. Lex();
  1620. _fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(),0,NOT_TABLE);
  1621. ParseTableOrClass(_SC(','),TK_ATTR_CLOSE);
  1622. attrs = _fs->TopTarget();
  1623. }
  1624. Expect(_SC('{'));
  1625. if(attrs != -1) _fs->PopTarget();
  1626. if(base != -1) _fs->PopTarget();
  1627. _fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(), base, attrs,NOT_CLASS);
  1628. ParseTableOrClass(_SC(';'),_SC('}'));
  1629. }
  1630. void DeleteExpr()
  1631. {
  1632. SQExpState es;
  1633. Lex();
  1634. es = _es;
  1635. _es.donot_get = true;
  1636. PrefixedExpr();
  1637. if(_es.etype==EXPR) Error(_SC("can't delete an expression"));
  1638. if(_es.etype==OBJECT || _es.etype==BASE) {
  1639. Emit2ArgsOP(_OP_DELETE);
  1640. }
  1641. else {
  1642. Error(_SC("cannot delete an (outer) local"));
  1643. }
  1644. _es = es;
  1645. }
  1646. void PrefixIncDec(SQInteger token)
  1647. {
  1648. SQExpState es;
  1649. SQInteger diff = (token==TK_MINUSMINUS) ? -1 : 1;
  1650. Lex();
  1651. es = _es;
  1652. _es.donot_get = true;
  1653. PrefixedExpr();
  1654. if(_es.etype==EXPR) {
  1655. Error(_SC("can't '++' or '--' an expression"));
  1656. }
  1657. else if(_es.etype==OBJECT || _es.etype==BASE) {
  1658. Emit2ArgsOP(_OP_INC, diff);
  1659. }
  1660. else if(_es.etype==LOCAL) {
  1661. SQInteger src = _fs->TopTarget();
  1662. _fs->AddInstruction(_OP_INCL, src, src, 0, diff);
  1663. }
  1664. else if(_es.etype==OUTER) {
  1665. SQInteger tmp = _fs->PushTarget();
  1666. _fs->AddInstruction(_OP_GETOUTER, tmp, _es.epos);
  1667. _fs->AddInstruction(_OP_INCL, tmp, tmp, 0, diff);
  1668. _fs->AddInstruction(_OP_SETOUTER, tmp, _es.epos, tmp);
  1669. }
  1670. _es = es;
  1671. }
  1672. void CreateFunction(SQObject &name,bool lambda = false, int stack_offset=0)
  1673. {
  1674. SQFuncState *funcstate = _fs->PushChildState(_ss(_vm));
  1675. funcstate->_name = name;
  1676. SQObject paramname, type_name;
  1677. funcstate->AddParameter(_fs->CreateString(_SC("this")), _scope.nested+1);
  1678. funcstate->_sourcename = _sourcename;
  1679. SQInteger defparams = 0;
  1680. SQInteger is_reference = 0;
  1681. while(_token!=_SC(')')) {
  1682. is_reference = 0; //reset is_reference
  1683. if(_token == TK_VARPARAMS) {
  1684. if(defparams > 0) Error(_SC("function with default parameters cannot have variable number of parameters"));
  1685. funcstate->AddParameter(_fs->CreateString(_SC("vargv")), _scope.nested+1);
  1686. funcstate->_varparams = true;
  1687. Lex();
  1688. if(_token != _SC(')')) Error(_SC("expected ')'"));
  1689. break;
  1690. }
  1691. else {
  1692. if(_token == _SC('&')){
  1693. is_reference = 1;
  1694. Lex();
  1695. }
  1696. paramname = Expect(TK_IDENTIFIER);
  1697. funcstate->AddParameter(paramname, _scope.nested+1, is_reference ? _VAR_REFERENCE : _VAR_ANY);
  1698. if(_token == _SC('=')) {
  1699. if(is_reference) Error(_SC("parameter passed by reference can't have default value"));
  1700. Lex();
  1701. if(_token == _SC('[') || _token == _SC('{')) Error(_SC("default parameter with array/table values not supported"));
  1702. Expression();
  1703. //stack_offset to compensate for local functions been relocated to allow recursion
  1704. funcstate->AddDefaultParam(_fs->TopTarget()+stack_offset);
  1705. defparams++;
  1706. }
  1707. else if(_token == _SC(':')){
  1708. //param type specifier like typescript
  1709. Lex();
  1710. type_name = Expect(TK_IDENTIFIER);
  1711. //printf("%d %s\n", __LINE__, _stringval(type_name));
  1712. }
  1713. else {
  1714. if(defparams > 0) Error(_SC("expected '='"));
  1715. }
  1716. if(_token == _SC(',')) Lex();
  1717. else if(_token != _SC(')')) Error(_SC("expected ')' or ','"));
  1718. }
  1719. }
  1720. Expect(_SC(')'));
  1721. if(_token == _SC(':')){
  1722. //return type specifier like typescript
  1723. Lex();
  1724. type_name = Expect(TK_IDENTIFIER);
  1725. //printf("%d %s\n", __LINE__, _stringval(type_name));
  1726. }
  1727. for(SQInteger n = 0; n < defparams; n++) {
  1728. _fs->PopTarget();
  1729. }
  1730. SQFuncState *currchunk = _fs;
  1731. _fs = funcstate;
  1732. if(lambda) {
  1733. Expression();
  1734. _fs->AddInstruction(_OP_RETURN, 1, _fs->PopTarget());}
  1735. else {
  1736. Statement(false);
  1737. }
  1738. funcstate->AddLineInfos(_lex._prevtoken == _SC('\n')?_lex._lasttokenline:_lex._currentline, _lineinfo, true);
  1739. funcstate->AddInstruction(_OP_RETURN, -1);
  1740. funcstate->SetStackSize(0);
  1741. SQFunctionProto *func = funcstate->BuildProto();
  1742. #ifdef _DEBUG_DUMP
  1743. funcstate->Dump(func);
  1744. #endif
  1745. _fs = currchunk;
  1746. _fs->_functions.push_back(func);
  1747. _fs->PopChildState();
  1748. }
  1749. void ResolveBreaks(SQFuncState *funcstate, SQInteger ntoresolve)
  1750. {
  1751. while(ntoresolve > 0) {
  1752. SQInteger pos = funcstate->_unresolvedbreaks.back();
  1753. funcstate->_unresolvedbreaks.pop_back();
  1754. //set the jmp instruction
  1755. funcstate->SetIntructionParams(pos, 0, funcstate->GetCurrentPos() - pos, 0);
  1756. ntoresolve--;
  1757. }
  1758. }
  1759. void ResolveContinues(SQFuncState *funcstate, SQInteger ntoresolve, SQInteger targetpos)
  1760. {
  1761. while(ntoresolve > 0) {
  1762. SQInteger pos = funcstate->_unresolvedcontinues.back();
  1763. funcstate->_unresolvedcontinues.pop_back();
  1764. //set the jmp instruction
  1765. funcstate->SetIntructionParams(pos, 0, targetpos - pos, 0);
  1766. ntoresolve--;
  1767. }
  1768. }
  1769. private:
  1770. SQInteger _token;
  1771. SQFuncState *_fs;
  1772. SQObjectPtr _sourcename;
  1773. SQLexer _lex;
  1774. bool _lineinfo;
  1775. bool _raiseerror;
  1776. bool _show_warnings;
  1777. SQInteger _debugline;
  1778. SQInteger _debugop;
  1779. SQExpState _es;
  1780. SQScope _scope;
  1781. SQChar *compilererror;
  1782. jmp_buf _errorjmp;
  1783. SQVM *_vm;
  1784. SQObjectPtrVec _scope_consts;
  1785. SQObjectPtr _globals;
  1786. };
  1787. bool Compile(SQVM *vm,SQLEXREADFUNC rg, SQUserPointer up, const SQChar *sourcename, SQObjectPtr &out,
  1788. bool raiseerror, bool lineinfo, bool show_warnings)
  1789. {
  1790. SQCompiler p(vm, rg, up, sourcename, raiseerror, lineinfo, show_warnings);
  1791. return p.Compile(out);
  1792. }
  1793. #endif