sqcompiler.cpp 85 KB

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