sqcompiler.cpp 55 KB

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