sqcompiler.cpp 57 KB

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