sqcompiler.cpp 116 KB

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