sqcompiler.cpp 43 KB

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