sqcompiler.cpp 85 KB

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