sqcompiler.cpp 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657
  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. //fix proposed by frosch to correct line number info in stack dumps
  1159. _fs->AddLineInfos(_lex._currentline, _lineinfo, true);
  1160. Expect(TK_WHILE);
  1161. SQInteger continuetrg = _fs->GetCurrentPos();
  1162. Expect(_SC('(')); CommaExpr(true); Expect(_SC(')'));
  1163. _fs->AddInstruction(_OP_JZ, _fs->PopTarget(), 1);
  1164. _fs->AddInstruction(_OP_JMP, 0, jmptrg - _fs->GetCurrentPos() - 1);
  1165. END_BREAKBLE_BLOCK(continuetrg);
  1166. }
  1167. void ForStatement()
  1168. {
  1169. Lex();
  1170. BEGIN_SCOPE();
  1171. Expect(_SC('('));
  1172. switch(_token){
  1173. case TK_LOCAL_CHAR_T:
  1174. case TK_LOCAL_WCHAR_T:
  1175. case TK_LOCAL_BOOL_T:
  1176. case TK_LOCAL_TABLE_T:
  1177. case TK_LOCAL_ARRAY_T:
  1178. case TK_LOCAL_INT8_T:
  1179. case TK_LOCAL_INT16_T:
  1180. case TK_LOCAL_INT32_T:
  1181. case TK_LOCAL_INT64_T:
  1182. case TK_LOCAL_INT_T:
  1183. case TK_LOCAL_UINT8_T:
  1184. case TK_LOCAL_UINT16_T:
  1185. case TK_LOCAL_UINT32_T:
  1186. case TK_LOCAL_UINT64_T:
  1187. case TK_LOCAL_UINT_T:
  1188. case TK_LOCAL_FLOAT_T:
  1189. case TK_LOCAL_DOUBLE_T:
  1190. case TK_LOCAL_LONG_DOUBLE_T:
  1191. case TK_LOCAL:
  1192. LocalDeclStatement();
  1193. break;
  1194. default:
  1195. if(_token != _SC(';')){
  1196. CommaExpr();
  1197. _fs->PopTarget();
  1198. }
  1199. }
  1200. Expect(_SC(';'));
  1201. _fs->SnoozeOpt();
  1202. SQInteger jmppos = _fs->GetCurrentPos();
  1203. SQInteger jzpos = -1;
  1204. if(_token != _SC(';')) { CommaExpr(); _fs->AddInstruction(_OP_JZ, _fs->PopTarget()); jzpos = _fs->GetCurrentPos(); }
  1205. Expect(_SC(';'));
  1206. _fs->SnoozeOpt();
  1207. SQInteger expstart = _fs->GetCurrentPos() + 1;
  1208. if(_token != _SC(')')) {
  1209. CommaExpr();
  1210. _fs->PopTarget();
  1211. }
  1212. Expect(_SC(')'));
  1213. _fs->SnoozeOpt();
  1214. SQInteger expend = _fs->GetCurrentPos();
  1215. SQInteger expsize = (expend - expstart) + 1;
  1216. SQInstructionVec exp;
  1217. if(expsize > 0) {
  1218. for(SQInteger i = 0; i < expsize; i++)
  1219. exp.push_back(_fs->GetInstruction(expstart + i));
  1220. _fs->PopInstructions(expsize);
  1221. }
  1222. BEGIN_BREAKBLE_BLOCK()
  1223. Statement();
  1224. SQInteger continuetrg = _fs->GetCurrentPos();
  1225. if(expsize > 0) {
  1226. for(SQInteger i = 0; i < expsize; i++)
  1227. _fs->AddInstruction(exp[i]);
  1228. }
  1229. _fs->AddInstruction(_OP_JMP, 0, jmppos - _fs->GetCurrentPos() - 1, 0);
  1230. if(jzpos> 0) _fs->SetIntructionParam(jzpos, 1, _fs->GetCurrentPos() - jzpos);
  1231. END_SCOPE();
  1232. END_BREAKBLE_BLOCK(continuetrg);
  1233. }
  1234. void ForEachStatement()
  1235. {
  1236. SQObject idxname, valname;
  1237. Lex(); Expect(_SC('(')); valname = Expect(TK_IDENTIFIER);
  1238. if(_token == _SC(',')) {
  1239. idxname = valname;
  1240. Lex(); valname = Expect(TK_IDENTIFIER);
  1241. }
  1242. else{
  1243. idxname = _fs->CreateString(_SC("@INDEX@"));
  1244. }
  1245. Expect(TK_IN);
  1246. //save the stack size
  1247. BEGIN_SCOPE();
  1248. //put the table in the stack(evaluate the table expression)
  1249. Expression(); Expect(_SC(')'));
  1250. SQInteger container = _fs->TopTarget();
  1251. //push the index local var
  1252. SQInteger indexpos = _fs->PushLocalVariable(idxname, _scope.nested);
  1253. _fs->AddInstruction(_OP_LOADNULLS, indexpos,1);
  1254. //push the value local var
  1255. SQInteger valuepos = _fs->PushLocalVariable(valname, _scope.nested);
  1256. _fs->AddInstruction(_OP_LOADNULLS, valuepos,1);
  1257. //push reference index
  1258. SQInteger itrpos = _fs->PushLocalVariable(_fs->CreateString(_SC("@ITERATOR@")), _scope.nested); //use invalid id to make it inaccessible
  1259. _fs->AddInstruction(_OP_LOADNULLS, itrpos,1);
  1260. SQInteger jmppos = _fs->GetCurrentPos();
  1261. _fs->AddInstruction(_OP_FOREACH, container, 0, indexpos);
  1262. SQInteger foreachpos = _fs->GetCurrentPos();
  1263. _fs->AddInstruction(_OP_POSTFOREACH, container, 0, indexpos);
  1264. //generate the statement code
  1265. BEGIN_BREAKBLE_BLOCK()
  1266. Statement();
  1267. _fs->AddInstruction(_OP_JMP, 0, jmppos - _fs->GetCurrentPos() - 1);
  1268. _fs->SetIntructionParam(foreachpos, 1, _fs->GetCurrentPos() - foreachpos);
  1269. _fs->SetIntructionParam(foreachpos + 1, 1, _fs->GetCurrentPos() - foreachpos);
  1270. END_BREAKBLE_BLOCK(foreachpos - 1);
  1271. //restore the local variable stack(remove index,val and ref idx)
  1272. _fs->PopTarget();
  1273. END_SCOPE();
  1274. }
  1275. void SwitchStatement()
  1276. {
  1277. Lex(); Expect(_SC('(')); CommaExpr(true); Expect(_SC(')'));
  1278. Expect(_SC('{'));
  1279. SQInteger expr = _fs->TopTarget();
  1280. bool bfirst = true;
  1281. SQInteger tonextcondjmp = -1;
  1282. SQInteger skipcondjmp = -1;
  1283. SQInteger __nbreaks__ = _fs->_unresolvedbreaks.size();
  1284. _fs->_breaktargets.push_back(0);
  1285. while(_token == TK_CASE) {
  1286. if(!bfirst) {
  1287. _fs->AddInstruction(_OP_JMP, 0, 0);
  1288. skipcondjmp = _fs->GetCurrentPos();
  1289. _fs->SetIntructionParam(tonextcondjmp, 1, _fs->GetCurrentPos() - tonextcondjmp);
  1290. }
  1291. //condition
  1292. Lex(); Expression(); Expect(_SC(':'));
  1293. SQInteger trg = _fs->PopTarget();
  1294. _fs->AddInstruction(_OP_EQ, trg, trg, expr);
  1295. _fs->AddInstruction(_OP_JZ, trg, 0);
  1296. //end condition
  1297. if(skipcondjmp != -1) {
  1298. _fs->SetIntructionParam(skipcondjmp, 1, (_fs->GetCurrentPos() - skipcondjmp));
  1299. }
  1300. tonextcondjmp = _fs->GetCurrentPos();
  1301. BEGIN_SCOPE();
  1302. Statements();
  1303. END_SCOPE();
  1304. bfirst = false;
  1305. }
  1306. if(tonextcondjmp != -1)
  1307. _fs->SetIntructionParam(tonextcondjmp, 1, _fs->GetCurrentPos() - tonextcondjmp);
  1308. if(_token == TK_DEFAULT) {
  1309. Lex(); Expect(_SC(':'));
  1310. BEGIN_SCOPE();
  1311. Statements();
  1312. END_SCOPE();
  1313. }
  1314. Expect(_SC('}'));
  1315. _fs->PopTarget();
  1316. __nbreaks__ = _fs->_unresolvedbreaks.size() - __nbreaks__;
  1317. if(__nbreaks__ > 0)ResolveBreaks(_fs, __nbreaks__);
  1318. _fs->_breaktargets.pop_back();
  1319. }
  1320. void FunctionStatement()
  1321. {
  1322. SQObject id;
  1323. Lex(); id = Expect(TK_IDENTIFIER);
  1324. _fs->PushTarget(0);
  1325. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(id));
  1326. if(_token == TK_DOUBLE_COLON) Emit2ArgsOP(_OP_GET);
  1327. while(_token == TK_DOUBLE_COLON) {
  1328. Lex();
  1329. id = Expect(TK_IDENTIFIER);
  1330. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(id));
  1331. if(_token == TK_DOUBLE_COLON) Emit2ArgsOP(_OP_GET);
  1332. }
  1333. Expect(_SC('('));
  1334. CreateFunction(id);
  1335. _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, 0);
  1336. EmitDerefOp(_OP_NEWSLOT);
  1337. _fs->PopTarget();
  1338. }
  1339. void ClassStatement()
  1340. {
  1341. SQExpState es;
  1342. Lex();
  1343. es = _es;
  1344. _es.donot_get = true;
  1345. PrefixedExpr();
  1346. if(_es.etype == EXPR) {
  1347. Error(_SC("invalid class name"));
  1348. }
  1349. else if(_es.etype == OBJECT || _es.etype == BASE) {
  1350. ClassExp();
  1351. EmitDerefOp(_OP_NEWSLOT);
  1352. _fs->PopTarget();
  1353. }
  1354. else {
  1355. Error(_SC("cannot create a class in a local with the syntax(class <local>)"));
  1356. }
  1357. _es = es;
  1358. }
  1359. SQObject ExpectScalar()
  1360. {
  1361. SQObject val;
  1362. val._type = OT_NULL; val._unVal.nInteger = 0; //shut up GCC 4.x
  1363. switch(_token) {
  1364. case TK_INTEGER:
  1365. val._type = OT_INTEGER;
  1366. val._unVal.nInteger = _lex._nvalue;
  1367. break;
  1368. case TK_FLOAT:
  1369. val._type = OT_FLOAT;
  1370. val._unVal.fFloat = _lex._fvalue;
  1371. break;
  1372. case TK_STRING_LITERAL:
  1373. val = _fs->CreateString(_lex._svalue,_lex._longstr.size()-1);
  1374. break;
  1375. case '-':
  1376. Lex();
  1377. switch(_token)
  1378. {
  1379. case TK_INTEGER:
  1380. val._type = OT_INTEGER;
  1381. val._unVal.nInteger = -_lex._nvalue;
  1382. break;
  1383. case TK_FLOAT:
  1384. val._type = OT_FLOAT;
  1385. val._unVal.fFloat = -_lex._fvalue;
  1386. break;
  1387. default:
  1388. Error(_SC("scalar expected : integer,float"));
  1389. }
  1390. break;
  1391. default:
  1392. Error(_SC("scalar expected : integer,float or string"));
  1393. }
  1394. Lex();
  1395. return val;
  1396. }
  1397. void EnumStatement()
  1398. {
  1399. Lex();
  1400. SQObject id = Expect(TK_IDENTIFIER);
  1401. Expect(_SC('{'));
  1402. SQObject table = _fs->CreateTable();
  1403. SQInteger nval = 0;
  1404. while(_token != _SC('}')) {
  1405. SQObject key = Expect(TK_IDENTIFIER);
  1406. SQObject val;
  1407. if(_token == _SC('=')) {
  1408. Lex();
  1409. val = ExpectScalar();
  1410. }
  1411. else {
  1412. val._type = OT_INTEGER;
  1413. val._unVal.nInteger = nval++;
  1414. }
  1415. _table(table)->NewSlot(SQObjectPtr(key),SQObjectPtr(val));
  1416. if(_token == ',') Lex();
  1417. }
  1418. SQTable *enums = _table(_ss(_vm)->_consts);
  1419. SQObjectPtr strongid = id;
  1420. enums->NewSlot(SQObjectPtr(strongid),SQObjectPtr(table));
  1421. strongid.Null();
  1422. Lex();
  1423. }
  1424. void TryCatchStatement()
  1425. {
  1426. SQObject exid;
  1427. Lex();
  1428. _fs->AddInstruction(_OP_PUSHTRAP,0,0);
  1429. _fs->_traps++;
  1430. if(_fs->_breaktargets.size()) _fs->_breaktargets.top()++;
  1431. if(_fs->_continuetargets.size()) _fs->_continuetargets.top()++;
  1432. SQInteger trappos = _fs->GetCurrentPos();
  1433. {
  1434. BEGIN_SCOPE();
  1435. Statement();
  1436. END_SCOPE();
  1437. }
  1438. _fs->_traps--;
  1439. _fs->AddInstruction(_OP_POPTRAP, 1, 0);
  1440. if(_fs->_breaktargets.size()) _fs->_breaktargets.top()--;
  1441. if(_fs->_continuetargets.size()) _fs->_continuetargets.top()--;
  1442. _fs->AddInstruction(_OP_JMP, 0, 0);
  1443. SQInteger jmppos = _fs->GetCurrentPos();
  1444. _fs->SetIntructionParam(trappos, 1, (_fs->GetCurrentPos() - trappos));
  1445. Expect(TK_CATCH); Expect(_SC('(')); exid = Expect(TK_IDENTIFIER); Expect(_SC(')'));
  1446. {
  1447. BEGIN_SCOPE();
  1448. SQInteger ex_target = _fs->PushLocalVariable(exid, _scope.nested);
  1449. _fs->SetIntructionParam(trappos, 0, ex_target);
  1450. Statement();
  1451. _fs->SetIntructionParams(jmppos, 0, (_fs->GetCurrentPos() - jmppos), 0);
  1452. END_SCOPE();
  1453. }
  1454. }
  1455. void FunctionExp(SQInteger ftype,bool lambda = false)
  1456. {
  1457. Lex(); Expect(_SC('('));
  1458. SQObjectPtr dummy;
  1459. CreateFunction(dummy,lambda);
  1460. _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, ftype == TK_FUNCTION?0:1);
  1461. }
  1462. void ClassExp()
  1463. {
  1464. SQInteger base = -1;
  1465. SQInteger attrs = -1;
  1466. if(_token == TK_EXTENDS) {
  1467. Lex(); Expression();
  1468. base = _fs->TopTarget();
  1469. }
  1470. if(_token == TK_ATTR_OPEN) {
  1471. Lex();
  1472. _fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(),0,NOT_TABLE);
  1473. ParseTableOrClass(_SC(','),TK_ATTR_CLOSE);
  1474. attrs = _fs->TopTarget();
  1475. }
  1476. Expect(_SC('{'));
  1477. if(attrs != -1) _fs->PopTarget();
  1478. if(base != -1) _fs->PopTarget();
  1479. _fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(), base, attrs,NOT_CLASS);
  1480. ParseTableOrClass(_SC(';'),_SC('}'));
  1481. }
  1482. void DeleteExpr()
  1483. {
  1484. SQExpState es;
  1485. Lex();
  1486. es = _es;
  1487. _es.donot_get = true;
  1488. PrefixedExpr();
  1489. if(_es.etype==EXPR) Error(_SC("can't delete an expression"));
  1490. if(_es.etype==OBJECT || _es.etype==BASE) {
  1491. Emit2ArgsOP(_OP_DELETE);
  1492. }
  1493. else {
  1494. Error(_SC("cannot delete an (outer) local"));
  1495. }
  1496. _es = es;
  1497. }
  1498. void PrefixIncDec(SQInteger token)
  1499. {
  1500. SQExpState es;
  1501. SQInteger diff = (token==TK_MINUSMINUS) ? -1 : 1;
  1502. Lex();
  1503. es = _es;
  1504. _es.donot_get = true;
  1505. PrefixedExpr();
  1506. if(_es.etype==EXPR) {
  1507. Error(_SC("can't '++' or '--' an expression"));
  1508. }
  1509. else if(_es.etype==OBJECT || _es.etype==BASE) {
  1510. Emit2ArgsOP(_OP_INC, diff);
  1511. }
  1512. else if(_es.etype==LOCAL) {
  1513. SQInteger src = _fs->TopTarget();
  1514. _fs->AddInstruction(_OP_INCL, src, src, 0, diff);
  1515. }
  1516. else if(_es.etype==OUTER) {
  1517. SQInteger tmp = _fs->PushTarget();
  1518. _fs->AddInstruction(_OP_GETOUTER, tmp, _es.epos);
  1519. _fs->AddInstruction(_OP_INCL, tmp, tmp, 0, diff);
  1520. _fs->AddInstruction(_OP_SETOUTER, tmp, _es.epos, tmp);
  1521. }
  1522. _es = es;
  1523. }
  1524. void CreateFunction(SQObject &name,bool lambda = false)
  1525. {
  1526. SQFuncState *funcstate = _fs->PushChildState(_ss(_vm));
  1527. funcstate->_name = name;
  1528. SQObject paramname;
  1529. funcstate->AddParameter(_fs->CreateString(_SC("this")), _scope.nested+1);
  1530. funcstate->_sourcename = _sourcename;
  1531. SQInteger defparams = 0;
  1532. while(_token!=_SC(')')) {
  1533. if(_token == TK_VARPARAMS) {
  1534. if(defparams > 0) Error(_SC("function with default parameters cannot have variable number of parameters"));
  1535. funcstate->AddParameter(_fs->CreateString(_SC("vargv")), _scope.nested+1);
  1536. funcstate->_varparams = true;
  1537. Lex();
  1538. if(_token != _SC(')')) Error(_SC("expected ')'"));
  1539. break;
  1540. }
  1541. else {
  1542. paramname = Expect(TK_IDENTIFIER);
  1543. funcstate->AddParameter(paramname, _scope.nested+1);
  1544. if(_token == _SC('=')) {
  1545. Lex();
  1546. Expression();
  1547. funcstate->AddDefaultParam(_fs->TopTarget());
  1548. defparams++;
  1549. }
  1550. else {
  1551. if(defparams > 0) Error(_SC("expected '='"));
  1552. }
  1553. if(_token == _SC(',')) Lex();
  1554. else if(_token != _SC(')')) Error(_SC("expected ')' or ','"));
  1555. }
  1556. }
  1557. Expect(_SC(')'));
  1558. for(SQInteger n = 0; n < defparams; n++) {
  1559. _fs->PopTarget();
  1560. }
  1561. SQFuncState *currchunk = _fs;
  1562. _fs = funcstate;
  1563. if(lambda) {
  1564. Expression();
  1565. _fs->AddInstruction(_OP_RETURN, 1, _fs->PopTarget());}
  1566. else {
  1567. Statement(false);
  1568. }
  1569. funcstate->AddLineInfos(_lex._prevtoken == _SC('\n')?_lex._lasttokenline:_lex._currentline, _lineinfo, true);
  1570. funcstate->AddInstruction(_OP_RETURN, -1);
  1571. funcstate->SetStackSize(0);
  1572. SQFunctionProto *func = funcstate->BuildProto();
  1573. #ifdef _DEBUG_DUMP
  1574. funcstate->Dump(func);
  1575. #endif
  1576. _fs = currchunk;
  1577. _fs->_functions.push_back(func);
  1578. _fs->PopChildState();
  1579. }
  1580. void ResolveBreaks(SQFuncState *funcstate, SQInteger ntoresolve)
  1581. {
  1582. while(ntoresolve > 0) {
  1583. SQInteger pos = funcstate->_unresolvedbreaks.back();
  1584. funcstate->_unresolvedbreaks.pop_back();
  1585. //set the jmp instruction
  1586. funcstate->SetIntructionParams(pos, 0, funcstate->GetCurrentPos() - pos, 0);
  1587. ntoresolve--;
  1588. }
  1589. }
  1590. void ResolveContinues(SQFuncState *funcstate, SQInteger ntoresolve, SQInteger targetpos)
  1591. {
  1592. while(ntoresolve > 0) {
  1593. SQInteger pos = funcstate->_unresolvedcontinues.back();
  1594. funcstate->_unresolvedcontinues.pop_back();
  1595. //set the jmp instruction
  1596. funcstate->SetIntructionParams(pos, 0, targetpos - pos, 0);
  1597. ntoresolve--;
  1598. }
  1599. }
  1600. private:
  1601. SQInteger _token;
  1602. SQFuncState *_fs;
  1603. SQObjectPtr _sourcename;
  1604. SQLexer _lex;
  1605. bool _lineinfo;
  1606. bool _raiseerror;
  1607. SQInteger _debugline;
  1608. SQInteger _debugop;
  1609. SQExpState _es;
  1610. SQScope _scope;
  1611. SQChar *compilererror;
  1612. jmp_buf _errorjmp;
  1613. SQVM *_vm;
  1614. };
  1615. bool Compile(SQVM *vm,SQLEXREADFUNC rg, SQUserPointer up, const SQChar *sourcename, SQObjectPtr &out, bool raiseerror, bool lineinfo)
  1616. {
  1617. SQCompiler p(vm, rg, up, sourcename, raiseerror, lineinfo);
  1618. return p.Compile(out);
  1619. }
  1620. #endif