2 * parser.c - ktap parser
4 * This file is part of ktap by Jovi Zhangwei.
6 * Copyright (C) 2012-2013 Jovi Zhangwei <jovi.zhangwei@gmail.com>.
8 * Copyright (C) 1994-2013 Lua.org, PUC-Rio.
9 * - The part of code in this file is copied from lua initially.
10 * - lua's MIT license is compatible with GPL.
12 * ktap is free software; you can redistribute it and/or modify it
13 * under the terms and conditions of the GNU General Public License,
14 * version 2, as published by the Free Software Foundation.
16 * ktap is distributed in the hope it will be useful, but WITHOUT
17 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
18 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
21 * You should have received a copy of the GNU General Public License along with
22 * this program; if not, write to the Free Software Foundation, Inc.,
23 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
30 #include "../include/ktap_types.h"
31 #include "../include/ktap_opcodes.h"
35 /* maximum number of local variables per function (must be smaller
36 than 250, due to the bytecode format) */
39 #define hasmultret(k) ((k) == VCALL || (k) == VVARARG)
42 * nodes for block list (list of active blocks)
44 typedef struct ktap_blockcnt {
45 struct ktap_blockcnt *previous; /* chain */
46 short firstlabel; /* index of first label in this block */
47 short firstgoto; /* index of first pending goto in this block */
48 u8 nactvar; /* # active locals outside the block */
49 u8 upval; /* true if some variable in the block is an upvalue */
50 u8 isloop; /* true if `block' is a loop */
54 * prototypes for recursive non-terminal functions
56 static void statement (ktap_lexstate *ls);
57 static void expr (ktap_lexstate *ls, ktap_expdesc *v);
59 static void anchor_token(ktap_lexstate *ls)
61 /* last token from outer function must be EOS */
62 ktap_assert((int)(ls->fs != NULL) || ls->t.token == TK_EOS);
63 if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) {
64 ktap_string *ts = ls->t.seminfo.ts;
65 lex_newstring(ls, getstr(ts), ts->tsv.len);
70 static void semerror(ktap_lexstate *ls, const char *msg)
72 ls->t.token = 0; /* remove 'near to' from final message */
73 lex_syntaxerror(ls, msg);
76 static void error_expected(ktap_lexstate *ls, int token)
79 ktapc_sprintf("%s expected", lex_token2str(ls, token)));
82 static void errorlimit(ktap_funcstate *fs, int limit, const char *what)
85 int line = fs->f->linedefined;
86 const char *where = (line == 0) ? "main function"
87 : ktapc_sprintf("function at line %d", line);
89 msg = ktapc_sprintf("too many %s (limit is %d) in %s",
91 lex_syntaxerror(fs->ls, msg);
94 static void checklimit(ktap_funcstate *fs, int v, int l, const char *what)
97 errorlimit(fs, l, what);
100 static int testnext(ktap_lexstate *ls, int c)
102 if (ls->t.token == c) {
110 static void check(ktap_lexstate *ls, int c)
112 if (ls->t.token != c)
113 error_expected(ls, c);
116 static void checknext(ktap_lexstate *ls, int c)
122 #define check_condition(ls,c,msg) { if (!(c)) lex_syntaxerror(ls, msg); }
124 static void check_match(ktap_lexstate *ls, int what, int who, int where)
126 if (!testnext(ls, what)) {
127 if (where == ls->linenumber)
128 error_expected(ls, what);
130 lex_syntaxerror(ls, ktapc_sprintf(
131 "%s expected (to close %s at line %d)",
132 lex_token2str(ls, what),
133 lex_token2str(ls, who), where));
138 static ktap_string *str_checkname(ktap_lexstate *ls)
143 ts = ls->t.seminfo.ts;
148 static void init_exp(ktap_expdesc *e, expkind k, int i)
150 e->f = e->t = NO_JUMP;
155 static void codestring(ktap_lexstate *ls, ktap_expdesc *e, ktap_string *s)
157 init_exp(e, VK, codegen_stringK(ls->fs, s));
160 static void codenumber(ktap_lexstate *ls, ktap_expdesc *e, ktap_number n)
162 init_exp(e, VK, codegen_numberK(ls->fs, n));
165 static void checkname(ktap_lexstate *ls, ktap_expdesc *e)
167 codestring(ls, e, str_checkname(ls));
170 static int registerlocalvar(ktap_lexstate *ls, ktap_string *varname)
172 ktap_funcstate *fs = ls->fs;
173 ktap_proto *f = fs->f;
174 int oldsize = f->sizelocvars;
176 ktapc_growvector(f->locvars, fs->nlocvars, f->sizelocvars,
177 ktap_locvar, SHRT_MAX, "local variables");
179 while (oldsize < f->sizelocvars)
180 f->locvars[oldsize++].varname = NULL;
182 f->locvars[fs->nlocvars].varname = varname;
183 return fs->nlocvars++;
186 static void new_localvar(ktap_lexstate *ls, ktap_string *name)
188 ktap_funcstate *fs = ls->fs;
189 ktap_dyndata *dyd = ls->dyd;
190 int reg = registerlocalvar(ls, name);
192 checklimit(fs, dyd->actvar.n + 1 - fs->firstlocal,
193 MAXVARS, "local variables");
194 ktapc_growvector(dyd->actvar.arr, dyd->actvar.n + 1,
195 dyd->actvar.size, ktap_vardesc, MAX_INT, "local variables");
196 dyd->actvar.arr[dyd->actvar.n++].idx = (short)reg;
199 static void new_localvarliteral_(ktap_lexstate *ls, const char *name, size_t sz)
201 new_localvar(ls, lex_newstring(ls, name, sz));
204 #define new_localvarliteral(ls,v) \
205 new_localvarliteral_(ls, "" v, (sizeof(v)/sizeof(char))-1)
207 static ktap_locvar *getlocvar(ktap_funcstate *fs, int i)
209 int idx = fs->ls->dyd->actvar.arr[fs->firstlocal + i].idx;
211 ktap_assert(idx < fs->nlocvars);
212 return &fs->f->locvars[idx];
215 static void adjustlocalvars(ktap_lexstate *ls, int nvars)
217 ktap_funcstate *fs = ls->fs;
219 fs->nactvar = (u8)(fs->nactvar + nvars);
220 for (; nvars; nvars--) {
221 getlocvar(fs, fs->nactvar - nvars)->startpc = fs->pc;
225 static void removevars(ktap_funcstate *fs, int tolevel)
227 fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel);
229 while (fs->nactvar > tolevel)
230 getlocvar(fs, --fs->nactvar)->endpc = fs->pc;
233 static int searchupvalue(ktap_funcstate *fs, ktap_string *name)
236 ktap_upvaldesc *up = fs->f->upvalues;
238 for (i = 0; i < fs->nups; i++) {
239 if (ktapc_ts_eqstr(up[i].name, name))
242 return -1; /* not found */
245 static int newupvalue(ktap_funcstate *fs, ktap_string *name, ktap_expdesc *v)
247 ktap_proto *f = fs->f;
248 int oldsize = f->sizeupvalues;
250 checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues");
251 ktapc_growvector(f->upvalues, fs->nups, f->sizeupvalues,
252 ktap_upvaldesc, MAXUPVAL, "upvalues");
254 while (oldsize < f->sizeupvalues)
255 f->upvalues[oldsize++].name = NULL;
256 f->upvalues[(int)fs->nups].instack = (v->k == VLOCAL);
257 f->upvalues[(int)fs->nups].idx = (u8)(v->u.info);
258 f->upvalues[(int)fs->nups].name = name;
262 static int searchvar(ktap_funcstate *fs, ktap_string *n)
266 for (i = fs->nactvar-1; i >= 0; i--) {
267 if (ktapc_ts_eqstr(n, getlocvar(fs, i)->varname))
270 return -1; /* not found */
274 * Mark block where variable at given level was defined
275 * (to emit close instructions later).
277 static void markupval(ktap_funcstate *fs, int level)
279 ktap_blockcnt *bl = fs->bl;
281 while (bl->nactvar > level)
287 * Find variable with given name 'n'. If it is an upvalue, add this
288 * upvalue into all intermediate functions.
290 static int singlevaraux(ktap_funcstate *fs, ktap_string *n, ktap_expdesc *var, int base)
292 if (fs == NULL) /* no more levels? */
293 return VVOID; /* default is global */
295 int v = searchvar(fs, n); /* look up locals at current level */
296 if (v >= 0) { /* found? */
297 init_exp(var, VLOCAL, v); /* variable is local */
299 markupval(fs, v); /* local will be used as an upval */
301 } else { /* not found as local at current level; try upvalues */
302 int idx = searchupvalue(fs, n); /* try existing upvalues */
303 if (idx < 0) { /* not found? */
304 if (singlevaraux(fs->prev, n, var, 0) == VVOID) /* try upper levels */
305 return VVOID; /* not found; is a global */
306 /* else was LOCAL or UPVAL */
307 idx = newupvalue(fs, n, var); /* will be a new upvalue */
309 init_exp(var, VUPVAL, idx);
315 static void singlevar(ktap_lexstate *ls, ktap_expdesc *var)
317 ktap_string *varname = str_checkname(ls);
318 ktap_funcstate *fs = ls->fs;
320 if (singlevaraux(fs, varname, var, 1) == VVOID) { /* global name? */
322 singlevaraux(fs, ls->envn, var, 1); /* get environment variable */
323 ktap_assert(var->k == VLOCAL || var->k == VUPVAL);
324 codestring(ls, &key, varname); /* key is variable name */
325 codegen_indexed(fs, var, &key); /* env[varname] */
329 static void adjust_assign(ktap_lexstate *ls, int nvars, int nexps, ktap_expdesc *e)
331 ktap_funcstate *fs = ls->fs;
332 int extra = nvars - nexps;
334 if (hasmultret(e->k)) {
335 extra++; /* includes call itself */
338 codegen_setreturns(fs, e, extra); /* last exp. provides the difference */
340 codegen_reserveregs(fs, extra-1);
343 codegen_exp2nextreg(fs, e); /* close last expression */
345 int reg = fs->freereg;
347 codegen_reserveregs(fs, extra);
348 codegen_nil(fs, reg, extra);
353 static void enterlevel(ktap_lexstate *ls)
356 checklimit(ls->fs, ls->nCcalls, KTAP_MAXCCALLS, "C levels");
359 static void closegoto(ktap_lexstate *ls, int g, ktap_labeldesc *label)
362 ktap_funcstate *fs = ls->fs;
363 ktap_labellist *gl = &ls->dyd->gt;
364 ktap_labeldesc *gt = &gl->arr[g];
366 ktap_assert(ktapc_ts_eqstr(gt->name, label->name));
367 if (gt->nactvar < label->nactvar) {
368 ktap_string *vname = getlocvar(fs, gt->nactvar)->varname;
369 const char *msg = ktapc_sprintf(
370 "<goto %s> at line %d jumps into the scope of local " KTAP_QS,
371 getstr(gt->name), gt->line, getstr(vname));
375 codegen_patchlist(fs, gt->pc, label->pc);
376 /* remove goto from pending list */
377 for (i = g; i < gl->n - 1; i++)
378 gl->arr[i] = gl->arr[i + 1];
383 * try to close a goto with existing labels; this solves backward jumps
385 static int findlabel(ktap_lexstate *ls, int g)
388 ktap_blockcnt *bl = ls->fs->bl;
389 ktap_dyndata *dyd = ls->dyd;
390 ktap_labeldesc *gt = &dyd->gt.arr[g];
392 /* check labels in current block for a match */
393 for (i = bl->firstlabel; i < dyd->label.n; i++) {
394 ktap_labeldesc *lb = &dyd->label.arr[i];
395 if (ktapc_ts_eqstr(lb->name, gt->name)) { /* correct label? */
396 if (gt->nactvar > lb->nactvar &&
397 (bl->upval || dyd->label.n > bl->firstlabel))
398 codegen_patchclose(ls->fs, gt->pc, lb->nactvar);
399 closegoto(ls, g, lb); /* close it */
403 return 0; /* label not found; cannot close goto */
406 static int newlabelentry(ktap_lexstate *ls, ktap_labellist *l, ktap_string *name,
411 ktapc_growvector(l->arr, n, l->size,
412 ktap_labeldesc, SHRT_MAX, "labels/gotos");
413 l->arr[n].name = name;
414 l->arr[n].line = line;
415 l->arr[n].nactvar = ls->fs->nactvar;
423 * check whether new label 'lb' matches any pending gotos in current
424 * block; solves forward jumps
426 static void findgotos(ktap_lexstate *ls, ktap_labeldesc *lb)
428 ktap_labellist *gl = &ls->dyd->gt;
429 int i = ls->fs->bl->firstgoto;
432 if (ktapc_ts_eqstr(gl->arr[i].name, lb->name))
433 closegoto(ls, i, lb);
440 * "export" pending gotos to outer level, to check them against
441 * outer labels; if the block being exited has upvalues, and
442 * the goto exits the scope of any variable (which can be the
443 * upvalue), close those variables being exited.
445 static void movegotosout(ktap_funcstate *fs, ktap_blockcnt *bl)
447 int i = bl->firstgoto;
448 ktap_labellist *gl = &fs->ls->dyd->gt;
450 /* correct pending gotos to current block and try to close it
451 with visible labels */
453 ktap_labeldesc *gt = &gl->arr[i];
455 if (gt->nactvar > bl->nactvar) {
457 codegen_patchclose(fs, gt->pc, bl->nactvar);
458 gt->nactvar = bl->nactvar;
460 if (!findlabel(fs->ls, i))
461 i++; /* move to next one */
465 static void enterblock(ktap_funcstate *fs, ktap_blockcnt *bl, u8 isloop)
468 bl->nactvar = fs->nactvar;
469 bl->firstlabel = fs->ls->dyd->label.n;
470 bl->firstgoto = fs->ls->dyd->gt.n;
472 bl->previous = fs->bl;
474 ktap_assert(fs->freereg == fs->nactvar);
479 * create a label named "break" to resolve break statements
481 static void breaklabel(ktap_lexstate *ls)
483 ktap_string *n = ktapc_ts_new("break");
484 int l = newlabelentry(ls, &ls->dyd->label, n, 0, ls->fs->pc);
486 findgotos(ls, &ls->dyd->label.arr[l]);
490 * generates an error for an undefined 'goto'; choose appropriate
491 * message when label name is a reserved word (which can only be 'break')
493 static void undefgoto(ktap_lexstate *ls, ktap_labeldesc *gt)
495 const char *msg = isreserved(gt->name)
496 ? "<%s> at line %d not inside a loop"
497 : "no visible label " KTAP_QS " for <goto> at line %d";
499 msg = ktapc_sprintf(msg, getstr(gt->name), gt->line);
503 static void leaveblock(ktap_funcstate *fs)
505 ktap_blockcnt *bl = fs->bl;
506 ktap_lexstate *ls = fs->ls;
507 if (bl->previous && bl->upval) {
508 /* create a 'jump to here' to close upvalues */
509 int j = codegen_jump(fs);
511 codegen_patchclose(fs, j, bl->nactvar);
512 codegen_patchtohere(fs, j);
516 breaklabel(ls); /* close pending breaks */
518 fs->bl = bl->previous;
519 removevars(fs, bl->nactvar);
520 ktap_assert(bl->nactvar == fs->nactvar);
521 fs->freereg = fs->nactvar; /* free registers */
522 ls->dyd->label.n = bl->firstlabel; /* remove local labels */
523 if (bl->previous) /* inner block? */
524 movegotosout(fs, bl); /* update pending gotos to outer block */
525 else if (bl->firstgoto < ls->dyd->gt.n) /* pending gotos in outer block? */
526 undefgoto(ls, &ls->dyd->gt.arr[bl->firstgoto]); /* error */
530 * adds a new prototype into list of prototypes
532 static ktap_proto *addprototype(ktap_lexstate *ls)
535 ktap_funcstate *fs = ls->fs;
536 ktap_proto *f = fs->f; /* prototype of current function */
538 if (fs->np >= f->sizep) {
539 int oldsize = f->sizep;
540 ktapc_growvector(f->p, fs->np, f->sizep, ktap_proto *, MAXARG_Bx, "functions");
541 while (oldsize < f->sizep)
542 f->p[oldsize++] = NULL;
544 f->p[fs->np++] = clp = ktapc_newproto();
549 * codes instruction to create new closure in parent function
551 static void codeclosure(ktap_lexstate *ls, ktap_expdesc *v)
553 ktap_funcstate *fs = ls->fs->prev;
554 init_exp(v, VRELOCABLE, codegen_codeABx(fs, OP_CLOSURE, 0, fs->np - 1));
555 codegen_exp2nextreg(fs, v); /* fix it at stack top (for GC) */
558 static void open_func(ktap_lexstate *ls, ktap_funcstate *fs, ktap_blockcnt *bl)
562 fs->prev = ls->fs; /* linked list of funcstates */
574 fs->firstlocal = ls->dyd->actvar.n;
577 f->source = ls->source;
578 f->maxstacksize = 2; /* registers 0/1 are always valid */
579 fs->h = ktapc_table_new();
580 //table_resize(NULL, fs->h, 32, 32);
581 enterblock(fs, bl, 0);
584 static void close_func(ktap_lexstate *ls)
586 ktap_funcstate *fs = ls->fs;
587 ktap_proto *f = fs->f;
589 codegen_ret(fs, 0, 0); /* final return */
591 ktapc_reallocvector(f->code, f->sizecode, fs->pc, ktap_instruction);
592 f->sizecode = fs->pc;
593 ktapc_reallocvector(f->lineinfo, f->sizelineinfo, fs->pc, int);
594 f->sizelineinfo = fs->pc;
595 ktapc_reallocvector(f->k, f->sizek, fs->nk, ktap_value);
597 ktapc_reallocvector(f->p, f->sizep, fs->np, ktap_proto *);
599 ktapc_reallocvector(f->locvars, f->sizelocvars, fs->nlocvars, ktap_locvar);
600 f->sizelocvars = fs->nlocvars;
601 ktapc_reallocvector(f->upvalues, f->sizeupvalues, fs->nups, ktap_upvaldesc);
602 f->sizeupvalues = fs->nups;
603 ktap_assert((int)(fs->bl == NULL));
605 /* last token read was anchored in defunct function; must re-anchor it */
610 /*============================================================*/
612 /*============================================================*/
615 * check whether current token is in the follow set of a block.
616 * 'until' closes syntactical blocks, but do not close scope,
617 * so it handled in separate.
619 static int block_follow(ktap_lexstate *ls, int withuntil)
621 switch (ls->t.token) {
622 case TK_ELSE: case TK_ELSEIF:
623 case TK_END: case TK_EOS:
634 static void statlist(ktap_lexstate *ls)
636 /* statlist -> { stat [`;'] } */
637 while (!block_follow(ls, 1)) {
638 if (ls->t.token == TK_RETURN) {
640 return; /* 'return' must be last statement */
646 static void fieldsel(ktap_lexstate *ls, ktap_expdesc *v)
648 /* fieldsel -> ['.' | ':'] NAME */
649 ktap_funcstate *fs = ls->fs;
652 codegen_exp2anyregup(fs, v);
653 lex_next(ls); /* skip the dot or colon */
655 codegen_indexed(fs, v, &key);
658 static void yindex(ktap_lexstate *ls, ktap_expdesc *v)
660 /* index -> '[' expr ']' */
661 lex_next(ls); /* skip the '[' */
663 codegen_exp2val(ls->fs, v);
668 * {======================================================================
669 * Rules for Constructors
670 * =======================================================================
673 ktap_expdesc v; /* last list item read */
674 ktap_expdesc *t; /* table descriptor */
675 int nh; /* total number of `record' elements */
676 int na; /* total number of array elements */
677 int tostore; /* number of array elements pending to be stored */
680 static void recfield(ktap_lexstate *ls, struct ConsControl *cc)
682 /* recfield -> (NAME | `['exp1`]') = exp1 */
683 ktap_funcstate *fs = ls->fs;
684 int reg = ls->fs->freereg;
685 ktap_expdesc key, val;
688 if (ls->t.token == TK_NAME) {
689 checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
691 } else /* ls->t.token == '[' */
696 rkkey = codegen_exp2RK(fs, &key);
698 codegen_codeABC(fs, OP_SETTABLE, cc->t->u.info, rkkey, codegen_exp2RK(fs, &val));
699 fs->freereg = reg; /* free registers */
702 static void closelistfield(ktap_funcstate *fs, struct ConsControl *cc)
704 if (cc->v.k == VVOID)
705 return; /* there is no list item */
706 codegen_exp2nextreg(fs, &cc->v);
708 if (cc->tostore == LFIELDS_PER_FLUSH) {
709 codegen_setlist(fs, cc->t->u.info, cc->na, cc->tostore); /* flush */
710 cc->tostore = 0; /* no more items pending */
714 static void lastlistfield(ktap_funcstate *fs, struct ConsControl *cc)
716 if (cc->tostore == 0)
719 if (hasmultret(cc->v.k)) {
720 codegen_setmultret(fs, &cc->v);
721 codegen_setlist(fs, cc->t->u.info, cc->na, KTAP_MULTRET);
722 cc->na--; /* do not count last expression (unknown number of elements) */
724 if (cc->v.k != VVOID)
725 codegen_exp2nextreg(fs, &cc->v);
726 codegen_setlist(fs, cc->t->u.info, cc->na, cc->tostore);
730 static void listfield(ktap_lexstate *ls, struct ConsControl *cc)
732 /* listfield -> exp */
734 checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
739 static void field(ktap_lexstate *ls, struct ConsControl *cc)
741 /* field -> listfield | recfield */
742 switch(ls->t.token) {
743 case TK_NAME: { /* may be 'listfield' or 'recfield' */
744 if (lex_lookahead(ls) != '=') /* expression? */
760 static void constructor(ktap_lexstate *ls, ktap_expdesc *t)
762 /* constructor -> '{' [ field { sep field } [sep] ] '}'
764 ktap_funcstate *fs = ls->fs;
765 int line = ls->linenumber;
766 int pc = codegen_codeABC(fs, OP_NEWTABLE, 0, 0, 0);
767 struct ConsControl cc;
769 cc.na = cc.nh = cc.tostore = 0;
771 init_exp(t, VRELOCABLE, pc);
772 init_exp(&cc.v, VVOID, 0); /* no value (yet) */
773 codegen_exp2nextreg(ls->fs, t); /* fix it at stack top */
776 ktap_assert(cc.v.k == VVOID || cc.tostore > 0);
777 if (ls->t.token == '}')
779 closelistfield(fs, &cc);
781 } while (testnext(ls, ',') || testnext(ls, ';'));
782 check_match(ls, '}', '{', line);
783 lastlistfield(fs, &cc);
784 SETARG_B(fs->f->code[pc], ktapc_int2fb(cc.na)); /* set initial array size */
785 SETARG_C(fs->f->code[pc], ktapc_int2fb(cc.nh)); /* set initial table size */
788 /* }====================================================================== */
790 static void parlist(ktap_lexstate *ls)
792 /* parlist -> [ param { `,' param } ] */
793 ktap_funcstate *fs = ls->fs;
794 ktap_proto *f = fs->f;
798 if (ls->t.token != ')') { /* is `parlist' not empty? */
800 switch (ls->t.token) {
801 case TK_NAME: { /* param -> NAME */
802 new_localvar(ls, str_checkname(ls));
806 case TK_DOTS: { /* param -> `...' */
812 lex_syntaxerror(ls, "<name> or " KTAP_QL("...") " expected");
814 } while (!f->is_vararg && testnext(ls, ','));
816 adjustlocalvars(ls, nparams);
817 f->numparams = (u8)(fs->nactvar);
818 codegen_reserveregs(fs, fs->nactvar); /* reserve register for parameters */
821 static void body(ktap_lexstate *ls, ktap_expdesc *e, int ismethod, int line)
823 /* body -> `(' parlist `)' block END */
824 ktap_funcstate new_fs;
827 new_fs.f = addprototype(ls);
828 new_fs.f->linedefined = line;
829 open_func(ls, &new_fs, &bl);
832 new_localvarliteral(ls, "self"); /* create 'self' parameter */
833 adjustlocalvars(ls, 1);
839 new_fs.f->lastlinedefined = ls->linenumber;
841 //check_match(ls, TK_END, TK_FUNCTION, line);
846 static void func_body_no_args(ktap_lexstate *ls, ktap_expdesc *e, int line)
848 /* body -> `(' parlist `)' block END */
849 ktap_funcstate new_fs;
852 new_fs.f = addprototype(ls);
853 new_fs.f->linedefined = line;
854 open_func(ls, &new_fs, &bl);
857 new_fs.f->lastlinedefined = ls->linenumber;
859 //check_match(ls, TK_END, TK_FUNCTION, line);
864 static int explist(ktap_lexstate *ls, ktap_expdesc *v)
866 /* explist -> expr { `,' expr } */
867 int n = 1; /* at least one expression */
870 while (testnext(ls, ',')) {
871 codegen_exp2nextreg(ls->fs, v);
878 static void funcargs(ktap_lexstate *ls, ktap_expdesc *f, int line)
880 ktap_funcstate *fs = ls->fs;
884 switch (ls->t.token) {
885 case '(': { /* funcargs -> `(' [ explist ] `)' */
887 if (ls->t.token == ')') /* arg list is empty? */
891 codegen_setmultret(fs, &args);
893 check_match(ls, ')', '(', line);
896 case '{': { /* funcargs -> constructor */
897 constructor(ls, &args);
900 case TK_STRING: { /* funcargs -> STRING */
901 codestring(ls, &args, ls->t.seminfo.ts);
902 lex_next(ls); /* must use `seminfo' before `next' */
906 lex_syntaxerror(ls, "function arguments expected");
909 ktap_assert(f->k == VNONRELOC);
910 base = f->u.info; /* base register for call */
911 if (hasmultret(args.k))
912 nparams = KTAP_MULTRET; /* open call */
915 codegen_exp2nextreg(fs, &args); /* close last argument */
916 nparams = fs->freereg - (base+1);
918 init_exp(f, VCALL, codegen_codeABC(fs, OP_CALL, base, nparams+1, 2));
919 codegen_fixline(fs, line);
920 fs->freereg = base+1; /* call remove function and arguments and leaves
921 (unless changed) one result */
925 * {======================================================================
927 * =======================================================================
929 static void primaryexp(ktap_lexstate *ls, ktap_expdesc *v)
931 /* primaryexp -> NAME | '(' expr ')' */
932 switch (ls->t.token) {
934 int line = ls->linenumber;
938 check_match(ls, ')', '(', line);
939 codegen_dischargevars(ls->fs, v);
946 lex_syntaxerror(ls, "unexpected symbol");
950 static void suffixedexp(ktap_lexstate *ls, ktap_expdesc *v)
953 primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */
954 ktap_funcstate *fs = ls->fs;
955 int line = ls->linenumber;
959 switch (ls->t.token) {
960 case '.': { /* fieldsel */
964 case '[': { /* `[' exp1 `]' */
966 codegen_exp2anyregup(fs, v);
968 codegen_indexed(fs, v, &key);
971 case ':': { /* `:' NAME funcargs */
975 codegen_self(fs, v, &key);
976 funcargs(ls, v, line);
979 case '(': case TK_STRING: case '{': { /* funcargs */
980 codegen_exp2nextreg(fs, v);
981 funcargs(ls, v, line);
990 static void simpleexp(ktap_lexstate *ls, ktap_expdesc *v)
992 /* simpleexp -> NUMBER | STRING | NIL | TRUE | FALSE | ... |
993 constructor | FUNCTION body | suffixedexp */
994 switch (ls->t.token) {
996 init_exp(v, VKNUM, 0);
997 v->u.nval = ls->t.seminfo.r;
1001 codestring(ls, v, ls->t.seminfo.ts);
1005 init_exp(v, VKNUM, 0);
1007 (ktap_number)find_kernel_symbol(getstr(ls->t.seminfo.ts));
1011 init_exp(v, VNIL, 0);
1015 init_exp(v, VTRUE, 0);
1019 init_exp(v, VFALSE, 0);
1022 case TK_DOTS: { /* vararg */
1023 ktap_funcstate *fs = ls->fs;
1024 check_condition(ls, fs->f->is_vararg,
1025 "cannot use " KTAP_QL("...") " outside a vararg function");
1026 init_exp(v, VVARARG, codegen_codeABC(fs, OP_VARARG, 0, 1, 0));
1029 case '{': { /* constructor */
1035 body(ls, v, 0, ls->linenumber);
1039 init_exp(v, VEVENT, 0);
1043 init_exp(v, VEVENTNAME, 0);
1054 init_exp(v, VEVENTARG, ls->t.token - TK_ARG1 + 1);
1064 static UnOpr getunopr(int op)
1067 case TK_NOT: return OPR_NOT;
1068 case '-': return OPR_MINUS;
1069 case '#': return OPR_LEN;
1070 default: return OPR_NOUNOPR;
1074 static BinOpr getbinopr(int op)
1077 case '+': return OPR_ADD;
1078 case '-': return OPR_SUB;
1079 case '*': return OPR_MUL;
1080 case '/': return OPR_DIV;
1081 case '%': return OPR_MOD;
1082 case '^': return OPR_POW;
1083 case TK_CONCAT: return OPR_CONCAT;
1084 case TK_NE: return OPR_NE;
1085 case TK_EQ: return OPR_EQ;
1086 case '<': return OPR_LT;
1087 case TK_LE: return OPR_LE;
1088 case '>': return OPR_GT;
1089 case TK_GE: return OPR_GE;
1090 case TK_AND: return OPR_AND;
1091 case TK_OR: return OPR_OR;
1092 default: return OPR_NOBINOPR;
1096 static const struct {
1097 u8 left; /* left priority for each binary operator */
1098 u8 right; /* right priority */
1099 } priority[] = { /* ORDER OPR */
1100 {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7}, /* `+' `-' `*' `/' `%' */
1101 {10, 9}, {5, 4}, /* ^, .. (right associative) */
1102 {3, 3}, {3, 3}, {3, 3}, /* ==, <, <= */
1103 {3, 3}, {3, 3}, {3, 3}, /* !=, >, >= */
1104 {2, 2}, {1, 1} /* and, or */
1107 #define UNARY_PRIORITY 8 /* priority for unary operators */
1109 #define leavelevel(ls) (ls->nCcalls--)
1112 * subexpr -> (simpleexp | unop subexpr) { binop subexpr }
1113 * where `binop' is any binary operator with a priority higher than `limit'
1115 static BinOpr subexpr(ktap_lexstate *ls, ktap_expdesc *v, int limit)
1121 uop = getunopr(ls->t.token);
1122 if (uop != OPR_NOUNOPR) {
1123 int line = ls->linenumber;
1126 subexpr(ls, v, UNARY_PRIORITY);
1127 codegen_prefix(ls->fs, uop, v, line);
1131 /* expand while operators have priorities higher than `limit' */
1132 op = getbinopr(ls->t.token);
1133 while (op != OPR_NOBINOPR && priority[op].left > limit) {
1136 int line = ls->linenumber;
1139 codegen_infix(ls->fs, op, v);
1140 /* read sub-expression with higher priority */
1141 nextop = subexpr(ls, &v2, priority[op].right);
1142 codegen_posfix(ls->fs, op, v, &v2, line);
1146 return op; /* return first untreated operator */
1149 static void expr(ktap_lexstate *ls, ktap_expdesc *v)
1154 /* }==================================================================== */
1157 * {======================================================================
1158 * Rules for Statements
1159 * =======================================================================
1161 static void block(ktap_lexstate *ls)
1163 /* block -> statlist */
1164 ktap_funcstate *fs = ls->fs;
1167 enterblock(fs, &bl, 0);
1173 * structure to chain all variables in the left-hand side of an
1177 struct LHS_assign *prev;
1178 ktap_expdesc v; /* variable (global, local, upvalue, or indexed) */
1182 * check whether, in an assignment to an upvalue/local variable, the
1183 * upvalue/local variable is begin used in a previous assignment to a
1184 * table. If so, save original upvalue/local value in a safe place and
1185 * use this safe copy in the previous assignment.
1187 static void check_conflict(ktap_lexstate *ls, struct LHS_assign *lh, ktap_expdesc *v)
1189 ktap_funcstate *fs = ls->fs;
1190 int extra = fs->freereg; /* eventual position to save local variable */
1193 for (; lh; lh = lh->prev) { /* check all previous assignments */
1194 if (lh->v.k == VINDEXED) { /* assigning to a table? */
1195 /* table is the upvalue/local being assigned now? */
1196 if (lh->v.u.ind.vt == v->k && lh->v.u.ind.t == v->u.info) {
1198 lh->v.u.ind.vt = VLOCAL;
1199 lh->v.u.ind.t = extra; /* previous assignment will use safe copy */
1201 /* index is the local being assigned? (index cannot be upvalue) */
1202 if (v->k == VLOCAL && lh->v.u.ind.idx == v->u.info) {
1204 lh->v.u.ind.idx = extra; /* previous assignment will use safe copy */
1209 /* copy upvalue/local value to a temporary (in position 'extra') */
1210 OpCode op = (v->k == VLOCAL) ? OP_MOVE : OP_GETUPVAL;
1211 codegen_codeABC(fs, op, extra, v->u.info, 0);
1212 codegen_reserveregs(fs, 1);
1216 static void assignment(ktap_lexstate *ls, struct LHS_assign *lh, int nvars)
1220 check_condition(ls, vkisvar(lh->v.k), "syntax error");
1221 if (testnext(ls, ',')) { /* assignment -> ',' suffixedexp assignment */
1222 struct LHS_assign nv;
1225 suffixedexp(ls, &nv.v);
1226 if (nv.v.k != VINDEXED)
1227 check_conflict(ls, lh, &nv.v);
1228 checklimit(ls->fs, nvars + ls->nCcalls, KTAP_MAXCCALLS,
1230 assignment(ls, &nv, nvars+1);
1231 } else if (testnext(ls, '=')) { /* assignment -> '=' explist */
1234 nexps = explist(ls, &e);
1235 if (nexps != nvars) {
1236 adjust_assign(ls, nvars, nexps, &e);
1237 /* remove extra values */
1239 ls->fs->freereg -= nexps - nvars;
1241 /* close last expression */
1242 codegen_setoneret(ls->fs, &e);
1243 codegen_storevar(ls->fs, &lh->v, &e);
1244 return; /* avoid default */
1246 } else if (testnext(ls, TK_INCR)) { /* assignment -> '+=' explist */
1249 nexps = explist(ls, &e);
1250 if (nexps != nvars) {
1251 lex_syntaxerror(ls, "don't allow multi-assign for +=");
1253 /* close last expression */
1254 codegen_setoneret(ls->fs, &e);
1255 codegen_storeincr(ls->fs, &lh->v, &e);
1256 return; /* avoid default */
1258 } else if (testnext(ls, TK_AGGR_ASSIGN)) { /* assignment -> '<<<' explist */
1261 nexps = explist(ls, &e);
1262 if (nexps != nvars) {
1263 lex_syntaxerror(ls, "don't allow multi-assign for <<<");
1265 /* close last expression */
1266 codegen_setoneret(ls->fs, &e);
1267 codegen_store_aggr(ls->fs, &lh->v, &e);
1268 return; /* avoid default */
1272 init_exp(&e, VNONRELOC, ls->fs->freereg-1); /* default assignment */
1273 codegen_storevar(ls->fs, &lh->v, &e);
1276 static int cond(ktap_lexstate *ls)
1280 expr(ls, &v); /* read condition */
1282 v.k = VFALSE; /* `falses' are all equal here */
1283 codegen_goiftrue(ls->fs, &v);
1287 static void gotostat(ktap_lexstate *ls, int pc)
1289 int line = ls->linenumber;
1293 if (testnext(ls, TK_GOTO))
1294 label = str_checkname(ls);
1296 lex_next(ls); /* skip break */
1297 label = ktapc_ts_new("break");
1299 g = newlabelentry(ls, &ls->dyd->gt, label, line, pc);
1300 findlabel(ls, g); /* close it if label already defined */
1303 /* check for repeated labels on the same block */
1304 static void checkrepeated(ktap_funcstate *fs, ktap_labellist *ll, ktap_string *label)
1307 for (i = fs->bl->firstlabel; i < ll->n; i++) {
1308 if (ktapc_ts_eqstr(label, ll->arr[i].name)) {
1309 const char *msg = ktapc_sprintf(
1310 "label " KTAP_QS " already defined on line %d",
1311 getstr(label), ll->arr[i].line);
1312 semerror(fs->ls, msg);
1317 /* skip no-op statements */
1318 static void skipnoopstat(ktap_lexstate *ls)
1320 while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)
1324 static void labelstat (ktap_lexstate *ls, ktap_string *label, int line)
1326 /* label -> '::' NAME '::' */
1327 ktap_funcstate *fs = ls->fs;
1328 ktap_labellist *ll = &ls->dyd->label;
1329 int l; /* index of new label being created */
1331 checkrepeated(fs, ll, label); /* check for repeated labels */
1332 checknext(ls, TK_DBCOLON); /* skip double colon */
1333 /* create new entry for this label */
1334 l = newlabelentry(ls, ll, label, line, fs->pc);
1335 skipnoopstat(ls); /* skip other no-op statements */
1336 if (block_follow(ls, 0)) { /* label is last no-op statement in the block? */
1337 /* assume that locals are already out of scope */
1338 ll->arr[l].nactvar = fs->bl->nactvar;
1340 findgotos(ls, &ll->arr[l]);
1343 static void whilestat(ktap_lexstate *ls, int line)
1345 /* whilestat -> WHILE cond DO block END */
1346 ktap_funcstate *fs = ls->fs;
1351 lex_next(ls); /* skip WHILE */
1352 whileinit = codegen_getlabel(fs);
1354 condexit = cond(ls);
1357 enterblock(fs, &bl, 1);
1358 //checknext(ls, TK_DO);
1361 codegen_jumpto(fs, whileinit);
1363 //check_match(ls, TK_END, TK_WHILE, line);
1365 codegen_patchtohere(fs, condexit); /* false conditions finish the loop */
1368 static void repeatstat(ktap_lexstate *ls, int line)
1370 /* repeatstat -> REPEAT block UNTIL cond */
1372 ktap_funcstate *fs = ls->fs;
1373 int repeat_init = codegen_getlabel(fs);
1374 ktap_blockcnt bl1, bl2;
1376 enterblock(fs, &bl1, 1); /* loop block */
1377 enterblock(fs, &bl2, 0); /* scope block */
1378 lex_next(ls); /* skip REPEAT */
1380 check_match(ls, TK_UNTIL, TK_REPEAT, line);
1381 condexit = cond(ls); /* read condition (inside scope block) */
1382 if (bl2.upval) /* upvalues? */
1383 codegen_patchclose(fs, condexit, bl2.nactvar);
1384 leaveblock(fs); /* finish scope */
1385 codegen_patchlist(fs, condexit, repeat_init); /* close the loop */
1386 leaveblock(fs); /* finish loop */
1389 static int exp1(ktap_lexstate *ls)
1395 codegen_exp2nextreg(ls->fs, &e);
1396 ktap_assert(e.k == VNONRELOC);
1401 static void forbody(ktap_lexstate *ls, int base, int line, int nvars, int isnum)
1403 /* forbody -> DO block */
1405 ktap_funcstate *fs = ls->fs;
1410 adjustlocalvars(ls, 3); /* control variables */
1411 //checknext(ls, TK_DO);
1413 prep = isnum ? codegen_codeAsBx(fs, OP_FORPREP, base, NO_JUMP) : codegen_jump(fs);
1414 enterblock(fs, &bl, 0); /* scope for declared variables */
1415 adjustlocalvars(ls, nvars);
1416 codegen_reserveregs(fs, nvars);
1418 leaveblock(fs); /* end of scope for declared variables */
1419 codegen_patchtohere(fs, prep);
1420 if (isnum) /* numeric for? */
1421 endfor = codegen_codeAsBx(fs, OP_FORLOOP, base, NO_JUMP);
1422 else { /* generic for */
1423 codegen_codeABC(fs, OP_TFORCALL, base, 0, nvars);
1424 codegen_fixline(fs, line);
1425 endfor = codegen_codeAsBx(fs, OP_TFORLOOP, base + 2, NO_JUMP);
1427 codegen_patchlist(fs, endfor, prep + 1);
1428 codegen_fixline(fs, line);
1431 static void fornum(ktap_lexstate *ls, ktap_string *varname, int line)
1433 /* fornum -> NAME = exp1,exp1[,exp1] forbody */
1434 ktap_funcstate *fs = ls->fs;
1435 int base = fs->freereg;
1437 new_localvarliteral(ls, "(for index)");
1438 new_localvarliteral(ls, "(for limit)");
1439 new_localvarliteral(ls, "(for step)");
1440 new_localvar(ls, varname);
1442 exp1(ls); /* initial value */
1444 exp1(ls); /* limit */
1445 if (testnext(ls, ','))
1446 exp1(ls); /* optional step */
1447 else { /* default step = 1 */
1448 codegen_codek(fs, fs->freereg, codegen_numberK(fs, 1));
1449 codegen_reserveregs(fs, 1);
1451 forbody(ls, base, line, 1, 1);
1454 static void forlist(ktap_lexstate *ls, ktap_string *indexname)
1456 /* forlist -> NAME {,NAME} IN explist forbody */
1457 ktap_funcstate *fs = ls->fs;
1459 int nvars = 4; /* gen, state, control, plus at least one declared var */
1461 int base = fs->freereg;
1463 /* create control variables */
1464 new_localvarliteral(ls, "(for generator)");
1465 new_localvarliteral(ls, "(for state)");
1466 new_localvarliteral(ls, "(for control)");
1467 /* create declared variables */
1468 new_localvar(ls, indexname);
1469 while (testnext(ls, ',')) {
1470 new_localvar(ls, str_checkname(ls));
1473 checknext(ls, TK_IN);
1474 line = ls->linenumber;
1475 adjust_assign(ls, 3, explist(ls, &e), &e);
1476 codegen_checkstack(fs, 3); /* extra space to call generator */
1477 forbody(ls, base, line, nvars - 3, 0);
1480 static void forstat(ktap_lexstate *ls, int line)
1482 /* forstat -> FOR (fornum | forlist) END */
1483 ktap_funcstate *fs = ls->fs;
1484 ktap_string *varname;
1487 enterblock(fs, &bl, 1); /* scope for loop and control variables */
1488 lex_next(ls); /* skip `for' */
1491 varname = str_checkname(ls); /* first variable name */
1492 switch (ls->t.token) {
1494 fornum(ls, varname, line);
1496 case ',': case TK_IN:
1497 forlist(ls, varname);
1500 lex_syntaxerror(ls, KTAP_QL("=") " or " KTAP_QL("in") " expected");
1502 //check_match(ls, TK_END, TK_FOR, line);
1504 leaveblock(fs); /* loop scope (`break' jumps to this point) */
1507 static void test_then_block(ktap_lexstate *ls, int *escapelist)
1509 /* test_then_block -> [IF | ELSEIF] cond THEN block */
1511 ktap_funcstate *fs = ls->fs;
1513 int jf; /* instruction to skip 'then' code (if condition is false) */
1515 lex_next(ls); /* skip IF or ELSEIF */
1517 expr(ls, &v); /* read condition */
1519 //checknext(ls, TK_THEN);
1521 if (ls->t.token == TK_GOTO || ls->t.token == TK_BREAK) {
1522 codegen_goiffalse(ls->fs, &v); /* will jump to label if condition is true */
1523 enterblock(fs, &bl, 0); /* must enter block before 'goto' */
1524 gotostat(ls, v.t); /* handle goto/break */
1525 skipnoopstat(ls); /* skip other no-op statements */
1526 if (block_follow(ls, 0)) { /* 'goto' is the entire block? */
1529 return; /* and that is it */
1530 } else /* must skip over 'then' part if condition is false */
1531 jf = codegen_jump(fs);
1532 } else { /* regular case (not goto/break) */
1533 codegen_goiftrue(ls->fs, &v); /* skip over block if condition is false */
1534 enterblock(fs, &bl, 0);
1537 statlist(ls); /* `then' part */
1540 if (ls->t.token == TK_ELSE || ls->t.token == TK_ELSEIF) /* followed by 'else'/'elseif'? */
1541 codegen_concat(fs, escapelist, codegen_jump(fs)); /* must jump over it */
1542 codegen_patchtohere(fs, jf);
1545 static void ifstat(ktap_lexstate *ls, int line)
1547 /* ifstat -> IF cond THEN block {ELSEIF cond THEN block} [ELSE block] END */
1548 ktap_funcstate *fs = ls->fs;
1549 int escapelist = NO_JUMP; /* exit list for finished parts */
1551 test_then_block(ls, &escapelist); /* IF cond THEN block */
1552 while (ls->t.token == TK_ELSEIF)
1553 test_then_block(ls, &escapelist); /* ELSEIF cond THEN block */
1554 if (testnext(ls, TK_ELSE)) {
1556 block(ls); /* `else' part */
1559 //check_match(ls, TK_END, TK_IF, line);
1560 codegen_patchtohere(fs, escapelist); /* patch escape list to 'if' end */
1563 static void localfunc(ktap_lexstate *ls)
1566 ktap_funcstate *fs = ls->fs;
1568 new_localvar(ls, str_checkname(ls)); /* new local variable */
1569 adjustlocalvars(ls, 1); /* enter its scope */
1570 body(ls, &b, 0, ls->linenumber); /* function created in next register */
1571 /* debug information will only see the variable after this point! */
1572 getlocvar(fs, b.u.info)->startpc = fs->pc;
1575 static void localstat(ktap_lexstate *ls)
1577 /* stat -> LOCAL NAME {`,' NAME} [`=' explist] */
1583 new_localvar(ls, str_checkname(ls));
1585 } while (testnext(ls, ','));
1586 if (testnext(ls, '='))
1587 nexps = explist(ls, &e);
1592 adjust_assign(ls, nvars, nexps, &e);
1593 adjustlocalvars(ls, nvars);
1596 static int funcname(ktap_lexstate *ls, ktap_expdesc *v)
1598 /* funcname -> NAME {fieldsel} [`:' NAME] */
1602 while (ls->t.token == '.')
1604 if (ls->t.token == ':') {
1611 static void funcstat(ktap_lexstate *ls, int line)
1613 /* funcstat -> FUNCTION funcname body */
1617 lex_next(ls); /* skip FUNCTION */
1618 ismethod = funcname(ls, &v);
1619 body(ls, &b, ismethod, line);
1620 codegen_storevar(ls->fs, &v, &b);
1621 codegen_fixline(ls->fs, line); /* definition `happens' in the first line */
1624 static void exprstat(ktap_lexstate *ls)
1626 /* stat -> func | assignment */
1627 ktap_funcstate *fs = ls->fs;
1628 struct LHS_assign v;
1630 suffixedexp(ls, &v.v);
1631 /* stat -> assignment ? */
1632 if (ls->t.token == '=' || ls->t.token == ',' ||
1633 ls->t.token == TK_INCR || ls->t.token == TK_AGGR_ASSIGN) {
1635 assignment(ls, &v, 1);
1636 } else { /* stat -> func */
1637 check_condition(ls, v.v.k == VCALL, "syntax error");
1638 SETARG_C(getcode(fs, &v.v), 1); /* call statement uses no results */
1642 static void retstat(ktap_lexstate *ls)
1644 /* stat -> RETURN [explist] [';'] */
1645 ktap_funcstate *fs = ls->fs;
1647 int first, nret; /* registers with returned values */
1649 if (block_follow(ls, 1) || ls->t.token == ';')
1650 first = nret = 0; /* return no values */
1652 nret = explist(ls, &e); /* optional return values */
1653 if (hasmultret(e.k)) {
1654 codegen_setmultret(fs, &e);
1655 if (e.k == VCALL && nret == 1) { /* tail call? */
1656 SET_OPCODE(getcode(fs,&e), OP_TAILCALL);
1657 ktap_assert(GETARG_A(getcode(fs,&e)) == fs->nactvar);
1659 first = fs->nactvar;
1660 nret = KTAP_MULTRET; /* return all values */
1662 if (nret == 1) /* only one single value? */
1663 first = codegen_exp2anyreg(fs, &e);
1665 codegen_exp2nextreg(fs, &e); /* values must go to the `stack' */
1666 first = fs->nactvar; /* return all `active' values */
1667 ktap_assert(nret == fs->freereg - first);
1671 codegen_ret(fs, first, nret);
1672 testnext(ls, ';'); /* skip optional semicolon */
1675 static void tracestat(ktap_lexstate *ls)
1677 ktap_expdesc v0, key, args;
1678 ktap_expdesc *v = &v0;
1679 ktap_string *kdebug_str = ktapc_ts_new("kdebug");
1680 ktap_string *probe_str = ktapc_ts_new("probe_by_id");
1681 ktap_string *probe_end_str = ktapc_ts_new("probe_end");
1682 ktap_funcstate *fs = ls->fs;
1683 int token = ls->t.token;
1684 int line = ls->linenumber;
1687 if (token == TK_TRACE)
1688 lex_read_string_until(ls, '{');
1690 lex_next(ls); /* skip "trace_end" keyword */
1693 singlevaraux(fs, ls->envn, v, 1); /* get environment variable */
1694 codestring(ls, &key, kdebug_str); /* key is variable name */
1695 codegen_indexed(fs, v, &key); /* env[varname] */
1697 /* fieldsel: kdebug.probe */
1698 codegen_exp2anyregup(fs, v);
1699 if (token == TK_TRACE)
1700 codestring(ls, &key, probe_str);
1701 else if (token == TK_TRACE_END)
1702 codestring(ls, &key, probe_end_str);
1703 codegen_indexed(fs, v, &key);
1706 codegen_exp2nextreg(fs, v);
1708 if (token == TK_TRACE) {
1709 ktap_eventdef_info *evdef_info;
1711 /* argument: EVENTDEF string */
1712 check(ls, TK_STRING);
1714 evdef_info = ktapc_parse_eventdef(getstr(ls->t.seminfo.ts));
1715 check_condition(ls, evdef_info != NULL, "Cannot parse eventdef");
1717 /* pass a userspace pointer to kernel */
1718 codenumber(ls, &args, (ktap_number)evdef_info);
1719 lex_next(ls); /* skip EVENTDEF string */
1722 codegen_exp2nextreg(fs, &args); /* for next argument */
1725 /* argument: callback function */
1727 func_body_no_args(ls, &args, ls->linenumber);
1730 codegen_setmultret(fs, &args);
1732 base = v->u.info; /* base register for call */
1733 if (hasmultret(args.k))
1734 nparams = KTAP_MULTRET; /* open call */
1736 codegen_exp2nextreg(fs, &args); /* close last argument */
1737 nparams = fs->freereg - (base+1);
1739 init_exp(v, VCALL, codegen_codeABC(fs, OP_CALL, base, nparams+1, 2));
1740 codegen_fixline(fs, line);
1741 fs->freereg = base+1;
1743 check_condition(ls, v->k == VCALL, "syntax error");
1744 SETARG_C(getcode(fs, v), 1); /* call statement uses no results */
1747 static void timerstat(ktap_lexstate *ls)
1749 ktap_expdesc v0, key, args;
1750 ktap_expdesc *v = &v0;
1751 ktap_funcstate *fs = ls->fs;
1752 ktap_string *token_str = ls->t.seminfo.ts;
1753 ktap_string *interval_str;
1754 int line = ls->linenumber;
1757 lex_next(ls); /* skip profile/tick keyword */
1760 lex_read_string_until(ls, '{');
1761 interval_str = ls->t.seminfo.ts;
1763 //printf("timerstat str: %s\n", getstr(interval_str));
1767 singlevaraux(fs, ls->envn, v, 1); /* get environment variable */
1768 codestring(ls, &key, ktapc_ts_new("timer")); /* key is variable name */
1769 codegen_indexed(fs, v, &key); /* env[varname] */
1771 /* fieldsel: timer.profile, timer.tick */
1772 codegen_exp2anyregup(fs, v);
1773 codestring(ls, &key, token_str);
1774 codegen_indexed(fs, v, &key);
1777 codegen_exp2nextreg(fs, v);
1779 /* argument: interval string */
1780 check(ls, TK_STRING);
1782 codestring(ls, &args, interval_str);
1783 lex_next(ls); /* skip interval string */
1786 codegen_exp2nextreg(fs, &args); /* for next argument */
1788 /* argument: callback function */
1790 func_body_no_args(ls, &args, ls->linenumber);
1793 codegen_setmultret(fs, &args);
1795 base = v->u.info; /* base register for call */
1796 if (hasmultret(args.k))
1797 nparams = KTAP_MULTRET; /* open call */
1799 codegen_exp2nextreg(fs, &args); /* close last argument */
1800 nparams = fs->freereg - (base+1);
1802 init_exp(v, VCALL, codegen_codeABC(fs, OP_CALL, base, nparams+1, 2));
1803 codegen_fixline(fs, line);
1804 fs->freereg = base+1;
1806 check_condition(ls, v->k == VCALL, "syntax error");
1807 SETARG_C(getcode(fs, v), 1); /* call statement uses no results */
1810 /* we still keep cdef keyword even FFI feature is disabled, it just does
1811 * nothing and prints out a warning */
1812 #ifdef CONFIG_KTAP_FFI
1813 static void parsecdef(ktap_lexstate *ls)
1815 /* read long string cdef */
1818 check(ls, TK_STRING);
1819 ffi_cdef(getstr(ls->t.seminfo.ts));
1821 /* consume newline */
1825 static void parsecdef(ktap_lexstate *ls)
1827 printf("Please compile with FFI support to use cdef!\n");
1833 static void statement(ktap_lexstate *ls)
1835 int line = ls->linenumber; /* may be needed for error messages */
1838 switch (ls->t.token) {
1839 case ';': { /* stat -> ';' (empty statement) */
1840 lex_next(ls); /* skip ';' */
1843 case TK_IF: { /* stat -> ifstat */
1847 case TK_WHILE: { /* stat -> whilestat */
1848 whilestat(ls, line);
1851 case TK_DO: { /* stat -> DO block END */
1852 lex_next(ls); /* skip DO */
1854 check_match(ls, TK_END, TK_DO, line);
1857 case TK_FOR: { /* stat -> forstat */
1861 case TK_REPEAT: { /* stat -> repeatstat */
1862 repeatstat(ls, line);
1865 case TK_FUNCTION: { /* stat -> funcstat */
1869 case TK_LOCAL: { /* stat -> localstat */
1870 lex_next(ls); /* skip LOCAL */
1871 if (testnext(ls, TK_FUNCTION)) /* local function? */
1877 case TK_DBCOLON: { /* stat -> label */
1878 lex_next(ls); /* skip double colon */
1879 labelstat(ls, str_checkname(ls), line);
1882 case TK_RETURN: { /* stat -> retstat */
1883 lex_next(ls); /* skip RETURN */
1887 case TK_BREAK: /* stat -> breakstat */
1888 case TK_GOTO: { /* stat -> 'goto' NAME */
1889 gotostat(ls, codegen_jump(ls->fs));
1904 default: { /* stat -> func | assignment */
1909 //ktap_assert(ls->fs->f->maxstacksize >= ls->fs->freereg &&
1910 // ls->fs->freereg >= ls->fs->nactvar);
1911 ls->fs->freereg = ls->fs->nactvar; /* free registers */
1914 /* }====================================================================== */
1917 * compiles the main function, which is a regular vararg function with an upvalue
1919 static void mainfunc(ktap_lexstate *ls, ktap_funcstate *fs)
1924 open_func(ls, fs, &bl);
1925 fs->f->is_vararg = 1; /* main function is always vararg */
1926 init_exp(&v, VLOCAL, 0); /* create and... */
1927 newupvalue(fs, ls->envn, &v); /* ...set environment upvalue */
1928 lex_next(ls); /* read first token */
1929 statlist(ls); /* parse main body */
1934 ktap_closure *ktapc_parser(char *ptr, const char *name)
1936 ktap_lexstate lexstate;
1937 ktap_funcstate funcstate;
1940 int firstchar = *ptr++;
1941 ktap_closure *cl = ktapc_newclosure(1); /* create main closure */
1943 memset(&lexstate, 0, sizeof(ktap_lexstate));
1944 memset(&funcstate, 0, sizeof(ktap_funcstate));
1945 funcstate.f = cl->p = ktapc_newproto();
1946 funcstate.f->source = ktapc_ts_new(name); /* create and anchor ktap_string */
1951 memset(&dyd, 0, sizeof(ktap_dyndata));
1952 lexstate.buff = &buff;
1953 lexstate.dyd = &dyd;
1954 lex_setinput(&lexstate, ptr, funcstate.f->source, firstchar);
1956 mainfunc(&lexstate, &funcstate);
1958 ktap_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
1960 /* all scopes should be correctly finished */
1961 ktap_assert(dyd.actvar.n == 0 && dyd.gt.n == 0 && dyd.label.n == 0);