sqcompiler.cpp 113 KB

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