lparser.c 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983
  1. /*
  2. ** $Id: lparser.c $
  3. ** Lua Parser
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define lparser_c
  7. #define LUA_CORE
  8. #include "lprefix.h"
  9. #include <limits.h>
  10. #include <string.h>
  11. #include "lua.h"
  12. #include "lcode.h"
  13. #include "ldebug.h"
  14. #include "ldo.h"
  15. #include "lfunc.h"
  16. #include "llex.h"
  17. #include "lmem.h"
  18. #include "lobject.h"
  19. #include "lopcodes.h"
  20. #include "lparser.h"
  21. #include "lstate.h"
  22. #include "lstring.h"
  23. #include "ltable.h"
  24. /* maximum number of local variables per function (must be smaller
  25. than 250, due to the bytecode format) */
  26. #define MAXVARS 200
  27. #define hasmultret(k) ((k) == VCALL || (k) == VVARARG)
  28. /* because all strings are unified by the scanner, the parser
  29. can use pointer equality for string equality */
  30. #define eqstr(a,b) ((a) == (b))
  31. /*
  32. ** nodes for block list (list of active blocks)
  33. */
  34. typedef struct BlockCnt {
  35. struct BlockCnt *previous; /* chain */
  36. int firstlabel; /* index of first label in this block */
  37. int firstgoto; /* index of first pending goto in this block */
  38. lu_byte nactvar; /* # active locals outside the block */
  39. lu_byte upval; /* true if some variable in the block is an upvalue */
  40. lu_byte isloop; /* true if 'block' is a loop */
  41. lu_byte insidetbc; /* true if inside the scope of a to-be-closed var. */
  42. } BlockCnt;
  43. /*
  44. ** prototypes for recursive non-terminal functions
  45. */
  46. static void statement (LexState *ls);
  47. static void expr (LexState *ls, expdesc *v);
  48. static l_noret error_expected (LexState *ls, int token) {
  49. luaX_syntaxerror(ls,
  50. luaO_pushfstring(ls->L, "%s expected", luaX_token2str(ls, token)));
  51. }
  52. static l_noret errorlimit (FuncState *fs, int limit, const char *what) {
  53. lua_State *L = fs->ls->L;
  54. const char *msg;
  55. int line = fs->f->linedefined;
  56. const char *where = (line == 0)
  57. ? "main function"
  58. : luaO_pushfstring(L, "function at line %d", line);
  59. msg = luaO_pushfstring(L, "too many %s (limit is %d) in %s",
  60. what, limit, where);
  61. luaX_syntaxerror(fs->ls, msg);
  62. }
  63. static void checklimit (FuncState *fs, int v, int l, const char *what) {
  64. if (v > l) errorlimit(fs, l, what);
  65. }
  66. /*
  67. ** Test whether next token is 'c'; if so, skip it.
  68. */
  69. static int testnext (LexState *ls, int c) {
  70. if (ls->t.token == c) {
  71. luaX_next(ls);
  72. return 1;
  73. }
  74. else return 0;
  75. }
  76. /*
  77. ** Check that next token is 'c'.
  78. */
  79. static void check (LexState *ls, int c) {
  80. if (ls->t.token != c)
  81. error_expected(ls, c);
  82. }
  83. /*
  84. ** Check that next token is 'c' and skip it.
  85. */
  86. static void checknext (LexState *ls, int c) {
  87. check(ls, c);
  88. luaX_next(ls);
  89. }
  90. #define check_condition(ls,c,msg) { if (!(c)) luaX_syntaxerror(ls, msg); }
  91. /*
  92. ** Check that next token is 'what' and skip it. In case of error,
  93. ** raise an error that the expected 'what' should match a 'who'
  94. ** in line 'where' (if that is not the current line).
  95. */
  96. static void check_match (LexState *ls, int what, int who, int where) {
  97. if (unlikely(!testnext(ls, what))) {
  98. if (where == ls->linenumber) /* all in the same line? */
  99. error_expected(ls, what); /* do not need a complex message */
  100. else {
  101. luaX_syntaxerror(ls, luaO_pushfstring(ls->L,
  102. "%s expected (to close %s at line %d)",
  103. luaX_token2str(ls, what), luaX_token2str(ls, who), where));
  104. }
  105. }
  106. }
  107. static TString *str_checkname (LexState *ls) {
  108. TString *ts;
  109. check(ls, TK_NAME);
  110. ts = ls->t.seminfo.ts;
  111. luaX_next(ls);
  112. return ts;
  113. }
  114. static void init_exp (expdesc *e, expkind k, int i) {
  115. e->f = e->t = NO_JUMP;
  116. e->k = k;
  117. e->u.info = i;
  118. }
  119. static void codestring (expdesc *e, TString *s) {
  120. e->f = e->t = NO_JUMP;
  121. e->k = VKSTR;
  122. e->u.strval = s;
  123. }
  124. static void codename (LexState *ls, expdesc *e) {
  125. codestring(e, str_checkname(ls));
  126. }
  127. /*
  128. ** Register a new local variable in the active 'Proto' (for debug
  129. ** information).
  130. */
  131. static int registerlocalvar (LexState *ls, FuncState *fs, TString *varname) {
  132. Proto *f = fs->f;
  133. int oldsize = f->sizelocvars;
  134. luaM_growvector(ls->L, f->locvars, fs->ndebugvars, f->sizelocvars,
  135. LocVar, SHRT_MAX, "local variables");
  136. while (oldsize < f->sizelocvars)
  137. f->locvars[oldsize++].varname = NULL;
  138. f->locvars[fs->ndebugvars].varname = varname;
  139. f->locvars[fs->ndebugvars].startpc = fs->pc;
  140. luaC_objbarrier(ls->L, f, varname);
  141. return fs->ndebugvars++;
  142. }
  143. /*
  144. ** Create a new local variable with the given 'name'. Return its index
  145. ** in the function.
  146. */
  147. static int new_localvar (LexState *ls, TString *name) {
  148. lua_State *L = ls->L;
  149. FuncState *fs = ls->fs;
  150. Dyndata *dyd = ls->dyd;
  151. Vardesc *var;
  152. checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal,
  153. MAXVARS, "local variables");
  154. luaM_growvector(L, dyd->actvar.arr, dyd->actvar.n + 1,
  155. dyd->actvar.size, Vardesc, USHRT_MAX, "local variables");
  156. var = &dyd->actvar.arr[dyd->actvar.n++];
  157. var->vd.kind = VDKREG; /* default */
  158. var->vd.name = name;
  159. return dyd->actvar.n - 1 - fs->firstlocal;
  160. }
  161. #define new_localvarliteral(ls,v) \
  162. new_localvar(ls, \
  163. luaX_newstring(ls, "" v, (sizeof(v)/sizeof(char)) - 1));
  164. /*
  165. ** Return the "variable description" (Vardesc) of a given
  166. ** variable
  167. */
  168. static Vardesc *getlocalvardesc (FuncState *fs, int i) {
  169. return &fs->ls->dyd->actvar.arr[fs->firstlocal + i];
  170. }
  171. /*
  172. ** Convert 'nvar' (number of active variables at some point) to
  173. ** number of variables in the stack at that point.
  174. */
  175. static int stacklevel (FuncState *fs, int nvar) {
  176. while (nvar > 0) {
  177. Vardesc *vd = getlocalvardesc(fs, nvar - 1);
  178. if (vd->vd.kind != RDKCTC) /* is in the stack? */
  179. return vd->vd.sidx + 1;
  180. else
  181. nvar--; /* try previous variable */
  182. }
  183. return 0; /* no variables */
  184. }
  185. /*
  186. ** Return the number of variables in the stack for function 'fs'
  187. */
  188. int luaY_nvarstack (FuncState *fs) {
  189. return stacklevel(fs, fs->nactvar);
  190. }
  191. /*
  192. ** Get the debug-information entry for current variable 'i'.
  193. */
  194. static LocVar *localdebuginfo (FuncState *fs, int i) {
  195. Vardesc *vd = getlocalvardesc(fs, i);
  196. if (vd->vd.kind == RDKCTC)
  197. return NULL; /* no debug info. for constants */
  198. else {
  199. int idx = vd->vd.pidx;
  200. lua_assert(idx < fs->ndebugvars);
  201. return &fs->f->locvars[idx];
  202. }
  203. }
  204. static void init_var (FuncState *fs, expdesc *e, int i) {
  205. e->f = e->t = NO_JUMP;
  206. e->k = VLOCAL;
  207. e->u.var.vidx = i;
  208. e->u.var.sidx = getlocalvardesc(fs, i)->vd.sidx;
  209. }
  210. static void check_readonly (LexState *ls, expdesc *e) {
  211. FuncState *fs = ls->fs;
  212. TString *varname = NULL; /* to be set if variable is const */
  213. switch (e->k) {
  214. case VCONST: {
  215. varname = ls->dyd->actvar.arr[e->u.info].vd.name;
  216. break;
  217. }
  218. case VLOCAL: {
  219. Vardesc *vardesc = getlocalvardesc(fs, e->u.var.vidx);
  220. if (vardesc->vd.kind != VDKREG) /* not a regular variable? */
  221. varname = vardesc->vd.name;
  222. break;
  223. }
  224. case VUPVAL: {
  225. Upvaldesc *up = &fs->f->upvalues[e->u.info];
  226. if (up->kind != VDKREG)
  227. varname = up->name;
  228. break;
  229. }
  230. default:
  231. return; /* other cases cannot be read-only */
  232. }
  233. if (varname) {
  234. const char *msg = luaO_pushfstring(ls->L,
  235. "attempt to assign to const variable '%s'", getstr(varname));
  236. luaK_semerror(ls, msg); /* error */
  237. }
  238. }
  239. /*
  240. ** Start the scope for the last 'nvars' created variables.
  241. */
  242. static void adjustlocalvars (LexState *ls, int nvars) {
  243. FuncState *fs = ls->fs;
  244. int stklevel = luaY_nvarstack(fs);
  245. int i;
  246. for (i = 0; i < nvars; i++) {
  247. int varidx = fs->nactvar++;
  248. Vardesc *var = getlocalvardesc(fs, varidx);
  249. var->vd.sidx = stklevel++;
  250. var->vd.pidx = registerlocalvar(ls, fs, var->vd.name);
  251. }
  252. }
  253. /*
  254. ** Close the scope for all variables up to level 'tolevel'.
  255. ** (debug info.)
  256. */
  257. static void removevars (FuncState *fs, int tolevel) {
  258. fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel);
  259. while (fs->nactvar > tolevel) {
  260. LocVar *var = localdebuginfo(fs, --fs->nactvar);
  261. if (var) /* does it have debug information? */
  262. var->endpc = fs->pc;
  263. }
  264. }
  265. /*
  266. ** Search the upvalues of the function 'fs' for one
  267. ** with the given 'name'.
  268. */
  269. static int searchupvalue (FuncState *fs, TString *name) {
  270. int i;
  271. Upvaldesc *up = fs->f->upvalues;
  272. for (i = 0; i < fs->nups; i++) {
  273. if (eqstr(up[i].name, name)) return i;
  274. }
  275. return -1; /* not found */
  276. }
  277. static Upvaldesc *allocupvalue (FuncState *fs) {
  278. Proto *f = fs->f;
  279. int oldsize = f->sizeupvalues;
  280. checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues");
  281. luaM_growvector(fs->ls->L, f->upvalues, fs->nups, f->sizeupvalues,
  282. Upvaldesc, MAXUPVAL, "upvalues");
  283. while (oldsize < f->sizeupvalues)
  284. f->upvalues[oldsize++].name = NULL;
  285. return &f->upvalues[fs->nups++];
  286. }
  287. static int newupvalue (FuncState *fs, TString *name, expdesc *v) {
  288. Upvaldesc *up = allocupvalue(fs);
  289. FuncState *prev = fs->prev;
  290. if (v->k == VLOCAL) {
  291. up->instack = 1;
  292. up->idx = v->u.var.sidx;
  293. up->kind = getlocalvardesc(prev, v->u.var.vidx)->vd.kind;
  294. lua_assert(eqstr(name, getlocalvardesc(prev, v->u.var.vidx)->vd.name));
  295. }
  296. else {
  297. up->instack = 0;
  298. up->idx = cast_byte(v->u.info);
  299. up->kind = prev->f->upvalues[v->u.info].kind;
  300. lua_assert(eqstr(name, prev->f->upvalues[v->u.info].name));
  301. }
  302. up->name = name;
  303. luaC_objbarrier(fs->ls->L, fs->f, name);
  304. return fs->nups - 1;
  305. }
  306. /*
  307. ** Look for an active local variable with the name 'n' in the
  308. ** function 'fs'.
  309. */
  310. static int searchvar (FuncState *fs, TString *n, expdesc *var) {
  311. int i;
  312. for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) {
  313. Vardesc *vd = getlocalvardesc(fs, i);
  314. if (eqstr(n, vd->vd.name)) { /* found? */
  315. if (vd->vd.kind == RDKCTC) /* compile-time constant? */
  316. init_exp(var, VCONST, fs->firstlocal + i);
  317. else /* real variable */
  318. init_var(fs, var, i);
  319. return var->k;
  320. }
  321. }
  322. return -1; /* not found */
  323. }
  324. /*
  325. ** Mark block where variable at given level was defined
  326. ** (to emit close instructions later).
  327. */
  328. static void markupval (FuncState *fs, int level) {
  329. BlockCnt *bl = fs->bl;
  330. while (bl->nactvar > level)
  331. bl = bl->previous;
  332. bl->upval = 1;
  333. fs->needclose = 1;
  334. }
  335. /*
  336. ** Find a variable with the given name 'n'. If it is an upvalue, add
  337. ** this upvalue into all intermediate functions. If it is a global, set
  338. ** 'var' as 'void' as a flag.
  339. */
  340. static void singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {
  341. if (fs == NULL) /* no more levels? */
  342. init_exp(var, VVOID, 0); /* default is global */
  343. else {
  344. int v = searchvar(fs, n, var); /* look up locals at current level */
  345. if (v >= 0) { /* found? */
  346. if (v == VLOCAL && !base)
  347. markupval(fs, var->u.var.vidx); /* local will be used as an upval */
  348. }
  349. else { /* not found as local at current level; try upvalues */
  350. int idx = searchupvalue(fs, n); /* try existing upvalues */
  351. if (idx < 0) { /* not found? */
  352. singlevaraux(fs->prev, n, var, 0); /* try upper levels */
  353. if (var->k == VLOCAL || var->k == VUPVAL) /* local or upvalue? */
  354. idx = newupvalue(fs, n, var); /* will be a new upvalue */
  355. else /* it is a global or a constant */
  356. return; /* don't need to do anything at this level */
  357. }
  358. init_exp(var, VUPVAL, idx); /* new or old upvalue */
  359. }
  360. }
  361. }
  362. /*
  363. ** Find a variable with the given name 'n', handling global variables
  364. ** too.
  365. */
  366. static void singlevar (LexState *ls, expdesc *var) {
  367. TString *varname = str_checkname(ls);
  368. FuncState *fs = ls->fs;
  369. singlevaraux(fs, varname, var, 1);
  370. if (var->k == VVOID) { /* global name? */
  371. expdesc key;
  372. singlevaraux(fs, ls->envn, var, 1); /* get environment variable */
  373. lua_assert(var->k != VVOID); /* this one must exist */
  374. codestring(&key, varname); /* key is variable name */
  375. luaK_indexed(fs, var, &key); /* env[varname] */
  376. }
  377. }
  378. /*
  379. ** Adjust the number of results from an expression list 'e' with 'nexps'
  380. ** expressions to 'nvars' values.
  381. */
  382. static void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {
  383. FuncState *fs = ls->fs;
  384. int needed = nvars - nexps; /* extra values needed */
  385. if (hasmultret(e->k)) { /* last expression has multiple returns? */
  386. int extra = needed + 1; /* discount last expression itself */
  387. if (extra < 0)
  388. extra = 0;
  389. luaK_setreturns(fs, e, extra); /* last exp. provides the difference */
  390. }
  391. else {
  392. if (e->k != VVOID) /* at least one expression? */
  393. luaK_exp2nextreg(fs, e); /* close last expression */
  394. if (needed > 0) /* missing values? */
  395. luaK_nil(fs, fs->freereg, needed); /* complete with nils */
  396. }
  397. if (needed > 0)
  398. luaK_reserveregs(fs, needed); /* registers for extra values */
  399. else /* adding 'needed' is actually a subtraction */
  400. fs->freereg += needed; /* remove extra values */
  401. }
  402. /*
  403. ** Macros to limit the maximum recursion depth while parsing
  404. */
  405. #define enterlevel(ls) luaE_enterCcall((ls)->L)
  406. #define leavelevel(ls) luaE_exitCcall((ls)->L)
  407. /*
  408. ** Generates an error that a goto jumps into the scope of some
  409. ** local variable.
  410. */
  411. static l_noret jumpscopeerror (LexState *ls, Labeldesc *gt) {
  412. const char *varname = getstr(getlocalvardesc(ls->fs, gt->nactvar)->vd.name);
  413. const char *msg = "<goto %s> at line %d jumps into the scope of local '%s'";
  414. msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line, varname);
  415. luaK_semerror(ls, msg); /* raise the error */
  416. }
  417. /*
  418. ** Solves the goto at index 'g' to given 'label' and removes it
  419. ** from the list of pending goto's.
  420. ** If it jumps into the scope of some variable, raises an error.
  421. */
  422. static void solvegoto (LexState *ls, int g, Labeldesc *label) {
  423. int i;
  424. Labellist *gl = &ls->dyd->gt; /* list of goto's */
  425. Labeldesc *gt = &gl->arr[g]; /* goto to be resolved */
  426. lua_assert(eqstr(gt->name, label->name));
  427. if (unlikely(gt->nactvar < label->nactvar)) /* enter some scope? */
  428. jumpscopeerror(ls, gt);
  429. luaK_patchlist(ls->fs, gt->pc, label->pc);
  430. for (i = g; i < gl->n - 1; i++) /* remove goto from pending list */
  431. gl->arr[i] = gl->arr[i + 1];
  432. gl->n--;
  433. }
  434. /*
  435. ** Search for an active label with the given name.
  436. */
  437. static Labeldesc *findlabel (LexState *ls, TString *name) {
  438. int i;
  439. Dyndata *dyd = ls->dyd;
  440. /* check labels in current function for a match */
  441. for (i = ls->fs->firstlabel; i < dyd->label.n; i++) {
  442. Labeldesc *lb = &dyd->label.arr[i];
  443. if (eqstr(lb->name, name)) /* correct label? */
  444. return lb;
  445. }
  446. return NULL; /* label not found */
  447. }
  448. /*
  449. ** Adds a new label/goto in the corresponding list.
  450. */
  451. static int newlabelentry (LexState *ls, Labellist *l, TString *name,
  452. int line, int pc) {
  453. int n = l->n;
  454. luaM_growvector(ls->L, l->arr, n, l->size,
  455. Labeldesc, SHRT_MAX, "labels/gotos");
  456. l->arr[n].name = name;
  457. l->arr[n].line = line;
  458. l->arr[n].nactvar = ls->fs->nactvar;
  459. l->arr[n].close = 0;
  460. l->arr[n].pc = pc;
  461. l->n = n + 1;
  462. return n;
  463. }
  464. static int newgotoentry (LexState *ls, TString *name, int line, int pc) {
  465. return newlabelentry(ls, &ls->dyd->gt, name, line, pc);
  466. }
  467. /*
  468. ** Solves forward jumps. Check whether new label 'lb' matches any
  469. ** pending gotos in current block and solves them. Return true
  470. ** if any of the goto's need to close upvalues.
  471. */
  472. static int solvegotos (LexState *ls, Labeldesc *lb) {
  473. Labellist *gl = &ls->dyd->gt;
  474. int i = ls->fs->bl->firstgoto;
  475. int needsclose = 0;
  476. while (i < gl->n) {
  477. if (eqstr(gl->arr[i].name, lb->name)) {
  478. needsclose |= gl->arr[i].close;
  479. solvegoto(ls, i, lb); /* will remove 'i' from the list */
  480. }
  481. else
  482. i++;
  483. }
  484. return needsclose;
  485. }
  486. /*
  487. ** Create a new label with the given 'name' at the given 'line'.
  488. ** 'last' tells whether label is the last non-op statement in its
  489. ** block. Solves all pending goto's to this new label and adds
  490. ** a close instruction if necessary.
  491. ** Returns true iff it added a close instruction.
  492. */
  493. static int createlabel (LexState *ls, TString *name, int line,
  494. int last) {
  495. FuncState *fs = ls->fs;
  496. Labellist *ll = &ls->dyd->label;
  497. int l = newlabelentry(ls, ll, name, line, luaK_getlabel(fs));
  498. if (last) { /* label is last no-op statement in the block? */
  499. /* assume that locals are already out of scope */
  500. ll->arr[l].nactvar = fs->bl->nactvar;
  501. }
  502. if (solvegotos(ls, &ll->arr[l])) { /* need close? */
  503. luaK_codeABC(fs, OP_CLOSE, luaY_nvarstack(fs), 0, 0);
  504. return 1;
  505. }
  506. return 0;
  507. }
  508. /*
  509. ** Adjust pending gotos to outer level of a block.
  510. */
  511. static void movegotosout (FuncState *fs, BlockCnt *bl) {
  512. int i;
  513. Labellist *gl = &fs->ls->dyd->gt;
  514. /* correct pending gotos to current block */
  515. for (i = bl->firstgoto; i < gl->n; i++) { /* for each pending goto */
  516. Labeldesc *gt = &gl->arr[i];
  517. /* leaving a variable scope? */
  518. if (stacklevel(fs, gt->nactvar) > stacklevel(fs, bl->nactvar))
  519. gt->close |= bl->upval; /* jump may need a close */
  520. gt->nactvar = bl->nactvar; /* update goto level */
  521. }
  522. }
  523. static void enterblock (FuncState *fs, BlockCnt *bl, lu_byte isloop) {
  524. bl->isloop = isloop;
  525. bl->nactvar = fs->nactvar;
  526. bl->firstlabel = fs->ls->dyd->label.n;
  527. bl->firstgoto = fs->ls->dyd->gt.n;
  528. bl->upval = 0;
  529. bl->insidetbc = (fs->bl != NULL && fs->bl->insidetbc);
  530. bl->previous = fs->bl;
  531. fs->bl = bl;
  532. lua_assert(fs->freereg == luaY_nvarstack(fs));
  533. }
  534. /*
  535. ** generates an error for an undefined 'goto'.
  536. */
  537. static l_noret undefgoto (LexState *ls, Labeldesc *gt) {
  538. const char *msg;
  539. if (eqstr(gt->name, luaS_newliteral(ls->L, "break"))) {
  540. msg = "break outside loop at line %d";
  541. msg = luaO_pushfstring(ls->L, msg, gt->line);
  542. }
  543. else {
  544. msg = "no visible label '%s' for <goto> at line %d";
  545. msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line);
  546. }
  547. luaK_semerror(ls, msg);
  548. }
  549. static void leaveblock (FuncState *fs) {
  550. BlockCnt *bl = fs->bl;
  551. LexState *ls = fs->ls;
  552. int hasclose = 0;
  553. int stklevel = stacklevel(fs, bl->nactvar); /* level outside the block */
  554. if (bl->isloop) /* fix pending breaks? */
  555. hasclose = createlabel(ls, luaS_newliteral(ls->L, "break"), 0, 0);
  556. if (!hasclose && bl->previous && bl->upval)
  557. luaK_codeABC(fs, OP_CLOSE, stklevel, 0, 0);
  558. fs->bl = bl->previous;
  559. removevars(fs, bl->nactvar);
  560. lua_assert(bl->nactvar == fs->nactvar);
  561. fs->freereg = stklevel; /* free registers */
  562. ls->dyd->label.n = bl->firstlabel; /* remove local labels */
  563. if (bl->previous) /* inner block? */
  564. movegotosout(fs, bl); /* update pending gotos to outer block */
  565. else {
  566. if (bl->firstgoto < ls->dyd->gt.n) /* pending gotos in outer block? */
  567. undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */
  568. }
  569. }
  570. /*
  571. ** adds a new prototype into list of prototypes
  572. */
  573. static Proto *addprototype (LexState *ls) {
  574. Proto *clp;
  575. lua_State *L = ls->L;
  576. FuncState *fs = ls->fs;
  577. Proto *f = fs->f; /* prototype of current function */
  578. if (fs->np >= f->sizep) {
  579. int oldsize = f->sizep;
  580. luaM_growvector(L, f->p, fs->np, f->sizep, Proto *, MAXARG_Bx, "functions");
  581. while (oldsize < f->sizep)
  582. f->p[oldsize++] = NULL;
  583. }
  584. f->p[fs->np++] = clp = luaF_newproto(L);
  585. luaC_objbarrier(L, f, clp);
  586. return clp;
  587. }
  588. /*
  589. ** codes instruction to create new closure in parent function.
  590. ** The OP_CLOSURE instruction uses the last available register,
  591. ** so that, if it invokes the GC, the GC knows which registers
  592. ** are in use at that time.
  593. */
  594. static void codeclosure (LexState *ls, expdesc *v) {
  595. FuncState *fs = ls->fs->prev;
  596. init_exp(v, VRELOC, luaK_codeABx(fs, OP_CLOSURE, 0, fs->np - 1));
  597. luaK_exp2nextreg(fs, v); /* fix it at the last register */
  598. }
  599. static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) {
  600. Proto *f = fs->f;
  601. fs->prev = ls->fs; /* linked list of funcstates */
  602. fs->ls = ls;
  603. ls->fs = fs;
  604. fs->pc = 0;
  605. fs->previousline = f->linedefined;
  606. fs->iwthabs = 0;
  607. fs->lasttarget = 0;
  608. fs->freereg = 0;
  609. fs->nk = 0;
  610. fs->nabslineinfo = 0;
  611. fs->np = 0;
  612. fs->nups = 0;
  613. fs->ndebugvars = 0;
  614. fs->nactvar = 0;
  615. fs->needclose = 0;
  616. fs->firstlocal = ls->dyd->actvar.n;
  617. fs->firstlabel = ls->dyd->label.n;
  618. fs->bl = NULL;
  619. f->source = ls->source;
  620. f->maxstacksize = 2; /* registers 0/1 are always valid */
  621. enterblock(fs, bl, 0);
  622. }
  623. static void close_func (LexState *ls) {
  624. lua_State *L = ls->L;
  625. FuncState *fs = ls->fs;
  626. Proto *f = fs->f;
  627. luaK_ret(fs, luaY_nvarstack(fs), 0); /* final return */
  628. leaveblock(fs);
  629. lua_assert(fs->bl == NULL);
  630. luaK_finish(fs);
  631. luaM_shrinkvector(L, f->code, f->sizecode, fs->pc, Instruction);
  632. luaM_shrinkvector(L, f->lineinfo, f->sizelineinfo, fs->pc, ls_byte);
  633. luaM_shrinkvector(L, f->abslineinfo, f->sizeabslineinfo,
  634. fs->nabslineinfo, AbsLineInfo);
  635. luaM_shrinkvector(L, f->k, f->sizek, fs->nk, TValue);
  636. luaM_shrinkvector(L, f->p, f->sizep, fs->np, Proto *);
  637. luaM_shrinkvector(L, f->locvars, f->sizelocvars, fs->ndebugvars, LocVar);
  638. luaM_shrinkvector(L, f->upvalues, f->sizeupvalues, fs->nups, Upvaldesc);
  639. ls->fs = fs->prev;
  640. luaC_checkGC(L);
  641. }
  642. /*============================================================*/
  643. /* GRAMMAR RULES */
  644. /*============================================================*/
  645. /*
  646. ** check whether current token is in the follow set of a block.
  647. ** 'until' closes syntactical blocks, but do not close scope,
  648. ** so it is handled in separate.
  649. */
  650. static int block_follow (LexState *ls, int withuntil) {
  651. switch (ls->t.token) {
  652. case TK_ELSE: case TK_ELSEIF:
  653. case TK_END: case TK_EOS:
  654. return 1;
  655. case TK_UNTIL: return withuntil;
  656. default: return 0;
  657. }
  658. }
  659. static void statlist (LexState *ls) {
  660. /* statlist -> { stat [';'] } */
  661. while (!block_follow(ls, 1)) {
  662. if (ls->t.token == TK_RETURN) {
  663. statement(ls);
  664. return; /* 'return' must be last statement */
  665. }
  666. statement(ls);
  667. }
  668. }
  669. static void fieldsel (LexState *ls, expdesc *v) {
  670. /* fieldsel -> ['.' | ':'] NAME */
  671. FuncState *fs = ls->fs;
  672. expdesc key;
  673. luaK_exp2anyregup(fs, v);
  674. luaX_next(ls); /* skip the dot or colon */
  675. codename(ls, &key);
  676. luaK_indexed(fs, v, &key);
  677. }
  678. static void yindex (LexState *ls, expdesc *v) {
  679. /* index -> '[' expr ']' */
  680. luaX_next(ls); /* skip the '[' */
  681. expr(ls, v);
  682. luaK_exp2val(ls->fs, v);
  683. checknext(ls, ']');
  684. }
  685. /*
  686. ** {======================================================================
  687. ** Rules for Constructors
  688. ** =======================================================================
  689. */
  690. typedef struct ConsControl {
  691. expdesc v; /* last list item read */
  692. expdesc *t; /* table descriptor */
  693. int nh; /* total number of 'record' elements */
  694. int na; /* number of array elements already stored */
  695. int tostore; /* number of array elements pending to be stored */
  696. } ConsControl;
  697. static void recfield (LexState *ls, ConsControl *cc) {
  698. /* recfield -> (NAME | '['exp']') = exp */
  699. FuncState *fs = ls->fs;
  700. int reg = ls->fs->freereg;
  701. expdesc tab, key, val;
  702. if (ls->t.token == TK_NAME) {
  703. checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
  704. codename(ls, &key);
  705. }
  706. else /* ls->t.token == '[' */
  707. yindex(ls, &key);
  708. cc->nh++;
  709. checknext(ls, '=');
  710. tab = *cc->t;
  711. luaK_indexed(fs, &tab, &key);
  712. expr(ls, &val);
  713. luaK_storevar(fs, &tab, &val);
  714. fs->freereg = reg; /* free registers */
  715. }
  716. static void closelistfield (FuncState *fs, ConsControl *cc) {
  717. if (cc->v.k == VVOID) return; /* there is no list item */
  718. luaK_exp2nextreg(fs, &cc->v);
  719. cc->v.k = VVOID;
  720. if (cc->tostore == LFIELDS_PER_FLUSH) {
  721. luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */
  722. cc->na += cc->tostore;
  723. cc->tostore = 0; /* no more items pending */
  724. }
  725. }
  726. static void lastlistfield (FuncState *fs, ConsControl *cc) {
  727. if (cc->tostore == 0) return;
  728. if (hasmultret(cc->v.k)) {
  729. luaK_setmultret(fs, &cc->v);
  730. luaK_setlist(fs, cc->t->u.info, cc->na, LUA_MULTRET);
  731. cc->na--; /* do not count last expression (unknown number of elements) */
  732. }
  733. else {
  734. if (cc->v.k != VVOID)
  735. luaK_exp2nextreg(fs, &cc->v);
  736. luaK_setlist(fs, cc->t->u.info, cc->na, cc->tostore);
  737. }
  738. cc->na += cc->tostore;
  739. }
  740. static void listfield (LexState *ls, ConsControl *cc) {
  741. /* listfield -> exp */
  742. expr(ls, &cc->v);
  743. cc->tostore++;
  744. }
  745. static void field (LexState *ls, ConsControl *cc) {
  746. /* field -> listfield | recfield */
  747. switch(ls->t.token) {
  748. case TK_NAME: { /* may be 'listfield' or 'recfield' */
  749. if (luaX_lookahead(ls) != '=') /* expression? */
  750. listfield(ls, cc);
  751. else
  752. recfield(ls, cc);
  753. break;
  754. }
  755. case '[': {
  756. recfield(ls, cc);
  757. break;
  758. }
  759. default: {
  760. listfield(ls, cc);
  761. break;
  762. }
  763. }
  764. }
  765. static void constructor (LexState *ls, expdesc *t) {
  766. /* constructor -> '{' [ field { sep field } [sep] ] '}'
  767. sep -> ',' | ';' */
  768. FuncState *fs = ls->fs;
  769. int line = ls->linenumber;
  770. int pc = luaK_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
  771. ConsControl cc;
  772. luaK_code(fs, 0); /* space for extra arg. */
  773. cc.na = cc.nh = cc.tostore = 0;
  774. cc.t = t;
  775. init_exp(t, VNONRELOC, fs->freereg); /* table will be at stack top */
  776. luaK_reserveregs(fs, 1);
  777. init_exp(&cc.v, VVOID, 0); /* no value (yet) */
  778. checknext(ls, '{');
  779. do {
  780. lua_assert(cc.v.k == VVOID || cc.tostore > 0);
  781. if (ls->t.token == '}') break;
  782. closelistfield(fs, &cc);
  783. field(ls, &cc);
  784. } while (testnext(ls, ',') || testnext(ls, ';'));
  785. check_match(ls, '}', '{', line);
  786. lastlistfield(fs, &cc);
  787. luaK_settablesize(fs, pc, t->u.info, cc.na, cc.nh);
  788. }
  789. /* }====================================================================== */
  790. static void setvararg (FuncState *fs, int nparams) {
  791. fs->f->is_vararg = 1;
  792. luaK_codeABC(fs, OP_VARARGPREP, nparams, 0, 0);
  793. }
  794. static void parlist (LexState *ls) {
  795. /* parlist -> [ param { ',' param } ] */
  796. FuncState *fs = ls->fs;
  797. Proto *f = fs->f;
  798. int nparams = 0;
  799. int isvararg = 0;
  800. if (ls->t.token != ')') { /* is 'parlist' not empty? */
  801. do {
  802. switch (ls->t.token) {
  803. case TK_NAME: { /* param -> NAME */
  804. new_localvar(ls, str_checkname(ls));
  805. nparams++;
  806. break;
  807. }
  808. case TK_DOTS: { /* param -> '...' */
  809. luaX_next(ls);
  810. isvararg = 1;
  811. break;
  812. }
  813. default: luaX_syntaxerror(ls, "<name> or '...' expected");
  814. }
  815. } while (!isvararg && testnext(ls, ','));
  816. }
  817. adjustlocalvars(ls, nparams);
  818. f->numparams = cast_byte(fs->nactvar);
  819. if (isvararg)
  820. setvararg(fs, f->numparams); /* declared vararg */
  821. luaK_reserveregs(fs, fs->nactvar); /* reserve registers for parameters */
  822. }
  823. static void body (LexState *ls, expdesc *e, int ismethod, int line) {
  824. /* body -> '(' parlist ')' block END */
  825. FuncState new_fs;
  826. BlockCnt bl;
  827. new_fs.f = addprototype(ls);
  828. new_fs.f->linedefined = line;
  829. open_func(ls, &new_fs, &bl);
  830. checknext(ls, '(');
  831. if (ismethod) {
  832. new_localvarliteral(ls, "self"); /* create 'self' parameter */
  833. adjustlocalvars(ls, 1);
  834. }
  835. parlist(ls);
  836. checknext(ls, ')');
  837. statlist(ls);
  838. new_fs.f->lastlinedefined = ls->linenumber;
  839. check_match(ls, TK_END, TK_FUNCTION, line);
  840. codeclosure(ls, e);
  841. close_func(ls);
  842. }
  843. static int explist (LexState *ls, expdesc *v) {
  844. /* explist -> expr { ',' expr } */
  845. int n = 1; /* at least one expression */
  846. expr(ls, v);
  847. while (testnext(ls, ',')) {
  848. luaK_exp2nextreg(ls->fs, v);
  849. expr(ls, v);
  850. n++;
  851. }
  852. return n;
  853. }
  854. static void funcargs (LexState *ls, expdesc *f, int line) {
  855. FuncState *fs = ls->fs;
  856. expdesc args;
  857. int base, nparams;
  858. switch (ls->t.token) {
  859. case '(': { /* funcargs -> '(' [ explist ] ')' */
  860. luaX_next(ls);
  861. if (ls->t.token == ')') /* arg list is empty? */
  862. args.k = VVOID;
  863. else {
  864. explist(ls, &args);
  865. luaK_setmultret(fs, &args);
  866. }
  867. check_match(ls, ')', '(', line);
  868. break;
  869. }
  870. case '{': { /* funcargs -> constructor */
  871. constructor(ls, &args);
  872. break;
  873. }
  874. case TK_STRING: { /* funcargs -> STRING */
  875. codestring(&args, ls->t.seminfo.ts);
  876. luaX_next(ls); /* must use 'seminfo' before 'next' */
  877. break;
  878. }
  879. default: {
  880. luaX_syntaxerror(ls, "function arguments expected");
  881. }
  882. }
  883. lua_assert(f->k == VNONRELOC);
  884. base = f->u.info; /* base register for call */
  885. if (hasmultret(args.k))
  886. nparams = LUA_MULTRET; /* open call */
  887. else {
  888. if (args.k != VVOID)
  889. luaK_exp2nextreg(fs, &args); /* close last argument */
  890. nparams = fs->freereg - (base+1);
  891. }
  892. init_exp(f, VCALL, luaK_codeABC(fs, OP_CALL, base, nparams+1, 2));
  893. luaK_fixline(fs, line);
  894. fs->freereg = base+1; /* call remove function and arguments and leaves
  895. (unless changed) one result */
  896. }
  897. /*
  898. ** {======================================================================
  899. ** Expression parsing
  900. ** =======================================================================
  901. */
  902. static void primaryexp (LexState *ls, expdesc *v) {
  903. /* primaryexp -> NAME | '(' expr ')' */
  904. switch (ls->t.token) {
  905. case '(': {
  906. int line = ls->linenumber;
  907. luaX_next(ls);
  908. expr(ls, v);
  909. check_match(ls, ')', '(', line);
  910. luaK_dischargevars(ls->fs, v);
  911. return;
  912. }
  913. case TK_NAME: {
  914. singlevar(ls, v);
  915. return;
  916. }
  917. default: {
  918. luaX_syntaxerror(ls, "unexpected symbol");
  919. }
  920. }
  921. }
  922. static void suffixedexp (LexState *ls, expdesc *v) {
  923. /* suffixedexp ->
  924. primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */
  925. FuncState *fs = ls->fs;
  926. int line = ls->linenumber;
  927. primaryexp(ls, v);
  928. for (;;) {
  929. switch (ls->t.token) {
  930. case '.': { /* fieldsel */
  931. fieldsel(ls, v);
  932. break;
  933. }
  934. case '[': { /* '[' exp ']' */
  935. expdesc key;
  936. luaK_exp2anyregup(fs, v);
  937. yindex(ls, &key);
  938. luaK_indexed(fs, v, &key);
  939. break;
  940. }
  941. case ':': { /* ':' NAME funcargs */
  942. expdesc key;
  943. luaX_next(ls);
  944. codename(ls, &key);
  945. luaK_self(fs, v, &key);
  946. funcargs(ls, v, line);
  947. break;
  948. }
  949. case '(': case TK_STRING: case '{': { /* funcargs */
  950. luaK_exp2nextreg(fs, v);
  951. funcargs(ls, v, line);
  952. break;
  953. }
  954. default: return;
  955. }
  956. }
  957. }
  958. static void simpleexp (LexState *ls, expdesc *v) {
  959. /* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... |
  960. constructor | FUNCTION body | suffixedexp */
  961. switch (ls->t.token) {
  962. case TK_FLT: {
  963. init_exp(v, VKFLT, 0);
  964. v->u.nval = ls->t.seminfo.r;
  965. break;
  966. }
  967. case TK_INT: {
  968. init_exp(v, VKINT, 0);
  969. v->u.ival = ls->t.seminfo.i;
  970. break;
  971. }
  972. case TK_STRING: {
  973. codestring(v, ls->t.seminfo.ts);
  974. break;
  975. }
  976. case TK_NIL: {
  977. init_exp(v, VNIL, 0);
  978. break;
  979. }
  980. case TK_TRUE: {
  981. init_exp(v, VTRUE, 0);
  982. break;
  983. }
  984. case TK_FALSE: {
  985. init_exp(v, VFALSE, 0);
  986. break;
  987. }
  988. case TK_DOTS: { /* vararg */
  989. FuncState *fs = ls->fs;
  990. check_condition(ls, fs->f->is_vararg,
  991. "cannot use '...' outside a vararg function");
  992. init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 0, 1));
  993. break;
  994. }
  995. case '{': { /* constructor */
  996. constructor(ls, v);
  997. return;
  998. }
  999. case TK_FUNCTION: {
  1000. luaX_next(ls);
  1001. body(ls, v, 0, ls->linenumber);
  1002. return;
  1003. }
  1004. default: {
  1005. suffixedexp(ls, v);
  1006. return;
  1007. }
  1008. }
  1009. luaX_next(ls);
  1010. }
  1011. static UnOpr getunopr (int op) {
  1012. switch (op) {
  1013. case TK_NOT: return OPR_NOT;
  1014. case '-': return OPR_MINUS;
  1015. case '~': return OPR_BNOT;
  1016. case '#': return OPR_LEN;
  1017. default: return OPR_NOUNOPR;
  1018. }
  1019. }
  1020. static BinOpr getbinopr (int op) {
  1021. switch (op) {
  1022. case '+': return OPR_ADD;
  1023. case '-': return OPR_SUB;
  1024. case '*': return OPR_MUL;
  1025. case '%': return OPR_MOD;
  1026. case '^': return OPR_POW;
  1027. case '/': return OPR_DIV;
  1028. case TK_IDIV: return OPR_IDIV;
  1029. case '&': return OPR_BAND;
  1030. case '|': return OPR_BOR;
  1031. case '~': return OPR_BXOR;
  1032. case TK_SHL: return OPR_SHL;
  1033. case TK_SHR: return OPR_SHR;
  1034. case TK_CONCAT: return OPR_CONCAT;
  1035. case TK_NE: return OPR_NE;
  1036. case TK_EQ: return OPR_EQ;
  1037. case '<': return OPR_LT;
  1038. case TK_LE: return OPR_LE;
  1039. case '>': return OPR_GT;
  1040. case TK_GE: return OPR_GE;
  1041. case TK_AND: return OPR_AND;
  1042. case TK_OR: return OPR_OR;
  1043. default: return OPR_NOBINOPR;
  1044. }
  1045. }
  1046. /*
  1047. ** Priority table for binary operators.
  1048. */
  1049. static const struct {
  1050. lu_byte left; /* left priority for each binary operator */
  1051. lu_byte right; /* right priority */
  1052. } priority[] = { /* ORDER OPR */
  1053. {10, 10}, {10, 10}, /* '+' '-' */
  1054. {11, 11}, {11, 11}, /* '*' '%' */
  1055. {14, 13}, /* '^' (right associative) */
  1056. {11, 11}, {11, 11}, /* '/' '//' */
  1057. {6, 6}, {4, 4}, {5, 5}, /* '&' '|' '~' */
  1058. {7, 7}, {7, 7}, /* '<<' '>>' */
  1059. {9, 8}, /* '..' (right associative) */
  1060. {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */
  1061. {3, 3}, {3, 3}, {3, 3}, /* ~=, >, >= */
  1062. {2, 2}, {1, 1} /* and, or */
  1063. };
  1064. #define UNARY_PRIORITY 12 /* priority for unary operators */
  1065. /*
  1066. ** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
  1067. ** where 'binop' is any binary operator with a priority higher than 'limit'
  1068. */
  1069. static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
  1070. BinOpr op;
  1071. UnOpr uop;
  1072. enterlevel(ls);
  1073. uop = getunopr(ls->t.token);
  1074. if (uop != OPR_NOUNOPR) { /* prefix (unary) operator? */
  1075. int line = ls->linenumber;
  1076. luaX_next(ls); /* skip operator */
  1077. subexpr(ls, v, UNARY_PRIORITY);
  1078. luaK_prefix(ls->fs, uop, v, line);
  1079. }
  1080. else simpleexp(ls, v);
  1081. /* expand while operators have priorities higher than 'limit' */
  1082. op = getbinopr(ls->t.token);
  1083. while (op != OPR_NOBINOPR && priority[op].left > limit) {
  1084. expdesc v2;
  1085. BinOpr nextop;
  1086. int line = ls->linenumber;
  1087. luaX_next(ls); /* skip operator */
  1088. luaK_infix(ls->fs, op, v);
  1089. /* read sub-expression with higher priority */
  1090. nextop = subexpr(ls, &v2, priority[op].right);
  1091. luaK_posfix(ls->fs, op, v, &v2, line);
  1092. op = nextop;
  1093. }
  1094. leavelevel(ls);
  1095. return op; /* return first untreated operator */
  1096. }
  1097. static void expr (LexState *ls, expdesc *v) {
  1098. subexpr(ls, v, 0);
  1099. }
  1100. /* }==================================================================== */
  1101. /*
  1102. ** {======================================================================
  1103. ** Rules for Statements
  1104. ** =======================================================================
  1105. */
  1106. static void block (LexState *ls) {
  1107. /* block -> statlist */
  1108. FuncState *fs = ls->fs;
  1109. BlockCnt bl;
  1110. enterblock(fs, &bl, 0);
  1111. statlist(ls);
  1112. leaveblock(fs);
  1113. }
  1114. /*
  1115. ** structure to chain all variables in the left-hand side of an
  1116. ** assignment
  1117. */
  1118. struct LHS_assign {
  1119. struct LHS_assign *prev;
  1120. expdesc v; /* variable (global, local, upvalue, or indexed) */
  1121. };
  1122. /*
  1123. ** check whether, in an assignment to an upvalue/local variable, the
  1124. ** upvalue/local variable is begin used in a previous assignment to a
  1125. ** table. If so, save original upvalue/local value in a safe place and
  1126. ** use this safe copy in the previous assignment.
  1127. */
  1128. static void check_conflict (LexState *ls, struct LHS_assign *lh, expdesc *v) {
  1129. FuncState *fs = ls->fs;
  1130. int extra = fs->freereg; /* eventual position to save local variable */
  1131. int conflict = 0;
  1132. for (; lh; lh = lh->prev) { /* check all previous assignments */
  1133. if (vkisindexed(lh->v.k)) { /* assignment to table field? */
  1134. if (lh->v.k == VINDEXUP) { /* is table an upvalue? */
  1135. if (v->k == VUPVAL && lh->v.u.ind.t == v->u.info) {
  1136. conflict = 1; /* table is the upvalue being assigned now */
  1137. lh->v.k = VINDEXSTR;
  1138. lh->v.u.ind.t = extra; /* assignment will use safe copy */
  1139. }
  1140. }
  1141. else { /* table is a register */
  1142. if (v->k == VLOCAL && lh->v.u.ind.t == v->u.var.sidx) {
  1143. conflict = 1; /* table is the local being assigned now */
  1144. lh->v.u.ind.t = extra; /* assignment will use safe copy */
  1145. }
  1146. /* is index the local being assigned? */
  1147. if (lh->v.k == VINDEXED && v->k == VLOCAL &&
  1148. lh->v.u.ind.idx == v->u.var.sidx) {
  1149. conflict = 1;
  1150. lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */
  1151. }
  1152. }
  1153. }
  1154. }
  1155. if (conflict) {
  1156. /* copy upvalue/local value to a temporary (in position 'extra') */
  1157. if (v->k == VLOCAL)
  1158. luaK_codeABC(fs, OP_MOVE, extra, v->u.var.sidx, 0);
  1159. else
  1160. luaK_codeABC(fs, OP_GETUPVAL, extra, v->u.info, 0);
  1161. luaK_reserveregs(fs, 1);
  1162. }
  1163. }
  1164. /*
  1165. ** Parse and compile a multiple assignment. The first "variable"
  1166. ** (a 'suffixedexp') was already read by the caller.
  1167. **
  1168. ** assignment -> suffixedexp restassign
  1169. ** restassign -> ',' suffixedexp restassign | '=' explist
  1170. */
  1171. static void restassign (LexState *ls, struct LHS_assign *lh, int nvars) {
  1172. expdesc e;
  1173. check_condition(ls, vkisvar(lh->v.k), "syntax error");
  1174. check_readonly(ls, &lh->v);
  1175. if (testnext(ls, ',')) { /* restassign -> ',' suffixedexp restassign */
  1176. struct LHS_assign nv;
  1177. nv.prev = lh;
  1178. suffixedexp(ls, &nv.v);
  1179. if (!vkisindexed(nv.v.k))
  1180. check_conflict(ls, lh, &nv.v);
  1181. enterlevel(ls); /* control recursion depth */
  1182. restassign(ls, &nv, nvars+1);
  1183. leavelevel(ls);
  1184. }
  1185. else { /* restassign -> '=' explist */
  1186. int nexps;
  1187. checknext(ls, '=');
  1188. nexps = explist(ls, &e);
  1189. if (nexps != nvars)
  1190. adjust_assign(ls, nvars, nexps, &e);
  1191. else {
  1192. luaK_setoneret(ls->fs, &e); /* close last expression */
  1193. luaK_storevar(ls->fs, &lh->v, &e);
  1194. return; /* avoid default */
  1195. }
  1196. }
  1197. init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */
  1198. luaK_storevar(ls->fs, &lh->v, &e);
  1199. }
  1200. static int cond (LexState *ls) {
  1201. /* cond -> exp */
  1202. expdesc v;
  1203. expr(ls, &v); /* read condition */
  1204. if (v.k == VNIL) v.k = VFALSE; /* 'falses' are all equal here */
  1205. luaK_goiftrue(ls->fs, &v);
  1206. return v.f;
  1207. }
  1208. static void gotostat (LexState *ls) {
  1209. FuncState *fs = ls->fs;
  1210. int line = ls->linenumber;
  1211. TString *name = str_checkname(ls); /* label's name */
  1212. Labeldesc *lb = findlabel(ls, name);
  1213. if (lb == NULL) /* no label? */
  1214. /* forward jump; will be resolved when the label is declared */
  1215. newgotoentry(ls, name, line, luaK_jump(fs));
  1216. else { /* found a label */
  1217. /* backward jump; will be resolved here */
  1218. int lblevel = stacklevel(fs, lb->nactvar); /* label level */
  1219. if (luaY_nvarstack(fs) > lblevel) /* leaving the scope of a variable? */
  1220. luaK_codeABC(fs, OP_CLOSE, lblevel, 0, 0);
  1221. /* create jump and link it to the label */
  1222. luaK_patchlist(fs, luaK_jump(fs), lb->pc);
  1223. }
  1224. }
  1225. /*
  1226. ** Break statement. Semantically equivalent to "goto break".
  1227. */
  1228. static void breakstat (LexState *ls) {
  1229. int line = ls->linenumber;
  1230. luaX_next(ls); /* skip break */
  1231. newgotoentry(ls, luaS_newliteral(ls->L, "break"), line, luaK_jump(ls->fs));
  1232. }
  1233. /*
  1234. ** Check whether there is already a label with the given 'name'.
  1235. */
  1236. static void checkrepeated (LexState *ls, TString *name) {
  1237. Labeldesc *lb = findlabel(ls, name);
  1238. if (unlikely(lb != NULL)) { /* already defined? */
  1239. const char *msg = "label '%s' already defined on line %d";
  1240. msg = luaO_pushfstring(ls->L, msg, getstr(name), lb->line);
  1241. luaK_semerror(ls, msg); /* error */
  1242. }
  1243. }
  1244. static void labelstat (LexState *ls, TString *name, int line) {
  1245. /* label -> '::' NAME '::' */
  1246. checknext(ls, TK_DBCOLON); /* skip double colon */
  1247. while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)
  1248. statement(ls); /* skip other no-op statements */
  1249. checkrepeated(ls, name); /* check for repeated labels */
  1250. createlabel(ls, name, line, block_follow(ls, 0));
  1251. }
  1252. static void whilestat (LexState *ls, int line) {
  1253. /* whilestat -> WHILE cond DO block END */
  1254. FuncState *fs = ls->fs;
  1255. int whileinit;
  1256. int condexit;
  1257. BlockCnt bl;
  1258. luaX_next(ls); /* skip WHILE */
  1259. whileinit = luaK_getlabel(fs);
  1260. condexit = cond(ls);
  1261. enterblock(fs, &bl, 1);
  1262. checknext(ls, TK_DO);
  1263. block(ls);
  1264. luaK_jumpto(fs, whileinit);
  1265. check_match(ls, TK_END, TK_WHILE, line);
  1266. leaveblock(fs);
  1267. luaK_patchtohere(fs, condexit); /* false conditions finish the loop */
  1268. }
  1269. static void repeatstat (LexState *ls, int line) {
  1270. /* repeatstat -> REPEAT block UNTIL cond */
  1271. int condexit;
  1272. FuncState *fs = ls->fs;
  1273. int repeat_init = luaK_getlabel(fs);
  1274. BlockCnt bl1, bl2;
  1275. enterblock(fs, &bl1, 1); /* loop block */
  1276. enterblock(fs, &bl2, 0); /* scope block */
  1277. luaX_next(ls); /* skip REPEAT */
  1278. statlist(ls);
  1279. check_match(ls, TK_UNTIL, TK_REPEAT, line);
  1280. condexit = cond(ls); /* read condition (inside scope block) */
  1281. leaveblock(fs); /* finish scope */
  1282. if (bl2.upval) { /* upvalues? */
  1283. int exit = luaK_jump(fs); /* normal exit must jump over fix */
  1284. luaK_patchtohere(fs, condexit); /* repetition must close upvalues */
  1285. luaK_codeABC(fs, OP_CLOSE, stacklevel(fs, bl2.nactvar), 0, 0);
  1286. condexit = luaK_jump(fs); /* repeat after closing upvalues */
  1287. luaK_patchtohere(fs, exit); /* normal exit comes to here */
  1288. }
  1289. luaK_patchlist(fs, condexit, repeat_init); /* close the loop */
  1290. leaveblock(fs); /* finish loop */
  1291. }
  1292. /*
  1293. ** Read an expression and generate code to put its results in next
  1294. ** stack slot.
  1295. **
  1296. */
  1297. static void exp1 (LexState *ls) {
  1298. expdesc e;
  1299. expr(ls, &e);
  1300. luaK_exp2nextreg(ls->fs, &e);
  1301. lua_assert(e.k == VNONRELOC);
  1302. }
  1303. /*
  1304. ** Fix for instruction at position 'pc' to jump to 'dest'.
  1305. ** (Jump addresses are relative in Lua). 'back' true means
  1306. ** a back jump.
  1307. */
  1308. static void fixforjump (FuncState *fs, int pc, int dest, int back) {
  1309. Instruction *jmp = &fs->f->code[pc];
  1310. int offset = dest - (pc + 1);
  1311. if (back)
  1312. offset = -offset;
  1313. if (unlikely(offset > MAXARG_Bx))
  1314. luaX_syntaxerror(fs->ls, "control structure too long");
  1315. SETARG_Bx(*jmp, offset);
  1316. }
  1317. /*
  1318. ** Generate code for a 'for' loop.
  1319. */
  1320. static void forbody (LexState *ls, int base, int line, int nvars, int isgen) {
  1321. /* forbody -> DO block */
  1322. static const OpCode forprep[2] = {OP_FORPREP, OP_TFORPREP};
  1323. static const OpCode forloop[2] = {OP_FORLOOP, OP_TFORLOOP};
  1324. BlockCnt bl;
  1325. FuncState *fs = ls->fs;
  1326. int prep, endfor;
  1327. checknext(ls, TK_DO);
  1328. prep = luaK_codeABx(fs, forprep[isgen], base, 0);
  1329. enterblock(fs, &bl, 0); /* scope for declared variables */
  1330. adjustlocalvars(ls, nvars);
  1331. luaK_reserveregs(fs, nvars);
  1332. block(ls);
  1333. leaveblock(fs); /* end of scope for declared variables */
  1334. fixforjump(fs, prep, luaK_getlabel(fs), 0);
  1335. if (isgen) { /* generic for? */
  1336. luaK_codeABC(fs, OP_TFORCALL, base, 0, nvars);
  1337. luaK_fixline(fs, line);
  1338. }
  1339. endfor = luaK_codeABx(fs, forloop[isgen], base, 0);
  1340. fixforjump(fs, endfor, prep + 1, 1);
  1341. luaK_fixline(fs, line);
  1342. }
  1343. static void fornum (LexState *ls, TString *varname, int line) {
  1344. /* fornum -> NAME = exp,exp[,exp] forbody */
  1345. FuncState *fs = ls->fs;
  1346. int base = fs->freereg;
  1347. new_localvarliteral(ls, "(for state)");
  1348. new_localvarliteral(ls, "(for state)");
  1349. new_localvarliteral(ls, "(for state)");
  1350. new_localvar(ls, varname);
  1351. checknext(ls, '=');
  1352. exp1(ls); /* initial value */
  1353. checknext(ls, ',');
  1354. exp1(ls); /* limit */
  1355. if (testnext(ls, ','))
  1356. exp1(ls); /* optional step */
  1357. else { /* default step = 1 */
  1358. luaK_int(fs, fs->freereg, 1);
  1359. luaK_reserveregs(fs, 1);
  1360. }
  1361. adjustlocalvars(ls, 3); /* control variables */
  1362. forbody(ls, base, line, 1, 0);
  1363. }
  1364. static void forlist (LexState *ls, TString *indexname) {
  1365. /* forlist -> NAME {,NAME} IN explist forbody */
  1366. FuncState *fs = ls->fs;
  1367. expdesc e;
  1368. int nvars = 5; /* gen, state, control, toclose, 'indexname' */
  1369. int line;
  1370. int base = fs->freereg;
  1371. /* create control variables */
  1372. new_localvarliteral(ls, "(for state)");
  1373. new_localvarliteral(ls, "(for state)");
  1374. new_localvarliteral(ls, "(for state)");
  1375. new_localvarliteral(ls, "(for state)");
  1376. /* create declared variables */
  1377. new_localvar(ls, indexname);
  1378. while (testnext(ls, ',')) {
  1379. new_localvar(ls, str_checkname(ls));
  1380. nvars++;
  1381. }
  1382. checknext(ls, TK_IN);
  1383. line = ls->linenumber;
  1384. adjust_assign(ls, 4, explist(ls, &e), &e);
  1385. adjustlocalvars(ls, 4); /* control variables */
  1386. markupval(fs, luaY_nvarstack(fs)); /* state may create an upvalue */
  1387. luaK_checkstack(fs, 3); /* extra space to call generator */
  1388. forbody(ls, base, line, nvars - 4, 1);
  1389. }
  1390. static void forstat (LexState *ls, int line) {
  1391. /* forstat -> FOR (fornum | forlist) END */
  1392. FuncState *fs = ls->fs;
  1393. TString *varname;
  1394. BlockCnt bl;
  1395. enterblock(fs, &bl, 1); /* scope for loop and control variables */
  1396. luaX_next(ls); /* skip 'for' */
  1397. varname = str_checkname(ls); /* first variable name */
  1398. switch (ls->t.token) {
  1399. case '=': fornum(ls, varname, line); break;
  1400. case ',': case TK_IN: forlist(ls, varname); break;
  1401. default: luaX_syntaxerror(ls, "'=' or 'in' expected");
  1402. }
  1403. check_match(ls, TK_END, TK_FOR, line);
  1404. leaveblock(fs); /* loop scope ('break' jumps to this point) */
  1405. }
  1406. /*
  1407. ** Check whether next instruction is a single jump (a 'break', a 'goto'
  1408. ** to a forward label, or a 'goto' to a backward label with no variable
  1409. ** to close). If so, set the name of the 'label' it is jumping to
  1410. ** ("break" for a 'break') or to where it is jumping to ('target') and
  1411. ** return true. If not a single jump, leave input unchanged, to be
  1412. ** handled as a regular statement.
  1413. */
  1414. static int issinglejump (LexState *ls, TString **label, int *target) {
  1415. if (testnext(ls, TK_BREAK)) { /* a break? */
  1416. *label = luaS_newliteral(ls->L, "break");
  1417. return 1;
  1418. }
  1419. else if (ls->t.token != TK_GOTO || luaX_lookahead(ls) != TK_NAME)
  1420. return 0; /* not a valid goto */
  1421. else {
  1422. TString *lname = ls->lookahead.seminfo.ts; /* label's id */
  1423. Labeldesc *lb = findlabel(ls, lname);
  1424. if (lb) { /* a backward jump? */
  1425. /* does it need to close variables? */
  1426. if (luaY_nvarstack(ls->fs) > stacklevel(ls->fs, lb->nactvar))
  1427. return 0; /* not a single jump; cannot optimize */
  1428. *target = lb->pc;
  1429. }
  1430. else /* jump forward */
  1431. *label = lname;
  1432. luaX_next(ls); /* skip goto */
  1433. luaX_next(ls); /* skip name */
  1434. return 1;
  1435. }
  1436. }
  1437. static void test_then_block (LexState *ls, int *escapelist) {
  1438. /* test_then_block -> [IF | ELSEIF] cond THEN block */
  1439. BlockCnt bl;
  1440. int line;
  1441. FuncState *fs = ls->fs;
  1442. TString *jlb = NULL;
  1443. int target = NO_JUMP;
  1444. expdesc v;
  1445. int jf; /* instruction to skip 'then' code (if condition is false) */
  1446. luaX_next(ls); /* skip IF or ELSEIF */
  1447. expr(ls, &v); /* read condition */
  1448. checknext(ls, TK_THEN);
  1449. line = ls->linenumber;
  1450. if (issinglejump(ls, &jlb, &target)) { /* 'if x then goto' ? */
  1451. luaK_goiffalse(ls->fs, &v); /* will jump to label if condition is true */
  1452. enterblock(fs, &bl, 0); /* must enter block before 'goto' */
  1453. if (jlb != NULL) /* forward jump? */
  1454. newgotoentry(ls, jlb, line, v.t); /* will be resolved later */
  1455. else /* backward jump */
  1456. luaK_patchlist(fs, v.t, target); /* jump directly to 'target' */
  1457. while (testnext(ls, ';')) {} /* skip semicolons */
  1458. if (block_follow(ls, 0)) { /* jump is the entire block? */
  1459. leaveblock(fs);
  1460. return; /* and that is it */
  1461. }
  1462. else /* must skip over 'then' part if condition is false */
  1463. jf = luaK_jump(fs);
  1464. }
  1465. else { /* regular case (not a jump) */
  1466. luaK_goiftrue(ls->fs, &v); /* skip over block if condition is false */
  1467. enterblock(fs, &bl, 0);
  1468. jf = v.f;
  1469. }
  1470. statlist(ls); /* 'then' part */
  1471. leaveblock(fs);
  1472. if (ls->t.token == TK_ELSE ||
  1473. ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */
  1474. luaK_concat(fs, escapelist, luaK_jump(fs)); /* must jump over it */
  1475. luaK_patchtohere(fs, jf);
  1476. }
  1477. static void ifstat (LexState *ls, int line) {
  1478. /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
  1479. FuncState *fs = ls->fs;
  1480. int escapelist = NO_JUMP; /* exit list for finished parts */
  1481. test_then_block(ls, &escapelist); /* IF cond THEN block */
  1482. while (ls->t.token == TK_ELSEIF)
  1483. test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */
  1484. if (testnext(ls, TK_ELSE))
  1485. block(ls); /* 'else' part */
  1486. check_match(ls, TK_END, TK_IF, line);
  1487. luaK_patchtohere(fs, escapelist); /* patch escape list to 'if' end */
  1488. }
  1489. static void localfunc (LexState *ls) {
  1490. expdesc b;
  1491. FuncState *fs = ls->fs;
  1492. int fvar = fs->nactvar; /* function's variable index */
  1493. new_localvar(ls, str_checkname(ls)); /* new local variable */
  1494. adjustlocalvars(ls, 1); /* enter its scope */
  1495. body(ls, &b, 0, ls->linenumber); /* function created in next register */
  1496. /* debug information will only see the variable after this point! */
  1497. localdebuginfo(fs, fvar)->startpc = fs->pc;
  1498. }
  1499. static int getlocalattribute (LexState *ls) {
  1500. /* ATTRIB -> ['<' Name '>'] */
  1501. if (testnext(ls, '<')) {
  1502. const char *attr = getstr(str_checkname(ls));
  1503. checknext(ls, '>');
  1504. if (strcmp(attr, "const") == 0)
  1505. return RDKCONST; /* read-only variable */
  1506. else if (strcmp(attr, "close") == 0)
  1507. return RDKTOCLOSE; /* to-be-closed variable */
  1508. else
  1509. luaK_semerror(ls,
  1510. luaO_pushfstring(ls->L, "unknown attribute '%s'", attr));
  1511. }
  1512. return VDKREG;
  1513. }
  1514. static void checktoclose (LexState *ls, int level) {
  1515. if (level != -1) { /* is there a to-be-closed variable? */
  1516. FuncState *fs = ls->fs;
  1517. markupval(fs, level + 1);
  1518. fs->bl->insidetbc = 1; /* in the scope of a to-be-closed variable */
  1519. luaK_codeABC(fs, OP_TBC, level, 0, 0);
  1520. }
  1521. }
  1522. static void localstat (LexState *ls) {
  1523. /* stat -> LOCAL ATTRIB NAME {',' ATTRIB NAME} ['=' explist] */
  1524. FuncState *fs = ls->fs;
  1525. int toclose = -1; /* index of to-be-closed variable (if any) */
  1526. Vardesc *var; /* last variable */
  1527. int ivar, kind; /* index and kind of last variable */
  1528. int nvars = 0;
  1529. int nexps;
  1530. expdesc e;
  1531. do {
  1532. ivar = new_localvar(ls, str_checkname(ls));
  1533. kind = getlocalattribute(ls);
  1534. getlocalvardesc(fs, ivar)->vd.kind = kind;
  1535. if (kind == RDKTOCLOSE) { /* to-be-closed? */
  1536. if (toclose != -1) /* one already present? */
  1537. luaK_semerror(ls, "multiple to-be-closed variables in local list");
  1538. toclose = luaY_nvarstack(fs) + nvars;
  1539. }
  1540. nvars++;
  1541. } while (testnext(ls, ','));
  1542. if (testnext(ls, '='))
  1543. nexps = explist(ls, &e);
  1544. else {
  1545. e.k = VVOID;
  1546. nexps = 0;
  1547. }
  1548. var = getlocalvardesc(fs, ivar); /* get last variable */
  1549. if (nvars == nexps && /* no adjustments? */
  1550. var->vd.kind == RDKCONST && /* last variable is const? */
  1551. luaK_exp2const(fs, &e, &var->k)) { /* compile-time constant? */
  1552. var->vd.kind = RDKCTC; /* variable is a compile-time constant */
  1553. adjustlocalvars(ls, nvars - 1); /* exclude last variable */
  1554. fs->nactvar++; /* but count it */
  1555. }
  1556. else {
  1557. adjust_assign(ls, nvars, nexps, &e);
  1558. adjustlocalvars(ls, nvars);
  1559. }
  1560. checktoclose(ls, toclose);
  1561. }
  1562. static int funcname (LexState *ls, expdesc *v) {
  1563. /* funcname -> NAME {fieldsel} [':' NAME] */
  1564. int ismethod = 0;
  1565. singlevar(ls, v);
  1566. while (ls->t.token == '.')
  1567. fieldsel(ls, v);
  1568. if (ls->t.token == ':') {
  1569. ismethod = 1;
  1570. fieldsel(ls, v);
  1571. }
  1572. return ismethod;
  1573. }
  1574. static void funcstat (LexState *ls, int line) {
  1575. /* funcstat -> FUNCTION funcname body */
  1576. int ismethod;
  1577. expdesc v, b;
  1578. luaX_next(ls); /* skip FUNCTION */
  1579. ismethod = funcname(ls, &v);
  1580. body(ls, &b, ismethod, line);
  1581. luaK_storevar(ls->fs, &v, &b);
  1582. luaK_fixline(ls->fs, line); /* definition "happens" in the first line */
  1583. }
  1584. static void exprstat (LexState *ls) {
  1585. /* stat -> func | assignment */
  1586. FuncState *fs = ls->fs;
  1587. struct LHS_assign v;
  1588. suffixedexp(ls, &v.v);
  1589. if (ls->t.token == '=' || ls->t.token == ',') { /* stat -> assignment ? */
  1590. v.prev = NULL;
  1591. restassign(ls, &v, 1);
  1592. }
  1593. else { /* stat -> func */
  1594. Instruction *inst = &getinstruction(fs, &v.v);
  1595. check_condition(ls, v.v.k == VCALL, "syntax error");
  1596. SETARG_C(*inst, 1); /* call statement uses no results */
  1597. }
  1598. }
  1599. static void retstat (LexState *ls) {
  1600. /* stat -> RETURN [explist] [';'] */
  1601. FuncState *fs = ls->fs;
  1602. expdesc e;
  1603. int nret; /* number of values being returned */
  1604. int first = luaY_nvarstack(fs); /* first slot to be returned */
  1605. if (block_follow(ls, 1) || ls->t.token == ';')
  1606. nret = 0; /* return no values */
  1607. else {
  1608. nret = explist(ls, &e); /* optional return values */
  1609. if (hasmultret(e.k)) {
  1610. luaK_setmultret(fs, &e);
  1611. if (e.k == VCALL && nret == 1 && !fs->bl->insidetbc) { /* tail call? */
  1612. SET_OPCODE(getinstruction(fs,&e), OP_TAILCALL);
  1613. lua_assert(GETARG_A(getinstruction(fs,&e)) == luaY_nvarstack(fs));
  1614. }
  1615. nret = LUA_MULTRET; /* return all values */
  1616. }
  1617. else {
  1618. if (nret == 1) /* only one single value? */
  1619. first = luaK_exp2anyreg(fs, &e); /* can use original slot */
  1620. else { /* values must go to the top of the stack */
  1621. luaK_exp2nextreg(fs, &e);
  1622. lua_assert(nret == fs->freereg - first);
  1623. }
  1624. }
  1625. }
  1626. luaK_ret(fs, first, nret);
  1627. testnext(ls, ';'); /* skip optional semicolon */
  1628. }
  1629. static void statement (LexState *ls) {
  1630. int line = ls->linenumber; /* may be needed for error messages */
  1631. enterlevel(ls);
  1632. switch (ls->t.token) {
  1633. case ';': { /* stat -> ';' (empty statement) */
  1634. luaX_next(ls); /* skip ';' */
  1635. break;
  1636. }
  1637. case TK_IF: { /* stat -> ifstat */
  1638. ifstat(ls, line);
  1639. break;
  1640. }
  1641. case TK_WHILE: { /* stat -> whilestat */
  1642. whilestat(ls, line);
  1643. break;
  1644. }
  1645. case TK_DO: { /* stat -> DO block END */
  1646. luaX_next(ls); /* skip DO */
  1647. block(ls);
  1648. check_match(ls, TK_END, TK_DO, line);
  1649. break;
  1650. }
  1651. case TK_FOR: { /* stat -> forstat */
  1652. forstat(ls, line);
  1653. break;
  1654. }
  1655. case TK_REPEAT: { /* stat -> repeatstat */
  1656. repeatstat(ls, line);
  1657. break;
  1658. }
  1659. case TK_FUNCTION: { /* stat -> funcstat */
  1660. funcstat(ls, line);
  1661. break;
  1662. }
  1663. case TK_LOCAL: { /* stat -> localstat */
  1664. luaX_next(ls); /* skip LOCAL */
  1665. if (testnext(ls, TK_FUNCTION)) /* local function? */
  1666. localfunc(ls);
  1667. else
  1668. localstat(ls);
  1669. break;
  1670. }
  1671. case TK_DBCOLON: { /* stat -> label */
  1672. luaX_next(ls); /* skip double colon */
  1673. labelstat(ls, str_checkname(ls), line);
  1674. break;
  1675. }
  1676. case TK_RETURN: { /* stat -> retstat */
  1677. luaX_next(ls); /* skip RETURN */
  1678. retstat(ls);
  1679. break;
  1680. }
  1681. case TK_BREAK: { /* stat -> breakstat */
  1682. breakstat(ls);
  1683. break;
  1684. }
  1685. case TK_GOTO: { /* stat -> 'goto' NAME */
  1686. luaX_next(ls); /* skip 'goto' */
  1687. gotostat(ls);
  1688. break;
  1689. }
  1690. default: { /* stat -> func | assignment */
  1691. exprstat(ls);
  1692. break;
  1693. }
  1694. }
  1695. lua_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
  1696. ls->fs->freereg >= luaY_nvarstack(ls->fs));
  1697. ls->fs->freereg = luaY_nvarstack(ls->fs); /* free registers */
  1698. leavelevel(ls);
  1699. }
  1700. /* }====================================================================== */
  1701. /*
  1702. ** compiles the main function, which is a regular vararg function with an
  1703. ** upvalue named LUA_ENV
  1704. */
  1705. static void mainfunc (LexState *ls, FuncState *fs) {
  1706. BlockCnt bl;
  1707. Upvaldesc *env;
  1708. open_func(ls, fs, &bl);
  1709. setvararg(fs, 0); /* main function is always declared vararg */
  1710. env = allocupvalue(fs); /* ...set environment upvalue */
  1711. env->instack = 1;
  1712. env->idx = 0;
  1713. env->kind = VDKREG;
  1714. env->name = ls->envn;
  1715. luaX_next(ls); /* read first token */
  1716. statlist(ls); /* parse main body */
  1717. check(ls, TK_EOS);
  1718. close_func(ls);
  1719. }
  1720. LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
  1721. Dyndata *dyd, const char *name, int firstchar) {
  1722. LexState lexstate;
  1723. FuncState funcstate;
  1724. LClosure *cl = luaF_newLclosure(L, 1); /* create main closure */
  1725. setclLvalue2s(L, L->top, cl); /* anchor it (to avoid being collected) */
  1726. luaD_inctop(L);
  1727. lexstate.h = luaH_new(L); /* create table for scanner */
  1728. sethvalue2s(L, L->top, lexstate.h); /* anchor it */
  1729. luaD_inctop(L);
  1730. funcstate.f = cl->p = luaF_newproto(L);
  1731. funcstate.f->source = luaS_new(L, name); /* create and anchor TString */
  1732. luaC_objbarrier(L, funcstate.f, funcstate.f->source);
  1733. lexstate.buff = buff;
  1734. lexstate.dyd = dyd;
  1735. dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;
  1736. luaX_setinput(L, &lexstate, z, funcstate.f->source, firstchar);
  1737. mainfunc(&lexstate, &funcstate);
  1738. lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
  1739. /* all scopes should be correctly finished */
  1740. lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0);
  1741. L->top--; /* remove scanner's table */
  1742. return cl; /* closure is on the stack, too */
  1743. }