sqcompiler.cpp 78 KB

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