sqcompiler.cpp 56 KB

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