sqcompiler.cpp 74 KB

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