sqcompiler.cpp 71 KB

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