sqcompiler.cpp 114 KB

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