]> git.mxchange.org Git - simgear.git/blob - simgear/nasal/code.c
Parse/GC interaction fixed.
[simgear.git] / simgear / nasal / code.c
1 #include "nasal.h"
2 #include "code.h"
3
4 ////////////////////////////////////////////////////////////////////////
5 // Debugging stuff. ////////////////////////////////////////////////////
6 ////////////////////////////////////////////////////////////////////////
7 #if !defined(DEBUG_NASAL)
8 # define DBG(expr) /* noop */
9 #else
10 # define DBG(expr) expr
11 # include <stdio.h>
12 # include <stdlib.h>
13 #endif
14 char* opStringDEBUG(int op);
15 void printOpDEBUG(int ip, int op);
16 void printRefDEBUG(naRef r);
17 void printStackDEBUG(struct Context* ctx);
18 ////////////////////////////////////////////////////////////////////////
19
20 // FIXME: need to store a list of all contexts
21 struct Context globalContext;
22
23 #define ERR(c, msg) naRuntimeError((c),(msg))
24 void naRuntimeError(struct Context* c, char* msg)
25
26     c->error = msg;
27     longjmp(c->jumpHandle, 1);
28 }
29
30 int boolify(struct Context* ctx, naRef r)
31 {
32     if(IS_NIL(r)) return 0;
33     if(IS_NUM(r)) return r.num != 0;
34     if(IS_STR(r)) return 1;
35     ERR(ctx, "non-scalar used in boolean context");
36     return 0;
37 }
38
39 static double numify(struct Context* ctx, naRef o)
40 {
41     double n;
42     if(IS_NUM(o)) return o.num;
43     else if(IS_NIL(o)) ERR(ctx, "nil used in numeric context");
44     else if(!IS_STR(o)) ERR(ctx, "non-scalar in numeric context");
45     else if(naStr_tonum(o, &n)) return n;
46     else ERR(ctx, "non-numeric string in numeric context");
47     return 0;
48 }
49
50 static naRef stringify(struct Context* ctx, naRef r)
51 {
52     if(IS_STR(r)) return r;
53     if(IS_NUM(r)) return naStr_fromnum(naNewString(ctx), r.num);
54     ERR(ctx, "non-scalar in string context");
55     return naNil();
56 }
57
58 static int checkVec(struct Context* ctx, naRef vec, naRef idx)
59 {
60     int i = (int)numify(ctx, idx);
61     if(i < 0 || i >= vec.ref.ptr.vec->size)
62         ERR(ctx, "vector index out of bounds");
63     return i;
64 }
65
66 static naRef containerGet(struct Context* ctx, naRef box, naRef key)
67 {
68     naRef result = naNil();
69     if(!IS_SCALAR(key)) ERR(ctx, "container index not scalar");
70     if(IS_HASH(box)) {
71         if(!naHash_get(box, key, &result))
72             ERR(ctx, "undefined value in container");
73     } else if(IS_VEC(box)) {
74         result = naVec_get(box, checkVec(ctx, box, key));
75     } else {
76         ERR(ctx, "extract from non-container");
77     }
78     return result;
79 }
80
81 static void containerSet(struct Context* ctx, naRef box, naRef key, naRef val)
82 {
83     if(!IS_SCALAR(key))   ERR(ctx, "container index not scalar");
84     else if(IS_HASH(box)) naHash_set(box, key, val);
85     else if(IS_VEC(box))  naVec_set(box, checkVec(ctx, box, key), val);
86     else                  ERR(ctx, "insert into non-container");
87 }
88
89 static void initContext(struct Context* c)
90 {
91     int i;
92     for(i=0; i<NUM_NASAL_TYPES; i++)
93         naGC_init(&(c->pools[i]), i);
94
95     c->fTop = c->opTop = c->markTop = 0;
96
97     naBZero(c->fStack, MAX_RECURSION * sizeof(struct Frame));
98     naBZero(c->opStack, MAX_STACK_DEPTH * sizeof(naRef));
99
100     // Make sure the args vectors (which are static with the context)
101     // are initialized to nil.
102     for(i=0; i<MAX_RECURSION; i++)
103         c->fStack[i].args = naNil();
104
105     // Note we can't use naNewVector() for this; it requires that
106     // temps exist first.
107     c->temps = naObj(T_VEC, naGC_get(&(c->pools[T_VEC])));
108
109     c->save = naNil();
110
111     // Cache pre-calculated "me", "arg" and "parents" scalars
112     c->meRef = naStr_fromdata(naNewString(c), "me", 2);
113     c->argRef = naStr_fromdata(naNewString(c), "arg", 3);
114     c->parentsRef = naStr_fromdata(naNewString(c), "parents", 7);
115 }
116
117 struct Context* naNewContext()
118 {
119     // FIXME: need more than one!
120     struct Context* c = &globalContext;
121     initContext(c);
122     return c;
123 }
124
125 void naGarbageCollect()
126 {
127     int i;
128     struct Context* c = &globalContext; // FIXME: more than one!
129
130     for(i=0; i < c->fTop; i++) {
131         naGC_mark(c->fStack[i].func);
132         naGC_mark(c->fStack[i].locals);
133     }
134     for(i=0; i < MAX_RECURSION; i++)
135         naGC_mark(c->fStack[i].args); // collect *all* the argument lists
136     for(i=0; i < c->opTop; i++)
137         naGC_mark(c->opStack[i]);
138
139     naGC_mark(c->temps);
140     naGC_mark(c->save);
141
142     naGC_mark(c->meRef);
143     naGC_mark(c->argRef);
144     naGC_mark(c->parentsRef);
145
146     // Finally collect all the freed objects
147     for(i=0; i<NUM_NASAL_TYPES; i++)
148         naGC_reap(&(c->pools[i]));
149 }
150
151 void setupFuncall(struct Context* ctx, naRef func, naRef args)
152 {
153     struct Frame* f;
154     f = &(ctx->fStack[ctx->fTop++]);
155     f->func = func;
156     f->ip = 0;
157     f->bp = ctx->opTop;
158     f->line = 0;
159
160     DBG(printf("Entering frame %d\n", ctx->fTop-1);)
161
162     if(!IS_REF(func))
163         ERR(ctx, "function/method call invoked on uncallable object");
164
165     f->args = args;
166     if(IS_CCODE(func.ref.ptr.func->code)) {
167         f->locals = naNil();
168     } else if(IS_CODE(func.ref.ptr.func->code)) {
169         f->locals = naNewHash(ctx);
170         naHash_set(f->locals, ctx->argRef, args);
171     } else {
172         ERR(ctx, "function/method call invoked on uncallable object");
173     }
174 }
175
176 static naRef evalAndOr(struct Context* ctx, int op, naRef ra, naRef rb)
177 {
178     int a = boolify(ctx, ra);
179     int b = boolify(ctx, rb);
180     int result;
181     if(op == OP_AND) result = a && b ? 1 : 0;
182     else             result = a || b ? 1 : 0;
183     return naNum(result);
184 }
185
186 static naRef evalEquality(int op, naRef ra, naRef rb)
187 {
188     int result = naEqual(ra, rb);
189     return naNum((op==OP_EQ) ? result : !result);
190 }
191
192 static naRef evalBinaryNumeric(struct Context* ctx, int op, naRef ra, naRef rb)
193 {
194     double a = numify(ctx, ra), b = numify(ctx, rb);
195     switch(op) {
196     case OP_PLUS:  return naNum(a + b);
197     case OP_MINUS: return naNum(a - b);
198     case OP_MUL:   return naNum(a * b);
199     case OP_DIV:   return naNum(a / b);
200     case OP_LT:    return naNum(a < b ? 1 : 0);
201     case OP_LTE:   return naNum(a <= b ? 1 : 0);
202     case OP_GT:    return naNum(a > b ? 1 : 0);
203     case OP_GTE:   return naNum(a >= b ? 1 : 0);
204     }
205     return naNil();
206 }
207
208 // When a code object comes out of the constant pool and shows up on
209 // the stack, it needs to be bound with the lexical context.
210 static naRef bindFunction(struct Context* ctx, struct Frame* f, naRef code)
211 {
212     naRef next = f->func.ref.ptr.func->closure;
213     naRef closure = naNewClosure(ctx, f->locals, next);
214     naRef result = naNewFunc(ctx, code);
215     result.ref.ptr.func->closure = closure;
216     return result;
217 }
218
219 static int getClosure(struct naClosure* c, naRef sym, naRef* result)
220 {
221     while(c) {
222         if(naHash_get(c->namespace, sym, result)) return 1;
223         c = c->next.ref.ptr.closure;
224     }
225     return 0;
226 }
227
228 // Get a local symbol, or check the closure list if it isn't there
229 static naRef getLocal(struct Context* ctx, struct Frame* f, naRef sym)
230 {
231     naRef result;
232     if(!naHash_get(f->locals, sym, &result)) {
233         naRef c = f->func.ref.ptr.func->closure;
234         if(!getClosure(c.ref.ptr.closure, sym, &result))
235             ERR(ctx, "undefined symbol");
236     }
237     return result;
238 }
239
240 static int setClosure(naRef closure, naRef sym, naRef val)
241 {
242     struct naClosure* c = closure.ref.ptr.closure;
243     if(c == 0) { return 0; }
244     else if(naHash_tryset(c->namespace, sym, val)) { return 1; }
245     else { return setClosure(c->next, sym, val); }
246 }
247
248 static naRef setLocal(struct Frame* f, naRef sym, naRef val)
249 {
250     // Try the locals first, if not already there try the closures in
251     // order.  Finally put it in the locals if nothing matched.
252     if(!naHash_tryset(f->locals, sym, val))
253         if(!setClosure(f->func.ref.ptr.func->closure, sym, val))
254             naHash_set(f->locals, sym, val);
255     return val;
256 }
257
258 // Recursively descend into the parents lists
259 static int getMember(struct Context* ctx, naRef obj, naRef fld, naRef* result)
260 {
261     naRef p;
262     if(!IS_HASH(obj)) ERR(ctx, "non-objects have no members");
263     if(naHash_get(obj, fld, result)) {
264         return 1;
265     } else if(naHash_get(obj, ctx->parentsRef, &p)) {
266         int i;
267         if(!IS_VEC(p)) ERR(ctx, "parents field not vector");
268         for(i=0; i<p.ref.ptr.vec->size; i++)
269             if(getMember(ctx, p.ref.ptr.vec->array[i], fld, result))
270                 return 1;
271     }
272     return 0;
273 }
274
275 static void PUSH(struct Context* ctx, naRef r)
276 {
277     if(ctx->opTop >= MAX_STACK_DEPTH) ERR(ctx, "stack overflow");
278     ctx->opStack[ctx->opTop++] = r;
279 }
280
281 static naRef POP(struct Context* ctx)
282 {
283     if(ctx->opTop == 0) ERR(ctx, "BUG: stack underflow");
284     return ctx->opStack[--ctx->opTop];
285 }
286
287 static naRef TOP(struct Context* ctx)
288 {
289     if(ctx->opTop == 0) ERR(ctx, "BUG: stack underflow");
290     return ctx->opStack[ctx->opTop-1];
291 }
292
293 static int ARG16(unsigned char* byteCode, struct Frame* f)
294 {
295     int arg = byteCode[f->ip]<<8 | byteCode[f->ip+1];
296     f->ip += 2;
297     return arg;
298 }
299
300 // OP_EACH works like a vector get, except that it leaves the vector
301 // and index on the stack, increments the index after use, and pops
302 // the arguments and pushes a nil if the index is beyond the end.
303 static void evalEach(struct Context* ctx)
304 {
305     int idx = (int)(ctx->opStack[ctx->opTop-1].num);
306     naRef vec = ctx->opStack[ctx->opTop-2];
307     if(idx >= vec.ref.ptr.vec->size) {
308         ctx->opTop -= 2; // pop two values
309         PUSH(ctx, naNil());
310         return;
311     }
312     ctx->opStack[ctx->opTop-1].num = idx+1; // modify in place
313     PUSH(ctx, naVec_get(vec, idx));
314 }
315
316 static void run1(struct Context* ctx, struct Frame* f, naRef code)
317 {
318     naRef a, b, c;
319     struct naCode* cd = code.ref.ptr.code;
320     int op, arg;
321
322     if(f->ip >= cd->nBytes) {
323         DBG(printf("Done with frame %d\n", ctx->fTop-1);)
324         ctx->fTop--;
325         if(ctx->fTop <= 0)
326             ctx->done = 1;
327         return;
328     }
329
330     op = cd->byteCode[f->ip++];
331     DBG(printf("Stack Depth: %d\n", ctx->opTop));
332     DBG(printOpDEBUG(f->ip-1, op));
333     switch(op) {
334     case OP_POP:
335         POP(ctx);
336         break;
337     case OP_DUP:
338         PUSH(ctx, ctx->opStack[ctx->opTop-1]);
339         break;
340     case OP_XCHG:
341         a = POP(ctx); b = POP(ctx);
342         PUSH(ctx, a); PUSH(ctx, b);
343         break;
344     case OP_PLUS: case OP_MUL: case OP_DIV: case OP_MINUS:
345     case OP_LT: case OP_LTE: case OP_GT: case OP_GTE:
346         a = POP(ctx); b = POP(ctx);
347         PUSH(ctx, evalBinaryNumeric(ctx, op, b, a));
348         break;
349     case OP_EQ: case OP_NEQ:
350         a = POP(ctx); b = POP(ctx);
351         PUSH(ctx, evalEquality(op, b, a));
352         break;
353     case OP_AND: case OP_OR:
354         a = POP(ctx); b = POP(ctx);
355         PUSH(ctx, evalAndOr(ctx, op, a, b));
356         break;
357     case OP_CAT:
358         // stringify can call the GC, so don't take stuff of the stack!
359         if(ctx->opTop <= 1) ERR(ctx, "BUG: stack underflow");
360         a = stringify(ctx, ctx->opStack[ctx->opTop-1]);
361         b = stringify(ctx, ctx->opStack[ctx->opTop-2]);
362         c = naStr_concat(naNewString(ctx), b, a);
363         ctx->opTop -= 2;
364         PUSH(ctx, c);
365         break;
366     case OP_NEG:
367         a = POP(ctx);
368         PUSH(ctx, naNum(-numify(ctx, a)));
369         break;
370     case OP_NOT:
371         a = POP(ctx);
372         PUSH(ctx, naNum(boolify(ctx, a) ? 0 : 1));
373         break;
374     case OP_PUSHCONST:
375         a = cd->constants[ARG16(cd->byteCode, f)];
376         if(IS_CODE(a)) a = bindFunction(ctx, f, a);
377         PUSH(ctx, a);
378         break;
379     case OP_PUSHONE:
380         PUSH(ctx, naNum(1));
381         break;
382     case OP_PUSHZERO:
383         PUSH(ctx, naNum(0));
384         break;
385     case OP_PUSHNIL:
386         PUSH(ctx, naNil());
387         break;
388     case OP_NEWVEC:
389         PUSH(ctx, naNewVector(ctx));
390         break;
391     case OP_VAPPEND:
392         b = POP(ctx); a = TOP(ctx);
393         naVec_append(a, b);
394         break;
395     case OP_NEWHASH:
396         PUSH(ctx, naNewHash(ctx));
397         break;
398     case OP_HAPPEND:
399         c = POP(ctx); b = POP(ctx); a = TOP(ctx); // a,b,c: hash, key, val
400         naHash_set(a, b, c);
401         break;
402     case OP_LOCAL:
403         a = getLocal(ctx, f, POP(ctx));
404         PUSH(ctx, a);
405         break;
406     case OP_SETLOCAL:
407         a = POP(ctx); b = POP(ctx);
408         PUSH(ctx, setLocal(f, b, a));
409         break;
410     case OP_MEMBER:
411         a = POP(ctx); b = POP(ctx);
412         if(!getMember(ctx, b, a, &c))
413             ERR(ctx, "no such member");
414         PUSH(ctx, c);
415         break;
416     case OP_SETMEMBER:
417         c = POP(ctx); b = POP(ctx); a = POP(ctx); // a,b,c: hash, key, val
418         if(!IS_HASH(a)) ERR(ctx, "non-objects have no members");
419         naHash_set(a, b, c);
420         PUSH(ctx, c);
421         break;
422     case OP_INSERT:
423         c = POP(ctx); b = POP(ctx); a = POP(ctx); // a,b,c: box, key, val
424         containerSet(ctx, a, b, c);
425         PUSH(ctx, c);
426         break;
427     case OP_EXTRACT:
428         b = POP(ctx); a = POP(ctx); // a,b: box, key
429         PUSH(ctx, containerGet(ctx, a, b));
430         break;
431     case OP_JMP:
432         f->ip = ARG16(cd->byteCode, f);
433         DBG(printf("   [Jump to: %d]\n", f->ip);)
434         break;
435     case OP_JIFNIL:
436         arg = ARG16(cd->byteCode, f);
437         a = TOP(ctx);
438         if(IS_NIL(a)) {
439             POP(ctx); // Pops **ONLY** if it's nil!
440             f->ip = arg;
441             DBG(printf("   [Jump to: %d]\n", f->ip);)
442         }
443         break;
444     case OP_JIFNOT:
445         arg = ARG16(cd->byteCode, f);
446         if(!boolify(ctx, POP(ctx))) {
447             f->ip = arg;
448             DBG(printf("   [Jump to: %d]\n", f->ip);)
449         }
450         break;
451     case OP_FCALL:
452         b = POP(ctx); a = POP(ctx); // a,b = func, args
453         setupFuncall(ctx, a, b);
454         break;
455     case OP_MCALL:
456         c = POP(ctx); b = POP(ctx); a = POP(ctx); // a,b,c = obj, func, args
457         setupFuncall(ctx, b, c);
458         naHash_set(ctx->fStack[ctx->fTop-1].locals, ctx->meRef, a);
459         break;
460     case OP_RETURN:
461         a = POP(ctx);
462         ctx->opTop = f->bp; // restore the correct stack frame!
463         ctx->fTop--;
464         ctx->fStack[ctx->fTop].args.ref.ptr.vec->size = 0;
465         PUSH(ctx, a);
466         break;
467     case OP_LINE:
468         f->line = ARG16(cd->byteCode, f);
469         break;
470     case OP_EACH:
471         evalEach(ctx);
472         break;
473     case OP_MARK: // save stack state (e.g. "setjmp")
474         ctx->markStack[ctx->markTop++] = ctx->opTop;
475         break;
476     case OP_UNMARK: // pop stack state set by mark
477         ctx->markTop--;
478         break;
479     case OP_BREAK: // restore stack state (FOLLOW WITH JMP!)
480         ctx->opTop = ctx->markStack[--ctx->markTop];
481         break;
482     default:
483         ERR(ctx, "BUG: bad opcode");
484     }
485
486     if(ctx->fTop <= 0)
487         ctx->done = 1;
488 }
489
490 static void nativeCall(struct Context* ctx, struct Frame* f, naRef ccode)
491 {
492     naCFunction fptr = ccode.ref.ptr.ccode->fptr;
493     naRef result = (*fptr)(ctx, f->args);
494     ctx->fTop--;
495     ctx->fStack[ctx->fTop].args.ref.ptr.vec->size = 0;
496     PUSH(ctx, result);
497 }
498
499 void naSave(struct Context* ctx, naRef obj)
500 {
501     ctx->save = obj;
502 }
503
504 int naStackDepth(struct Context* ctx)
505 {
506     return ctx->fTop;
507 }
508
509 int naGetLine(struct Context* ctx, int frame)
510 {
511     return ctx->fStack[ctx->fTop-1-frame].line;
512 }
513
514 naRef naGetSourceFile(struct Context* ctx, int frame)
515 {
516     naRef f = ctx->fStack[ctx->fTop-1-frame].func;
517     f = f.ref.ptr.func->code;
518     return f.ref.ptr.code->srcFile;
519 }
520
521 char* naGetError(struct Context* ctx)
522 {
523     return ctx->error;
524 }
525
526 static naRef run(naContext ctx)
527 {
528     // Return early if an error occurred.  It will be visible to the
529     // caller via naGetError().
530     ctx->error = 0;
531     if(setjmp(ctx->jumpHandle))
532         return naNil();
533     
534     ctx->done = 0;
535     while(!ctx->done) {
536         struct Frame* f = &(ctx->fStack[ctx->fTop-1]);
537         naRef code = f->func.ref.ptr.func->code;
538         if(IS_CCODE(code)) nativeCall(ctx, f, code);
539         else               run1(ctx, f, code);
540         
541         ctx->temps.ref.ptr.vec->size = 0; // Reset the temporaries
542         DBG(printStackDEBUG(ctx);)
543     }
544
545     DBG(printStackDEBUG(ctx);)
546     return ctx->opStack[--ctx->opTop];
547 }
548
549 naRef naBindFunction(naContext ctx, naRef code, naRef closure)
550 {
551     naRef func = naNewFunc(ctx, code);
552     func.ref.ptr.func->closure = naNewClosure(ctx, closure, naNil());
553     return func;
554 }
555
556 naRef naCall(naContext ctx, naRef func, naRef args, naRef obj, naRef locals)
557 {
558     // We might have to allocate objects, which can call the GC.  But
559     // the call isn't on the Nasal stack yet, so the GC won't find our
560     // C-space arguments.
561     naVec_append(ctx->temps, func);
562     naVec_append(ctx->temps, args);
563     naVec_append(ctx->temps, obj);
564     naVec_append(ctx->temps, locals);
565
566     if(IS_NIL(args))
567         args = naNewVector(ctx);
568     if(IS_NIL(locals))
569         locals = naNewHash(ctx);
570     if(!IS_FUNC(func)) {
571         // Generate a noop closure for bare code objects
572         naRef code = func;
573         func = naNewFunc(ctx, code);
574         func.ref.ptr.func->closure = naNewClosure(ctx, locals, naNil());
575     }
576     if(!IS_NIL(obj))
577         naHash_set(locals, ctx->meRef, obj);
578
579     ctx->fTop = ctx->opTop = ctx->markTop = 0;
580     setupFuncall(ctx, func, args);
581     ctx->fStack[ctx->fTop-1].locals = locals;
582
583     return run(ctx);
584 }
585