sqcompiler.cpp 46 KB

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