sqcompiler.cpp 55 KB

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