sqcompiler.cpp 81 KB

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