sqcompiler.cpp 56 KB

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