sqcompiler.cpp 73 KB

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