Merge tag 'v3.14.25' into backport/v3.14.24-ltsi-rc1+v3.14.25/snapshot-merge.wip
[platform/adaptation/renesas_rcar/renesas_kernel.git] / drivers / staging / ktap / userspace / parser.c
1 /*
2  * parser.c - ktap parser
3  *
4  * This file is part of ktap by Jovi Zhangwei.
5  *
6  * Copyright (C) 2012-2013 Jovi Zhangwei <jovi.zhangwei@gmail.com>.
7  *
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.
11  *
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.
15  *
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
19  * more details.
20  *
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.
24  */
25
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29
30 #include "../include/ktap_types.h"
31 #include "../include/ktap_opcodes.h"
32 #include "ktapc.h"
33 #include "cparser.h"
34
35 /* maximum number of local variables per function (must be smaller
36    than 250, due to the bytecode format) */
37 #define MAXVARS         200
38
39 #define hasmultret(k)           ((k) == VCALL || (k) == VVARARG)
40
41 /*
42  * nodes for block list (list of active blocks)
43  */
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 */
51 } ktap_blockcnt;
52
53 /*
54  * prototypes for recursive non-terminal functions
55  */
56 static void statement (ktap_lexstate *ls);
57 static void expr (ktap_lexstate *ls, ktap_expdesc *v);
58
59 static void anchor_token(ktap_lexstate *ls)
60 {
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);
66         }
67 }
68
69 /* semantic error */
70 static void semerror(ktap_lexstate *ls, const char *msg)
71 {
72         ls->t.token = 0;  /* remove 'near to' from final message */
73         lex_syntaxerror(ls, msg);
74 }
75
76 static void error_expected(ktap_lexstate *ls, int token)
77 {
78         lex_syntaxerror(ls,
79                 ktapc_sprintf("%s expected", lex_token2str(ls, token)));
80 }
81
82 static void errorlimit(ktap_funcstate *fs, int limit, const char *what)
83 {
84         const char *msg;
85         int line = fs->f->linedefined;
86         const char *where = (line == 0) ? "main function"
87                                 : ktapc_sprintf("function at line %d", line);
88
89         msg = ktapc_sprintf("too many %s (limit is %d) in %s",
90                                 what, limit, where);
91         lex_syntaxerror(fs->ls, msg);
92 }
93
94 static void checklimit(ktap_funcstate *fs, int v, int l, const char *what)
95 {
96         if (v > l)
97                 errorlimit(fs, l, what);
98 }
99
100 static int testnext(ktap_lexstate *ls, int c)
101 {
102         if (ls->t.token == c) {
103                 lex_next(ls);
104                 return 1;
105         }
106         else
107                 return 0;
108 }
109
110 static void check(ktap_lexstate *ls, int c)
111 {
112         if (ls->t.token != c)
113                 error_expected(ls, c);
114 }
115
116 static void checknext(ktap_lexstate *ls, int c)
117 {
118         check(ls, c);
119         lex_next(ls);
120 }
121
122 #define check_condition(ls,c,msg)       { if (!(c)) lex_syntaxerror(ls, msg); }
123
124 static void check_match(ktap_lexstate *ls, int what, int who, int where)
125 {
126         if (!testnext(ls, what)) {
127                 if (where == ls->linenumber)
128                         error_expected(ls, what);
129                 else {
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));
134                 }
135         }
136 }
137
138 static ktap_string *str_checkname(ktap_lexstate *ls)
139 {
140         ktap_string *ts;
141
142         check(ls, TK_NAME);
143         ts = ls->t.seminfo.ts;
144         lex_next(ls);
145         return ts;
146 }
147
148 static void init_exp(ktap_expdesc *e, expkind k, int i)
149 {
150         e->f = e->t = NO_JUMP;
151         e->k = k;
152         e->u.info = i;
153 }
154
155 static void codestring(ktap_lexstate *ls, ktap_expdesc *e, ktap_string *s)
156 {
157         init_exp(e, VK, codegen_stringK(ls->fs, s));
158 }
159
160 static void codenumber(ktap_lexstate *ls, ktap_expdesc *e, ktap_number n)
161 {
162         init_exp(e, VK, codegen_numberK(ls->fs, n));
163 }
164
165 static void checkname(ktap_lexstate *ls, ktap_expdesc *e)
166 {
167         codestring(ls, e, str_checkname(ls));
168 }
169
170 static int registerlocalvar(ktap_lexstate *ls, ktap_string *varname)
171 {
172         ktap_funcstate *fs = ls->fs;
173         ktap_proto *f = fs->f;
174         int oldsize = f->sizelocvars;
175
176         ktapc_growvector(f->locvars, fs->nlocvars, f->sizelocvars,
177                          ktap_locvar, SHRT_MAX, "local variables");
178
179         while (oldsize < f->sizelocvars)
180                 f->locvars[oldsize++].varname = NULL;
181
182         f->locvars[fs->nlocvars].varname = varname;
183         return fs->nlocvars++;
184 }
185
186 static void new_localvar(ktap_lexstate *ls, ktap_string *name)
187 {
188         ktap_funcstate *fs = ls->fs;
189         ktap_dyndata *dyd = ls->dyd;
190         int reg = registerlocalvar(ls, name);
191
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;
197 }
198
199 static void new_localvarliteral_(ktap_lexstate *ls, const char *name, size_t sz)
200 {
201         new_localvar(ls, lex_newstring(ls, name, sz));
202 }
203
204 #define new_localvarliteral(ls,v) \
205         new_localvarliteral_(ls, "" v, (sizeof(v)/sizeof(char))-1)
206
207 static ktap_locvar *getlocvar(ktap_funcstate *fs, int i)
208 {
209         int idx = fs->ls->dyd->actvar.arr[fs->firstlocal + i].idx;
210
211         ktap_assert(idx < fs->nlocvars);
212         return &fs->f->locvars[idx];
213 }
214
215 static void adjustlocalvars(ktap_lexstate *ls, int nvars)
216 {
217         ktap_funcstate *fs = ls->fs;
218
219         fs->nactvar = (u8)(fs->nactvar + nvars);
220         for (; nvars; nvars--) {
221                 getlocvar(fs, fs->nactvar - nvars)->startpc = fs->pc;
222         }
223 }
224
225 static void removevars(ktap_funcstate *fs, int tolevel)
226 {
227         fs->ls->dyd->actvar.n -= (fs->nactvar - tolevel);
228
229         while (fs->nactvar > tolevel)
230                 getlocvar(fs, --fs->nactvar)->endpc = fs->pc;
231 }
232
233 static int searchupvalue(ktap_funcstate *fs, ktap_string *name)
234 {
235         int i;
236         ktap_upvaldesc *up = fs->f->upvalues;
237
238         for (i = 0; i < fs->nups; i++) {
239                 if (ktapc_ts_eqstr(up[i].name, name))
240                         return i;
241         }
242         return -1;  /* not found */
243 }
244
245 static int newupvalue(ktap_funcstate *fs, ktap_string *name, ktap_expdesc *v)
246 {
247         ktap_proto *f = fs->f;
248         int oldsize = f->sizeupvalues;
249
250         checklimit(fs, fs->nups + 1, MAXUPVAL, "upvalues");
251         ktapc_growvector(f->upvalues, fs->nups, f->sizeupvalues,
252                          ktap_upvaldesc, MAXUPVAL, "upvalues");
253
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;
259         return fs->nups++;
260 }
261
262 static int searchvar(ktap_funcstate *fs, ktap_string *n)
263 {
264         int i;
265
266         for (i = fs->nactvar-1; i >= 0; i--) {
267                 if (ktapc_ts_eqstr(n, getlocvar(fs, i)->varname))
268                         return i;
269         }
270         return -1;  /* not found */
271 }
272
273 /*
274  * Mark block where variable at given level was defined
275  * (to emit close instructions later).
276  */
277 static void markupval(ktap_funcstate *fs, int level)
278 {
279         ktap_blockcnt *bl = fs->bl;
280
281         while (bl->nactvar > level)
282                 bl = bl->previous;
283         bl->upval = 1;
284 }
285
286 /*
287  * Find variable with given name 'n'. If it is an upvalue, add this
288  * upvalue into all intermediate functions.
289  */
290 static int singlevaraux(ktap_funcstate *fs, ktap_string *n, ktap_expdesc *var, int base)
291 {
292         if (fs == NULL)  /* no more levels? */
293                 return VVOID;  /* default is global */
294         else {
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 */
298                         if (!base)
299                                 markupval(fs, v);  /* local will be used as an upval */
300                         return VLOCAL;
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 */
308                         }
309                         init_exp(var, VUPVAL, idx);
310                         return VUPVAL;
311                 }
312         }
313 }
314
315 static void singlevar(ktap_lexstate *ls, ktap_expdesc *var)
316 {
317         ktap_string *varname = str_checkname(ls);
318         ktap_funcstate *fs = ls->fs;
319
320         if (singlevaraux(fs, varname, var, 1) == VVOID) {  /* global name? */
321                 ktap_expdesc key;
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] */
326         }
327 }
328
329 static void adjust_assign(ktap_lexstate *ls, int nvars, int nexps, ktap_expdesc *e)
330 {
331         ktap_funcstate *fs = ls->fs;
332         int extra = nvars - nexps;
333
334         if (hasmultret(e->k)) {
335                 extra++;  /* includes call itself */
336                 if (extra < 0)
337                         extra = 0;
338                 codegen_setreturns(fs, e, extra);  /* last exp. provides the difference */
339                 if (extra > 1)
340                         codegen_reserveregs(fs, extra-1);
341         } else {
342                 if (e->k != VVOID)
343                         codegen_exp2nextreg(fs, e);  /* close last expression */
344                 if (extra > 0) {
345                         int reg = fs->freereg;
346
347                         codegen_reserveregs(fs, extra);
348                         codegen_nil(fs, reg, extra);
349                 }
350         }
351 }
352
353 static void enterlevel(ktap_lexstate *ls)
354 {
355         ++ls->nCcalls;
356         checklimit(ls->fs, ls->nCcalls, KTAP_MAXCCALLS, "C levels");
357 }
358
359 static void closegoto(ktap_lexstate *ls, int g, ktap_labeldesc *label)
360 {
361         int i;
362         ktap_funcstate *fs = ls->fs;
363         ktap_labellist *gl = &ls->dyd->gt;
364         ktap_labeldesc *gt = &gl->arr[g];
365
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));
372                 semerror(ls, msg);
373         }
374
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];
379         gl->n--;
380 }
381
382 /*
383  * try to close a goto with existing labels; this solves backward jumps
384  */
385 static int findlabel(ktap_lexstate *ls, int g)
386 {
387         int i;
388         ktap_blockcnt *bl = ls->fs->bl;
389         ktap_dyndata *dyd = ls->dyd;
390         ktap_labeldesc *gt = &dyd->gt.arr[g];
391
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 */
400                         return 1;
401                 }
402         }
403         return 0;  /* label not found; cannot close goto */
404 }
405
406 static int newlabelentry(ktap_lexstate *ls, ktap_labellist *l, ktap_string *name,
407                          int line, int pc)
408 {
409         int n = l->n;
410
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;
416         l->arr[n].pc = pc;
417         l->n++;
418         return n;
419 }
420
421
422 /*
423  * check whether new label 'lb' matches any pending gotos in current
424  * block; solves forward jumps
425  */
426 static void findgotos(ktap_lexstate *ls, ktap_labeldesc *lb)
427 {
428         ktap_labellist *gl = &ls->dyd->gt;
429         int i = ls->fs->bl->firstgoto;
430
431         while (i < gl->n) {
432                 if (ktapc_ts_eqstr(gl->arr[i].name, lb->name))
433                         closegoto(ls, i, lb);
434                 else
435                         i++;
436         }
437 }
438
439 /*
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.
444  */
445 static void movegotosout(ktap_funcstate *fs, ktap_blockcnt *bl)
446 {
447         int i = bl->firstgoto;
448         ktap_labellist *gl = &fs->ls->dyd->gt;
449
450         /* correct pending gotos to current block and try to close it
451                 with visible labels */
452         while (i < gl->n) {
453                 ktap_labeldesc *gt = &gl->arr[i];
454
455                 if (gt->nactvar > bl->nactvar) {
456                         if (bl->upval)
457                                 codegen_patchclose(fs, gt->pc, bl->nactvar);
458                         gt->nactvar = bl->nactvar;
459                 }
460                 if (!findlabel(fs->ls, i))
461                         i++;  /* move to next one */
462         }
463 }
464
465 static void enterblock(ktap_funcstate *fs, ktap_blockcnt *bl, u8 isloop)
466 {
467         bl->isloop = isloop;
468         bl->nactvar = fs->nactvar;
469         bl->firstlabel = fs->ls->dyd->label.n;
470         bl->firstgoto = fs->ls->dyd->gt.n;
471         bl->upval = 0;
472         bl->previous = fs->bl;
473         fs->bl = bl;
474         ktap_assert(fs->freereg == fs->nactvar);
475 }
476
477
478 /*
479  * create a label named "break" to resolve break statements
480  */
481 static void breaklabel(ktap_lexstate *ls)
482 {
483         ktap_string *n = ktapc_ts_new("break");
484         int l = newlabelentry(ls, &ls->dyd->label, n, 0, ls->fs->pc);
485
486         findgotos(ls, &ls->dyd->label.arr[l]);
487 }
488
489 /*
490  * generates an error for an undefined 'goto'; choose appropriate
491  * message when label name is a reserved word (which can only be 'break')
492  */
493 static void undefgoto(ktap_lexstate *ls, ktap_labeldesc *gt)
494 {
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";
498
499         msg = ktapc_sprintf(msg, getstr(gt->name), gt->line);
500         semerror(ls, msg);
501 }
502
503 static void leaveblock(ktap_funcstate *fs)
504 {
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);
510
511                 codegen_patchclose(fs, j, bl->nactvar);
512                 codegen_patchtohere(fs, j);
513         }
514
515         if (bl->isloop)
516                 breaklabel(ls);  /* close pending breaks */
517
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 */
527 }
528
529 /*
530  * adds a new prototype into list of prototypes
531  */
532 static ktap_proto *addprototype(ktap_lexstate *ls)
533 {
534         ktap_proto *clp;
535         ktap_funcstate *fs = ls->fs;
536         ktap_proto *f = fs->f;  /* prototype of current function */
537
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;
543         }
544         f->p[fs->np++] = clp = ktapc_newproto();
545         return clp;
546 }
547
548 /*
549  * codes instruction to create new closure in parent function
550  */
551 static void codeclosure(ktap_lexstate *ls, ktap_expdesc *v)
552 {
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) */
556 }
557
558 static void open_func(ktap_lexstate *ls, ktap_funcstate *fs, ktap_blockcnt *bl)
559 {
560         ktap_proto *f;
561
562         fs->prev = ls->fs;  /* linked list of funcstates */
563         fs->ls = ls;
564         ls->fs = fs;
565         fs->pc = 0;
566         fs->lasttarget = 0;
567         fs->jpc = NO_JUMP;
568         fs->freereg = 0;
569         fs->nk = 0;
570         fs->np = 0;
571         fs->nups = 0;
572         fs->nlocvars = 0;
573         fs->nactvar = 0;
574         fs->firstlocal = ls->dyd->actvar.n;
575         fs->bl = NULL;
576         f = fs->f;
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);
582 }
583
584 static void close_func(ktap_lexstate *ls)
585 {
586         ktap_funcstate *fs = ls->fs;
587         ktap_proto *f = fs->f;
588
589         codegen_ret(fs, 0, 0);  /* final return */
590         leaveblock(fs);
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);
596         f->sizek = fs->nk;
597         ktapc_reallocvector(f->p, f->sizep, fs->np, ktap_proto *);
598         f->sizep = fs->np;
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));
604         ls->fs = fs->prev;
605         /* last token read was anchored in defunct function; must re-anchor it */
606         anchor_token(ls);
607 }
608
609
610 /*============================================================*/
611 /* GRAMMAR RULES */
612 /*============================================================*/
613
614 /*
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.
618  */
619 static int block_follow(ktap_lexstate *ls, int withuntil)
620 {
621         switch (ls->t.token) {
622         case TK_ELSE: case TK_ELSEIF:
623         case TK_END: case TK_EOS:
624                 return 1;
625         case TK_UNTIL:
626                 return withuntil;
627         case '}':
628                 return 1;
629         default:
630                 return 0;
631         }
632 }
633
634 static void statlist(ktap_lexstate *ls)
635 {
636         /* statlist -> { stat [`;'] } */
637         while (!block_follow(ls, 1)) {
638                 if (ls->t.token == TK_RETURN) {
639                         statement(ls);
640                         return;  /* 'return' must be last statement */
641                 }
642                 statement(ls);
643         }
644 }
645
646 static void fieldsel(ktap_lexstate *ls, ktap_expdesc *v)
647 {
648         /* fieldsel -> ['.' | ':'] NAME */
649         ktap_funcstate *fs = ls->fs;
650         ktap_expdesc key;
651
652         codegen_exp2anyregup(fs, v);
653         lex_next(ls);  /* skip the dot or colon */
654         checkname(ls, &key);
655         codegen_indexed(fs, v, &key);
656 }
657
658 static void yindex(ktap_lexstate *ls, ktap_expdesc *v)
659 {
660         /* index -> '[' expr ']' */
661         lex_next(ls);  /* skip the '[' */
662         expr(ls, v);
663         codegen_exp2val(ls->fs, v);
664         checknext(ls, ']');
665 }
666
667 /*
668  * {======================================================================
669  * Rules for Constructors
670  * =======================================================================
671  */
672 struct ConsControl {
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 */
678 };
679
680 static void recfield(ktap_lexstate *ls, struct ConsControl *cc)
681 {
682         /* recfield -> (NAME | `['exp1`]') = exp1 */
683         ktap_funcstate *fs = ls->fs;
684         int reg = ls->fs->freereg;
685         ktap_expdesc key, val;
686         int rkkey;
687
688         if (ls->t.token == TK_NAME) {
689                 checklimit(fs, cc->nh, MAX_INT, "items in a constructor");
690                 checkname(ls, &key);
691         } else  /* ls->t.token == '[' */
692                 yindex(ls, &key);
693
694         cc->nh++;
695         checknext(ls, '=');
696         rkkey = codegen_exp2RK(fs, &key);
697         expr(ls, &val);
698         codegen_codeABC(fs, OP_SETTABLE, cc->t->u.info, rkkey, codegen_exp2RK(fs, &val));
699         fs->freereg = reg;  /* free registers */
700 }
701
702 static void closelistfield(ktap_funcstate *fs, struct ConsControl *cc)
703 {
704         if (cc->v.k == VVOID)
705                 return;  /* there is no list item */
706         codegen_exp2nextreg(fs, &cc->v);
707         cc->v.k = VVOID;
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 */
711         }
712 }
713
714 static void lastlistfield(ktap_funcstate *fs, struct ConsControl *cc)
715 {
716         if (cc->tostore == 0)
717                 return;
718
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) */
723         } else {
724                 if (cc->v.k != VVOID)
725                         codegen_exp2nextreg(fs, &cc->v);
726                 codegen_setlist(fs, cc->t->u.info, cc->na, cc->tostore);
727         }
728 }
729
730 static void listfield(ktap_lexstate *ls, struct ConsControl *cc)
731 {
732         /* listfield -> exp */
733         expr(ls, &cc->v);
734         checklimit(ls->fs, cc->na, MAX_INT, "items in a constructor");
735         cc->na++;
736         cc->tostore++;
737 }
738
739 static void field(ktap_lexstate *ls, struct ConsControl *cc)
740 {
741         /* field -> listfield | recfield */
742         switch(ls->t.token) {
743         case TK_NAME: {  /* may be 'listfield' or 'recfield' */
744                 if (lex_lookahead(ls) != '=')  /* expression? */
745                         listfield(ls, cc);
746                 else
747                         recfield(ls, cc);
748                 break;
749         }
750         case '[': {
751                 recfield(ls, cc);
752                 break;
753         }
754         default:
755                 listfield(ls, cc);
756                 break;
757         }
758 }
759
760 static void constructor(ktap_lexstate *ls, ktap_expdesc *t)
761 {
762         /* constructor -> '{' [ field { sep field } [sep] ] '}'
763                 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;
768
769         cc.na = cc.nh = cc.tostore = 0;
770         cc.t = t;
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 */
774         checknext(ls, '{');
775         do {
776                 ktap_assert(cc.v.k == VVOID || cc.tostore > 0);
777                 if (ls->t.token == '}')
778                         break;
779                 closelistfield(fs, &cc);
780                 field(ls, &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 */
786 }
787
788 /* }====================================================================== */
789
790 static void parlist(ktap_lexstate *ls)
791 {
792         /* parlist -> [ param { `,' param } ] */
793         ktap_funcstate *fs = ls->fs;
794         ktap_proto *f = fs->f;
795         int nparams = 0;
796         f->is_vararg = 0;
797
798         if (ls->t.token != ')') {  /* is `parlist' not empty? */
799                 do {
800                         switch (ls->t.token) {
801                         case TK_NAME: {  /* param -> NAME */
802                                 new_localvar(ls, str_checkname(ls));
803                                 nparams++;
804                                 break;
805                         }
806                         case TK_DOTS: {  /* param -> `...' */
807                                 lex_next(ls);
808                                 f->is_vararg = 1;
809                                 break;
810                         }
811                         default:
812                                 lex_syntaxerror(ls, "<name> or " KTAP_QL("...") " expected");
813                         }
814                 } while (!f->is_vararg && testnext(ls, ','));
815         }
816         adjustlocalvars(ls, nparams);
817         f->numparams = (u8)(fs->nactvar);
818         codegen_reserveregs(fs, fs->nactvar);  /* reserve register for parameters */
819 }
820
821 static void body(ktap_lexstate *ls, ktap_expdesc *e, int ismethod, int line)
822 {
823         /* body ->  `(' parlist `)' block END */
824         ktap_funcstate new_fs;
825         ktap_blockcnt bl;
826
827         new_fs.f = addprototype(ls);
828         new_fs.f->linedefined = line;
829         open_func(ls, &new_fs, &bl);
830         checknext(ls, '(');
831         if (ismethod) {
832                 new_localvarliteral(ls, "self");  /* create 'self' parameter */
833                 adjustlocalvars(ls, 1);
834         }
835         parlist(ls);
836         checknext(ls, ')');
837         checknext(ls, '{');
838         statlist(ls);
839         new_fs.f->lastlinedefined = ls->linenumber;
840         checknext(ls, '}');
841         //check_match(ls, TK_END, TK_FUNCTION, line);
842         codeclosure(ls, e);
843         close_func(ls);
844 }
845
846 static void func_body_no_args(ktap_lexstate *ls, ktap_expdesc *e, int line)
847 {
848         /* body ->  `(' parlist `)' block END */
849         ktap_funcstate new_fs;
850         ktap_blockcnt bl;
851
852         new_fs.f = addprototype(ls);
853         new_fs.f->linedefined = line;
854         open_func(ls, &new_fs, &bl);
855         checknext(ls, '{');
856         statlist(ls);
857         new_fs.f->lastlinedefined = ls->linenumber;
858         checknext(ls, '}');
859         //check_match(ls, TK_END, TK_FUNCTION, line);
860         codeclosure(ls, e);
861         close_func(ls);
862 }
863
864 static int explist(ktap_lexstate *ls, ktap_expdesc *v)
865 {
866         /* explist -> expr { `,' expr } */
867         int n = 1;  /* at least one expression */
868
869         expr(ls, v);
870         while (testnext(ls, ',')) {
871                 codegen_exp2nextreg(ls->fs, v);
872                 expr(ls, v);
873                 n++;
874         }
875         return n;
876 }
877
878 static void funcargs(ktap_lexstate *ls, ktap_expdesc *f, int line)
879 {
880         ktap_funcstate *fs = ls->fs;
881         ktap_expdesc args;
882         int base, nparams;
883
884         switch (ls->t.token) {
885         case '(': {  /* funcargs -> `(' [ explist ] `)' */
886                 lex_next(ls);
887                 if (ls->t.token == ')')  /* arg list is empty? */
888                         args.k = VVOID;
889                 else {
890                         explist(ls, &args);
891                         codegen_setmultret(fs, &args);
892                 }
893                 check_match(ls, ')', '(', line);
894                 break;
895         }
896         case '{': {  /* funcargs -> constructor */
897                 constructor(ls, &args);
898                 break;
899         }
900         case TK_STRING: {  /* funcargs -> STRING */
901                 codestring(ls, &args, ls->t.seminfo.ts);
902                 lex_next(ls);  /* must use `seminfo' before `next' */
903                 break;
904         }
905         default: {
906                 lex_syntaxerror(ls, "function arguments expected");
907         }
908         }
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 */
913         else {
914                 if (args.k != VVOID)
915                         codegen_exp2nextreg(fs, &args);  /* close last argument */
916                 nparams = fs->freereg - (base+1);
917         }
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 */
922 }
923
924 /*
925  * {======================================================================
926  * Expression parsing
927  * =======================================================================
928  */
929 static void primaryexp(ktap_lexstate *ls, ktap_expdesc *v)
930 {
931         /* primaryexp -> NAME | '(' expr ')' */
932         switch (ls->t.token) {
933         case '(': {
934                 int line = ls->linenumber;
935
936                 lex_next(ls);
937                 expr(ls, v);
938                 check_match(ls, ')', '(', line);
939                 codegen_dischargevars(ls->fs, v);
940                 return;
941         }
942         case TK_NAME:
943                 singlevar(ls, v);
944                 return;
945         default:
946                 lex_syntaxerror(ls, "unexpected symbol");
947         }
948 }
949
950 static void suffixedexp(ktap_lexstate *ls, ktap_expdesc *v)
951 {
952         /* suffixedexp ->
953                 primaryexp { '.' NAME | '[' exp ']' | ':' NAME funcargs | funcargs } */
954         ktap_funcstate *fs = ls->fs;
955         int line = ls->linenumber;
956
957         primaryexp(ls, v);
958         for (;;) {
959                 switch (ls->t.token) {
960                 case '.': {  /* fieldsel */
961                         fieldsel(ls, v);
962                         break;
963                 }
964                 case '[': {  /* `[' exp1 `]' */
965                         ktap_expdesc key;
966                         codegen_exp2anyregup(fs, v);
967                         yindex(ls, &key);
968                         codegen_indexed(fs, v, &key);
969                         break;
970                 }
971                 case ':': {  /* `:' NAME funcargs */
972                         ktap_expdesc key;
973                         lex_next(ls);
974                         checkname(ls, &key);
975                         codegen_self(fs, v, &key);
976                         funcargs(ls, v, line);
977                         break;
978                 }
979                 case '(': case TK_STRING: case '{': {  /* funcargs */
980                         codegen_exp2nextreg(fs, v);
981                         funcargs(ls, v, line);
982                         break;
983                 }
984                 default:
985                         return;
986                 }
987         }
988 }
989
990 static void simpleexp(ktap_lexstate *ls, ktap_expdesc *v)
991 {
992         /* simpleexp -> NUMBER | STRING | NIL | TRUE | FALSE | ... |
993                 constructor | FUNCTION body | suffixedexp */
994         switch (ls->t.token) {
995         case TK_NUMBER: {
996                 init_exp(v, VKNUM, 0);
997                 v->u.nval = ls->t.seminfo.r;
998                 break;
999         }
1000         case TK_STRING: {
1001                 codestring(ls, v, ls->t.seminfo.ts);
1002                 break;
1003         }
1004         case TK_KSYM: {
1005                 init_exp(v, VKNUM, 0);
1006                 v->u.nval =
1007                 (ktap_number)find_kernel_symbol(getstr(ls->t.seminfo.ts));
1008                 break;
1009         }
1010         case TK_NIL: {
1011                 init_exp(v, VNIL, 0);
1012                 break;
1013         }
1014         case TK_TRUE: {
1015                 init_exp(v, VTRUE, 0);
1016                 break;
1017         }
1018         case TK_FALSE: {
1019                 init_exp(v, VFALSE, 0);
1020                 break;
1021         }
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));
1027                 break;
1028         }
1029         case '{': {  /* constructor */
1030                 constructor(ls, v);
1031                 return;
1032         }
1033         case TK_FUNCTION: {
1034                 lex_next(ls);
1035                 body(ls, v, 0, ls->linenumber);
1036                 return;
1037         }
1038         case TK_ARGEVENT:
1039                 init_exp(v, VEVENT, 0);
1040                 break;
1041
1042         case TK_ARGNAME:
1043                 init_exp(v, VEVENTNAME, 0);
1044                 break;
1045         case TK_ARG1:
1046         case TK_ARG2:
1047         case TK_ARG3:
1048         case TK_ARG4:
1049         case TK_ARG5:
1050         case TK_ARG6:
1051         case TK_ARG7:
1052         case TK_ARG8:
1053         case TK_ARG9:
1054                 init_exp(v, VEVENTARG, ls->t.token - TK_ARG1 + 1);
1055                 break;
1056         default: {
1057                 suffixedexp(ls, v);
1058                 return;
1059         }
1060         }
1061         lex_next(ls);
1062 }
1063
1064 static UnOpr getunopr(int op)
1065 {
1066         switch (op) {
1067         case TK_NOT: return OPR_NOT;
1068         case '-': return OPR_MINUS;
1069         case '#': return OPR_LEN;
1070         default: return OPR_NOUNOPR;
1071         }
1072 }
1073
1074 static BinOpr getbinopr(int op)
1075 {
1076         switch (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;
1093         }
1094 }
1095
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 */
1105 };
1106
1107 #define UNARY_PRIORITY  8  /* priority for unary operators */
1108
1109 #define leavelevel(ls)  (ls->nCcalls--)
1110
1111 /*
1112  * subexpr -> (simpleexp | unop subexpr) { binop subexpr }
1113  * where `binop' is any binary operator with a priority higher than `limit'
1114  */
1115 static BinOpr subexpr(ktap_lexstate *ls, ktap_expdesc *v, int limit)
1116 {
1117         BinOpr op;
1118         UnOpr uop;
1119
1120         enterlevel(ls);
1121         uop = getunopr(ls->t.token);
1122         if (uop != OPR_NOUNOPR) {
1123                 int line = ls->linenumber;
1124
1125                 lex_next(ls);
1126                 subexpr(ls, v, UNARY_PRIORITY);
1127                 codegen_prefix(ls->fs, uop, v, line);
1128         } else
1129                 simpleexp(ls, v);
1130
1131         /* expand while operators have priorities higher than `limit' */
1132         op = getbinopr(ls->t.token);
1133         while (op != OPR_NOBINOPR && priority[op].left > limit) {
1134                 ktap_expdesc v2;
1135                 BinOpr nextop;
1136                 int line = ls->linenumber;
1137
1138                 lex_next(ls);
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);
1143                 op = nextop;
1144         }
1145         leavelevel(ls);
1146         return op;  /* return first untreated operator */
1147 }
1148
1149 static void expr(ktap_lexstate *ls, ktap_expdesc *v)
1150 {
1151         subexpr(ls, v, 0);
1152 }
1153
1154 /* }==================================================================== */
1155
1156 /*
1157  * {======================================================================
1158  * Rules for Statements
1159  * =======================================================================
1160  */
1161 static void block(ktap_lexstate *ls)
1162 {
1163         /* block -> statlist */
1164         ktap_funcstate *fs = ls->fs;
1165         ktap_blockcnt bl;
1166
1167         enterblock(fs, &bl, 0);
1168         statlist(ls);
1169         leaveblock(fs);
1170 }
1171
1172 /*
1173  * structure to chain all variables in the left-hand side of an
1174  * assignment
1175  */
1176 struct LHS_assign {
1177         struct LHS_assign *prev;
1178         ktap_expdesc v;  /* variable (global, local, upvalue, or indexed) */
1179 };
1180
1181 /*
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.
1186  */
1187 static void check_conflict(ktap_lexstate *ls, struct LHS_assign *lh, ktap_expdesc *v)
1188 {
1189         ktap_funcstate *fs = ls->fs;
1190         int extra = fs->freereg;  /* eventual position to save local variable */
1191         int conflict = 0;
1192
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) {
1197                                 conflict = 1;
1198                                 lh->v.u.ind.vt = VLOCAL;
1199                                 lh->v.u.ind.t = extra;  /* previous assignment will use safe copy */
1200                         }
1201                         /* index is the local being assigned? (index cannot be upvalue) */
1202                         if (v->k == VLOCAL && lh->v.u.ind.idx == v->u.info) {
1203                                 conflict = 1;
1204                                 lh->v.u.ind.idx = extra;  /* previous assignment will use safe copy */
1205                         }
1206                 }
1207         }
1208         if (conflict) {
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);
1213         }
1214 }
1215
1216 static void assignment(ktap_lexstate *ls, struct LHS_assign *lh, int nvars)
1217 {
1218         ktap_expdesc e;
1219
1220         check_condition(ls, vkisvar(lh->v.k), "syntax error");
1221         if (testnext(ls, ',')) {  /* assignment -> ',' suffixedexp assignment */
1222                 struct LHS_assign nv;
1223
1224                 nv.prev = lh;
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,
1229                                 "C levels");
1230                 assignment(ls, &nv, nvars+1);
1231         } else if (testnext(ls, '=')) {  /* assignment -> '=' explist */
1232                 int nexps;
1233
1234                 nexps = explist(ls, &e);
1235                 if (nexps != nvars) {
1236                         adjust_assign(ls, nvars, nexps, &e);
1237                         /* remove extra values */
1238                         if (nexps > nvars)
1239                                 ls->fs->freereg -= nexps - nvars;
1240                 } else {
1241                         /* close last expression */
1242                         codegen_setoneret(ls->fs, &e);
1243                         codegen_storevar(ls->fs, &lh->v, &e);
1244                         return;  /* avoid default */
1245                 }
1246         } else if (testnext(ls, TK_INCR)) { /* assignment -> '+=' explist */
1247                 int nexps;
1248
1249                 nexps = explist(ls, &e);
1250                 if (nexps != nvars) {
1251                         lex_syntaxerror(ls, "don't allow multi-assign for +=");
1252                 } else {
1253                         /* close last expression */
1254                         codegen_setoneret(ls->fs, &e);
1255                         codegen_storeincr(ls->fs, &lh->v, &e);
1256                         return;  /* avoid default */
1257                 }
1258         } else if (testnext(ls, TK_AGGR_ASSIGN)) { /* assignment -> '<<<' explist */
1259                 int nexps;
1260
1261                 nexps = explist(ls, &e);
1262                 if (nexps != nvars) {
1263                         lex_syntaxerror(ls, "don't allow multi-assign for <<<");
1264                 } else {
1265                         /* close last expression */
1266                         codegen_setoneret(ls->fs, &e);
1267                         codegen_store_aggr(ls->fs, &lh->v, &e);
1268                         return;  /* avoid default */
1269                 }
1270         }
1271
1272         init_exp(&e, VNONRELOC, ls->fs->freereg-1);  /* default assignment */
1273         codegen_storevar(ls->fs, &lh->v, &e);
1274 }
1275
1276 static int cond(ktap_lexstate *ls)
1277 {
1278         /* cond -> exp */
1279         ktap_expdesc v;
1280         expr(ls, &v);  /* read condition */
1281         if (v.k == VNIL)
1282                 v.k = VFALSE;  /* `falses' are all equal here */
1283         codegen_goiftrue(ls->fs, &v);
1284         return v.f;
1285 }
1286
1287 static void gotostat(ktap_lexstate *ls, int pc)
1288 {
1289         int line = ls->linenumber;
1290         ktap_string *label;
1291         int g;
1292
1293         if (testnext(ls, TK_GOTO))
1294                 label = str_checkname(ls);
1295         else {
1296                 lex_next(ls);  /* skip break */
1297                 label = ktapc_ts_new("break");
1298         }
1299         g = newlabelentry(ls, &ls->dyd->gt, label, line, pc);
1300         findlabel(ls, g);  /* close it if label already defined */
1301 }
1302
1303 /* check for repeated labels on the same block */
1304 static void checkrepeated(ktap_funcstate *fs, ktap_labellist *ll, ktap_string *label)
1305 {
1306         int i;
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);
1313                 }
1314         }
1315 }
1316
1317 /* skip no-op statements */
1318 static void skipnoopstat(ktap_lexstate *ls)
1319 {
1320         while (ls->t.token == ';' || ls->t.token == TK_DBCOLON)
1321                 statement(ls);
1322 }
1323
1324 static void labelstat (ktap_lexstate *ls, ktap_string *label, int line)
1325 {
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 */
1330
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;
1339         }
1340         findgotos(ls, &ll->arr[l]);
1341 }
1342
1343 static void whilestat(ktap_lexstate *ls, int line)
1344 {
1345         /* whilestat -> WHILE cond DO block END */
1346         ktap_funcstate *fs = ls->fs;
1347         int whileinit;
1348         int condexit;
1349         ktap_blockcnt bl;
1350
1351         lex_next(ls);  /* skip WHILE */
1352         whileinit = codegen_getlabel(fs);
1353         checknext(ls, '(');
1354         condexit = cond(ls);
1355         checknext(ls, ')');
1356
1357         enterblock(fs, &bl, 1);
1358         //checknext(ls, TK_DO);
1359         checknext(ls, '{');
1360         block(ls);
1361         codegen_jumpto(fs, whileinit);
1362         checknext(ls, '}');
1363         //check_match(ls, TK_END, TK_WHILE, line);
1364         leaveblock(fs);
1365         codegen_patchtohere(fs, condexit);  /* false conditions finish the loop */
1366 }
1367
1368 static void repeatstat(ktap_lexstate *ls, int line)
1369 {
1370         /* repeatstat -> REPEAT block UNTIL cond */
1371         int condexit;
1372         ktap_funcstate *fs = ls->fs;
1373         int repeat_init = codegen_getlabel(fs);
1374         ktap_blockcnt bl1, bl2;
1375
1376         enterblock(fs, &bl1, 1);  /* loop block */
1377         enterblock(fs, &bl2, 0);  /* scope block */
1378         lex_next(ls);  /* skip REPEAT */
1379         statlist(ls);
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 */
1387 }
1388
1389 static int exp1(ktap_lexstate *ls)
1390 {
1391         ktap_expdesc e;
1392         int reg;
1393
1394         expr(ls, &e);
1395         codegen_exp2nextreg(ls->fs, &e);
1396         ktap_assert(e.k == VNONRELOC);
1397         reg = e.u.info;
1398         return reg;
1399 }
1400
1401 static void forbody(ktap_lexstate *ls, int base, int line, int nvars, int isnum)
1402 {
1403         /* forbody -> DO block */
1404         ktap_blockcnt bl;
1405         ktap_funcstate *fs = ls->fs;
1406         int prep, endfor;
1407
1408         checknext(ls, ')');
1409
1410         adjustlocalvars(ls, 3);  /* control variables */
1411         //checknext(ls, TK_DO);
1412         checknext(ls, '{');
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);
1417         block(ls);
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);
1426         }
1427         codegen_patchlist(fs, endfor, prep + 1);
1428         codegen_fixline(fs, line);
1429 }
1430
1431 static void fornum(ktap_lexstate *ls, ktap_string *varname, int line)
1432 {
1433         /* fornum -> NAME = exp1,exp1[,exp1] forbody */
1434         ktap_funcstate *fs = ls->fs;
1435         int base = fs->freereg;
1436
1437         new_localvarliteral(ls, "(for index)");
1438         new_localvarliteral(ls, "(for limit)");
1439         new_localvarliteral(ls, "(for step)");
1440         new_localvar(ls, varname);
1441         checknext(ls, '=');
1442         exp1(ls);  /* initial value */
1443         checknext(ls, ',');
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);
1450         }
1451         forbody(ls, base, line, 1, 1);
1452 }
1453
1454 static void forlist(ktap_lexstate *ls, ktap_string *indexname)
1455 {
1456         /* forlist -> NAME {,NAME} IN explist forbody */
1457         ktap_funcstate *fs = ls->fs;
1458         ktap_expdesc e;
1459         int nvars = 4;  /* gen, state, control, plus at least one declared var */
1460         int line;
1461         int base = fs->freereg;
1462
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));
1471                 nvars++;
1472         }
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);
1478 }
1479
1480 static void forstat(ktap_lexstate *ls, int line)
1481 {
1482         /* forstat -> FOR (fornum | forlist) END */
1483         ktap_funcstate *fs = ls->fs;
1484         ktap_string *varname;
1485         ktap_blockcnt bl;
1486
1487         enterblock(fs, &bl, 1);  /* scope for loop and control variables */
1488         lex_next(ls);  /* skip `for' */
1489
1490         checknext(ls, '(');
1491         varname = str_checkname(ls);  /* first variable name */
1492         switch (ls->t.token) {
1493         case '=':
1494                 fornum(ls, varname, line);
1495                 break;
1496         case ',': case TK_IN:
1497                 forlist(ls, varname);
1498                 break;
1499         default:
1500                 lex_syntaxerror(ls, KTAP_QL("=") " or " KTAP_QL("in") " expected");
1501         }
1502         //check_match(ls, TK_END, TK_FOR, line);
1503         checknext(ls, '}');
1504         leaveblock(fs);  /* loop scope (`break' jumps to this point) */
1505 }
1506
1507 static void test_then_block(ktap_lexstate *ls, int *escapelist)
1508 {
1509         /* test_then_block -> [IF | ELSEIF] cond THEN block */
1510         ktap_blockcnt bl;
1511         ktap_funcstate *fs = ls->fs;
1512         ktap_expdesc v;
1513         int jf;  /* instruction to skip 'then' code (if condition is false) */
1514
1515         lex_next(ls);  /* skip IF or ELSEIF */
1516         checknext(ls, '(');
1517         expr(ls, &v);  /* read condition */
1518         checknext(ls, ')');
1519         //checknext(ls, TK_THEN);
1520         checknext(ls, '{');
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? */
1527                         leaveblock(fs);
1528                         checknext(ls, '}');
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);
1535                 jf = v.f;
1536         }
1537         statlist(ls);  /* `then' part */
1538         checknext(ls, '}');
1539         leaveblock(fs);
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);
1543 }
1544
1545 static void ifstat(ktap_lexstate *ls, int line)
1546 {
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 */
1550
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)) {
1555                 checknext(ls, '{');
1556                 block(ls);  /* `else' part */
1557                 checknext(ls, '}');
1558         }
1559         //check_match(ls, TK_END, TK_IF, line);
1560         codegen_patchtohere(fs, escapelist);  /* patch escape list to 'if' end */
1561 }
1562
1563 static void localfunc(ktap_lexstate *ls)
1564 {
1565         ktap_expdesc b;
1566         ktap_funcstate *fs = ls->fs;
1567
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;
1573 }
1574
1575 static void localstat(ktap_lexstate *ls)
1576 {
1577         /* stat -> LOCAL NAME {`,' NAME} [`=' explist] */
1578         int nvars = 0;
1579         int nexps;
1580         ktap_expdesc e;
1581
1582         do {
1583                 new_localvar(ls, str_checkname(ls));
1584                 nvars++;
1585         } while (testnext(ls, ','));
1586         if (testnext(ls, '='))
1587                 nexps = explist(ls, &e);
1588         else {
1589                 e.k = VVOID;
1590                 nexps = 0;
1591         }
1592         adjust_assign(ls, nvars, nexps, &e);
1593         adjustlocalvars(ls, nvars);
1594 }
1595
1596 static int funcname(ktap_lexstate *ls, ktap_expdesc *v)
1597 {
1598         /* funcname -> NAME {fieldsel} [`:' NAME] */
1599         int ismethod = 0;
1600
1601         singlevar(ls, v);
1602         while (ls->t.token == '.')
1603                 fieldsel(ls, v);
1604                 if (ls->t.token == ':') {
1605                         ismethod = 1;
1606                         fieldsel(ls, v);
1607         }
1608         return ismethod;
1609 }
1610
1611 static void funcstat(ktap_lexstate *ls, int line)
1612 {
1613         /* funcstat -> FUNCTION funcname body */
1614         int ismethod;
1615         ktap_expdesc v, b;
1616
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 */
1622 }
1623
1624 static void exprstat(ktap_lexstate *ls)
1625 {
1626         /* stat -> func | assignment */
1627         ktap_funcstate *fs = ls->fs;
1628         struct LHS_assign v;
1629
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) {
1634                 v.prev = NULL;
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 */
1639         }
1640 }
1641
1642 static void retstat(ktap_lexstate *ls)
1643 {
1644         /* stat -> RETURN [explist] [';'] */
1645         ktap_funcstate *fs = ls->fs;
1646         ktap_expdesc e;
1647         int first, nret;  /* registers with returned values */
1648
1649         if (block_follow(ls, 1) || ls->t.token == ';')
1650                 first = nret = 0;  /* return no values */
1651         else {
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);
1658                         }
1659                         first = fs->nactvar;
1660                         nret = KTAP_MULTRET;  /* return all values */
1661                 } else {
1662                         if (nret == 1)  /* only one single value? */
1663                                 first = codegen_exp2anyreg(fs, &e);
1664                         else {
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);
1668                         }
1669                 }
1670         }
1671         codegen_ret(fs, first, nret);
1672         testnext(ls, ';');  /* skip optional semicolon */
1673 }
1674
1675 static void tracestat(ktap_lexstate *ls)
1676 {
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;
1685         int base, nparams;
1686
1687         if (token == TK_TRACE)
1688                 lex_read_string_until(ls, '{');
1689         else
1690                 lex_next(ls);  /* skip "trace_end" keyword */
1691
1692         /* kdebug */
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] */
1696
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);
1704
1705         /* funcargs*/
1706         codegen_exp2nextreg(fs, v);
1707
1708         if (token == TK_TRACE) {
1709                 ktap_eventdef_info *evdef_info;
1710
1711                 /* argument: EVENTDEF string */
1712                 check(ls, TK_STRING);
1713                 enterlevel(ls);
1714                 evdef_info = ktapc_parse_eventdef(getstr(ls->t.seminfo.ts));
1715                 check_condition(ls, evdef_info != NULL, "Cannot parse eventdef");
1716
1717                 /* pass a userspace pointer to kernel */
1718                 codenumber(ls, &args, (ktap_number)evdef_info);
1719                 lex_next(ls);  /* skip EVENTDEF string */
1720                 leavelevel(ls);
1721
1722                 codegen_exp2nextreg(fs, &args); /* for next argument */
1723         }
1724
1725         /* argument: callback function */
1726         enterlevel(ls);
1727         func_body_no_args(ls, &args, ls->linenumber);
1728         leavelevel(ls);
1729
1730         codegen_setmultret(fs, &args);
1731
1732         base = v->u.info;  /* base register for call */
1733         if (hasmultret(args.k))
1734                 nparams = KTAP_MULTRET;  /* open call */
1735         else {
1736                 codegen_exp2nextreg(fs, &args);  /* close last argument */
1737                 nparams = fs->freereg - (base+1);
1738         }
1739         init_exp(v, VCALL, codegen_codeABC(fs, OP_CALL, base, nparams+1, 2));
1740         codegen_fixline(fs, line);
1741         fs->freereg = base+1;
1742
1743         check_condition(ls, v->k == VCALL, "syntax error");
1744         SETARG_C(getcode(fs, v), 1);  /* call statement uses no results */
1745 }
1746
1747 static void timerstat(ktap_lexstate *ls)
1748 {
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;
1755         int base, nparams;
1756
1757         lex_next(ls);  /* skip profile/tick keyword */
1758         check(ls, '-');
1759
1760         lex_read_string_until(ls, '{');
1761         interval_str = ls->t.seminfo.ts;
1762
1763         //printf("timerstat str: %s\n", getstr(interval_str));
1764         //exit(0);
1765
1766         /* timer */
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] */
1770
1771         /* fieldsel: timer.profile, timer.tick */
1772         codegen_exp2anyregup(fs, v);
1773         codestring(ls, &key, token_str);
1774         codegen_indexed(fs, v, &key);
1775
1776         /* funcargs*/
1777         codegen_exp2nextreg(fs, v);
1778
1779         /* argument: interval string */
1780         check(ls, TK_STRING);
1781         enterlevel(ls);
1782         codestring(ls, &args, interval_str);
1783         lex_next(ls);  /* skip interval string */
1784         leavelevel(ls);
1785
1786         codegen_exp2nextreg(fs, &args); /* for next argument */
1787
1788         /* argument: callback function */
1789         enterlevel(ls);
1790         func_body_no_args(ls, &args, ls->linenumber);
1791         leavelevel(ls);
1792
1793         codegen_setmultret(fs, &args);
1794
1795         base = v->u.info;  /* base register for call */
1796         if (hasmultret(args.k))
1797                 nparams = KTAP_MULTRET;  /* open call */
1798         else {
1799                 codegen_exp2nextreg(fs, &args);  /* close last argument */
1800                 nparams = fs->freereg - (base+1);
1801         }
1802         init_exp(v, VCALL, codegen_codeABC(fs, OP_CALL, base, nparams+1, 2));
1803         codegen_fixline(fs, line);
1804         fs->freereg = base+1;
1805
1806         check_condition(ls, v->k == VCALL, "syntax error");
1807         SETARG_C(getcode(fs, v), 1);  /* call statement uses no results */
1808 }
1809
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)
1814 {
1815         /* read long string cdef */
1816         lex_next(ls);
1817
1818         check(ls, TK_STRING);
1819         ffi_cdef(getstr(ls->t.seminfo.ts));
1820
1821         /* consume newline */
1822         lex_next(ls);
1823 }
1824 #else
1825 static void parsecdef(ktap_lexstate *ls)
1826 {
1827         printf("Please compile with FFI support to use cdef!\n");
1828         exit(EXIT_SUCCESS);
1829 }
1830 #endif
1831
1832
1833 static void statement(ktap_lexstate *ls)
1834 {
1835         int line = ls->linenumber;  /* may be needed for error messages */
1836
1837         enterlevel(ls);
1838         switch (ls->t.token) {
1839         case ';': {  /* stat -> ';' (empty statement) */
1840                 lex_next(ls);  /* skip ';' */
1841                 break;
1842         }
1843         case TK_IF: {  /* stat -> ifstat */
1844                 ifstat(ls, line);
1845                 break;
1846         }
1847         case TK_WHILE: {  /* stat -> whilestat */
1848                 whilestat(ls, line);
1849                 break;
1850         }
1851         case TK_DO: {  /* stat -> DO block END */
1852                 lex_next(ls);  /* skip DO */
1853                 block(ls);
1854                 check_match(ls, TK_END, TK_DO, line);
1855                 break;
1856         }
1857         case TK_FOR: {  /* stat -> forstat */
1858                 forstat(ls, line);
1859                 break;
1860         }
1861         case TK_REPEAT: {  /* stat -> repeatstat */
1862                 repeatstat(ls, line);
1863                 break;
1864         }
1865         case TK_FUNCTION: {  /* stat -> funcstat */
1866                 funcstat(ls, line);
1867                 break;
1868         }
1869         case TK_LOCAL: {  /* stat -> localstat */
1870                 lex_next(ls);  /* skip LOCAL */
1871                 if (testnext(ls, TK_FUNCTION))  /* local function? */
1872                         localfunc(ls);
1873                 else
1874                         localstat(ls);
1875                 break;
1876         }
1877         case TK_DBCOLON: {  /* stat -> label */
1878                 lex_next(ls);  /* skip double colon */
1879                 labelstat(ls, str_checkname(ls), line);
1880                 break;
1881         }
1882         case TK_RETURN: {  /* stat -> retstat */
1883                 lex_next(ls);  /* skip RETURN */
1884                 retstat(ls);
1885                 break;
1886         }
1887         case TK_BREAK:   /* stat -> breakstat */
1888         case TK_GOTO: {  /* stat -> 'goto' NAME */
1889                 gotostat(ls, codegen_jump(ls->fs));
1890                 break;
1891         }
1892
1893         case TK_TRACE:
1894         case TK_TRACE_END:
1895                 tracestat(ls);
1896                 break;
1897         case TK_PROFILE:
1898         case TK_TICK:
1899                 timerstat(ls);
1900                 break;
1901         case TK_FFI_CDEF:
1902                 parsecdef(ls);
1903                 break;
1904         default: {  /* stat -> func | assignment */
1905                 exprstat(ls);
1906                 break;
1907         }
1908         }
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 */
1912         leavelevel(ls);
1913 }
1914 /* }====================================================================== */
1915
1916 /*
1917  * compiles the main function, which is a regular vararg function with an upvalue
1918  */
1919 static void mainfunc(ktap_lexstate *ls, ktap_funcstate *fs)
1920 {
1921         ktap_blockcnt bl;
1922         ktap_expdesc v;
1923
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 */
1930         check(ls, TK_EOS);
1931         close_func(ls);
1932 }
1933
1934 ktap_closure *ktapc_parser(char *ptr, const char *name)
1935 {
1936         ktap_lexstate lexstate;
1937         ktap_funcstate funcstate;
1938         ktap_dyndata dyd;
1939         ktap_mbuffer buff;
1940         int firstchar = *ptr++;
1941         ktap_closure *cl = ktapc_newclosure(1);  /* create main closure */
1942
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 */
1947
1948         lex_init();
1949
1950         mbuff_init(&buff);
1951         memset(&dyd, 0, sizeof(ktap_dyndata));
1952         lexstate.buff = &buff;
1953         lexstate.dyd = &dyd;
1954         lex_setinput(&lexstate, ptr, funcstate.f->source, firstchar);
1955
1956         mainfunc(&lexstate, &funcstate);
1957
1958         ktap_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
1959
1960         /* all scopes should be correctly finished */
1961         ktap_assert(dyd.actvar.n == 0 && dyd.gt.n == 0 && dyd.label.n == 0);
1962         return cl;
1963 }