lparser.c 54 KB

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