sqcompiler.cpp 79 KB

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