sqcompiler.cpp 45 KB

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