sqcompiler.cpp 67 KB

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