sqcompiler.cpp 110 KB

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