sqcompiler.cpp 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583
  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_RAWCALL: Lex(); Expect('('); FunctionCallArgs(true); break;
  841. case TK_MINUSMINUS :
  842. case TK_PLUSPLUS :PrefixIncDec(_token); break;
  843. case TK_DELETE : DeleteExpr(); break;
  844. case _SC('('): Lex(); CommaExpr(); Expect(_SC(')'));
  845. break;
  846. case TK___LINE__: EmitLoadConstInt(_lex._currentline,-1); Lex(); break;
  847. case TK___FILE__: _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(_sourcename)); Lex(); break;
  848. default: Error(_SC("expression expected"));
  849. }
  850. _es.etype = EXPR;
  851. return -1;
  852. }
  853. void EmitLoadConstInt(SQInteger value,SQInteger target)
  854. {
  855. if(target < 0) {
  856. target = _fs->PushTarget();
  857. }
  858. if(value <= INT_MAX && value > INT_MIN) { //does it fit in 32 bits?
  859. _fs->AddInstruction(_OP_LOADINT, target,value);
  860. }
  861. else {
  862. _fs->AddInstruction(_OP_LOAD, target, _fs->GetNumericConstant(value));
  863. }
  864. }
  865. void EmitLoadConstFloat(SQFloat value,SQInteger target)
  866. {
  867. if(target < 0) {
  868. target = _fs->PushTarget();
  869. }
  870. if(sizeof(SQFloat) == sizeof(SQInt32)) {
  871. _fs->AddInstruction(_OP_LOADFLOAT, target,*((SQInt32 *)&value));
  872. }
  873. else {
  874. _fs->AddInstruction(_OP_LOAD, target, _fs->GetNumericConstant(value));
  875. }
  876. }
  877. void UnaryOP(SQOpcode op)
  878. {
  879. PrefixedExpr();
  880. SQInteger src = _fs->PopTarget();
  881. _fs->AddInstruction(op, _fs->PushTarget(), src);
  882. }
  883. bool NeedGet()
  884. {
  885. switch(_token) {
  886. case _SC('='): case _SC('('): case TK_NEWSLOT: case TK_MODEQ: case TK_MULEQ:
  887. case TK_DIVEQ: case TK_MINUSEQ: case TK_PLUSEQ:
  888. return false;
  889. case TK_PLUSPLUS: case TK_MINUSMINUS:
  890. if (!IsEndOfStatement()) {
  891. return false;
  892. }
  893. break;
  894. }
  895. return (!_es.donot_get || ( _es.donot_get && (_token == _SC('.') || _token == _SC('['))));
  896. }
  897. void FunctionCallArgs(bool rawcall = false)
  898. {
  899. SQInteger nargs = 1;//this
  900. while(_token != _SC(')')) {
  901. Expression();
  902. MoveIfCurrentTargetIsLocal();
  903. nargs++;
  904. if(_token == _SC(',')){
  905. Lex();
  906. if(_token == ')') Error(_SC("expression expected, found ')'"));
  907. }
  908. }
  909. Lex();
  910. if (rawcall) {
  911. if (nargs < 3) Error(_SC("rawcall requires at least 2 parameters (callee and this)"));
  912. nargs -= 2; //removes callee and this from count
  913. }
  914. for(SQInteger i = 0; i < (nargs - 1); i++) _fs->PopTarget();
  915. SQInteger stackbase = _fs->PopTarget();
  916. SQInteger closure = _fs->PopTarget();
  917. _fs->AddInstruction(_OP_CALL, _fs->PushTarget(), closure, stackbase, nargs);
  918. }
  919. void ParseTableOrClass(SQInteger separator,SQInteger terminator)
  920. {
  921. SQInteger tpos = _fs->GetCurrentPos(),nkeys = 0;
  922. while(_token != terminator) {
  923. bool hasattrs = false;
  924. bool isstatic = false;
  925. //check if is an attribute
  926. if(separator == ';') {
  927. if(_token == TK_ATTR_OPEN) {
  928. _fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(),0,NOT_TABLE); Lex();
  929. ParseTableOrClass(',',TK_ATTR_CLOSE);
  930. hasattrs = true;
  931. }
  932. if(_token == TK_STATIC) {
  933. isstatic = true;
  934. Lex();
  935. }
  936. }
  937. switch(_token) {
  938. case TK_FUNCTION:
  939. case TK_CONSTRUCTOR:{
  940. SQInteger tk = _token;
  941. Lex();
  942. SQObject id = tk == TK_FUNCTION ? Expect(TK_IDENTIFIER) : _fs->CreateString(_SC("constructor"));
  943. Expect(_SC('('));
  944. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(id));
  945. CreateFunction(id);
  946. _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, 0);
  947. }
  948. break;
  949. case _SC('['):
  950. Lex(); CommaExpr(); Expect(_SC(']'));
  951. Expect(_SC('=')); Expression();
  952. break;
  953. case TK_STRING_LITERAL: //JSON
  954. if(separator == ',') { //only works for tables
  955. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(Expect(TK_STRING_LITERAL)));
  956. Expect(_SC(':')); Expression();
  957. break;
  958. }
  959. default :
  960. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(Expect(TK_IDENTIFIER)));
  961. Expect(_SC('=')); Expression();
  962. }
  963. if(_token == separator) Lex();//optional comma/semicolon
  964. nkeys++;
  965. SQInteger val = _fs->PopTarget();
  966. SQInteger key = _fs->PopTarget();
  967. SQInteger attrs = hasattrs ? _fs->PopTarget():-1;
  968. ((void)attrs);
  969. assert((hasattrs && (attrs == key-1)) || !hasattrs);
  970. unsigned char flags = (hasattrs?NEW_SLOT_ATTRIBUTES_FLAG:0)|(isstatic?NEW_SLOT_STATIC_FLAG:0);
  971. SQInteger table = _fs->TopTarget(); //<<BECAUSE OF THIS NO COMMON EMIT FUNC IS POSSIBLE
  972. if(separator == _SC(',')) { //hack recognizes a table from the separator
  973. _fs->AddInstruction(_OP_NEWSLOT, 0xFF, table, key, val);
  974. }
  975. else {
  976. _fs->AddInstruction(_OP_NEWSLOTA, flags, table, key, val); //this for classes only as it invokes _newmember
  977. }
  978. }
  979. if(separator == _SC(',')) //hack recognizes a table from the separator
  980. _fs->SetIntructionParam(tpos, 1, nkeys);
  981. Lex();
  982. }
  983. void LocalDeclStatement()
  984. {
  985. SQObject varname;
  986. Lex();
  987. if( _token == TK_FUNCTION) {
  988. Lex();
  989. varname = Expect(TK_IDENTIFIER);
  990. Expect(_SC('('));
  991. CreateFunction(varname,false);
  992. _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, 0);
  993. _fs->PopTarget();
  994. _fs->PushLocalVariable(varname);
  995. return;
  996. }
  997. do {
  998. varname = Expect(TK_IDENTIFIER);
  999. if(_token == _SC('=')) {
  1000. Lex(); Expression();
  1001. SQInteger src = _fs->PopTarget();
  1002. SQInteger dest = _fs->PushTarget();
  1003. if(dest != src) _fs->AddInstruction(_OP_MOVE, dest, src);
  1004. }
  1005. else{
  1006. _fs->AddInstruction(_OP_LOADNULLS, _fs->PushTarget(),1);
  1007. }
  1008. _fs->PopTarget();
  1009. _fs->PushLocalVariable(varname);
  1010. if(_token == _SC(',')) Lex(); else break;
  1011. } while(1);
  1012. }
  1013. void IfBlock()
  1014. {
  1015. if (_token == _SC('{'))
  1016. {
  1017. BEGIN_SCOPE();
  1018. Lex();
  1019. Statements();
  1020. Expect(_SC('}'));
  1021. if (true) {
  1022. END_SCOPE();
  1023. }
  1024. else {
  1025. END_SCOPE_NO_CLOSE();
  1026. }
  1027. }
  1028. else {
  1029. //BEGIN_SCOPE();
  1030. Statement();
  1031. if (_lex._prevtoken != _SC('}') && _lex._prevtoken != _SC(';')) OptionalSemicolon();
  1032. //END_SCOPE();
  1033. }
  1034. }
  1035. void IfStatement()
  1036. {
  1037. SQInteger jmppos;
  1038. bool haselse = false;
  1039. Lex(); Expect(_SC('(')); CommaExpr(); Expect(_SC(')'));
  1040. _fs->AddInstruction(_OP_JZ, _fs->PopTarget());
  1041. SQInteger jnepos = _fs->GetCurrentPos();
  1042. IfBlock();
  1043. //
  1044. /*static int n = 0;
  1045. if (_token != _SC('}') && _token != TK_ELSE) {
  1046. printf("IF %d-----------------------!!!!!!!!!\n", n);
  1047. if (n == 5)
  1048. {
  1049. printf("asd");
  1050. }
  1051. n++;
  1052. //OptionalSemicolon();
  1053. }*/
  1054. SQInteger endifblock = _fs->GetCurrentPos();
  1055. if(_token == TK_ELSE){
  1056. haselse = true;
  1057. //BEGIN_SCOPE();
  1058. _fs->AddInstruction(_OP_JMP);
  1059. jmppos = _fs->GetCurrentPos();
  1060. Lex();
  1061. //Statement(); if(_lex._prevtoken != _SC('}')) OptionalSemicolon();
  1062. IfBlock();
  1063. //END_SCOPE();
  1064. _fs->SetIntructionParam(jmppos, 1, _fs->GetCurrentPos() - jmppos);
  1065. }
  1066. _fs->SetIntructionParam(jnepos, 1, endifblock - jnepos + (haselse?1:0));
  1067. }
  1068. void WhileStatement()
  1069. {
  1070. SQInteger jzpos, jmppos;
  1071. jmppos = _fs->GetCurrentPos();
  1072. Lex(); Expect(_SC('(')); CommaExpr(); Expect(_SC(')'));
  1073. BEGIN_BREAKBLE_BLOCK();
  1074. _fs->AddInstruction(_OP_JZ, _fs->PopTarget());
  1075. jzpos = _fs->GetCurrentPos();
  1076. BEGIN_SCOPE();
  1077. Statement();
  1078. END_SCOPE();
  1079. _fs->AddInstruction(_OP_JMP, 0, jmppos - _fs->GetCurrentPos() - 1);
  1080. _fs->SetIntructionParam(jzpos, 1, _fs->GetCurrentPos() - jzpos);
  1081. END_BREAKBLE_BLOCK(jmppos);
  1082. }
  1083. void DoWhileStatement()
  1084. {
  1085. Lex();
  1086. SQInteger jmptrg = _fs->GetCurrentPos();
  1087. BEGIN_BREAKBLE_BLOCK()
  1088. BEGIN_SCOPE();
  1089. Statement();
  1090. END_SCOPE();
  1091. Expect(TK_WHILE);
  1092. SQInteger continuetrg = _fs->GetCurrentPos();
  1093. Expect(_SC('(')); CommaExpr(); Expect(_SC(')'));
  1094. _fs->AddInstruction(_OP_JZ, _fs->PopTarget(), 1);
  1095. _fs->AddInstruction(_OP_JMP, 0, jmptrg - _fs->GetCurrentPos() - 1);
  1096. END_BREAKBLE_BLOCK(continuetrg);
  1097. }
  1098. void ForStatement()
  1099. {
  1100. Lex();
  1101. BEGIN_SCOPE();
  1102. Expect(_SC('('));
  1103. if(_token == TK_LOCAL) LocalDeclStatement();
  1104. else if(_token != _SC(';')){
  1105. CommaExpr();
  1106. _fs->PopTarget();
  1107. }
  1108. Expect(_SC(';'));
  1109. _fs->SnoozeOpt();
  1110. SQInteger jmppos = _fs->GetCurrentPos();
  1111. SQInteger jzpos = -1;
  1112. if(_token != _SC(';')) { CommaExpr(); _fs->AddInstruction(_OP_JZ, _fs->PopTarget()); jzpos = _fs->GetCurrentPos(); }
  1113. Expect(_SC(';'));
  1114. _fs->SnoozeOpt();
  1115. SQInteger expstart = _fs->GetCurrentPos() + 1;
  1116. if(_token != _SC(')')) {
  1117. CommaExpr();
  1118. _fs->PopTarget();
  1119. }
  1120. Expect(_SC(')'));
  1121. _fs->SnoozeOpt();
  1122. SQInteger expend = _fs->GetCurrentPos();
  1123. SQInteger expsize = (expend - expstart) + 1;
  1124. SQInstructionVec exp;
  1125. if(expsize > 0) {
  1126. for(SQInteger i = 0; i < expsize; i++)
  1127. exp.push_back(_fs->GetInstruction(expstart + i));
  1128. _fs->PopInstructions(expsize);
  1129. }
  1130. BEGIN_BREAKBLE_BLOCK()
  1131. Statement();
  1132. SQInteger continuetrg = _fs->GetCurrentPos();
  1133. if(expsize > 0) {
  1134. for(SQInteger i = 0; i < expsize; i++)
  1135. _fs->AddInstruction(exp[i]);
  1136. }
  1137. _fs->AddInstruction(_OP_JMP, 0, jmppos - _fs->GetCurrentPos() - 1, 0);
  1138. if(jzpos> 0) _fs->SetIntructionParam(jzpos, 1, _fs->GetCurrentPos() - jzpos);
  1139. END_SCOPE();
  1140. END_BREAKBLE_BLOCK(continuetrg);
  1141. }
  1142. void ForEachStatement()
  1143. {
  1144. SQObject idxname, valname;
  1145. Lex(); Expect(_SC('(')); valname = Expect(TK_IDENTIFIER);
  1146. if(_token == _SC(',')) {
  1147. idxname = valname;
  1148. Lex(); valname = Expect(TK_IDENTIFIER);
  1149. }
  1150. else{
  1151. idxname = _fs->CreateString(_SC("@INDEX@"));
  1152. }
  1153. Expect(TK_IN);
  1154. //save the stack size
  1155. BEGIN_SCOPE();
  1156. //put the table in the stack(evaluate the table expression)
  1157. Expression(); Expect(_SC(')'));
  1158. SQInteger container = _fs->TopTarget();
  1159. //push the index local var
  1160. SQInteger indexpos = _fs->PushLocalVariable(idxname);
  1161. _fs->AddInstruction(_OP_LOADNULLS, indexpos,1);
  1162. //push the value local var
  1163. SQInteger valuepos = _fs->PushLocalVariable(valname);
  1164. _fs->AddInstruction(_OP_LOADNULLS, valuepos,1);
  1165. //push reference index
  1166. SQInteger itrpos = _fs->PushLocalVariable(_fs->CreateString(_SC("@ITERATOR@"))); //use invalid id to make it inaccessible
  1167. _fs->AddInstruction(_OP_LOADNULLS, itrpos,1);
  1168. SQInteger jmppos = _fs->GetCurrentPos();
  1169. _fs->AddInstruction(_OP_FOREACH, container, 0, indexpos);
  1170. SQInteger foreachpos = _fs->GetCurrentPos();
  1171. _fs->AddInstruction(_OP_POSTFOREACH, container, 0, indexpos);
  1172. //generate the statement code
  1173. BEGIN_BREAKBLE_BLOCK()
  1174. Statement();
  1175. _fs->AddInstruction(_OP_JMP, 0, jmppos - _fs->GetCurrentPos() - 1);
  1176. _fs->SetIntructionParam(foreachpos, 1, _fs->GetCurrentPos() - foreachpos);
  1177. _fs->SetIntructionParam(foreachpos + 1, 1, _fs->GetCurrentPos() - foreachpos);
  1178. END_BREAKBLE_BLOCK(foreachpos - 1);
  1179. //restore the local variable stack(remove index,val and ref idx)
  1180. _fs->PopTarget();
  1181. END_SCOPE();
  1182. }
  1183. void SwitchStatement()
  1184. {
  1185. Lex(); Expect(_SC('(')); CommaExpr(); Expect(_SC(')'));
  1186. Expect(_SC('{'));
  1187. SQInteger expr = _fs->TopTarget();
  1188. bool bfirst = true;
  1189. SQInteger tonextcondjmp = -1;
  1190. SQInteger skipcondjmp = -1;
  1191. SQInteger __nbreaks__ = _fs->_unresolvedbreaks.size();
  1192. _fs->_breaktargets.push_back(0);
  1193. while(_token == TK_CASE) {
  1194. if(!bfirst) {
  1195. _fs->AddInstruction(_OP_JMP, 0, 0);
  1196. skipcondjmp = _fs->GetCurrentPos();
  1197. _fs->SetIntructionParam(tonextcondjmp, 1, _fs->GetCurrentPos() - tonextcondjmp);
  1198. }
  1199. //condition
  1200. Lex(); Expression(); Expect(_SC(':'));
  1201. SQInteger trg = _fs->PopTarget();
  1202. SQInteger eqtarget = trg;
  1203. bool local = _fs->IsLocal(trg);
  1204. if(local) {
  1205. eqtarget = _fs->PushTarget(); //we need to allocate a extra reg
  1206. }
  1207. _fs->AddInstruction(_OP_EQ, eqtarget, trg, expr);
  1208. _fs->AddInstruction(_OP_JZ, eqtarget, 0);
  1209. if(local) {
  1210. _fs->PopTarget();
  1211. }
  1212. //end condition
  1213. if(skipcondjmp != -1) {
  1214. _fs->SetIntructionParam(skipcondjmp, 1, (_fs->GetCurrentPos() - skipcondjmp));
  1215. }
  1216. tonextcondjmp = _fs->GetCurrentPos();
  1217. BEGIN_SCOPE();
  1218. Statements();
  1219. END_SCOPE();
  1220. bfirst = false;
  1221. }
  1222. if(tonextcondjmp != -1)
  1223. _fs->SetIntructionParam(tonextcondjmp, 1, _fs->GetCurrentPos() - tonextcondjmp);
  1224. if(_token == TK_DEFAULT) {
  1225. Lex(); Expect(_SC(':'));
  1226. BEGIN_SCOPE();
  1227. Statements();
  1228. END_SCOPE();
  1229. }
  1230. Expect(_SC('}'));
  1231. _fs->PopTarget();
  1232. __nbreaks__ = _fs->_unresolvedbreaks.size() - __nbreaks__;
  1233. if(__nbreaks__ > 0)ResolveBreaks(_fs, __nbreaks__);
  1234. _fs->_breaktargets.pop_back();
  1235. }
  1236. void FunctionStatement()
  1237. {
  1238. SQObject id;
  1239. Lex(); id = Expect(TK_IDENTIFIER);
  1240. _fs->PushTarget(0);
  1241. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(id));
  1242. if(_token == TK_DOUBLE_COLON) Emit2ArgsOP(_OP_GET);
  1243. while(_token == TK_DOUBLE_COLON) {
  1244. Lex();
  1245. id = Expect(TK_IDENTIFIER);
  1246. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(id));
  1247. if(_token == TK_DOUBLE_COLON) Emit2ArgsOP(_OP_GET);
  1248. }
  1249. Expect(_SC('('));
  1250. CreateFunction(id);
  1251. _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, 0);
  1252. EmitDerefOp(_OP_NEWSLOT);
  1253. _fs->PopTarget();
  1254. }
  1255. void ClassStatement()
  1256. {
  1257. SQExpState es;
  1258. Lex();
  1259. es = _es;
  1260. _es.donot_get = true;
  1261. PrefixedExpr();
  1262. if(_es.etype == EXPR) {
  1263. Error(_SC("invalid class name"));
  1264. }
  1265. else if(_es.etype == OBJECT || _es.etype == BASE) {
  1266. ClassExp();
  1267. EmitDerefOp(_OP_NEWSLOT);
  1268. _fs->PopTarget();
  1269. }
  1270. else {
  1271. Error(_SC("cannot create a class in a local with the syntax(class <local>)"));
  1272. }
  1273. _es = es;
  1274. }
  1275. SQObject ExpectScalar()
  1276. {
  1277. SQObject val;
  1278. val._type = OT_NULL; val._unVal.nInteger = 0; //shut up GCC 4.x
  1279. switch(_token) {
  1280. case TK_INTEGER:
  1281. val._type = OT_INTEGER;
  1282. val._unVal.nInteger = _lex._nvalue;
  1283. break;
  1284. case TK_FLOAT:
  1285. val._type = OT_FLOAT;
  1286. val._unVal.fFloat = _lex._fvalue;
  1287. break;
  1288. case TK_STRING_LITERAL:
  1289. val = _fs->CreateString(_lex._svalue,_lex._longstr.size()-1);
  1290. break;
  1291. case TK_TRUE:
  1292. case TK_FALSE:
  1293. val._type = OT_BOOL;
  1294. val._unVal.nInteger = _token == TK_TRUE ? 1 : 0;
  1295. break;
  1296. case '-':
  1297. Lex();
  1298. switch(_token)
  1299. {
  1300. case TK_INTEGER:
  1301. val._type = OT_INTEGER;
  1302. val._unVal.nInteger = -_lex._nvalue;
  1303. break;
  1304. case TK_FLOAT:
  1305. val._type = OT_FLOAT;
  1306. val._unVal.fFloat = -_lex._fvalue;
  1307. break;
  1308. default:
  1309. Error(_SC("scalar expected : integer, float"));
  1310. }
  1311. break;
  1312. default:
  1313. Error(_SC("scalar expected : integer, float, or string"));
  1314. }
  1315. Lex();
  1316. return val;
  1317. }
  1318. void EnumStatement()
  1319. {
  1320. Lex();
  1321. SQObject id = Expect(TK_IDENTIFIER);
  1322. Expect(_SC('{'));
  1323. SQObject table = _fs->CreateTable();
  1324. SQInteger nval = 0;
  1325. while(_token != _SC('}')) {
  1326. SQObject key = Expect(TK_IDENTIFIER);
  1327. SQObject val;
  1328. if(_token == _SC('=')) {
  1329. Lex();
  1330. val = ExpectScalar();
  1331. }
  1332. else {
  1333. val._type = OT_INTEGER;
  1334. val._unVal.nInteger = nval++;
  1335. }
  1336. _table(table)->NewSlot(SQObjectPtr(key),SQObjectPtr(val));
  1337. if(_token == ',') Lex();
  1338. }
  1339. SQTable *enums = _table(_ss(_vm)->_consts);
  1340. SQObjectPtr strongid = id;
  1341. enums->NewSlot(SQObjectPtr(strongid),SQObjectPtr(table));
  1342. strongid.Null();
  1343. Lex();
  1344. }
  1345. void TryCatchStatement()
  1346. {
  1347. SQObject exid;
  1348. Lex();
  1349. _fs->AddInstruction(_OP_PUSHTRAP,0,0);
  1350. _fs->_traps++;
  1351. if(_fs->_breaktargets.size()) _fs->_breaktargets.top()++;
  1352. if(_fs->_continuetargets.size()) _fs->_continuetargets.top()++;
  1353. SQInteger trappos = _fs->GetCurrentPos();
  1354. {
  1355. BEGIN_SCOPE();
  1356. Statement();
  1357. END_SCOPE();
  1358. }
  1359. _fs->_traps--;
  1360. _fs->AddInstruction(_OP_POPTRAP, 1, 0);
  1361. if(_fs->_breaktargets.size()) _fs->_breaktargets.top()--;
  1362. if(_fs->_continuetargets.size()) _fs->_continuetargets.top()--;
  1363. _fs->AddInstruction(_OP_JMP, 0, 0);
  1364. SQInteger jmppos = _fs->GetCurrentPos();
  1365. _fs->SetIntructionParam(trappos, 1, (_fs->GetCurrentPos() - trappos));
  1366. Expect(TK_CATCH); Expect(_SC('(')); exid = Expect(TK_IDENTIFIER); Expect(_SC(')'));
  1367. {
  1368. BEGIN_SCOPE();
  1369. SQInteger ex_target = _fs->PushLocalVariable(exid);
  1370. _fs->SetIntructionParam(trappos, 0, ex_target);
  1371. Statement();
  1372. _fs->SetIntructionParams(jmppos, 0, (_fs->GetCurrentPos() - jmppos), 0);
  1373. END_SCOPE();
  1374. }
  1375. }
  1376. void FunctionExp(SQInteger ftype,bool lambda = false)
  1377. {
  1378. Lex(); Expect(_SC('('));
  1379. SQObjectPtr dummy;
  1380. CreateFunction(dummy,lambda);
  1381. _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, ftype == TK_FUNCTION?0:1);
  1382. }
  1383. void ClassExp()
  1384. {
  1385. SQInteger base = -1;
  1386. SQInteger attrs = -1;
  1387. if(_token == TK_EXTENDS) {
  1388. Lex(); Expression();
  1389. base = _fs->TopTarget();
  1390. }
  1391. if(_token == TK_ATTR_OPEN) {
  1392. Lex();
  1393. _fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(),0,NOT_TABLE);
  1394. ParseTableOrClass(_SC(','),TK_ATTR_CLOSE);
  1395. attrs = _fs->TopTarget();
  1396. }
  1397. Expect(_SC('{'));
  1398. if(attrs != -1) _fs->PopTarget();
  1399. if(base != -1) _fs->PopTarget();
  1400. _fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(), base, attrs,NOT_CLASS);
  1401. ParseTableOrClass(_SC(';'),_SC('}'));
  1402. }
  1403. void DeleteExpr()
  1404. {
  1405. SQExpState es;
  1406. Lex();
  1407. es = _es;
  1408. _es.donot_get = true;
  1409. PrefixedExpr();
  1410. if(_es.etype==EXPR) Error(_SC("can't delete an expression"));
  1411. if(_es.etype==OBJECT || _es.etype==BASE) {
  1412. Emit2ArgsOP(_OP_DELETE);
  1413. }
  1414. else {
  1415. Error(_SC("cannot delete an (outer) local"));
  1416. }
  1417. _es = es;
  1418. }
  1419. void PrefixIncDec(SQInteger token)
  1420. {
  1421. SQExpState es;
  1422. SQInteger diff = (token==TK_MINUSMINUS) ? -1 : 1;
  1423. Lex();
  1424. es = _es;
  1425. _es.donot_get = true;
  1426. PrefixedExpr();
  1427. if(_es.etype==EXPR) {
  1428. Error(_SC("can't '++' or '--' an expression"));
  1429. }
  1430. else if(_es.etype==OBJECT || _es.etype==BASE) {
  1431. Emit2ArgsOP(_OP_INC, diff);
  1432. }
  1433. else if(_es.etype==LOCAL) {
  1434. SQInteger src = _fs->TopTarget();
  1435. _fs->AddInstruction(_OP_INCL, src, src, 0, diff);
  1436. }
  1437. else if(_es.etype==OUTER) {
  1438. SQInteger tmp = _fs->PushTarget();
  1439. _fs->AddInstruction(_OP_GETOUTER, tmp, _es.epos);
  1440. _fs->AddInstruction(_OP_INCL, tmp, tmp, 0, diff);
  1441. _fs->AddInstruction(_OP_SETOUTER, tmp, _es.epos, tmp);
  1442. }
  1443. _es = es;
  1444. }
  1445. void CreateFunction(SQObject &name,bool lambda = false)
  1446. {
  1447. SQFuncState *funcstate = _fs->PushChildState(_ss(_vm));
  1448. funcstate->_name = name;
  1449. SQObject paramname;
  1450. funcstate->AddParameter(_fs->CreateString(_SC("this")));
  1451. funcstate->_sourcename = _sourcename;
  1452. SQInteger defparams = 0;
  1453. while(_token!=_SC(')')) {
  1454. if(_token == TK_VARPARAMS) {
  1455. if(defparams > 0) Error(_SC("function with default parameters cannot have variable number of parameters"));
  1456. funcstate->AddParameter(_fs->CreateString(_SC("vargv")));
  1457. funcstate->_varparams = true;
  1458. Lex();
  1459. if(_token != _SC(')')) Error(_SC("expected ')'"));
  1460. break;
  1461. }
  1462. else {
  1463. paramname = Expect(TK_IDENTIFIER);
  1464. funcstate->AddParameter(paramname);
  1465. if(_token == _SC('=')) {
  1466. Lex();
  1467. Expression();
  1468. funcstate->AddDefaultParam(_fs->TopTarget());
  1469. defparams++;
  1470. }
  1471. else {
  1472. if(defparams > 0) Error(_SC("expected '='"));
  1473. }
  1474. if(_token == _SC(',')) Lex();
  1475. else if(_token != _SC(')')) Error(_SC("expected ')' or ','"));
  1476. }
  1477. }
  1478. Expect(_SC(')'));
  1479. for(SQInteger n = 0; n < defparams; n++) {
  1480. _fs->PopTarget();
  1481. }
  1482. SQFuncState *currchunk = _fs;
  1483. _fs = funcstate;
  1484. if(lambda) {
  1485. Expression();
  1486. _fs->AddInstruction(_OP_RETURN, 1, _fs->PopTarget());}
  1487. else {
  1488. Statement(false);
  1489. }
  1490. funcstate->AddLineInfos(_lex._prevtoken == _SC('\n')?_lex._lasttokenline:_lex._currentline, _lineinfo, true);
  1491. funcstate->AddInstruction(_OP_RETURN, -1);
  1492. funcstate->SetStackSize(0);
  1493. SQFunctionProto *func = funcstate->BuildProto();
  1494. #ifdef _DEBUG_DUMP
  1495. funcstate->Dump(func);
  1496. #endif
  1497. _fs = currchunk;
  1498. _fs->_functions.push_back(func);
  1499. _fs->PopChildState();
  1500. }
  1501. void ResolveBreaks(SQFuncState *funcstate, SQInteger ntoresolve)
  1502. {
  1503. while(ntoresolve > 0) {
  1504. SQInteger pos = funcstate->_unresolvedbreaks.back();
  1505. funcstate->_unresolvedbreaks.pop_back();
  1506. //set the jmp instruction
  1507. funcstate->SetIntructionParams(pos, 0, funcstate->GetCurrentPos() - pos, 0);
  1508. ntoresolve--;
  1509. }
  1510. }
  1511. void ResolveContinues(SQFuncState *funcstate, SQInteger ntoresolve, SQInteger targetpos)
  1512. {
  1513. while(ntoresolve > 0) {
  1514. SQInteger pos = funcstate->_unresolvedcontinues.back();
  1515. funcstate->_unresolvedcontinues.pop_back();
  1516. //set the jmp instruction
  1517. funcstate->SetIntructionParams(pos, 0, targetpos - pos, 0);
  1518. ntoresolve--;
  1519. }
  1520. }
  1521. private:
  1522. SQInteger _token;
  1523. SQFuncState *_fs;
  1524. SQObjectPtr _sourcename;
  1525. SQLexer _lex;
  1526. bool _lineinfo;
  1527. bool _raiseerror;
  1528. SQInteger _debugline;
  1529. SQInteger _debugop;
  1530. SQExpState _es;
  1531. SQScope _scope;
  1532. SQChar _compilererror[MAX_COMPILER_ERROR_LEN];
  1533. jmp_buf _errorjmp;
  1534. SQVM *_vm;
  1535. };
  1536. bool Compile(SQVM *vm,SQLEXREADFUNC rg, SQUserPointer up, const SQChar *sourcename, SQObjectPtr &out, bool raiseerror, bool lineinfo)
  1537. {
  1538. SQCompiler p(vm, rg, up, sourcename, raiseerror, lineinfo);
  1539. return p.Compile(out);
  1540. }
  1541. #endif