sqcompiler.cpp 52 KB

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