sqcompiler.cpp 45 KB

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