sqcompiler.cpp 59 KB

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