sqcompiler.cpp 117 KB

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