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