sqcompiler.cpp 111 KB

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