lparser.c 36 KB

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