sqcompiler.cpp 46 KB

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