lparser.c 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356
  1. /*
  2. ** $Id: lparser.c,v 1.58 2000/02/11 16:52:54 roberto Exp roberto $
  3. ** LL(1) Parser and code generator for Lua
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include "ldo.h"
  9. #include "lfunc.h"
  10. #include "llex.h"
  11. #include "lmem.h"
  12. #include "lobject.h"
  13. #include "lopcodes.h"
  14. #include "lparser.h"
  15. #include "lstate.h"
  16. #include "lstring.h"
  17. /* maximum number of local variables */
  18. #ifndef MAXLOCALS
  19. #define MAXLOCALS 200 /* arbitrary limit (<MAXARG_B) */
  20. #endif
  21. /* maximum number of upvalues */
  22. #ifndef MAXUPVALUES
  23. #define MAXUPVALUES 32 /* arbitrary limit (<MAXARG_B) */
  24. #endif
  25. /* maximum number of variables in the left side of an assignment */
  26. #ifndef MAXVARSLH
  27. #define MAXVARSLH 100 /* arbitrary limit (<MAXARG_B) */
  28. #endif
  29. /* maximum number of parameters in a function */
  30. #ifndef MAXPARAMS
  31. #define MAXPARAMS 100 /* arbitrary limit (<MAXLOCALS) */
  32. #endif
  33. /*
  34. ** Variable descriptor:
  35. ** must include an `exp' option because LL(1) cannot distinguish
  36. ** between variables, upvalues and function calls on first sight.
  37. */
  38. typedef enum {
  39. VGLOBAL, /* info is constant index of global name */
  40. VLOCAL, /* info is stack index */
  41. VDOT, /* info is constant index of index name */
  42. VINDEXED, /* no info (table and index are on the stack) */
  43. VEXP /* info is pc index of a call (or 0 if exp is closed) */
  44. } varkind;
  45. typedef struct vardesc {
  46. varkind k;
  47. int info;
  48. } vardesc;
  49. /*
  50. ** Expression List descriptor:
  51. ** tells number of expressions in the list,
  52. ** and, if last expression is open (a function call),
  53. ** where is the call pc index.
  54. */
  55. typedef struct listdesc {
  56. int n;
  57. int pc; /* 0 if last expression is closed */
  58. } listdesc;
  59. /*
  60. ** Constructors descriptor:
  61. ** `n' indicates number of elements, and `k' signals whether
  62. ** it is a list constructor (k = 0) or a record constructor (k = 1)
  63. ** or empty (k = ';' or '}')
  64. */
  65. typedef struct constdesc {
  66. int n;
  67. int k;
  68. } constdesc;
  69. /* state needed to generate code for a given function */
  70. typedef struct FuncState {
  71. TProtoFunc *f; /* current function header */
  72. struct FuncState *prev; /* enclosing function */
  73. int pc; /* next position to code */
  74. int stacksize; /* number of values on activation register */
  75. int nlocalvar; /* number of active local variables */
  76. int nupvalues; /* number of upvalues */
  77. int nvars; /* number of entries in f->locvars (-1 if no debug information) */
  78. int lastsetline; /* line where last SETLINE was issued */
  79. vardesc upvalues[MAXUPVALUES]; /* upvalues */
  80. TaggedString *localvar[MAXLOCALS]; /* store local variable names */
  81. } FuncState;
  82. /*
  83. ** prototypes for recursive non-terminal functions
  84. */
  85. static void body (LexState *ls, int needself, int line);
  86. static void chunk (LexState *ls);
  87. static void constructor (LexState *ls);
  88. static void expr (LexState *ls, vardesc *v);
  89. static void exp1 (LexState *ls);
  90. static void luaY_error (LexState *ls, const char *msg) {
  91. luaX_error(ls, msg, ls->token);
  92. }
  93. static void checklimit (LexState *ls, int val, int limit, const char *msg) {
  94. if (val > limit) {
  95. char buff[100];
  96. sprintf(buff, "too many %.50s (limit=%d)", msg, limit);
  97. luaY_error(ls, buff);
  98. }
  99. }
  100. static int code_instruction (LexState *ls, Instruction i) {
  101. FuncState *fs = ls->fs;
  102. luaM_growvector(ls->L, fs->f->code, fs->pc, 1, Instruction, codeEM, MAXARG_S);
  103. fs->f->code[fs->pc] = i;
  104. return fs->pc++;
  105. }
  106. static void fix_jump (LexState *ls, int pc, int dest) {
  107. Instruction *jmp = &ls->fs->f->code[pc];
  108. /* jump is relative to position following jump instruction */
  109. *jmp = SETARG_S(*jmp, dest-(pc+1));
  110. }
  111. static void deltastack (LexState *ls, int delta) {
  112. FuncState *fs = ls->fs;
  113. fs->stacksize += delta;
  114. if (delta > 0 && fs->stacksize > fs->f->maxstacksize) {
  115. fs->f->maxstacksize = fs->stacksize;
  116. }
  117. }
  118. static int aux_code (LexState *ls, OpCode op, Instruction i, int delta) {
  119. deltastack(ls, delta);
  120. return code_instruction(ls, SET_OPCODE(i, op));
  121. }
  122. static int code_0 (LexState *ls, OpCode op, int delta) {
  123. return aux_code(ls, op, 0, delta);
  124. }
  125. static int code_U (LexState *ls, OpCode op, int u, int delta) {
  126. Instruction i = SETARG_U(0, u);
  127. return aux_code(ls, op, i, delta);
  128. }
  129. static int code_S (LexState *ls, OpCode op, int s, int delta) {
  130. Instruction i = SETARG_S(0, s);
  131. return aux_code(ls, op, i, delta);
  132. }
  133. static int code_AB (LexState *ls, OpCode op, int a, int b, int delta) {
  134. Instruction i = SETARG_A(0, a);
  135. i = SETARG_B(i, b);
  136. return aux_code(ls, op, i, delta);
  137. }
  138. static void code_kstr (LexState *ls, int c) {
  139. code_U(ls, PUSHSTRING, c, 1);
  140. }
  141. static void assertglobal (LexState *ls, int index) {
  142. luaS_assertglobal(ls->L, ls->fs->f->kstr[index]);
  143. }
  144. static int string_constant (LexState *ls, FuncState *fs, TaggedString *s) {
  145. TProtoFunc *f = fs->f;
  146. int c = s->constindex;
  147. if (c >= f->nkstr || f->kstr[c] != s) {
  148. luaM_growvector(ls->L, f->kstr, f->nkstr, 1, TaggedString *,
  149. constantEM, MAXARG_U);
  150. c = f->nkstr++;
  151. f->kstr[c] = s;
  152. s->constindex = c; /* hint for next time */
  153. }
  154. return c;
  155. }
  156. static void code_string (LexState *ls, TaggedString *s) {
  157. code_kstr(ls, string_constant(ls, ls->fs, s));
  158. }
  159. #define LIM 20
  160. static int real_constant (LexState *ls, real r) {
  161. /* check whether `r' has appeared within the last LIM entries */
  162. TProtoFunc *f = ls->fs->f;
  163. int c = f->nknum;
  164. int lim = c < LIM ? 0 : c-LIM;
  165. while (--c >= lim)
  166. if (f->knum[c] == r) return c;
  167. /* not found; create a new entry */
  168. luaM_growvector(ls->L, f->knum, f->nknum, 1, real, constantEM, MAXARG_U);
  169. c = f->nknum++;
  170. f->knum[c] = r;
  171. return c;
  172. }
  173. static void code_number (LexState *ls, real f) {
  174. if ((real)(-MAXARG_S) <= f && f <= (real)MAXARG_S && (int)f == f)
  175. code_S(ls, PUSHINT, (int)f, 1); /* f has a short integer value */
  176. else
  177. code_U(ls, PUSHNUMBER, real_constant(ls, f), 1);
  178. }
  179. static void luaI_registerlocalvar (LexState *ls, TaggedString *varname,
  180. int line) {
  181. FuncState *fs = ls->fs;
  182. if (fs->nvars != -1) { /* debug information? */
  183. TProtoFunc *f = fs->f;
  184. luaM_growvector(ls->L, f->locvars, fs->nvars, 1, LocVar, "", MAX_INT);
  185. f->locvars[fs->nvars].varname = varname;
  186. f->locvars[fs->nvars].line = line;
  187. fs->nvars++;
  188. }
  189. }
  190. static void luaI_unregisterlocalvar (LexState *ls, int line) {
  191. luaI_registerlocalvar(ls, NULL, line);
  192. }
  193. static void store_localvar (LexState *ls, TaggedString *name, int n) {
  194. FuncState *fs = ls->fs;
  195. checklimit(ls, fs->nlocalvar+n+1, MAXLOCALS, "local variables");
  196. fs->localvar[fs->nlocalvar+n] = name;
  197. }
  198. static void adjustlocalvars (LexState *ls, int nvars, int line) {
  199. FuncState *fs = ls->fs;
  200. int i;
  201. fs->nlocalvar += nvars;
  202. for (i=fs->nlocalvar-nvars; i<fs->nlocalvar; i++)
  203. luaI_registerlocalvar(ls, fs->localvar[i], line);
  204. }
  205. static void add_localvar (LexState *ls, TaggedString *name) {
  206. store_localvar(ls, name, 0);
  207. adjustlocalvars(ls, 1, 0);
  208. }
  209. static int aux_localname (FuncState *fs, TaggedString *n) {
  210. int i;
  211. for (i=fs->nlocalvar-1; i >= 0; i--)
  212. if (n == fs->localvar[i]) return i; /* local var index */
  213. return -1; /* not found */
  214. }
  215. static void singlevar (LexState *ls, TaggedString *n, vardesc *var, int prev) {
  216. FuncState *fs = prev ? ls->fs->prev : ls->fs;
  217. int i = aux_localname(fs, n);
  218. if (i >= 0) { /* local value? */
  219. var->k = VLOCAL;
  220. var->info = i;
  221. }
  222. else {
  223. FuncState *level = fs;
  224. while ((level = level->prev) != NULL) /* check shadowing */
  225. if (aux_localname(level, n) >= 0)
  226. luaX_syntaxerror(ls, "cannot access a variable in outer scope", n->str);
  227. var->k = VGLOBAL;
  228. var->info = string_constant(ls, fs, n);
  229. }
  230. }
  231. static int indexupvalue (LexState *ls, TaggedString *n) {
  232. FuncState *fs = ls->fs;
  233. vardesc v;
  234. int i;
  235. singlevar(ls, n, &v, 1);
  236. for (i=0; i<fs->nupvalues; i++) {
  237. if (fs->upvalues[i].k == v.k && fs->upvalues[i].info == v.info)
  238. return i;
  239. }
  240. /* new one */
  241. ++(fs->nupvalues);
  242. checklimit(ls, fs->nupvalues, MAXUPVALUES, "upvalues");
  243. fs->upvalues[i] = v; /* i = fs->nupvalues - 1 */
  244. return i;
  245. }
  246. static void pushupvalue (LexState *ls, TaggedString *n) {
  247. if (ls->fs->prev == NULL)
  248. luaX_syntaxerror(ls, "cannot access upvalue in main", n->str);
  249. if (aux_localname(ls->fs, n) >= 0)
  250. luaX_syntaxerror(ls, "cannot access an upvalue in current scope", n->str);
  251. code_U(ls, PUSHUPVALUE, indexupvalue(ls, n), 1);
  252. }
  253. static void check_debugline (LexState *ls) {
  254. if (ls->L->debug && ls->linenumber != ls->fs->lastsetline) {
  255. code_U(ls, SETLINE, ls->linenumber, 0);
  256. ls->fs->lastsetline = ls->linenumber;
  257. }
  258. }
  259. static void adjuststack (LexState *ls, int n) {
  260. if (n > 0)
  261. code_U(ls, POP, n, -n);
  262. else if (n < 0)
  263. code_U(ls, PUSHNIL, (-n)-1, -n);
  264. }
  265. static void close_exp (LexState *ls, int pc, int nresults) {
  266. if (pc > 0) { /* expression is an open function call? */
  267. Instruction *i = &ls->fs->f->code[pc];
  268. *i = SETARG_B(*i, nresults); /* set nresults */
  269. if (nresults != MULT_RET)
  270. deltastack(ls, nresults); /* push results */
  271. }
  272. }
  273. static void adjust_mult_assign (LexState *ls, int nvars, listdesc *d) {
  274. int diff = d->n - nvars;
  275. if (d->pc == 0) { /* list is closed */
  276. /* push or pop eventual difference between list lengths */
  277. adjuststack(ls, diff);
  278. }
  279. else { /* must correct function call */
  280. diff--; /* do not count function call itself */
  281. if (diff <= 0) { /* more variables than values? */
  282. /* function call must provide extra values */
  283. close_exp(ls, d->pc, -diff);
  284. }
  285. else { /* more values than variables */
  286. close_exp(ls, d->pc, 0); /* call should provide no value */
  287. adjuststack(ls, diff); /* pop eventual extra values */
  288. }
  289. }
  290. }
  291. static void code_args (LexState *ls, int nparams, int dots) {
  292. FuncState *fs = ls->fs;
  293. adjustlocalvars(ls, nparams, 0);
  294. checklimit(ls, fs->nlocalvar, MAXPARAMS, "parameters");
  295. nparams = fs->nlocalvar; /* `self' could be there already */
  296. fs->f->numparams = nparams;
  297. fs->f->is_vararg = dots;
  298. if (!dots)
  299. deltastack(ls, nparams);
  300. else {
  301. deltastack(ls, nparams+1);
  302. add_localvar(ls, luaS_newfixed(ls->L, "arg"));
  303. }
  304. }
  305. static void unloaddot (LexState *ls, vardesc *v) {
  306. /* dotted variables <a.x> must be stored as regular indexed vars <a["x"]> */
  307. if (v->k == VDOT) {
  308. code_kstr(ls, v->info);
  309. v->k = VINDEXED;
  310. }
  311. }
  312. static void lua_pushvar (LexState *ls, vardesc *var) {
  313. switch (var->k) {
  314. case VLOCAL:
  315. code_U(ls, PUSHLOCAL, var->info, 1);
  316. break;
  317. case VGLOBAL:
  318. code_U(ls, GETGLOBAL, var->info, 1);
  319. assertglobal(ls, var->info); /* make sure that there is a global */
  320. break;
  321. case VDOT:
  322. code_U(ls, GETDOTTED, var->info, 0);
  323. break;
  324. case VINDEXED:
  325. code_0(ls, GETTABLE, -1);
  326. break;
  327. case VEXP:
  328. close_exp(ls, var->info, 1); /* function must return 1 value */
  329. break;
  330. }
  331. var->k = VEXP;
  332. var->info = 0; /* now this is a closed expression */
  333. }
  334. static void storevar (LexState *ls, const vardesc *var) {
  335. switch (var->k) {
  336. case VLOCAL:
  337. code_U(ls, SETLOCAL, var->info, -1);
  338. break;
  339. case VGLOBAL:
  340. code_U(ls, SETGLOBAL, var->info, -1);
  341. assertglobal(ls, var->info); /* make sure that there is a global */
  342. break;
  343. case VINDEXED:
  344. code_0(ls, SETTABLEPOP, -3);
  345. break;
  346. default:
  347. LUA_INTERNALERROR(ls->L, "invalid var kind to store");
  348. }
  349. }
  350. static void func_onstack (LexState *ls, FuncState *func) {
  351. TProtoFunc *f = ls->fs->f;
  352. int i;
  353. for (i=0; i<func->nupvalues; i++)
  354. lua_pushvar(ls, &func->upvalues[i]);
  355. luaM_growvector(ls->L, f->kproto, f->nkproto, 1, TProtoFunc *,
  356. constantEM, MAXARG_A);
  357. f->kproto[f->nkproto++] = func->f;
  358. deltastack(ls, 1); /* CLOSURE puts one extra element (before popping) */
  359. code_AB(ls, CLOSURE, f->nkproto-1, func->nupvalues, -func->nupvalues);
  360. }
  361. static void init_state (LexState *ls, FuncState *fs, TaggedString *source) {
  362. lua_State *L = ls->L;
  363. TProtoFunc *f = luaF_newproto(ls->L);
  364. fs->prev = ls->fs; /* linked list of funcstates */
  365. ls->fs = fs;
  366. fs->stacksize = 0;
  367. fs->nlocalvar = 0;
  368. fs->nupvalues = 0;
  369. fs->lastsetline = 0;
  370. fs->f = f;
  371. f->source = source;
  372. fs->pc = 0;
  373. f->code = NULL;
  374. f->maxstacksize = 0;
  375. f->numparams = 0; /* default for main chunk */
  376. f->is_vararg = 0; /* default for main chunk */
  377. fs->nvars = (L->debug) ? 0 : -1; /* flag no debug information? */
  378. /* push function (to avoid GC) */
  379. tfvalue(L->top) = f;
  380. ttype(L->top) = LUA_T_LPROTO;
  381. incr_top;
  382. }
  383. static void close_func (LexState *ls) {
  384. FuncState *fs = ls->fs;
  385. TProtoFunc *f = fs->f;
  386. code_0(ls, ENDCODE, 0);
  387. luaM_reallocvector(ls->L, f->code, fs->pc, Instruction);
  388. luaM_reallocvector(ls->L, f->kstr, f->nkstr, TaggedString *);
  389. luaM_reallocvector(ls->L, f->knum, f->nknum, real);
  390. luaM_reallocvector(ls->L, f->kproto, f->nkproto, TProtoFunc *);
  391. if (fs->nvars != -1) { /* debug information? */
  392. luaI_registerlocalvar(ls, NULL, -1); /* flag end of vector */
  393. luaM_reallocvector(ls->L, f->locvars, fs->nvars, LocVar);
  394. }
  395. ls->fs = fs->prev;
  396. ls->L->top--; /* pop function */
  397. }
  398. static void next (LexState *ls) {
  399. ls->token = luaX_lex(ls);
  400. }
  401. static void error_expected (LexState *ls, int token) {
  402. char buff[100], t[TOKEN_LEN];
  403. luaX_token2str(token, t);
  404. sprintf(buff, "`%.20s' expected", t);
  405. luaY_error(ls, buff);
  406. }
  407. static void error_unexpected (LexState *ls) {
  408. luaY_error(ls, "unexpected token");
  409. }
  410. static void error_unmatched (LexState *ls, int what, int who, int where) {
  411. if (where == ls->linenumber)
  412. error_expected(ls, what);
  413. else {
  414. char buff[100];
  415. char t_what[TOKEN_LEN], t_who[TOKEN_LEN];
  416. luaX_token2str(what, t_what);
  417. luaX_token2str(who, t_who);
  418. sprintf(buff, "`%.20s' expected (to close `%.20s' at line %d)",
  419. t_what, t_who, where);
  420. luaY_error(ls, buff);
  421. }
  422. }
  423. static void check (LexState *ls, int c) {
  424. if (ls->token != c)
  425. error_expected(ls, c);
  426. next(ls);
  427. }
  428. static void check_match (LexState *ls, int what, int who, int where) {
  429. if (ls->token != what)
  430. error_unmatched(ls, what, who, where);
  431. check_debugline(ls); /* to `mark' the `what' */
  432. next(ls);
  433. }
  434. static int checkname (LexState *ls) {
  435. int sc;
  436. if (ls->token != NAME)
  437. luaY_error(ls, "<name> expected");
  438. sc = string_constant(ls, ls->fs, ls->seminfo.ts);
  439. next(ls);
  440. return sc;
  441. }
  442. static TaggedString *str_checkname (LexState *ls) {
  443. int i = checkname(ls); /* this call may realloc `f->consts' */
  444. return ls->fs->f->kstr[i];
  445. }
  446. static int optional (LexState *ls, int c) {
  447. if (ls->token == c) {
  448. next(ls);
  449. return 1;
  450. }
  451. else return 0;
  452. }
  453. TProtoFunc *luaY_parser (lua_State *L, ZIO *z) {
  454. struct LexState lexstate;
  455. struct FuncState funcstate;
  456. luaX_setinput(L, &lexstate, z);
  457. init_state(&lexstate, &funcstate, luaS_new(L, zname(z)));
  458. next(&lexstate); /* read first token */
  459. chunk(&lexstate);
  460. if (lexstate.token != EOS)
  461. luaY_error(&lexstate, "<eof> expected");
  462. close_func(&lexstate);
  463. return funcstate.f;
  464. }
  465. /*============================================================*/
  466. /* GRAMAR RULES */
  467. /*============================================================*/
  468. static void explist1 (LexState *ls, listdesc *d) {
  469. vardesc v;
  470. expr(ls, &v);
  471. d->n = 1;
  472. while (ls->token == ',') {
  473. d->n++;
  474. lua_pushvar(ls, &v);
  475. next(ls);
  476. expr(ls, &v);
  477. }
  478. if (v.k == VEXP)
  479. d->pc = v.info;
  480. else {
  481. lua_pushvar(ls, &v);
  482. d->pc = 0;
  483. }
  484. }
  485. static void explist (LexState *ls, listdesc *d) {
  486. switch (ls->token) {
  487. case ELSE: case ELSEIF: case END: case UNTIL:
  488. case EOS: case ';': case ')':
  489. d->pc = 0;
  490. d->n = 0;
  491. break;
  492. default:
  493. explist1(ls, d);
  494. }
  495. }
  496. static int funcparams (LexState *ls, int slf) {
  497. FuncState *fs = ls->fs;
  498. int slevel = fs->stacksize - slf - 1; /* where is func in the stack */
  499. switch (ls->token) {
  500. case '(': { /* funcparams -> '(' explist ')' */
  501. int line = ls->linenumber;
  502. listdesc e;
  503. next(ls);
  504. explist(ls, &e);
  505. check_match(ls, ')', '(', line);
  506. close_exp(ls, e.pc, MULT_RET); /* close 1 for old semantics */
  507. break;
  508. }
  509. case '{': /* funcparams -> constructor */
  510. constructor(ls);
  511. break;
  512. case STRING: /* funcparams -> STRING */
  513. code_string(ls, ls->seminfo.ts); /* must use 'seminfo' before `next' */
  514. next(ls);
  515. break;
  516. default:
  517. luaY_error(ls, "function arguments expected");
  518. break;
  519. }
  520. fs->stacksize = slevel; /* call will remove func and params */
  521. return code_AB(ls, CALL, slevel, 0, 0);
  522. }
  523. static void var_or_func_tail (LexState *ls, vardesc *v) {
  524. for (;;) {
  525. switch (ls->token) {
  526. case '.': /* var_or_func_tail -> '.' NAME */
  527. next(ls);
  528. lua_pushvar(ls, v); /* `v' must be on stack */
  529. v->k = VDOT;
  530. v->info = checkname(ls);
  531. break;
  532. case '[': /* var_or_func_tail -> '[' exp1 ']' */
  533. next(ls);
  534. lua_pushvar(ls, v); /* `v' must be on stack */
  535. exp1(ls);
  536. check(ls, ']');
  537. v->k = VINDEXED;
  538. break;
  539. case ':': { /* var_or_func_tail -> ':' NAME funcparams */
  540. int name;
  541. next(ls);
  542. name = checkname(ls);
  543. lua_pushvar(ls, v); /* `v' must be on stack */
  544. code_U(ls, PUSHSELF, name, 1);
  545. v->k = VEXP;
  546. v->info = funcparams(ls, 1);
  547. break;
  548. }
  549. case '(': case STRING: case '{': /* var_or_func_tail -> funcparams */
  550. lua_pushvar(ls, v); /* `v' must be on stack */
  551. v->k = VEXP;
  552. v->info = funcparams(ls, 0);
  553. break;
  554. default: return; /* should be follow... */
  555. }
  556. }
  557. }
  558. static void var_or_func (LexState *ls, vardesc *v) {
  559. /* var_or_func -> ['%'] NAME var_or_func_tail */
  560. if (optional(ls, '%')) { /* upvalue? */
  561. pushupvalue(ls, str_checkname(ls));
  562. v->k = VEXP;
  563. v->info = 0; /* closed expression */
  564. }
  565. else /* variable name */
  566. singlevar(ls, str_checkname(ls), v, 0);
  567. var_or_func_tail(ls, v);
  568. }
  569. /*
  570. ** {======================================================================
  571. ** Rules for Constructors
  572. ** =======================================================================
  573. */
  574. static void recfield (LexState *ls) {
  575. /* recfield -> (NAME | '['exp1']') = exp1 */
  576. switch (ls->token) {
  577. case NAME:
  578. code_kstr(ls, checkname(ls));
  579. break;
  580. case '[':
  581. next(ls);
  582. exp1(ls);
  583. check(ls, ']');
  584. break;
  585. default: luaY_error(ls, "<name> or `[' expected");
  586. }
  587. check(ls, '=');
  588. exp1(ls);
  589. }
  590. static int recfields (LexState *ls) {
  591. /* recfields -> { ',' recfield } [','] */
  592. int n = 1; /* one has been read before */
  593. int mod_n = 1; /* mod_n == n%RFIELDS_PER_FLUSH */
  594. while (ls->token == ',') {
  595. next(ls);
  596. if (ls->token == ';' || ls->token == '}')
  597. break;
  598. recfield(ls);
  599. n++;
  600. if (++mod_n == RFIELDS_PER_FLUSH) {
  601. code_U(ls, SETMAP, RFIELDS_PER_FLUSH-1, -2*RFIELDS_PER_FLUSH);
  602. mod_n = 0;
  603. }
  604. }
  605. if (mod_n)
  606. code_U(ls, SETMAP, mod_n-1, -2*mod_n);
  607. return n;
  608. }
  609. static int listfields (LexState *ls) {
  610. /* listfields -> { ',' exp1 } [','] */
  611. int n = 1; /* one has been read before */
  612. int mod_n = 1; /* mod_n == n%LFIELDS_PER_FLUSH */
  613. while (ls->token == ',') {
  614. next(ls);
  615. if (ls->token == ';' || ls->token == '}')
  616. break;
  617. exp1(ls);
  618. n++;
  619. checklimit(ls, n, MAXARG_A*LFIELDS_PER_FLUSH,
  620. "items in a list initializer");
  621. if (++mod_n == LFIELDS_PER_FLUSH) {
  622. code_AB(ls, SETLIST, n/LFIELDS_PER_FLUSH - 1, LFIELDS_PER_FLUSH-1,
  623. -LFIELDS_PER_FLUSH);
  624. mod_n = 0;
  625. }
  626. }
  627. if (mod_n > 0)
  628. code_AB(ls, SETLIST, n/LFIELDS_PER_FLUSH, mod_n-1, -mod_n);
  629. return n;
  630. }
  631. static void constructor_part (LexState *ls, constdesc *cd) {
  632. switch (ls->token) {
  633. case ';': case '}': /* constructor_part -> empty */
  634. cd->n = 0;
  635. cd->k = ls->token;
  636. return;
  637. case NAME: {
  638. vardesc v;
  639. expr(ls, &v);
  640. if (ls->token == '=') {
  641. switch (v.k) {
  642. case VGLOBAL:
  643. code_kstr(ls, v.info);
  644. break;
  645. case VLOCAL:
  646. code_string(ls, ls->fs->localvar[v.info]);
  647. break;
  648. default:
  649. error_unexpected(ls);
  650. }
  651. next(ls);
  652. exp1(ls);
  653. cd->n = recfields(ls);
  654. cd->k = 1; /* record */
  655. }
  656. else {
  657. lua_pushvar(ls, &v);
  658. cd->n = listfields(ls);
  659. cd->k = 0; /* list */
  660. }
  661. break;
  662. }
  663. case '[': /* constructor_part -> recfield recfields */
  664. recfield(ls);
  665. cd->n = recfields(ls);
  666. cd->k = 1; /* record */
  667. break;
  668. default: /* constructor_part -> exp1 listfields */
  669. exp1(ls);
  670. cd->n = listfields(ls);
  671. cd->k = 0; /* list */
  672. break;
  673. }
  674. }
  675. static void constructor (LexState *ls) {
  676. /* constructor -> '{' constructor_part [';' constructor_part] '}' */
  677. int line = ls->linenumber;
  678. int pc = code_U(ls, CREATETABLE, 0, 1);
  679. int nelems;
  680. constdesc cd;
  681. check(ls, '{');
  682. constructor_part(ls, &cd);
  683. nelems = cd.n;
  684. if (ls->token == ';') {
  685. constdesc other_cd;
  686. next(ls);
  687. constructor_part(ls, &other_cd);
  688. if (cd.k == other_cd.k) /* repeated parts? */
  689. luaY_error(ls, "invalid constructor syntax");
  690. nelems += other_cd.n;
  691. }
  692. check_match(ls, '}', '{', line);
  693. /* set initial table size */
  694. ls->fs->f->code[pc] = SETARG_U(ls->fs->f->code[pc], nelems);
  695. }
  696. /* }====================================================================== */
  697. /*
  698. ** {======================================================================
  699. ** For parsing expressions, we use a classic stack with priorities.
  700. ** Each binary operator is represented by an index: EQ=2, NE=3, ... '^'=13.
  701. ** The unary NOT is 0 and UNMINUS is 1.
  702. ** =======================================================================
  703. */
  704. #define INDNOT 0
  705. #define INDMINUS 1
  706. /* code of first binary operator */
  707. #define FIRSTBIN 2
  708. /* code for power operator (last operator)
  709. ** '^' needs special treatment because it is right associative
  710. */
  711. #define POW 13
  712. static const int priority [POW+1] = {5, 5, 1, 1, 1, 1, 1, 1, 2, 3, 3, 4, 4, 6};
  713. static const OpCode opcodes [POW+1] = {NOTOP, MINUSOP, EQOP, NEQOP, GTOP,
  714. LTOP, LEOP, GEOP, CONCOP, ADDOP, SUBOP, MULTOP, DIVOP, POWOP};
  715. #define MAXOPS 20 /* op's stack size (arbitrary limit) */
  716. typedef struct stack_op {
  717. int ops[MAXOPS];
  718. int top;
  719. } stack_op;
  720. /*
  721. ** returns the index of a binary operator
  722. */
  723. static int binop (int op) {
  724. switch (op) {
  725. case EQ: return FIRSTBIN;
  726. case NE: return FIRSTBIN+1;
  727. case '>': return FIRSTBIN+2;
  728. case '<': return FIRSTBIN+3;
  729. case LE: return FIRSTBIN+4;
  730. case GE: return FIRSTBIN+5;
  731. case CONC: return FIRSTBIN+6;
  732. case '+': return FIRSTBIN+7;
  733. case '-': return FIRSTBIN+8;
  734. case '*': return FIRSTBIN+9;
  735. case '/': return FIRSTBIN+10;
  736. case '^': return FIRSTBIN+11;
  737. default: return -1;
  738. }
  739. }
  740. static void push (LexState *ls, stack_op *s, int op) {
  741. if (s->top >= MAXOPS)
  742. luaY_error(ls, "expression too complex");
  743. s->ops[s->top++] = op;
  744. }
  745. static void pop_to (LexState *ls, stack_op *s, int prio) {
  746. int op;
  747. while (s->top > 0 && priority[(op=s->ops[s->top-1])] >= prio) {
  748. code_0(ls, opcodes[op], op<FIRSTBIN?0:-1);
  749. s->top--;
  750. }
  751. }
  752. static void simpleexp (LexState *ls, vardesc *v, stack_op *s) {
  753. check_debugline(ls);
  754. switch (ls->token) {
  755. case NUMBER: { /* simpleexp -> NUMBER */
  756. real r = ls->seminfo.r;
  757. next(ls);
  758. /* dirty trick: check whether it is a -NUMBER not followed by '^' */
  759. /* (because the priority of '^' is higher than the priority of '-') */
  760. if (s->top > 0 && s->ops[s->top-1] == INDMINUS && ls->token != '^') {
  761. s->top--; /* remove '-' from stack */
  762. r = -r;
  763. }
  764. code_number(ls, r);
  765. break;
  766. }
  767. case STRING: /* simpleexp -> STRING */
  768. code_string(ls, ls->seminfo.ts); /* must use 'seminfo' before `next' */
  769. next(ls);
  770. break;
  771. case NIL: /* simpleexp -> NIL */
  772. adjuststack(ls, -1);
  773. next(ls);
  774. break;
  775. case '{': /* simpleexp -> constructor */
  776. constructor(ls);
  777. break;
  778. case FUNCTION: /* simpleexp -> FUNCTION body */
  779. next(ls);
  780. body(ls, 0, ls->linenumber);
  781. break;
  782. case '(': /* simpleexp -> '(' expr ')' */
  783. next(ls);
  784. expr(ls, v);
  785. check(ls, ')');
  786. return;
  787. case NAME: case '%':
  788. var_or_func(ls, v);
  789. return;
  790. default:
  791. luaY_error(ls, "<expression> expected");
  792. return;
  793. }
  794. v->k = VEXP; v->info = 0;
  795. }
  796. static void prefixexp (LexState *ls, vardesc *v, stack_op *s) {
  797. /* prefixexp -> {NOT | '-'} simpleexp */
  798. while (ls->token == NOT || ls->token == '-') {
  799. push(ls, s, (ls->token==NOT)?INDNOT:INDMINUS);
  800. next(ls);
  801. }
  802. simpleexp(ls, v, s);
  803. }
  804. static void arith_exp (LexState *ls, vardesc *v) {
  805. stack_op s;
  806. int op;
  807. s.top = 0;
  808. prefixexp(ls, v, &s);
  809. while ((op = binop(ls->token)) >= 0) {
  810. lua_pushvar(ls, v);
  811. /* '^' is right associative, so must 'simulate' a higher priority */
  812. pop_to(ls, &s, (op == POW)?priority[op]+1:priority[op]);
  813. push(ls, &s, op);
  814. next(ls);
  815. prefixexp(ls, v, &s);
  816. lua_pushvar(ls, v);
  817. }
  818. if (s.top > 0) {
  819. lua_pushvar(ls, v);
  820. pop_to(ls, &s, 0);
  821. }
  822. }
  823. static void exp1 (LexState *ls) {
  824. vardesc v;
  825. expr(ls, &v);
  826. lua_pushvar(ls, &v);
  827. }
  828. static void expr (LexState *ls, vardesc *v) {
  829. /* expr -> arith_exp {(AND | OR) arith_exp} */
  830. arith_exp(ls, v);
  831. while (ls->token == AND || ls->token == OR) {
  832. OpCode op = (ls->token == AND) ? ONFJMP : ONTJMP;
  833. int pc;
  834. lua_pushvar(ls, v);
  835. next(ls);
  836. pc = code_S(ls, op, 0, -1);
  837. arith_exp(ls, v);
  838. lua_pushvar(ls, v);
  839. fix_jump(ls, pc, ls->fs->pc);
  840. }
  841. }
  842. /* }==================================================================== */
  843. /*
  844. ** {======================================================================
  845. ** Rules for Statements
  846. ** =======================================================================
  847. */
  848. static void block (LexState *ls) {
  849. /* block -> chunk */
  850. FuncState *fs = ls->fs;
  851. int nlocalvar = fs->nlocalvar;
  852. chunk(ls);
  853. adjuststack(ls, fs->nlocalvar - nlocalvar);
  854. for (; fs->nlocalvar > nlocalvar; fs->nlocalvar--)
  855. luaI_unregisterlocalvar(ls, fs->lastsetline);
  856. }
  857. static int assignment (LexState *ls, vardesc *v, int nvars) {
  858. int left = 0;
  859. checklimit(ls, nvars, MAXVARSLH, "variables in a multiple assignment");
  860. unloaddot(ls, v);
  861. if (ls->token == ',') { /* assignment -> ',' NAME assignment */
  862. vardesc nv;
  863. next(ls);
  864. var_or_func(ls, &nv);
  865. if (nv.k == VEXP)
  866. luaY_error(ls, "syntax error");
  867. left = assignment(ls, &nv, nvars+1);
  868. }
  869. else { /* assignment -> '=' explist1 */
  870. listdesc d;
  871. if (ls->token != '=')
  872. error_unexpected(ls);
  873. next(ls);
  874. explist1(ls, &d);
  875. adjust_mult_assign(ls, nvars, &d);
  876. }
  877. if (v->k != VINDEXED || left+(nvars-1) == 0) {
  878. /* global/local var or indexed var without values in between */
  879. storevar(ls, v);
  880. }
  881. else { /* indexed var with values in between*/
  882. code_U(ls, SETTABLE, left+(nvars-1), -1);
  883. left += 2; /* table&index are not popped, because they aren't on top */
  884. }
  885. return left;
  886. }
  887. static void whilestat (LexState *ls, int line) {
  888. /* whilestat -> WHILE exp1 DO block END */
  889. FuncState *fs = ls->fs;
  890. int while_init = fs->pc;
  891. int j1;
  892. next(ls);
  893. exp1(ls);
  894. j1 = code_U(ls, IFFJMP, 0, -1); /* jump to exit loop */
  895. check(ls, DO);
  896. block(ls);
  897. check_match(ls, END, WHILE, line);
  898. fix_jump(ls, code_U(ls, JMP, 0, 0), while_init); /* jump to keep loop */
  899. fix_jump(ls, j1, fs->pc);
  900. }
  901. static void repeatstat (LexState *ls, int line) {
  902. /* repeatstat -> REPEAT block UNTIL exp1 */
  903. FuncState *fs = ls->fs;
  904. int repeat_init = fs->pc;
  905. next(ls);
  906. block(ls);
  907. check_match(ls, UNTIL, REPEAT, line);
  908. exp1(ls);
  909. fix_jump(ls, code_U(ls, IFFJMP, 0, -1), repeat_init);
  910. }
  911. static int localnamelist (LexState *ls) {
  912. /* localnamelist -> NAME {',' NAME} */
  913. int i = 1;
  914. store_localvar(ls, str_checkname(ls), 0);
  915. while (ls->token == ',') {
  916. next(ls);
  917. store_localvar(ls, str_checkname(ls), i++);
  918. }
  919. return i;
  920. }
  921. static void decinit (LexState *ls, listdesc *d) {
  922. /* decinit -> ['=' explist1] */
  923. if (ls->token == '=') {
  924. next(ls);
  925. explist1(ls, d);
  926. }
  927. else {
  928. d->n = 0;
  929. d->pc = 0;
  930. }
  931. }
  932. static void localstat (LexState *ls) {
  933. /* stat -> LOCAL localnamelist decinit */
  934. FuncState *fs = ls->fs;
  935. listdesc d;
  936. int nvars;
  937. check_debugline(ls);
  938. next(ls);
  939. nvars = localnamelist(ls);
  940. decinit(ls, &d);
  941. adjustlocalvars(ls, nvars, fs->lastsetline);
  942. adjust_mult_assign(ls, nvars, &d);
  943. }
  944. static int funcname (LexState *ls, vardesc *v) {
  945. /* funcname -> NAME [':' NAME | '.' NAME] */
  946. int needself = 0;
  947. singlevar(ls, str_checkname(ls), v, 0);
  948. if (ls->token == ':' || ls->token == '.') {
  949. needself = (ls->token == ':');
  950. next(ls);
  951. lua_pushvar(ls, v);
  952. code_kstr(ls, checkname(ls));
  953. v->k = VINDEXED;
  954. }
  955. return needself;
  956. }
  957. static int funcstat (LexState *ls, int line) {
  958. /* funcstat -> FUNCTION funcname body */
  959. int needself;
  960. vardesc v;
  961. if (ls->fs->prev) /* inside other function? */
  962. return 0;
  963. check_debugline(ls);
  964. next(ls);
  965. needself = funcname(ls, &v);
  966. body(ls, needself, line);
  967. storevar(ls, &v);
  968. return 1;
  969. }
  970. static void namestat (LexState *ls) {
  971. /* stat -> func | ['%'] NAME assignment */
  972. vardesc v;
  973. check_debugline(ls);
  974. var_or_func(ls, &v);
  975. if (v.k == VEXP) { /* stat -> func */
  976. if (v.info == 0) /* is just an upper value? */
  977. luaY_error(ls, "syntax error");
  978. close_exp(ls, v.info, 0);
  979. }
  980. else { /* stat -> ['%'] NAME assignment */
  981. int left = assignment(ls, &v, 1);
  982. adjuststack(ls, left); /* remove eventual garbage left on stack */
  983. }
  984. }
  985. static void ifpart (LexState *ls, int line) {
  986. /* ifpart -> cond THEN block [ELSE block | ELSEIF ifpart] */
  987. FuncState *fs = ls->fs;
  988. int c;
  989. int je;
  990. next(ls); /* skip IF or ELSEIF */
  991. exp1(ls); /* cond */
  992. c = code_U(ls, IFFJMP, 0, -1); /* jump `then' if `cond' is false */
  993. check(ls, THEN);
  994. block(ls); /* `then' part */
  995. je = code_U(ls, JMP, 0, 0); /* jump `else' part after `then' */
  996. if (ls->token == ELSEIF)
  997. ifpart(ls, line);
  998. else {
  999. if (optional(ls, ELSE))
  1000. block(ls); /* `else' part */
  1001. check_match(ls, END, IF, line);
  1002. }
  1003. if (fs->pc == je+1) { /* `else' part empty? */
  1004. fs->pc--; /* remove last jump */
  1005. je--; /* first jump will be smaller */
  1006. }
  1007. else
  1008. fix_jump(ls, je, fs->pc); /* fix last jump */
  1009. fix_jump(ls, c, je+1); /* fix first jump to beginning of `else' part */
  1010. }
  1011. static int stat (LexState *ls) {
  1012. int line = ls->linenumber; /* may be needed for error messages */
  1013. switch (ls->token) {
  1014. case IF: /* stat -> IF ifpart END */
  1015. ifpart(ls, line);
  1016. return 1;
  1017. case WHILE: /* stat -> whilestat */
  1018. whilestat(ls, line);
  1019. return 1;
  1020. case DO: { /* stat -> DO block END */
  1021. next(ls);
  1022. block(ls);
  1023. check_match(ls, END, DO, line);
  1024. return 1;
  1025. }
  1026. case REPEAT: /* stat -> repeatstat */
  1027. repeatstat(ls, line);
  1028. return 1;
  1029. case FUNCTION: /* stat -> funcstat */
  1030. return funcstat(ls, line);
  1031. case LOCAL: /* stat -> localstat */
  1032. localstat(ls);
  1033. return 1;
  1034. case NAME: case '%': /* stat -> namestat */
  1035. namestat(ls);
  1036. return 1;
  1037. case RETURN: case ';': case ELSE: case ELSEIF:
  1038. case END: case UNTIL: case EOS: /* 'stat' follow */
  1039. return 0;
  1040. default:
  1041. error_unexpected(ls);
  1042. return 0; /* to avoid warnings */
  1043. }
  1044. }
  1045. static void parlist (LexState *ls) {
  1046. int nparams = 0;
  1047. int dots = 0;
  1048. switch (ls->token) {
  1049. case DOTS: /* parlist -> DOTS */
  1050. next(ls);
  1051. dots = 1;
  1052. break;
  1053. case NAME: /* parlist, tailparlist -> NAME [',' tailparlist] */
  1054. init:
  1055. store_localvar(ls, str_checkname(ls), nparams++);
  1056. if (ls->token == ',') {
  1057. next(ls);
  1058. switch (ls->token) {
  1059. case DOTS: /* tailparlist -> DOTS */
  1060. next(ls);
  1061. dots = 1;
  1062. break;
  1063. case NAME: /* tailparlist -> NAME [',' tailparlist] */
  1064. goto init;
  1065. default: luaY_error(ls, "<name> or `...' expected");
  1066. }
  1067. }
  1068. break;
  1069. case ')': break; /* parlist -> empty */
  1070. default: luaY_error(ls, "<name> or `...' expected");
  1071. }
  1072. code_args(ls, nparams, dots);
  1073. }
  1074. static void body (LexState *ls, int needself, int line) {
  1075. /* body -> '(' parlist ')' chunk END */
  1076. FuncState new_fs;
  1077. init_state(ls, &new_fs, ls->fs->f->source);
  1078. new_fs.f->lineDefined = line;
  1079. check(ls, '(');
  1080. if (needself)
  1081. add_localvar(ls, luaS_newfixed(ls->L, "self"));
  1082. parlist(ls);
  1083. check(ls, ')');
  1084. chunk(ls);
  1085. check_match(ls, END, FUNCTION, line);
  1086. close_func(ls);
  1087. func_onstack(ls, &new_fs);
  1088. }
  1089. static void ret (LexState *ls) {
  1090. /* ret -> [RETURN explist sc] */
  1091. if (ls->token == RETURN) {
  1092. listdesc e;
  1093. check_debugline(ls);
  1094. next(ls);
  1095. explist(ls, &e);
  1096. if (e.pc > 0) { /* expression is an open function call? */
  1097. Instruction *i = &ls->fs->f->code[e.pc];
  1098. *i = SET_OPCODE(*i, TAILCALL); /* instead of a conventional CALL */
  1099. *i = SETARG_B(*i, ls->fs->nlocalvar);
  1100. }
  1101. else
  1102. code_U(ls, RETCODE, ls->fs->nlocalvar, 0);
  1103. ls->fs->stacksize = ls->fs->nlocalvar; /* removes all temp values */
  1104. optional(ls, ';');
  1105. }
  1106. }
  1107. /* }====================================================================== */
  1108. static void chunk (LexState *ls) {
  1109. /* chunk -> { stat [;] } ret */
  1110. while (stat(ls)) {
  1111. LUA_ASSERT(ls->L, ls->fs->stacksize == ls->fs->nlocalvar,
  1112. "stack size != # local vars");
  1113. optional(ls, ';');
  1114. }
  1115. ret(ls); /* optional return */
  1116. }