sqcompiler.cpp 52 KB

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