sqcompiler.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707
  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_IGNORE:
  893. //Warning("Keyword ignored \"%s\" at line %d:%d\n", _lex.Tok2Str(_token),
  894. // _lex._currentline, _lex._currentcolumn);
  895. Lex(); Factor();
  896. break;
  897. default: Error(_SC("expression expected"));
  898. }
  899. return -1;
  900. }
  901. void EmitLoadConstInt(SQInteger value,SQInteger target)
  902. {
  903. if(target < 0) {
  904. target = _fs->PushTarget();
  905. }
  906. if((value & (~((SQInteger)0xFFFFFFFF))) == 0) { //does it fit in 32 bits?
  907. _fs->AddInstruction(_OP_LOADINT, target,value);
  908. }
  909. else {
  910. _fs->AddInstruction(_OP_LOAD, target, _fs->GetNumericConstant(value));
  911. }
  912. }
  913. void EmitLoadConstFloat(SQFloat value,SQInteger target)
  914. {
  915. if(target < 0) {
  916. target = _fs->PushTarget();
  917. }
  918. if(sizeof(SQFloat) == sizeof(SQInt32)) {
  919. _fs->AddInstruction(_OP_LOADFLOAT, target,*((SQInt32 *)&value));
  920. }
  921. else {
  922. _fs->AddInstruction(_OP_LOAD, target, _fs->GetNumericConstant(value));
  923. }
  924. }
  925. void UnaryOP(SQOpcode op)
  926. {
  927. PrefixedExpr();
  928. SQInteger src = _fs->PopTarget();
  929. _fs->AddInstruction(op, _fs->PushTarget(), src);
  930. }
  931. bool NeedGet()
  932. {
  933. switch(_token) {
  934. case _SC('='): case _SC('('): case TK_NEWSLOT: case TK_MODEQ: case TK_MULEQ:
  935. case TK_DIVEQ: case TK_MINUSEQ: case TK_PLUSEQ: case TK_PLUSPLUS: case TK_MINUSMINUS:
  936. return false;
  937. }
  938. return (!_es.donot_get || ( _es.donot_get && (_token == _SC('.') || _token == _SC('['))));
  939. }
  940. void FunctionCallArgs()
  941. {
  942. SQInteger nargs = 1;//this
  943. while(_token != _SC(')')) {
  944. Expression();
  945. MoveIfCurrentTargetIsLocal();
  946. nargs++;
  947. if(_token == _SC(',')){
  948. Lex();
  949. if(_token == ')') Error(_SC("expression expected, found ')'"));
  950. }
  951. }
  952. Lex();
  953. for(SQInteger i = 0; i < (nargs - 1); i++) _fs->PopTarget();
  954. SQInteger stackbase = _fs->PopTarget();
  955. SQInteger closure = _fs->PopTarget();
  956. _fs->AddInstruction(_OP_CALL, _fs->PushTarget(), closure, stackbase, nargs);
  957. }
  958. void ParseTableOrClass(SQInteger separator,SQInteger terminator)
  959. {
  960. SQInteger tpos = _fs->GetCurrentPos(),nkeys = 0;
  961. while(_token != terminator) {
  962. bool hasattrs = false;
  963. bool isstatic = false;
  964. //check if is an attribute
  965. if(separator == ';') {
  966. if(_token == TK_ATTR_OPEN) {
  967. _fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(),0,NOT_TABLE); Lex();
  968. ParseTableOrClass(',',TK_ATTR_CLOSE);
  969. hasattrs = true;
  970. }
  971. if(_token == TK_STATIC) {
  972. isstatic = true;
  973. Lex();
  974. }
  975. }
  976. switch(_token) {
  977. case TK_FUNCTION:
  978. case TK_CONSTRUCTOR:{
  979. SQInteger tk = _token;
  980. Lex();
  981. SQObject id = tk == TK_FUNCTION ? Expect(TK_IDENTIFIER) : _fs->CreateString(_SC("constructor"));
  982. Expect(_SC('('));
  983. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(id));
  984. CreateFunction(id);
  985. _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, 0);
  986. }
  987. break;
  988. case _SC('['):
  989. Lex(); CommaExpr(); Expect(_SC(']'));
  990. Expect(_SC('=')); Expression();
  991. break;
  992. case TK_STRING_LITERAL: //JSON
  993. case TK_IDENTIFIER: {//JSON
  994. SQObjectPtr obj = GetTokenObject(_token);
  995. SQInteger next_token = _SC('=');
  996. if(separator == ',' && _token == _SC(':')){ //only works for tables
  997. next_token = _token;
  998. }
  999. Expect(next_token);
  1000. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(obj));
  1001. Expression();
  1002. break;
  1003. }
  1004. default :
  1005. ErrorIfNotToken(TK_IDENTIFIER);
  1006. }
  1007. if(_token == separator) Lex();//optional comma/semicolon
  1008. nkeys++;
  1009. SQInteger val = _fs->PopTarget();
  1010. SQInteger key = _fs->PopTarget();
  1011. SQInteger attrs = hasattrs ? _fs->PopTarget():-1;
  1012. assert((hasattrs && (attrs == key-1)) || !hasattrs);
  1013. unsigned char flags = (hasattrs?NEW_SLOT_ATTRIBUTES_FLAG:0)|(isstatic?NEW_SLOT_STATIC_FLAG:0);
  1014. SQInteger table = _fs->TopTarget(); //<<BECAUSE OF THIS NO COMMON EMIT FUNC IS POSSIBLE
  1015. if(separator == _SC(',')) { //hack recognizes a table from the separator
  1016. _fs->AddInstruction(_OP_NEWSLOT, 0xFF, table, key, val);
  1017. }
  1018. else {
  1019. _fs->AddInstruction(_OP_NEWSLOTA, flags, table, key, val); //this for classes only as it invokes _newmember
  1020. }
  1021. }
  1022. if(separator == _SC(',')) //hack recognizes a table from the separator
  1023. _fs->SetIntructionParam(tpos, 1, nkeys);
  1024. Lex();
  1025. }
  1026. void checkLocalNameScope(const SQObject &name, SQInteger scope){
  1027. SQInteger found = _fs->GetLocalVariable(name);
  1028. if(found >= 0){
  1029. SQLocalVarInfo &lvi = _fs->_vlocals[found];
  1030. if(lvi._scope == scope)
  1031. Error(_SC("local '%s' already declared"), _stringval(name));
  1032. else
  1033. Warning(_SC("WARNING: at line %d:%d local '%s' already declared will be shadowed\n"),
  1034. _lex._currentline, _lex._currentcolumn, _stringval(name));
  1035. }
  1036. else
  1037. {
  1038. found = _fs->FindOuterVariable(name);
  1039. if(found >= 0) Warning(_SC("WARNING: at line %d:%d outer variable '%s' already declared will be shadowed\n"),
  1040. _lex._currentline, _lex._currentcolumn, _stringval(name));
  1041. }
  1042. }
  1043. void LocalDeclStatement()
  1044. {
  1045. SQObject varname;
  1046. SQBool is_const_declaration = _token == TK_CONST;
  1047. SQInteger declType = _token;
  1048. Lex();
  1049. if( _token == TK_FUNCTION) {
  1050. Lex();
  1051. varname = Expect(TK_IDENTIFIER);
  1052. checkLocalNameScope(varname, _scope.nested);
  1053. Expect(_SC('('));
  1054. CreateFunction(varname,false);
  1055. _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, 0);
  1056. _fs->PopTarget();
  1057. _fs->PushLocalVariable(varname, _scope.nested, _VAR_CLOSURE);
  1058. return;
  1059. }
  1060. do {
  1061. varname = Expect(TK_IDENTIFIER);
  1062. checkLocalNameScope(varname, _scope.nested);
  1063. if(_token == _SC('=')) {
  1064. Lex(); Expression();
  1065. SQInteger src = _fs->PopTarget();
  1066. SQInteger dest = _fs->PushTarget();
  1067. if(dest != src) _fs->AddInstruction(_OP_MOVE, dest, src);
  1068. declType = _VAR_ANY;
  1069. }
  1070. else if(is_const_declaration) Error(_SC("const '%s' need an initializer"), _stringval(varname));
  1071. else{
  1072. SQInteger dest = _fs->PushTarget();
  1073. switch(declType){
  1074. case TK_LOCAL_CHAR_T:
  1075. case TK_LOCAL_WCHAR_T:
  1076. _fs->AddInstruction(_OP_LOADNULLS, dest,1);
  1077. declType = _VAR_STRING;
  1078. break;
  1079. case TK_LOCAL_BOOL_T:
  1080. //default value false
  1081. _fs->AddInstruction(_OP_LOADBOOL, dest,0);
  1082. declType = _VAR_BOOL;
  1083. break;
  1084. case TK_LOCAL_TABLE_T:
  1085. _fs->AddInstruction(_OP_LOADNULLS, dest,1);
  1086. declType = _VAR_TABLE;
  1087. break;
  1088. case TK_LOCAL_ARRAY_T:
  1089. _fs->AddInstruction(_OP_LOADNULLS, dest,1);
  1090. declType = _VAR_ARRAY;
  1091. break;
  1092. case TK_LOCAL_INT8_T:
  1093. case TK_LOCAL_INT16_T:
  1094. case TK_LOCAL_INT32_T:
  1095. case TK_LOCAL_INT64_T:
  1096. case TK_LOCAL_INT_T:
  1097. case TK_LOCAL_UINT8_T:
  1098. case TK_LOCAL_UINT16_T:
  1099. case TK_LOCAL_UINT32_T:
  1100. case TK_LOCAL_UINT64_T:
  1101. case TK_LOCAL_UINT_T:
  1102. //default value 0
  1103. _fs->AddInstruction(_OP_LOADINT, dest,0);
  1104. declType = _VAR_INTEGER;
  1105. break;
  1106. case TK_LOCAL_FLOAT_T:
  1107. case TK_LOCAL_DOUBLE_T:
  1108. case TK_LOCAL_LONG_DOUBLE_T:
  1109. //default value 0.0
  1110. _fs->AddInstruction(_OP_LOADFLOAT, dest,0);
  1111. declType = _VAR_FLOAT;
  1112. break;
  1113. //case TK_LOCAL:
  1114. default:
  1115. //default value null
  1116. _fs->AddInstruction(_OP_LOADNULLS, dest,1);
  1117. declType = _VAR_ANY;
  1118. }
  1119. }
  1120. _fs->PopTarget();
  1121. _fs->PushLocalVariable(varname, _scope.nested, is_const_declaration ? _VAR_CONST : declType);
  1122. if(_token == _SC(',')) Lex(); else break;
  1123. } while(1);
  1124. }
  1125. void IfStatement()
  1126. {
  1127. SQInteger jmppos;
  1128. bool haselse = false;
  1129. Lex(); Expect(_SC('(')); CommaExpr(true); Expect(_SC(')'));
  1130. _fs->AddInstruction(_OP_JZ, _fs->PopTarget());
  1131. SQInteger jnepos = _fs->GetCurrentPos();
  1132. BEGIN_SCOPE();
  1133. //there is a situation where the if statement has a statement enclosed by {}
  1134. //and after the closing "}" there is no newline or semicolom
  1135. //it's a valid construction but the compiler was complaining about it
  1136. //for now added "&& _token != TK_IDENTIFIER" to the check after "Statement()" call
  1137. /*
  1138. local color = "blue";
  1139. if(color == "yellow"){
  1140. print(color);
  1141. } print("Waht color is it ?");
  1142. */
  1143. Statement();
  1144. //
  1145. if(_token != _SC('}') && _token != TK_ELSE && _token != TK_IDENTIFIER) OptionalSemicolon();
  1146. END_SCOPE();
  1147. SQInteger endifblock = _fs->GetCurrentPos();
  1148. if(_token == TK_ELSE){
  1149. haselse = true;
  1150. BEGIN_SCOPE();
  1151. _fs->AddInstruction(_OP_JMP);
  1152. jmppos = _fs->GetCurrentPos();
  1153. Lex();
  1154. Statement(); if(_token != TK_IDENTIFIER) OptionalSemicolon();
  1155. END_SCOPE();
  1156. _fs->SetIntructionParam(jmppos, 1, _fs->GetCurrentPos() - jmppos);
  1157. }
  1158. _fs->SetIntructionParam(jnepos, 1, endifblock - jnepos + (haselse?1:0));
  1159. }
  1160. void WhileStatement()
  1161. {
  1162. SQInteger jzpos, jmppos;
  1163. jmppos = _fs->GetCurrentPos();
  1164. Lex(); Expect(_SC('(')); CommaExpr(true); Expect(_SC(')'));
  1165. BEGIN_BREAKBLE_BLOCK();
  1166. _fs->AddInstruction(_OP_JZ, _fs->PopTarget());
  1167. jzpos = _fs->GetCurrentPos();
  1168. BEGIN_SCOPE();
  1169. Statement();
  1170. END_SCOPE();
  1171. _fs->AddInstruction(_OP_JMP, 0, jmppos - _fs->GetCurrentPos() - 1);
  1172. _fs->SetIntructionParam(jzpos, 1, _fs->GetCurrentPos() - jzpos);
  1173. END_BREAKBLE_BLOCK(jmppos);
  1174. }
  1175. void DoWhileStatement()
  1176. {
  1177. Lex();
  1178. SQInteger jmptrg = _fs->GetCurrentPos();
  1179. BEGIN_BREAKBLE_BLOCK()
  1180. BEGIN_SCOPE();
  1181. Statement();
  1182. END_SCOPE();
  1183. //fix proposed by frosch to correct line number info in stack dumps
  1184. _fs->AddLineInfos(_lex._currentline, _lineinfo, true);
  1185. Expect(TK_WHILE);
  1186. SQInteger continuetrg = _fs->GetCurrentPos();
  1187. Expect(_SC('(')); CommaExpr(true); Expect(_SC(')'));
  1188. _fs->AddInstruction(_OP_JZ, _fs->PopTarget(), 1);
  1189. _fs->AddInstruction(_OP_JMP, 0, jmptrg - _fs->GetCurrentPos() - 1);
  1190. END_BREAKBLE_BLOCK(continuetrg);
  1191. }
  1192. void ForStatement()
  1193. {
  1194. Lex();
  1195. BEGIN_SCOPE();
  1196. Expect(_SC('('));
  1197. switch(_token){
  1198. case TK_LOCAL_CHAR_T:
  1199. case TK_LOCAL_WCHAR_T:
  1200. case TK_LOCAL_BOOL_T:
  1201. case TK_LOCAL_TABLE_T:
  1202. case TK_LOCAL_ARRAY_T:
  1203. case TK_LOCAL_INT8_T:
  1204. case TK_LOCAL_INT16_T:
  1205. case TK_LOCAL_INT32_T:
  1206. case TK_LOCAL_INT64_T:
  1207. case TK_LOCAL_INT_T:
  1208. case TK_LOCAL_UINT8_T:
  1209. case TK_LOCAL_UINT16_T:
  1210. case TK_LOCAL_UINT32_T:
  1211. case TK_LOCAL_UINT64_T:
  1212. case TK_LOCAL_UINT_T:
  1213. case TK_LOCAL_FLOAT_T:
  1214. case TK_LOCAL_DOUBLE_T:
  1215. case TK_LOCAL_LONG_DOUBLE_T:
  1216. case TK_LOCAL:
  1217. LocalDeclStatement();
  1218. break;
  1219. default:
  1220. if(_token != _SC(';')){
  1221. CommaExpr();
  1222. _fs->PopTarget();
  1223. }
  1224. }
  1225. Expect(_SC(';'));
  1226. _fs->SnoozeOpt();
  1227. SQInteger jmppos = _fs->GetCurrentPos();
  1228. SQInteger jzpos = -1;
  1229. if(_token != _SC(';')) { CommaExpr(); _fs->AddInstruction(_OP_JZ, _fs->PopTarget()); jzpos = _fs->GetCurrentPos(); }
  1230. Expect(_SC(';'));
  1231. _fs->SnoozeOpt();
  1232. SQInteger expstart = _fs->GetCurrentPos() + 1;
  1233. if(_token != _SC(')')) {
  1234. CommaExpr();
  1235. _fs->PopTarget();
  1236. }
  1237. Expect(_SC(')'));
  1238. _fs->SnoozeOpt();
  1239. SQInteger expend = _fs->GetCurrentPos();
  1240. SQInteger expsize = (expend - expstart) + 1;
  1241. SQInstructionVec exp;
  1242. if(expsize > 0) {
  1243. for(SQInteger i = 0; i < expsize; i++)
  1244. exp.push_back(_fs->GetInstruction(expstart + i));
  1245. _fs->PopInstructions(expsize);
  1246. }
  1247. BEGIN_BREAKBLE_BLOCK()
  1248. Statement();
  1249. SQInteger continuetrg = _fs->GetCurrentPos();
  1250. if(expsize > 0) {
  1251. for(SQInteger i = 0; i < expsize; i++)
  1252. _fs->AddInstruction(exp[i]);
  1253. }
  1254. _fs->AddInstruction(_OP_JMP, 0, jmppos - _fs->GetCurrentPos() - 1, 0);
  1255. if(jzpos> 0) _fs->SetIntructionParam(jzpos, 1, _fs->GetCurrentPos() - jzpos);
  1256. END_SCOPE();
  1257. END_BREAKBLE_BLOCK(continuetrg);
  1258. }
  1259. void ForEachStatement()
  1260. {
  1261. SQObject idxname, valname;
  1262. Lex(); Expect(_SC('(')); valname = Expect(TK_IDENTIFIER);
  1263. if(_token == _SC(',')) {
  1264. idxname = valname;
  1265. Lex(); valname = Expect(TK_IDENTIFIER);
  1266. }
  1267. else{
  1268. idxname = _fs->CreateString(_SC("@INDEX@"));
  1269. }
  1270. Expect(TK_IN);
  1271. //save the stack size
  1272. BEGIN_SCOPE();
  1273. //put the table in the stack(evaluate the table expression)
  1274. Expression(); Expect(_SC(')'));
  1275. SQInteger container = _fs->TopTarget();
  1276. //push the index local var
  1277. SQInteger indexpos = _fs->PushLocalVariable(idxname, _scope.nested);
  1278. _fs->AddInstruction(_OP_LOADNULLS, indexpos,1);
  1279. //push the value local var
  1280. SQInteger valuepos = _fs->PushLocalVariable(valname, _scope.nested);
  1281. _fs->AddInstruction(_OP_LOADNULLS, valuepos,1);
  1282. //push reference index
  1283. SQInteger itrpos = _fs->PushLocalVariable(_fs->CreateString(_SC("@ITERATOR@")), _scope.nested); //use invalid id to make it inaccessible
  1284. _fs->AddInstruction(_OP_LOADNULLS, itrpos,1);
  1285. SQInteger jmppos = _fs->GetCurrentPos();
  1286. _fs->AddInstruction(_OP_FOREACH, container, 0, indexpos);
  1287. SQInteger foreachpos = _fs->GetCurrentPos();
  1288. _fs->AddInstruction(_OP_POSTFOREACH, container, 0, indexpos);
  1289. //generate the statement code
  1290. BEGIN_BREAKBLE_BLOCK()
  1291. Statement();
  1292. _fs->AddInstruction(_OP_JMP, 0, jmppos - _fs->GetCurrentPos() - 1);
  1293. _fs->SetIntructionParam(foreachpos, 1, _fs->GetCurrentPos() - foreachpos);
  1294. _fs->SetIntructionParam(foreachpos + 1, 1, _fs->GetCurrentPos() - foreachpos);
  1295. END_BREAKBLE_BLOCK(foreachpos - 1);
  1296. //restore the local variable stack(remove index,val and ref idx)
  1297. _fs->PopTarget();
  1298. END_SCOPE();
  1299. }
  1300. void SwitchStatement()
  1301. {
  1302. Lex(); Expect(_SC('(')); CommaExpr(true); Expect(_SC(')'));
  1303. Expect(_SC('{'));
  1304. SQInteger expr = _fs->TopTarget();
  1305. bool bfirst = true;
  1306. SQInteger tonextcondjmp = -1;
  1307. SQInteger skipcondjmp = -1;
  1308. SQInteger __nbreaks__ = _fs->_unresolvedbreaks.size();
  1309. _fs->_breaktargets.push_back(0);
  1310. while(_token == TK_CASE) {
  1311. if(!bfirst) {
  1312. _fs->AddInstruction(_OP_JMP, 0, 0);
  1313. skipcondjmp = _fs->GetCurrentPos();
  1314. _fs->SetIntructionParam(tonextcondjmp, 1, _fs->GetCurrentPos() - tonextcondjmp);
  1315. }
  1316. //condition
  1317. Lex(); Expression(); Expect(_SC(':'));
  1318. SQInteger trg = _fs->PopTarget();
  1319. _fs->AddInstruction(_OP_EQ, trg, trg, expr);
  1320. _fs->AddInstruction(_OP_JZ, trg, 0);
  1321. //end condition
  1322. if(skipcondjmp != -1) {
  1323. _fs->SetIntructionParam(skipcondjmp, 1, (_fs->GetCurrentPos() - skipcondjmp));
  1324. }
  1325. tonextcondjmp = _fs->GetCurrentPos();
  1326. BEGIN_SCOPE();
  1327. Statements();
  1328. END_SCOPE();
  1329. bfirst = false;
  1330. }
  1331. if(tonextcondjmp != -1)
  1332. _fs->SetIntructionParam(tonextcondjmp, 1, _fs->GetCurrentPos() - tonextcondjmp);
  1333. if(_token == TK_DEFAULT) {
  1334. Lex(); Expect(_SC(':'));
  1335. BEGIN_SCOPE();
  1336. Statements();
  1337. END_SCOPE();
  1338. }
  1339. Expect(_SC('}'));
  1340. _fs->PopTarget();
  1341. __nbreaks__ = _fs->_unresolvedbreaks.size() - __nbreaks__;
  1342. if(__nbreaks__ > 0)ResolveBreaks(_fs, __nbreaks__);
  1343. _fs->_breaktargets.pop_back();
  1344. }
  1345. void FunctionStatement()
  1346. {
  1347. SQObject id;
  1348. Lex(); id = Expect(TK_IDENTIFIER);
  1349. _fs->PushTarget(0);
  1350. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(id));
  1351. if(_token == TK_DOUBLE_COLON) Emit2ArgsOP(_OP_GET);
  1352. while(_token == TK_DOUBLE_COLON) {
  1353. Lex();
  1354. id = Expect(TK_IDENTIFIER);
  1355. _fs->AddInstruction(_OP_LOAD, _fs->PushTarget(), _fs->GetConstant(id));
  1356. if(_token == TK_DOUBLE_COLON) Emit2ArgsOP(_OP_GET);
  1357. }
  1358. Expect(_SC('('));
  1359. CreateFunction(id);
  1360. _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, 0);
  1361. EmitDerefOp(_OP_NEWSLOT);
  1362. _fs->PopTarget();
  1363. }
  1364. void ClassStatement()
  1365. {
  1366. SQExpState es;
  1367. Lex();
  1368. es = _es;
  1369. _es.donot_get = true;
  1370. PrefixedExpr();
  1371. if(_es.etype == EXPR) {
  1372. Error(_SC("invalid class name"));
  1373. }
  1374. else if(_es.etype == OBJECT || _es.etype == BASE) {
  1375. ClassExp();
  1376. EmitDerefOp(_OP_NEWSLOT);
  1377. _fs->PopTarget();
  1378. }
  1379. else {
  1380. Error(_SC("cannot create a class in a local with the syntax(class <local>)"));
  1381. }
  1382. _es = es;
  1383. }
  1384. SQObject ExpectScalar()
  1385. {
  1386. SQObject val;
  1387. val._type = OT_NULL; val._unVal.nInteger = 0; //shut up GCC 4.x
  1388. switch(_token) {
  1389. case TK_INTEGER:
  1390. val._type = OT_INTEGER;
  1391. val._unVal.nInteger = _lex._nvalue;
  1392. break;
  1393. case TK_FLOAT:
  1394. val._type = OT_FLOAT;
  1395. val._unVal.fFloat = _lex._fvalue;
  1396. break;
  1397. case TK_STRING_LITERAL:
  1398. val = _fs->CreateString(_lex._svalue,_lex._longstr.size()-1);
  1399. break;
  1400. case '-':
  1401. Lex();
  1402. switch(_token)
  1403. {
  1404. case TK_INTEGER:
  1405. val._type = OT_INTEGER;
  1406. val._unVal.nInteger = -_lex._nvalue;
  1407. break;
  1408. case TK_FLOAT:
  1409. val._type = OT_FLOAT;
  1410. val._unVal.fFloat = -_lex._fvalue;
  1411. break;
  1412. default:
  1413. Error(_SC("scalar expected : integer,float"));
  1414. }
  1415. break;
  1416. default:
  1417. Error(_SC("scalar expected : integer,float or string"));
  1418. }
  1419. Lex();
  1420. return val;
  1421. }
  1422. void EnumStatement()
  1423. {
  1424. Lex();
  1425. SQObject id = Expect(TK_IDENTIFIER);
  1426. Expect(_SC('{'));
  1427. //checkLocalNameScope(id, _scope.nested);
  1428. SQTable *enums = _table(_ss(_vm)->_consts);
  1429. SQObjectPtr strongid = id;
  1430. if(enums->Exists(strongid)) {
  1431. strongid.Null();
  1432. Error(_SC("constant '%s' already exists"), _stringval(id));
  1433. }
  1434. SQObject table = _fs->CreateTable();
  1435. //_fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(),0,NOT_TABLE);
  1436. SQInteger nval = 0;
  1437. while(_token != _SC('}')) {
  1438. SQObject key = Expect(TK_IDENTIFIER);
  1439. SQObject val;
  1440. if(_token == _SC('=')) {
  1441. Lex();
  1442. val = ExpectScalar();
  1443. }
  1444. else {
  1445. val._type = OT_INTEGER;
  1446. val._unVal.nInteger = nval++;
  1447. }
  1448. //SQInteger table = _fs->TopTarget(); //<<BECAUSE OF THIS NO COMMON EMIT FUNC IS POSSIBLE
  1449. //_fs->AddInstruction(_OP_NEWSLOT, 0xFF, table, key, val);
  1450. _table(table)->NewSlot(SQObjectPtr(key),SQObjectPtr(val));
  1451. if(_token == ',') Lex();
  1452. }
  1453. enums->NewSlot(SQObjectPtr(strongid),SQObjectPtr(table));
  1454. strongid.Null();
  1455. Lex();
  1456. }
  1457. void TryCatchStatement()
  1458. {
  1459. SQObject exid;
  1460. Lex();
  1461. _fs->AddInstruction(_OP_PUSHTRAP,0,0);
  1462. _fs->_traps++;
  1463. if(_fs->_breaktargets.size()) _fs->_breaktargets.top()++;
  1464. if(_fs->_continuetargets.size()) _fs->_continuetargets.top()++;
  1465. SQInteger trappos = _fs->GetCurrentPos();
  1466. {
  1467. BEGIN_SCOPE();
  1468. Statement();
  1469. END_SCOPE();
  1470. }
  1471. _fs->_traps--;
  1472. _fs->AddInstruction(_OP_POPTRAP, 1, 0);
  1473. if(_fs->_breaktargets.size()) _fs->_breaktargets.top()--;
  1474. if(_fs->_continuetargets.size()) _fs->_continuetargets.top()--;
  1475. _fs->AddInstruction(_OP_JMP, 0, 0);
  1476. SQInteger jmppos = _fs->GetCurrentPos();
  1477. _fs->SetIntructionParam(trappos, 1, (_fs->GetCurrentPos() - trappos));
  1478. Expect(TK_CATCH); Expect(_SC('(')); exid = Expect(TK_IDENTIFIER); Expect(_SC(')'));
  1479. {
  1480. BEGIN_SCOPE();
  1481. SQInteger ex_target = _fs->PushLocalVariable(exid, _scope.nested);
  1482. _fs->SetIntructionParam(trappos, 0, ex_target);
  1483. Statement();
  1484. _fs->SetIntructionParams(jmppos, 0, (_fs->GetCurrentPos() - jmppos), 0);
  1485. END_SCOPE();
  1486. }
  1487. }
  1488. void FunctionExp(SQInteger ftype,bool lambda = false)
  1489. {
  1490. Lex(); Expect(_SC('('));
  1491. SQObjectPtr dummy;
  1492. CreateFunction(dummy,lambda);
  1493. _fs->AddInstruction(_OP_CLOSURE, _fs->PushTarget(), _fs->_functions.size() - 1, ftype == TK_FUNCTION?0:1);
  1494. }
  1495. void ClassExp()
  1496. {
  1497. SQInteger base = -1;
  1498. SQInteger attrs = -1;
  1499. if(_token == TK_EXTENDS) {
  1500. Lex(); Expression();
  1501. base = _fs->TopTarget();
  1502. }
  1503. if(_token == TK_ATTR_OPEN) {
  1504. Lex();
  1505. _fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(),0,NOT_TABLE);
  1506. ParseTableOrClass(_SC(','),TK_ATTR_CLOSE);
  1507. attrs = _fs->TopTarget();
  1508. }
  1509. Expect(_SC('{'));
  1510. if(attrs != -1) _fs->PopTarget();
  1511. if(base != -1) _fs->PopTarget();
  1512. _fs->AddInstruction(_OP_NEWOBJ, _fs->PushTarget(), base, attrs,NOT_CLASS);
  1513. ParseTableOrClass(_SC(';'),_SC('}'));
  1514. }
  1515. void DeleteExpr()
  1516. {
  1517. SQExpState es;
  1518. Lex();
  1519. es = _es;
  1520. _es.donot_get = true;
  1521. PrefixedExpr();
  1522. if(_es.etype==EXPR) Error(_SC("can't delete an expression"));
  1523. if(_es.etype==OBJECT || _es.etype==BASE) {
  1524. Emit2ArgsOP(_OP_DELETE);
  1525. }
  1526. else {
  1527. Error(_SC("cannot delete an (outer) local"));
  1528. }
  1529. _es = es;
  1530. }
  1531. void PrefixIncDec(SQInteger token)
  1532. {
  1533. SQExpState es;
  1534. SQInteger diff = (token==TK_MINUSMINUS) ? -1 : 1;
  1535. Lex();
  1536. es = _es;
  1537. _es.donot_get = true;
  1538. PrefixedExpr();
  1539. if(_es.etype==EXPR) {
  1540. Error(_SC("can't '++' or '--' an expression"));
  1541. }
  1542. else if(_es.etype==OBJECT || _es.etype==BASE) {
  1543. Emit2ArgsOP(_OP_INC, diff);
  1544. }
  1545. else if(_es.etype==LOCAL) {
  1546. SQInteger src = _fs->TopTarget();
  1547. _fs->AddInstruction(_OP_INCL, src, src, 0, diff);
  1548. }
  1549. else if(_es.etype==OUTER) {
  1550. SQInteger tmp = _fs->PushTarget();
  1551. _fs->AddInstruction(_OP_GETOUTER, tmp, _es.epos);
  1552. _fs->AddInstruction(_OP_INCL, tmp, tmp, 0, diff);
  1553. _fs->AddInstruction(_OP_SETOUTER, tmp, _es.epos, tmp);
  1554. }
  1555. _es = es;
  1556. }
  1557. void CreateFunction(SQObject &name,bool lambda = false)
  1558. {
  1559. SQFuncState *funcstate = _fs->PushChildState(_ss(_vm));
  1560. funcstate->_name = name;
  1561. SQObject paramname;
  1562. funcstate->AddParameter(_fs->CreateString(_SC("this")), _scope.nested+1);
  1563. funcstate->_sourcename = _sourcename;
  1564. SQInteger defparams = 0;
  1565. SQInteger is_reference = 0;
  1566. while(_token!=_SC(')')) {
  1567. is_reference = 0; //reset is_reference
  1568. if(_token == TK_VARPARAMS) {
  1569. if(defparams > 0) Error(_SC("function with default parameters cannot have variable number of parameters"));
  1570. funcstate->AddParameter(_fs->CreateString(_SC("vargv")), _scope.nested+1);
  1571. funcstate->_varparams = true;
  1572. Lex();
  1573. if(_token != _SC(')')) Error(_SC("expected ')'"));
  1574. break;
  1575. }
  1576. else {
  1577. if(_token == _SC('&')){
  1578. is_reference = 1;
  1579. Lex();
  1580. }
  1581. paramname = Expect(TK_IDENTIFIER);
  1582. funcstate->AddParameter(paramname, _scope.nested+1, is_reference ? _VAR_REFERENCE : _VAR_ANY);
  1583. if(_token == _SC('=')) {
  1584. if(is_reference) Error(_SC("parameter passed by reference can't have default value"));
  1585. Lex();
  1586. Expression();
  1587. funcstate->AddDefaultParam(_fs->TopTarget());
  1588. defparams++;
  1589. }
  1590. else {
  1591. if(defparams > 0) Error(_SC("expected '='"));
  1592. }
  1593. if(_token == _SC(',')) Lex();
  1594. else if(_token != _SC(')')) Error(_SC("expected ')' or ','"));
  1595. }
  1596. }
  1597. Expect(_SC(')'));
  1598. for(SQInteger n = 0; n < defparams; n++) {
  1599. _fs->PopTarget();
  1600. }
  1601. SQFuncState *currchunk = _fs;
  1602. _fs = funcstate;
  1603. if(lambda) {
  1604. Expression();
  1605. _fs->AddInstruction(_OP_RETURN, 1, _fs->PopTarget());}
  1606. else {
  1607. Statement(false);
  1608. }
  1609. funcstate->AddLineInfos(_lex._prevtoken == _SC('\n')?_lex._lasttokenline:_lex._currentline, _lineinfo, true);
  1610. funcstate->AddInstruction(_OP_RETURN, -1);
  1611. funcstate->SetStackSize(0);
  1612. SQFunctionProto *func = funcstate->BuildProto();
  1613. #ifdef _DEBUG_DUMP
  1614. funcstate->Dump(func);
  1615. #endif
  1616. _fs = currchunk;
  1617. _fs->_functions.push_back(func);
  1618. _fs->PopChildState();
  1619. }
  1620. void ResolveBreaks(SQFuncState *funcstate, SQInteger ntoresolve)
  1621. {
  1622. while(ntoresolve > 0) {
  1623. SQInteger pos = funcstate->_unresolvedbreaks.back();
  1624. funcstate->_unresolvedbreaks.pop_back();
  1625. //set the jmp instruction
  1626. funcstate->SetIntructionParams(pos, 0, funcstate->GetCurrentPos() - pos, 0);
  1627. ntoresolve--;
  1628. }
  1629. }
  1630. void ResolveContinues(SQFuncState *funcstate, SQInteger ntoresolve, SQInteger targetpos)
  1631. {
  1632. while(ntoresolve > 0) {
  1633. SQInteger pos = funcstate->_unresolvedcontinues.back();
  1634. funcstate->_unresolvedcontinues.pop_back();
  1635. //set the jmp instruction
  1636. funcstate->SetIntructionParams(pos, 0, targetpos - pos, 0);
  1637. ntoresolve--;
  1638. }
  1639. }
  1640. private:
  1641. SQInteger _token;
  1642. SQFuncState *_fs;
  1643. SQObjectPtr _sourcename;
  1644. SQLexer _lex;
  1645. bool _lineinfo;
  1646. bool _raiseerror;
  1647. SQInteger _debugline;
  1648. SQInteger _debugop;
  1649. SQExpState _es;
  1650. SQScope _scope;
  1651. SQChar *compilererror;
  1652. jmp_buf _errorjmp;
  1653. SQVM *_vm;
  1654. };
  1655. bool Compile(SQVM *vm,SQLEXREADFUNC rg, SQUserPointer up, const SQChar *sourcename, SQObjectPtr &out, bool raiseerror, bool lineinfo)
  1656. {
  1657. SQCompiler p(vm, rg, up, sourcename, raiseerror, lineinfo);
  1658. return p.Compile(out);
  1659. }
  1660. #endif