sqcompiler.cpp 80 KB

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