sqcompiler.cpp 106 KB

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