sqcompiler.cpp 56 KB

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