4 ////////////////////////////////////////////////////////////////////////
5 // Debugging stuff. ////////////////////////////////////////////////////
6 ////////////////////////////////////////////////////////////////////////
8 #if !defined(DEBUG_NASAL)
9 # define DBG(expr) /* noop */
11 # define DBG(expr) expr
15 char* opStringDEBUG(int op);
16 void printOpDEBUG(int ip, int op);
17 void printStackDEBUG(struct Context* ctx);
18 ////////////////////////////////////////////////////////////////////////
20 struct Globals* globals = 0;
22 static naRef bindFunction(struct Context* ctx, struct Frame* f, naRef code);
24 #define ERR(c, msg) naRuntimeError((c),(msg))
25 void naRuntimeError(struct Context* c, char* msg)
28 longjmp(c->jumpHandle, 1);
31 static int boolify(struct Context* ctx, naRef r)
33 if(IS_NUM(r)) return r.num != 0;
34 if(IS_NIL(r)) return 0;
37 if(naStr_len(r) == 0) return 0;
38 if(naStr_tonum(r, &d)) return d != 0;
41 ERR(ctx, "non-scalar used in boolean context");
45 static double numify(struct Context* ctx, naRef o)
48 if(IS_NUM(o)) return o.num;
49 else if(IS_NIL(o)) ERR(ctx, "nil used in numeric context");
50 else if(!IS_STR(o)) ERR(ctx, "non-scalar in numeric context");
51 else if(naStr_tonum(o, &n)) return n;
52 else ERR(ctx, "non-numeric string in numeric context");
56 static naRef stringify(struct Context* ctx, naRef r)
58 if(IS_STR(r)) return r;
59 if(IS_NUM(r)) return naStr_fromnum(naNewString(ctx), r.num);
60 ERR(ctx, "non-scalar in string context");
64 static int checkVec(struct Context* ctx, naRef vec, naRef idx)
66 int i = (int)numify(ctx, idx);
67 if(i < 0) i += naVec_size(vec);
68 if(i < 0 || i >= naVec_size(vec)) ERR(ctx, "vector index out of bounds");
72 static int checkStr(struct Context* ctx, naRef str, naRef idx)
74 int i = (int)numify(ctx, idx);
75 if(i < 0) i += naStr_len(str);
76 if(i < 0 || i >= naStr_len(str)) ERR(ctx, "string index out of bounds");
80 static naRef containerGet(struct Context* ctx, naRef box, naRef key)
82 naRef result = naNil();
83 if(!IS_SCALAR(key)) ERR(ctx, "container index not scalar");
85 if(!naHash_get(box, key, &result))
86 ERR(ctx, "undefined value in container");
87 } else if(IS_VEC(box)) {
88 result = naVec_get(box, checkVec(ctx, box, key));
89 } else if(IS_STR(box)) {
90 result = naNum((unsigned char)naStr_data(box)[checkStr(ctx, box, key)]);
92 ERR(ctx, "extract from non-container");
97 static void containerSet(struct Context* ctx, naRef box, naRef key, naRef val)
99 if(!IS_SCALAR(key)) ERR(ctx, "container index not scalar");
100 else if(IS_HASH(box)) naHash_set(box, key, val);
101 else if(IS_VEC(box)) naVec_set(box, checkVec(ctx, box, key), val);
102 else if(IS_STR(box)) {
103 if(box.ref.ptr.str->hashcode)
104 ERR(ctx, "cannot change immutable string");
105 naStr_data(box)[checkStr(ctx, box, key)] = (char)numify(ctx, val);
106 } else ERR(ctx, "insert into non-container");
109 static void initTemps(struct Context* c)
112 c->temps = naAlloc(c->tempsz * sizeof(struct naObj*));
116 static void initContext(struct Context* c)
119 c->fTop = c->opTop = c->markTop = 0;
120 for(i=0; i<NUM_NASAL_TYPES; i++)
134 static void initGlobals()
138 globals = (struct Globals*)naAlloc(sizeof(struct Globals));
139 naBZero(globals, sizeof(struct Globals));
141 globals->sem = naNewSem();
142 globals->lock = naNewLock();
144 globals->allocCount = 256; // reasonable starting value
145 for(i=0; i<NUM_NASAL_TYPES; i++)
146 naGC_init(&(globals->pools[i]), i);
147 globals->deadsz = 256;
149 globals->deadBlocks = naAlloc(sizeof(void*) * globals->deadsz);
151 // Initialize a single context
152 globals->freeContexts = 0;
153 globals->allContexts = 0;
156 globals->symbols = naNewHash(c);
157 globals->save = naNewVector(c);
159 // Cache pre-calculated "me", "arg" and "parents" scalars
160 globals->meRef = naInternSymbol(naStr_fromdata(naNewString(c), "me", 2));
161 globals->argRef = naInternSymbol(naStr_fromdata(naNewString(c), "arg", 3));
162 globals->parentsRef = naInternSymbol(naStr_fromdata(naNewString(c), "parents", 7));
167 struct Context* naNewContext()
174 c = globals->freeContexts;
176 globals->freeContexts = c->nextFree;
182 c = (struct Context*)naAlloc(sizeof(struct Context));
186 c->nextAll = globals->allContexts;
188 globals->allContexts = c;
194 void naFreeContext(struct Context* c)
198 c->nextFree = globals->freeContexts;
199 globals->freeContexts = c;
203 // Note that opTop is incremented separately, to avoid situations
204 // where the "r" expression also references opTop. The SGI compiler
205 // is known to have issues with such code.
206 #define PUSH(r) do { \
207 if(ctx->opTop >= MAX_STACK_DEPTH) ERR(ctx, "stack overflow"); \
208 ctx->opStack[ctx->opTop] = r; \
212 static void setupArgs(naContext ctx, struct Frame* f, naRef* args, int nargs)
215 struct naCode* c = f->func.ref.ptr.func->code.ref.ptr.code;
217 // Set the argument symbols, and put any remaining args in a vector
218 if(nargs < c->nArgs) ERR(ctx, "not enough arguments to function call");
219 for(i=0; i<c->nArgs; i++)
220 naHash_newsym(f->locals.ref.ptr.hash,
221 &c->constants[c->argSyms[i]], &args[i]);
224 for(i=0; i<c->nOptArgs; i++, nargs--) {
225 naRef val = nargs > 0 ? args[i] : c->constants[c->optArgVals[i]];
227 val = bindFunction(ctx, &ctx->fStack[ctx->fTop-2], val);
228 naHash_newsym(f->locals.ref.ptr.hash, &c->constants[c->optArgSyms[i]],
232 if(c->needArgVector || nargs > 0) {
233 naRef argsv = naNewVector(ctx);
234 naVec_setsize(argsv, nargs > 0 ? nargs : 0);
235 for(i=0; i<nargs; i++)
236 argsv.ref.ptr.vec->rec->array[i] = *args++;
237 naHash_newsym(f->locals.ref.ptr.hash, &c->restArgSym, &argsv);
241 struct Frame* setupFuncall(struct Context* ctx, int nargs, int mcall, int tail)
246 DBG(printf("setupFuncall(nargs:%d, mcall:%d)\n", nargs, mcall);)
248 frame = &ctx->opStack[ctx->opTop - nargs - 1];
249 if(!IS_FUNC(frame[0]))
250 ERR(ctx, "function/method call invoked on uncallable object");
252 // Just do native calls right here, and don't touch the stack
253 // frames; return the current one (unless it's a tail call!).
254 if(frame[0].ref.ptr.func->code.ref.ptr.obj->type == T_CCODE) {
255 naRef obj = mcall ? frame[-1] : naNil();
256 naCFunction fp = frame[0].ref.ptr.func->code.ref.ptr.ccode->fptr;
257 naRef result = (*fp)(ctx, obj, nargs, frame + 1);
258 ctx->opTop -= nargs + 1 + mcall;
260 return &(ctx->fStack[ctx->fTop-1]);
263 if(tail) ctx->fTop--;
264 else if(ctx->fTop >= MAX_RECURSION) ERR(ctx, "call stack overflow");
266 // Note: assign nil first, otherwise the naNew() can cause a GC,
267 // which will now (after fTop++) see the *old* reference as a
269 f = &(ctx->fStack[ctx->fTop++]);
270 f->locals = f->func = naNil();
271 f->locals = naNewHash(ctx);
274 f->bp = ctx->opTop - (nargs + 1 + mcall);
277 naHash_set(f->locals, globals->meRef, frame[-1]);
279 setupArgs(ctx, f, frame+1, nargs);
281 ctx->opTop = f->bp; // Pop the stack last, to avoid GC lossage
282 DBG(printf("Entering frame %d with %d args\n", ctx->fTop-1, nargs);)
286 static naRef evalAndOr(struct Context* ctx, int op, naRef ra, naRef rb)
288 int a = boolify(ctx, ra);
289 int b = boolify(ctx, rb);
291 if(op == OP_AND) result = a && b ? 1 : 0;
292 else result = a || b ? 1 : 0;
293 return naNum(result);
296 static naRef evalEquality(int op, naRef ra, naRef rb)
298 int result = naEqual(ra, rb);
299 return naNum((op==OP_EQ) ? result : !result);
302 // When a code object comes out of the constant pool and shows up on
303 // the stack, it needs to be bound with the lexical context.
304 static naRef bindFunction(struct Context* ctx, struct Frame* f, naRef code)
306 naRef result = naNewFunc(ctx, code);
307 result.ref.ptr.func->namespace = f->locals;
308 result.ref.ptr.func->next = f->func;
312 static int getClosure(struct naFunc* c, naRef sym, naRef* result)
315 if(naHash_get(c->namespace, sym, result)) return 1;
316 c = c->next.ref.ptr.func;
321 static naRef getLocal2(struct Context* ctx, struct Frame* f, naRef sym)
324 if(!naHash_get(f->locals, sym, &result))
325 if(!getClosure(f->func.ref.ptr.func, sym, &result))
326 ERR(ctx, "undefined symbol");
330 static void getLocal(struct Context* ctx, struct Frame* f,
331 naRef* sym, naRef* out)
334 struct naStr* str = sym->ref.ptr.str;
335 if(naHash_sym(f->locals.ref.ptr.hash, str, out))
337 func = f->func.ref.ptr.func;
338 while(func && func->namespace.ref.ptr.hash) {
339 if(naHash_sym(func->namespace.ref.ptr.hash, str, out))
341 func = func->next.ref.ptr.func;
343 // Now do it again using the more general naHash_get(). This will
344 // only be necessary if something has created the value in the
345 // namespace using the more generic hash syntax
346 // (e.g. namespace["symbol"] and not namespace.symbol).
347 *out = getLocal2(ctx, f, *sym);
350 static int setClosure(naRef func, naRef sym, naRef val)
352 struct naFunc* c = func.ref.ptr.func;
353 if(c == 0) { return 0; }
354 else if(naHash_tryset(c->namespace, sym, val)) { return 1; }
355 else { return setClosure(c->next, sym, val); }
358 static naRef setSymbol(struct Frame* f, naRef sym, naRef val)
360 // Try the locals first, if not already there try the closures in
361 // order. Finally put it in the locals if nothing matched.
362 if(!naHash_tryset(f->locals, sym, val))
363 if(!setClosure(f->func, sym, val))
364 naHash_set(f->locals, sym, val);
368 // Recursively descend into the parents lists
369 static int getMember(struct Context* ctx, naRef obj, naRef fld,
370 naRef* result, int count)
373 if(--count < 0) ERR(ctx, "too many parents");
374 if(!IS_HASH(obj)) ERR(ctx, "non-objects have no members");
375 if(naHash_get(obj, fld, result)) {
377 } else if(naHash_get(obj, globals->parentsRef, &p)) {
380 struct VecRec* v = p.ref.ptr.vec->rec;
381 for(i=0; i<v->size; i++)
382 if(getMember(ctx, v->array[i], fld, result, count))
385 ERR(ctx, "parents field not vector");
390 // OP_EACH works like a vector get, except that it leaves the vector
391 // and index on the stack, increments the index after use, and
392 // pushes a nil if the index is beyond the end.
393 static void evalEach(struct Context* ctx, int useIndex)
395 int idx = (int)(ctx->opStack[ctx->opTop-1].num);
396 naRef vec = ctx->opStack[ctx->opTop-2];
397 if(!IS_VEC(vec)) naRuntimeError(ctx, "foreach enumeration of non-vector");
398 if(!vec.ref.ptr.vec->rec || idx >= vec.ref.ptr.vec->rec->size) {
402 ctx->opStack[ctx->opTop-1].num = idx+1; // modify in place
403 PUSH(useIndex ? naNum(idx) : naVec_get(vec, idx));
406 #define ARG() cd->byteCode[f->ip++]
407 #define CONSTARG() cd->constants[ARG()]
408 #define POP() ctx->opStack[--ctx->opTop]
409 #define STK(n) (ctx->opStack[ctx->opTop-(n)])
410 #define FIXFRAME() f = &(ctx->fStack[ctx->fTop-1]); \
411 cd = f->func.ref.ptr.func->code.ref.ptr.code;
412 static naRef run(struct Context* ctx)
422 op = cd->byteCode[f->ip++];
423 DBG(printf("Stack Depth: %d\n", ctx->opTop));
424 DBG(printOpDEBUG(f->ip-1, op));
430 PUSH(ctx->opStack[ctx->opTop-1]);
433 PUSH(ctx->opStack[ctx->opTop-2]);
434 PUSH(ctx->opStack[ctx->opTop-2]);
437 a = STK(1); STK(1) = STK(2); STK(2) = a;
440 #define BINOP(expr) do { \
441 double l = IS_NUM(STK(2)) ? STK(2).num : numify(ctx, STK(2)); \
442 double r = IS_NUM(STK(1)) ? STK(1).num : numify(ctx, STK(1)); \
443 STK(2).ref.reftag = ~NASAL_REFTAG; \
445 ctx->opTop--; } while(0)
447 case OP_PLUS: BINOP(l + r); break;
448 case OP_MINUS: BINOP(l - r); break;
449 case OP_MUL: BINOP(l * r); break;
450 case OP_DIV: BINOP(l / r); break;
451 case OP_LT: BINOP(l < r ? 1 : 0); break;
452 case OP_LTE: BINOP(l <= r ? 1 : 0); break;
453 case OP_GT: BINOP(l > r ? 1 : 0); break;
454 case OP_GTE: BINOP(l >= r ? 1 : 0); break;
458 case OP_EQ: case OP_NEQ:
459 STK(2) = evalEquality(op, STK(2), STK(1));
462 case OP_AND: case OP_OR:
463 STK(2) = evalAndOr(ctx, op, STK(2), STK(1));
467 // stringify can call the GC, so don't take stuff of the stack!
468 a = stringify(ctx, ctx->opStack[ctx->opTop-1]);
469 b = stringify(ctx, ctx->opStack[ctx->opTop-2]);
470 c = naStr_concat(naNewString(ctx), b, a);
475 STK(1) = naNum(-numify(ctx, STK(1)));
478 STK(1) = naNum(boolify(ctx, STK(1)) ? 0 : 1);
482 if(IS_CODE(a)) a = bindFunction(ctx, f, a);
495 PUSH(naNewVector(ctx));
498 naVec_append(STK(2), STK(1));
502 PUSH(naNewHash(ctx));
505 naHash_set(STK(3), STK(2), STK(1));
510 getLocal(ctx, f, &a, &b);
514 STK(2) = setSymbol(f, STK(2), STK(1));
518 naHash_set(f->locals, STK(2), STK(1));
519 STK(2) = STK(1); // FIXME: reverse order of arguments instead!
523 if(!getMember(ctx, STK(1), CONSTARG(), &STK(1), 64))
524 ERR(ctx, "no such member");
527 if(!IS_HASH(STK(3))) ERR(ctx, "non-objects have no members");
528 naHash_set(STK(3), STK(2), STK(1));
529 STK(3) = STK(1); // FIXME: fix arg order instead
533 containerSet(ctx, STK(3), STK(2), STK(1));
534 STK(3) = STK(1); // FIXME: codegen order again...
538 STK(2) = containerGet(ctx, STK(2), STK(1));
542 // Identical to JMP, except for locking
544 f->ip = cd->byteCode[f->ip];
545 DBG(printf(" [Jump to: %d]\n", f->ip);)
548 f->ip = cd->byteCode[f->ip];
549 DBG(printf(" [Jump to: %d]\n", f->ip);)
554 ctx->opTop--; // Pops **ONLY** if it's nil!
556 DBG(printf(" [Jump to: %d]\n", f->ip);)
561 if(!boolify(ctx, POP())) {
563 DBG(printf(" [Jump to: %d]\n", f->ip);)
567 f = setupFuncall(ctx, ARG(), 0, 0);
568 cd = f->func.ref.ptr.func->code.ref.ptr.code;
571 f = setupFuncall(ctx, ARG(), 0, 1);
572 cd = f->func.ref.ptr.func->code.ref.ptr.code;
575 f = setupFuncall(ctx, ARG(), 1, 0);
576 cd = f->func.ref.ptr.func->code.ref.ptr.code;
579 f = setupFuncall(ctx, ARG(), 1, 1);
580 cd = f->func.ref.ptr.func->code.ref.ptr.code;
584 if(--ctx->fTop <= 0) return a;
585 ctx->opTop = f->bp + 1; // restore the correct opstack frame!
595 case OP_MARK: // save stack state (e.g. "setjmp")
596 if(ctx->markTop >= MAX_MARK_DEPTH)
597 naRuntimeError(ctx, "mark stack overflow");
598 ctx->markStack[ctx->markTop++] = ctx->opTop;
600 case OP_UNMARK: // pop stack state set by mark
603 case OP_BREAK: // restore stack state (FOLLOW WITH JMP!)
604 ctx->opTop = ctx->markStack[ctx->markTop-1];
606 case OP_BREAK2: // same, but also pop the mark stack
607 ctx->opTop = ctx->markStack[--ctx->markTop];
610 ERR(ctx, "BUG: bad opcode");
612 ctx->ntemps = 0; // reset GC temp vector
613 DBG(printStackDEBUG(ctx);)
615 return naNil(); // unreachable
622 void naSave(struct Context* ctx, naRef obj)
624 naVec_append(globals->save, obj);
627 // FIXME: handle ctx->callParent
628 int naStackDepth(struct Context* ctx)
633 // FIXME: handle ctx->callParent
634 int naGetLine(struct Context* ctx, int frame)
636 struct Frame* f = &ctx->fStack[ctx->fTop-1-frame];
637 naRef func = f->func;
639 if(IS_FUNC(func) && IS_CODE(func.ref.ptr.func->code)) {
640 struct naCode* c = func.ref.ptr.func->code.ref.ptr.code;
641 unsigned short* p = c->lineIps + c->nLines - 2;
642 while(p >= c->lineIps && p[0] > ip)
649 // FIXME: handle ctx->callParent
650 naRef naGetSourceFile(struct Context* ctx, int frame)
652 naRef f = ctx->fStack[ctx->fTop-1-frame].func;
653 f = f.ref.ptr.func->code;
654 return f.ref.ptr.code->srcFile;
657 char* naGetError(struct Context* ctx)
659 if(IS_STR(ctx->dieArg))
660 return (char*)ctx->dieArg.ref.ptr.str->data;
664 naRef naBindFunction(naContext ctx, naRef code, naRef closure)
666 naRef func = naNewFunc(ctx, code);
667 func.ref.ptr.func->namespace = closure;
668 func.ref.ptr.func->next = naNil();
672 naRef naBindToContext(naContext ctx, naRef code)
674 naRef func = naNewFunc(ctx, code);
675 struct Frame* f = &ctx->fStack[ctx->fTop-1];
676 func.ref.ptr.func->namespace = f->locals;
677 func.ref.ptr.func->next = f->func;
681 naRef naCall(naContext ctx, naRef func, int argc, naRef* args,
682 naRef obj, naRef locals)
686 if(!ctx->callParent) naModLock(ctx);
688 // We might have to allocate objects, which can call the GC. But
689 // the call isn't on the Nasal stack yet, so the GC won't find our
690 // C-space arguments.
691 naTempSave(ctx, func);
692 for(i=0; i<argc; i++)
693 naTempSave(ctx, args[i]);
694 naTempSave(ctx, obj);
695 naTempSave(ctx, locals);
697 if(IS_CCODE(func.ref.ptr.func->code)) {
698 naCFunction fp = func.ref.ptr.func->code.ref.ptr.ccode->fptr;
699 result = (*fp)(ctx, obj, argc, args);
700 if(!ctx->callParent) naModUnlock(ctx);
705 locals = naNewHash(ctx);
707 func = naNewFunc(ctx, func); // bind bare code objects
709 naHash_set(locals, globals->meRef, obj);
711 ctx->dieArg = naNil();
713 ctx->opTop = ctx->markTop = 0;
715 ctx->fStack[0].func = func;
716 ctx->fStack[0].locals = locals;
717 ctx->fStack[0].ip = 0;
718 ctx->fStack[0].bp = ctx->opTop;
720 setupArgs(ctx, ctx->fStack, args, argc);
722 // Return early if an error occurred. It will be visible to the
723 // caller via naGetError().
725 if(setjmp(ctx->jumpHandle)) {
726 if(!ctx->callParent) naModUnlock(ctx);
731 if(!ctx->callParent) naModUnlock(ctx);