sqcompiler.cpp 72 KB

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