sqcompiler.cpp 88 KB

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