]> git.mxchange.org Git - simgear.git/blob - simgear/nasal/codegen.c
Removal of PLIB/SG from SimGear
[simgear.git] / simgear / nasal / codegen.c
1 #include <string.h>
2 #include "parse.h"
3 #include "code.h"
4
5 #define MAX_FUNARGS 32
6
7 // These are more sensical predicate names in most contexts in this file
8 #define LEFT(tok)   ((tok)->children)
9 #define RIGHT(tok)  ((tok)->lastChild)
10 #define BINARY(tok) (LEFT(tok) && RIGHT(tok) && LEFT(tok)->next == RIGHT(tok))
11
12 // Forward references for recursion
13 static void genExpr(struct Parser* p, struct Token* t);
14 static void genExprList(struct Parser* p, struct Token* t);
15 static naRef newLambda(struct Parser* p, struct Token* t);
16
17 static void emit(struct Parser* p, int val)
18 {
19     if(p->cg->codesz >= p->cg->codeAlloced) {
20         int i, sz = p->cg->codeAlloced * 2;
21         unsigned short* buf = naParseAlloc(p, sz*sizeof(unsigned short));
22         for(i=0; i<p->cg->codeAlloced; i++) buf[i] = p->cg->byteCode[i];
23         p->cg->byteCode = buf;
24         p->cg->codeAlloced = sz;
25     }
26     p->cg->byteCode[p->cg->codesz++] = (unsigned short)val;
27 }
28
29 static void emitImmediate(struct Parser* p, int val, int arg)
30 {
31     emit(p, val);
32     emit(p, arg);
33 }
34
35 static void genBinOp(int op, struct Parser* p, struct Token* t)
36 {
37     if(!LEFT(t) || !RIGHT(t))
38         naParseError(p, "empty subexpression", t->line);
39     genExpr(p, LEFT(t));
40     genExpr(p, RIGHT(t));
41     emit(p, op);
42 }
43
44 static int newConstant(struct Parser* p, naRef c)
45 {
46     int i;
47     naVec_append(p->cg->consts, c);
48     i = naVec_size(p->cg->consts) - 1;
49     if(i > 0xffff) naParseError(p, "too many constants in code block", 0);
50    return i;
51 }
52
53 // Interns a scalar (!) constant and returns its index
54 static int internConstant(struct Parser* p, naRef c)
55 {
56     int i, n = naVec_size(p->cg->consts);
57     if(IS_CODE(c)) return newConstant(p, c);
58     for(i=0; i<n; i++) {
59         naRef b = naVec_get(p->cg->consts, i);
60         if(IS_NUM(b) && IS_NUM(c) && b.num == c.num) return i;
61         else if(IS_NIL(b) && IS_NIL(c)) return i;
62         else if(naStrEqual(b, c)) return i;
63     }
64     return newConstant(p, c);
65 }
66
67 /* FIXME: this API is fundamentally a resource leak, because symbols
68  * can't be deregistered.  The "proper" way to do this would be to
69  * keep a reference count for each symbol, and decrement it when a
70  * code object referencing it is deleted. */
71 naRef naInternSymbol(naRef sym)
72 {
73     naRef result;
74     if(naHash_get(globals->symbols, sym, &result))
75         return result;
76     naHash_set(globals->symbols, sym, sym);
77     return sym;
78 }
79
80 static int findConstantIndex(struct Parser* p, struct Token* t)
81 {
82     naRef c, dummy;
83     if(t->type == TOK_NIL) c = naNil();
84     else if(t->str) {
85         c = naStr_fromdata(naNewString(p->context), t->str, t->strlen);
86         naHash_get(globals->symbols, c, &dummy); // noop, make c immutable
87         if(t->type == TOK_SYMBOL) c = naInternSymbol(c);
88     } else if(t->type == TOK_FUNC) c = newLambda(p, t);
89     else if(t->type == TOK_LITERAL) c = naNum(t->num);
90     else naParseError(p, "invalid/non-constant constant", t->line);
91     return internConstant(p, c);
92 }
93
94 static int genScalarConstant(struct Parser* p, struct Token* t)
95 {
96     int idx;
97     if(t->str == 0 && t->num == 1) { emit(p, OP_PUSHONE); return 0; }
98     if(t->str == 0 && t->num == 0) { emit(p, OP_PUSHZERO); return 0; }
99     emitImmediate(p, OP_PUSHCONST, idx = findConstantIndex(p, t));
100     return idx;
101 }
102
103 static int genLValue(struct Parser* p, struct Token* t, int* cidx)
104 {
105     if(!t) naParseError(p, "bad lvalue", -1);
106     if(t->type == TOK_LPAR && t->rule != PREC_SUFFIX) {
107         return genLValue(p, LEFT(t), cidx); // Handle stuff like "(a) = 1"
108     } else if(t->type == TOK_SYMBOL) {
109         *cidx = genScalarConstant(p, t);
110         return OP_SETSYM;
111     } else if(t->type == TOK_DOT && RIGHT(t) && RIGHT(t)->type == TOK_SYMBOL) {
112         genExpr(p, LEFT(t));
113         *cidx = genScalarConstant(p, RIGHT(t));
114         return OP_SETMEMBER;
115     } else if(t->type == TOK_LBRA) {
116         genExpr(p, LEFT(t));
117         genExpr(p, RIGHT(t));
118         return OP_INSERT;
119     } else if(t->type == TOK_VAR && RIGHT(t) && RIGHT(t)->type == TOK_SYMBOL) {
120         *cidx = genScalarConstant(p, RIGHT(t));
121         return OP_SETLOCAL;
122     } else {
123         naParseError(p, "bad lvalue", t->line);
124         return -1;
125     }
126 }
127
128 static void genEqOp(int op, struct Parser* p, struct Token* t)
129 {
130     int cidx, n = 2, setop = genLValue(p, LEFT(t), &cidx);
131     if(setop == OP_SETMEMBER) {
132         emit(p, OP_DUP2);
133         emit(p, OP_POP);
134         emitImmediate(p, OP_MEMBER, cidx);
135     } else if(setop == OP_INSERT) {
136         emit(p, OP_DUP2);
137         emit(p, OP_EXTRACT);
138     } else {
139         emitImmediate(p, OP_LOCAL, cidx);
140         n = 1;
141     }
142     genExpr(p, RIGHT(t));
143     emit(p, op);
144     emit(p, n == 1 ? OP_XCHG : OP_XCHG2);
145     emit(p, setop);
146 }
147
148 static int defArg(struct Parser* p, struct Token* t)
149 {
150     if(t->type == TOK_LPAR) return defArg(p, RIGHT(t));
151     if(t->type == TOK_MINUS && RIGHT(t) && 
152        RIGHT(t)->type == TOK_LITERAL && !RIGHT(t)->str)
153     {
154         /* default arguments are constants, but "-1" parses as two
155          * tokens, so we have to subset the expression generator for that
156          * case */
157         RIGHT(t)->num *= -1;
158         return defArg(p, RIGHT(t));
159     }
160     return findConstantIndex(p, t);
161 }
162
163 static void genArgList(struct Parser* p, struct naCode* c, struct Token* t)
164 {
165     naRef sym;
166     if(t->type == TOK_EMPTY) return;
167     if(!IDENTICAL(p->cg->restArgSym, globals->argRef))
168         naParseError(p, "remainder must be last", t->line);
169     if(t->type == TOK_ELLIPSIS) {
170         if(LEFT(t)->type != TOK_SYMBOL)
171             naParseError(p, "bad function argument expression", t->line);
172         sym = naStr_fromdata(naNewString(p->context),
173                              LEFT(t)->str, LEFT(t)->strlen);
174         p->cg->restArgSym = naInternSymbol(sym);
175         c->needArgVector = 1;
176     } else if(t->type == TOK_ASSIGN) {
177         if(LEFT(t)->type != TOK_SYMBOL)
178             naParseError(p, "bad function argument expression", t->line);
179         p->cg->optArgSyms[c->nOptArgs] = findConstantIndex(p, LEFT(t));
180         p->cg->optArgVals[c->nOptArgs++] = defArg(p, RIGHT(t));
181     } else if(t->type == TOK_SYMBOL) {
182         if(c->nOptArgs)
183             naParseError(p, "optional arguments must be last", t->line);
184         if(c->nArgs >= MAX_FUNARGS)
185             naParseError(p, "too many named function arguments", t->line);
186         p->cg->argSyms[c->nArgs++] = findConstantIndex(p, t);
187     } else if(t->type == TOK_COMMA) {
188         if(!LEFT(t) || !RIGHT(t))
189             naParseError(p, "empty function argument", t->line);
190         genArgList(p, c, LEFT(t));
191         genArgList(p, c, RIGHT(t));
192     } else
193         naParseError(p, "bad function argument expression", t->line);
194 }
195
196 static naRef newLambda(struct Parser* p, struct Token* t)
197 {
198     struct CodeGenerator* cgSave;
199     naRef codeObj;
200     struct Token* arglist;
201     if(RIGHT(t)->type != TOK_LCURL)
202         naParseError(p, "bad function definition", t->line);
203
204     // Save off the generator state while we do the new one
205     cgSave = p->cg;
206     arglist = LEFT(t)->type == TOK_LPAR ? LEFT(LEFT(t)) : 0;
207     codeObj = naCodeGen(p, LEFT(RIGHT(t)), arglist);
208     p->cg = cgSave;
209     return codeObj;
210 }
211
212 static void genLambda(struct Parser* p, struct Token* t)
213 {
214     emitImmediate(p, OP_PUSHCONST, newConstant(p, newLambda(p, t)));
215 }
216
217 static int genList(struct Parser* p, struct Token* t, int doAppend)
218 {
219     if(!t || t->type == TOK_EMPTY) {
220         return 0;
221     } else if(t->type == TOK_COMMA) {
222         genExpr(p, LEFT(t));
223         if(doAppend) emit(p, OP_VAPPEND);
224         return 1 + genList(p, RIGHT(t), doAppend);
225     } else {
226         genExpr(p, t);
227         if(doAppend) emit(p, OP_VAPPEND);
228         return 1;
229     }
230 }
231
232 static void genHashElem(struct Parser* p, struct Token* t)
233 {
234     if(!t || t->type == TOK_EMPTY)
235         return;
236     if(t->type != TOK_COLON || !LEFT(t))
237         naParseError(p, "bad hash/object initializer", t->line);
238     if(LEFT(t)->type == TOK_SYMBOL) genScalarConstant(p, LEFT(t));
239     else if(LEFT(t)->type == TOK_LITERAL) genExpr(p, LEFT(t));
240     else naParseError(p, "bad hash/object initializer", t->line);
241     genExpr(p, RIGHT(t));
242     emit(p, OP_HAPPEND);
243 }
244
245 static void genHash(struct Parser* p, struct Token* t)
246 {
247     if(t && t->type == TOK_COMMA) {
248         genHashElem(p, LEFT(t));
249         genHash(p, RIGHT(t));
250     } else if(t && t->type != TOK_EMPTY) {
251         genHashElem(p, t);
252     }
253 }
254
255 static int isHashcall(struct Parser* p, struct Token* t)
256 {
257     if(t) {
258         int sep = LEFT(t) && t->type == TOK_COMMA ? t->children->type : t->type;
259         return sep == TOK_COLON;
260     }
261     return 0;
262 }
263
264 static void genFuncall(struct Parser* p, struct Token* t)
265 {
266     int method = 0;
267     if(LEFT(t)->type == TOK_DOT) {
268         method = 1;
269         genExpr(p, LEFT(LEFT(t)));
270         emit(p, OP_DUP);
271         emitImmediate(p, OP_MEMBER, findConstantIndex(p, RIGHT(LEFT(t))));
272     } else {
273         genExpr(p, LEFT(t));
274     }
275     if(isHashcall(p, RIGHT(t))) {
276         emit(p, OP_NEWHASH);
277         genHash(p, RIGHT(t));
278         emit(p, method ? OP_MCALLH : OP_FCALLH);
279     } else {
280         int nargs = genList(p, RIGHT(t), 0);
281         emitImmediate(p, method ? OP_MCALL : OP_FCALL, nargs);
282     }
283 }
284
285 static int startLoop(struct Parser* p, struct Token* label)
286 {
287     int i = p->cg->loopTop;
288     p->cg->loops[i].breakIP = 0xffffff;
289     p->cg->loops[i].contIP = 0xffffff;
290     p->cg->loops[i].label = label;
291     p->cg->loopTop++;
292     emit(p, OP_MARK);
293     return p->cg->codesz;
294 }
295
296 // Emit a jump operation, and return the location of the address in
297 // the bytecode for future fixup in fixJumpTarget
298 static int emitJump(struct Parser* p, int op)
299 {
300     int ip;
301     emit(p, op);
302     ip = p->cg->codesz;
303     emit(p, 0xffff); // dummy address
304     return ip;
305 }
306
307 // Points a previous jump instruction at the current "end-of-bytecode"
308 static void fixJumpTarget(struct Parser* p, int spot)
309 {
310     p->cg->byteCode[spot] = p->cg->codesz;
311 }
312
313 static void genShortCircuit(struct Parser* p, struct Token* t)
314 {
315     int end;
316     genExpr(p, LEFT(t));
317     end = emitJump(p, t->type == TOK_AND ? OP_JIFNOT : OP_JIFTRUE);
318     emit(p, OP_POP);
319     genExpr(p, RIGHT(t));
320     fixJumpTarget(p, end);
321 }
322
323
324 static void genIf(struct Parser* p, struct Token* tif, struct Token* telse)
325 {
326     int jumpNext, jumpEnd;
327     genExpr(p, tif->children); // the test
328     jumpNext = emitJump(p, OP_JIFNOTPOP);
329     genExprList(p, tif->children->next->children); // the body
330     jumpEnd = emitJump(p, OP_JMP);
331     fixJumpTarget(p, jumpNext);
332     if(telse) {
333         if(telse->type == TOK_ELSIF) genIf(p, telse, telse->next);
334         else genExprList(p, telse->children->children);
335     } else {
336         emit(p, OP_PUSHNIL);
337     }
338     fixJumpTarget(p, jumpEnd);
339 }
340
341 static void genIfElse(struct Parser* p, struct Token* t)
342 {
343     genIf(p, t, t->children->next->next);
344 }
345
346 static void genQuestion(struct Parser* p, struct Token* t)
347 {
348     int jumpNext, jumpEnd;
349     if(!RIGHT(t) || RIGHT(t)->type != TOK_COLON)
350         naParseError(p, "invalid ?: expression", t->line);
351     genExpr(p, LEFT(t)); // the test
352     jumpNext = emitJump(p, OP_JIFNOTPOP);
353     genExpr(p, LEFT(RIGHT(t))); // the "if true" expr
354     jumpEnd = emitJump(p, OP_JMP);
355     fixJumpTarget(p, jumpNext);
356     genExpr(p, RIGHT(RIGHT(t))); // the "else" expr
357     fixJumpTarget(p, jumpEnd);
358 }
359
360 static int countList(struct Token* t, int type)
361 {
362     int n;
363     for(n = 1; t && t->type == type; t = RIGHT(t)) n++;
364     return n;
365 }
366
367 static void genLoop(struct Parser* p, struct Token* body,
368                     struct Token* update, struct Token* label,
369                     int loopTop, int jumpEnd)
370 {
371     int cont, jumpOverContinue;
372     
373     p->cg->loops[p->cg->loopTop-1].breakIP = jumpEnd-1;
374
375     jumpOverContinue = emitJump(p, OP_JMP);
376     p->cg->loops[p->cg->loopTop-1].contIP = p->cg->codesz;
377     cont = emitJump(p, OP_JMP);
378     fixJumpTarget(p, jumpOverContinue);
379
380     genExprList(p, body);
381     emit(p, OP_POP);
382     fixJumpTarget(p, cont);
383     if(update) { genExpr(p, update); emit(p, OP_POP); }
384     emitImmediate(p, OP_JMPLOOP, loopTop);
385     fixJumpTarget(p, jumpEnd);
386     p->cg->loopTop--;
387     emit(p, OP_UNMARK);
388     emit(p, OP_PUSHNIL); // Leave something on the stack
389 }
390
391 static void genForWhile(struct Parser* p, struct Token* init,
392                         struct Token* test, struct Token* update,
393                         struct Token* body, struct Token* label)
394 {
395     int loopTop, jumpEnd;
396     if(init) { genExpr(p, init); emit(p, OP_POP); }
397     loopTop = startLoop(p, label);
398     genExpr(p, test);
399     jumpEnd = emitJump(p, OP_JIFNOTPOP);
400     genLoop(p, body, update, label, loopTop, jumpEnd);
401 }
402
403 static void genWhile(struct Parser* p, struct Token* t)
404 {
405     struct Token *test=LEFT(t)->children, *body, *label=0;
406     int len = countList(test, TOK_SEMI);
407     if(len == 2) {
408         label = LEFT(test);
409         if(!label || label->type != TOK_SYMBOL)
410             naParseError(p, "bad loop label", t->line);
411         test = RIGHT(test);
412     } else if(len != 1)
413         naParseError(p, "too many semicolons in while test", t->line);
414     body = LEFT(RIGHT(t));
415     genForWhile(p, 0, test, 0, body, label);
416 }
417
418 static void genFor(struct Parser* p, struct Token* t)
419 {
420     struct Token *init, *test, *body, *update, *label=0;
421     struct Token *h = LEFT(t)->children;
422     int len = countList(h, TOK_SEMI);
423     if(len == 4) {
424         if(!LEFT(h) || LEFT(h)->type != TOK_SYMBOL)
425             naParseError(p, "bad loop label", h->line);
426         label = LEFT(h);
427         h=RIGHT(h);
428     } else if(len != 3)
429         naParseError(p, "wrong number of terms in for header", t->line);
430     init = LEFT(h);
431     test = LEFT(RIGHT(h));
432     update = RIGHT(RIGHT(h));
433     body = RIGHT(t)->children;
434     genForWhile(p, init, test, update, body, label);
435 }
436
437 static void genForEach(struct Parser* p, struct Token* t)
438 {
439     int loopTop, jumpEnd, assignOp, dummy;
440     struct Token *elem, *body, *vec, *label=0;
441     struct Token *h = LEFT(LEFT(t));
442     int len = countList(h, TOK_SEMI);
443     if(len == 3) {
444         if(!LEFT(h) || LEFT(h)->type != TOK_SYMBOL)
445             naParseError(p, "bad loop label", h->line);
446         label = LEFT(h);
447         h = RIGHT(h);
448     } else if (len != 2) {
449         naParseError(p, "wrong number of terms in foreach header", t->line);
450     }
451     elem = LEFT(h);
452     vec = RIGHT(h);
453     body = RIGHT(t)->children;
454
455     genExpr(p, vec);
456     emit(p, OP_PUSHZERO);
457     loopTop = startLoop(p, label);
458     emit(p, t->type == TOK_FOREACH ? OP_EACH : OP_INDEX);
459     jumpEnd = emitJump(p, OP_JIFEND);
460     assignOp = genLValue(p, elem, &dummy);
461     emit(p, assignOp);
462     emit(p, OP_POP);
463     genLoop(p, body, 0, label, loopTop, jumpEnd);
464     emit(p, OP_POP); // Pull off the vector and index
465     emit(p, OP_POP);
466 }
467
468 static int tokMatch(struct Token* a, struct Token* b)
469 {
470     int i, l = a->strlen;
471     if(!a || !b) return 0;
472     if(l != b->strlen) return 0;
473     for(i=0; i<l; i++) if(a->str[i] != b->str[i]) return 0;
474     return 1;
475 }
476
477 static void genBreakContinue(struct Parser* p, struct Token* t)
478 {
479     int levels = 1, loop = -1, bp, cp, i;
480     if(RIGHT(t)) {
481         if(RIGHT(t)->type != TOK_SYMBOL)
482             naParseError(p, "bad break/continue label", t->line);
483         for(i=0; i<p->cg->loopTop; i++)
484             if(tokMatch(RIGHT(t), p->cg->loops[i].label))
485                 loop = i;
486         if(loop == -1)
487             naParseError(p, "no match for break/continue label", t->line);
488         levels = p->cg->loopTop - loop;
489     }
490     bp = p->cg->loops[p->cg->loopTop - levels].breakIP;
491     cp = p->cg->loops[p->cg->loopTop - levels].contIP;
492     for(i=0; i<levels; i++)
493         emit(p, (i<levels-1) ? OP_BREAK2 : OP_BREAK);
494     if(t->type == TOK_BREAK)
495         emit(p, OP_PUSHEND); // breakIP is always a JIFNOTPOP/JIFEND!
496     emitImmediate(p, OP_JMP, t->type == TOK_BREAK ? bp : cp);
497 }
498
499 static void newLineEntry(struct Parser* p, int line)
500 {
501     int i;
502     if(p->cg->nextLineIp >= p->cg->nLineIps) {
503         int nsz = p->cg->nLineIps*2 + 1;
504         unsigned short* n = naParseAlloc(p, sizeof(unsigned short)*2*nsz);
505         for(i=0; i<(p->cg->nextLineIp*2); i++)
506             n[i] = p->cg->lineIps[i];
507         p->cg->lineIps = n;
508         p->cg->nLineIps = nsz;
509     }
510     p->cg->lineIps[p->cg->nextLineIp++] = (unsigned short) p->cg->codesz;
511     p->cg->lineIps[p->cg->nextLineIp++] = (unsigned short) line;
512 }
513
514 static int parListLen(struct Token* t)
515 {
516     if(t->type != TOK_LPAR || !LEFT(t) || LEFT(t)->type != TOK_COMMA) return 0;
517     return countList(LEFT(t), TOK_COMMA);
518 }
519
520 static void genCommaList(struct Parser* p, struct Token* t)
521 {
522     if(t->type != TOK_COMMA) { genExpr(p, t); return; }
523     genCommaList(p, RIGHT(t));
524     genExpr(p, LEFT(t));
525 }
526
527 static void genMultiLV(struct Parser* p, struct Token* t, int var)
528 {
529     if(!var) { emit(p, genLValue(p, t, &var)); return; }
530     if(t->type != TOK_SYMBOL) naParseError(p, "bad lvalue", t->line);
531     genScalarConstant(p, t);
532     emit(p, OP_SETLOCAL);
533 }
534
535 static void genAssign(struct Parser* p, struct Token* t)
536 {
537     struct Token *lv = LEFT(t), *rv = RIGHT(t);
538     int len, dummy, var=0;
539     if(parListLen(lv) || (lv->type == TOK_VAR && parListLen(RIGHT(lv)))) {
540         if(lv->type == TOK_VAR) { lv = RIGHT(lv); var = 1; }
541         len = parListLen(lv);
542         if(rv->type == TOK_LPAR) {
543             if(len != parListLen(rv))
544                 naParseError(p, "bad assignment count", rv->line);
545             genCommaList(p, LEFT(rv));
546         } else {
547             genExpr(p, rv);
548             emitImmediate(p, OP_UNPACK, len);
549         }
550         for(t = LEFT(lv); t && t->type == TOK_COMMA; t = RIGHT(t)) {
551             genMultiLV(p, LEFT(t), var);
552             emit(p, OP_POP);
553         }
554         genMultiLV(p, t, var);
555     } else {
556         genExpr(p, rv);
557         emit(p, genLValue(p, lv, &dummy));
558     }
559 }
560
561 static void genSlice(struct Parser* p, struct Token* t)
562 {
563     if(!t || t->type==TOK_EMPTY) naParseError(p, "empty slice expression", -1);
564     if(t->type == TOK_COLON) {
565         if(LEFT(t))  genExpr(p, LEFT(t));  else emit(p, OP_PUSHNIL);
566         if(RIGHT(t)) genExpr(p, RIGHT(t)); else emit(p, OP_PUSHNIL);
567         emit(p, OP_SLICE2);
568     } else {
569         genExpr(p, t);
570         emit(p, OP_SLICE);
571     }
572 }
573
574 static void genExtract(struct Parser* p, struct Token* t)
575 {
576     genExpr(p, LEFT(t));
577     if(countList(RIGHT(t), TOK_COMMA) == 1 && RIGHT(t)->type != TOK_COLON) {
578         genExpr(p, RIGHT(t));
579         emit(p, OP_EXTRACT);
580     } else {
581         emit(p, OP_NEWVEC);
582         for(t = RIGHT(t); t->type == TOK_COMMA; t = RIGHT(t))
583             genSlice(p, LEFT(t));
584         genSlice(p, t);
585         emit(p, OP_XCHG);
586         emit(p, OP_POP);
587     }
588 }
589
590 static void genExpr(struct Parser* p, struct Token* t)
591 {
592     int i;
593     if(!t) naParseError(p, "parse error", -1); // throw line -1...
594     p->errLine = t->line;                      // ...to use this one instead
595     if(t->line != p->cg->lastLine)
596         newLineEntry(p, t->line);
597     p->cg->lastLine = t->line;
598     switch(t->type) {
599     case TOK_TOP:      genExprList(p, LEFT(t)); break;
600     case TOK_IF:       genIfElse(p, t);   break;
601     case TOK_QUESTION: genQuestion(p, t); break;
602     case TOK_WHILE:    genWhile(p, t);    break;
603     case TOK_FOR:      genFor(p, t);      break;
604     case TOK_FUNC:     genLambda(p, t);   break;
605     case TOK_ASSIGN:   genAssign(p, t);   break;
606     case TOK_LITERAL:  genScalarConstant(p, t); break;
607     case TOK_FOREACH: case TOK_FORINDEX:
608         genForEach(p, t);
609         break;
610     case TOK_BREAK: case TOK_CONTINUE:
611         genBreakContinue(p, t);
612         break;
613     case TOK_LPAR:
614         if(BINARY(t) || !RIGHT(t)) genFuncall(p, t);
615         else genExpr(p, LEFT(t));
616         break;
617     case TOK_LBRA:
618         if(BINARY(t)) {
619             genExtract(p, t);
620         } else {
621             emit(p, OP_NEWVEC);
622             genList(p, LEFT(t), 1);
623         }
624         break;
625     case TOK_LCURL:
626         emit(p, OP_NEWHASH);
627         genHash(p, LEFT(t));
628         break;
629     case TOK_RETURN:
630         if(RIGHT(t)) genExpr(p, RIGHT(t));
631         else emit(p, OP_PUSHNIL);
632         for(i=0; i<p->cg->loopTop; i++) emit(p, OP_UNMARK);
633         emit(p, OP_RETURN);
634         break;
635     case TOK_NOT:
636         genExpr(p, RIGHT(t));
637         emit(p, OP_NOT);
638         break;
639     case TOK_SYMBOL:
640         emitImmediate(p, OP_LOCAL, findConstantIndex(p, t));
641         break;
642     case TOK_MINUS:
643         if(BINARY(t)) {
644             genBinOp(OP_MINUS,  p, t);  // binary subtraction
645         } else if(RIGHT(t) && RIGHT(t)->type == TOK_LITERAL && !RIGHT(t)->str) {
646             RIGHT(t)->num *= -1;        // Pre-negate constants
647             genScalarConstant(p, RIGHT(t));
648         } else {
649             genExpr(p, RIGHT(t));       // unary negation
650             emit(p, OP_NEG);
651         }
652         break;
653     case TOK_NEG:
654         genExpr(p, RIGHT(t)); // unary negation (see also TOK_MINUS!)
655         emit(p, OP_NEG);
656         break;
657     case TOK_DOT:
658         genExpr(p, LEFT(t));
659         if(!RIGHT(t) || RIGHT(t)->type != TOK_SYMBOL)
660             naParseError(p, "object field not symbol", RIGHT(t)->line);
661         emitImmediate(p, OP_MEMBER, findConstantIndex(p, RIGHT(t)));
662         break;
663     case TOK_EMPTY: case TOK_NIL:
664         emit(p, OP_PUSHNIL);
665         break;
666     case TOK_AND: case TOK_OR:
667         genShortCircuit(p, t);
668         break;
669     case TOK_MUL:   genBinOp(OP_MUL,    p, t); break;
670     case TOK_PLUS:  genBinOp(OP_PLUS,   p, t); break;
671     case TOK_DIV:   genBinOp(OP_DIV,    p, t); break;
672     case TOK_CAT:   genBinOp(OP_CAT,    p, t); break;
673     case TOK_LT:    genBinOp(OP_LT,     p, t); break;
674     case TOK_LTE:   genBinOp(OP_LTE,    p, t); break;
675     case TOK_EQ:    genBinOp(OP_EQ,     p, t); break;
676     case TOK_NEQ:   genBinOp(OP_NEQ,    p, t); break;
677     case TOK_GT:    genBinOp(OP_GT,     p, t); break;
678     case TOK_GTE:   genBinOp(OP_GTE,    p, t); break;
679     case TOK_PLUSEQ:  genEqOp(OP_PLUS, p, t);  break;
680     case TOK_MINUSEQ: genEqOp(OP_MINUS, p, t); break;
681     case TOK_MULEQ:   genEqOp(OP_MUL, p, t);   break;
682     case TOK_DIVEQ:   genEqOp(OP_DIV, p, t);   break;
683     case TOK_CATEQ:   genEqOp(OP_CAT, p, t);   break;
684     default:
685         naParseError(p, "parse error", t->line);
686     };
687 }
688
689 static void genExprList(struct Parser* p, struct Token* t)
690 {
691     if(t && t->type == TOK_SEMI) {
692         genExpr(p, LEFT(t));
693         if(RIGHT(t) && RIGHT(t)->type != TOK_EMPTY) {
694             emit(p, OP_POP);
695             genExprList(p, RIGHT(t));
696         }
697     } else {
698         genExpr(p, t);
699     }
700 }
701
702 naRef naCodeGen(struct Parser* p, struct Token* block, struct Token* arglist)
703 {
704     int i;
705     naRef codeObj;
706     struct naCode* code;
707     struct CodeGenerator cg;
708
709     cg.lastLine = 0;
710     cg.codeAlloced = 1024; // Start fairly big, this is a cheap allocation
711     cg.byteCode = naParseAlloc(p, cg.codeAlloced *sizeof(unsigned short));
712     cg.codesz = 0;
713     cg.consts = naNewVector(p->context);
714     cg.loopTop = 0;
715     cg.lineIps = 0;
716     cg.nLineIps = 0;
717     cg.nextLineIp = 0;
718     p->cg = &cg;
719
720     genExprList(p, block);
721     emit(p, OP_RETURN);
722     
723     // Now make a code object
724     codeObj = naNewCode(p->context);
725     code = PTR(codeObj).code;
726     
727     // Parse the argument list, if any
728     p->cg->restArgSym = globals->argRef;
729     code->nArgs = code->nOptArgs = 0;
730     p->cg->argSyms = p->cg->optArgSyms = p->cg->optArgVals = 0;
731     code->needArgVector = 1;
732     if(arglist) {
733         p->cg->argSyms    = naParseAlloc(p, sizeof(int) * MAX_FUNARGS);
734         p->cg->optArgSyms = naParseAlloc(p, sizeof(int) * MAX_FUNARGS);
735         p->cg->optArgVals = naParseAlloc(p, sizeof(int) * MAX_FUNARGS);
736         code->needArgVector = 0;
737         genArgList(p, code, arglist);
738     }
739
740     code->restArgSym = internConstant(p, p->cg->restArgSym);
741
742     /* Set the size fields and allocate the combined array buffer.
743      * Note cute trick with null pointer to get the array size. */
744     code->nConstants = naVec_size(cg.consts);
745     code->codesz = cg.codesz;
746     code->nLines = cg.nextLineIp;
747     code->srcFile = p->srcFile;
748     code->constants = 0;
749     code->constants = naAlloc((int)(size_t)(LINEIPS(code)+code->nLines));
750     for(i=0; i<code->nConstants; i++)
751         code->constants[i] = naVec_get(p->cg->consts, i);
752
753     for(i=0; i<code->nArgs; i++) ARGSYMS(code)[i] = cg.argSyms[i];
754     for(i=0; i<code->nOptArgs; i++) OPTARGSYMS(code)[i] = cg.optArgSyms[i];
755     for(i=0; i<code->nOptArgs; i++) OPTARGVALS(code)[i] = cg.optArgVals[i];
756     for(i=0; i<code->codesz; i++) BYTECODE(code)[i] = cg.byteCode[i];
757     for(i=0; i<code->nLines; i++) LINEIPS(code)[i] = cg.lineIps[i];
758
759     return codeObj;
760 }