commit 54736a958eca2f5833d04b6495a6742f30a337b6 from: Omar Polo date: Wed Aug 04 21:41:22 2021 UTC pp->print & better vararg support for builtin functions commit - 219cbeaa58fa0f4f6a90d357d38414dd80bc8463 commit + 54736a958eca2f5833d04b6495a6742f30a337b6 blob - f04e9995a11e0f1ef8a590d58081409203b239c1 blob + fd1a044836520b54961cdb44e442b7af2f8a811b --- script.c +++ script.c @@ -45,6 +45,19 @@ static struct value v_false = {.type = V_NUM, .v = {.n static struct value v_true = {.type = V_NUM, .v = {.num = 1}}; static inline void +peekn(int depth, struct value *v) +{ + if (depth > stackh) + errx(1, "can't peek the stack at %d: underflow", + depth); + memcpy(v, &vstack[stackh - depth], sizeof(*v)); + +#if DEBUG + printf("peeking(%d) ", depth); pp_val(v); printf("\n"); +#endif +} + +static inline void popv(struct value *v) { if (stackh == 0) @@ -57,6 +70,15 @@ popv(struct value *v) } static inline void +popvn(int n) +{ + struct value v; + + while (n-- > 0) + popv(&v); +} + +static inline void pushv(struct value *v) { if (stackh == STACK_HEIGHT) @@ -672,7 +694,7 @@ op_funcall(struct proc *proc) } void -add_builtin_proc(const char *name, int (*fn)(int), int argc) +add_builtin_proc(const char *name, int (*fn)(int), int argc, int vararg) { struct proc *proc; @@ -680,6 +702,7 @@ add_builtin_proc(const char *name, int (*fn)(int), int proc->name = xstrdup(name); proc->nativefn = fn; proc->minargs = argc; + proc->vararg = vararg; TAILQ_INSERT_HEAD(&procs, proc, entry); } @@ -784,14 +807,24 @@ test_done(char *name, char *dir) } static int -builtin_pp(int argc) +builtin_print(int argc) { - struct value v; + struct value v; + int i; - popv(&v); - pp_val(&v); + for (i = argc; i > 0; --i) { + peekn(i, &v); + if (v.type == V_STR) + printf("%s", v.v.str); + else + pp_val(&v); + printf(" "); + } + printf("\n"); + popvn(argc); + return EVAL_OK; } @@ -826,8 +859,8 @@ main(int argc, char **argv) /* prepare the global env */ pushenv(); - add_builtin_proc("pp", builtin_pp, 1); - add_builtin_proc("skip", builtin_skip, 0); + add_builtin_proc("print", builtin_print, 1, 1); + add_builtin_proc("skip", builtin_skip, 0, 0); for (i = 1; i < argc; ++i) loadfile(argv[i]); blob - a644397cfc8bc4e38c3109e89be35ec043b65e9f blob + 28896865a4f7b7adaaf21480fa6c533b78787ea4 --- script.h +++ script.h @@ -115,7 +115,7 @@ struct proc { TAILQ_ENTRY(proc) entry; char *name; int minargs; - int varargs; + int vararg; char *args[MAXWELEM]; struct op *body; int (*nativefn)(int); @@ -162,7 +162,7 @@ void push_arg(struct op *); struct op *op_funcall(struct proc *); /* proc */ -void add_builtin_proc(const char *name, int (*)(int), int); +void add_builtin_proc(const char *name, int (*)(int), int, int); void prepare_proc(void); /* push_arg works on procs too */ int proc_setup_body(void);