sqcompiler.cpp 88 KB

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