sqcompiler.cpp 85 KB

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