sqcompiler.cpp 49 KB

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