sqcompiler.cpp 67 KB

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