add shift/reset

This commit is contained in:
Yuichi Nishiwaki
2017-04-26 02:10:40 +09:00
parent 4618afec94
commit b1ebda613b
4 changed files with 203 additions and 149 deletions
+47 -16
View File
@@ -8,17 +8,58 @@
#if PIC_USE_CALLCC
/*
* [(reset e)]k = k ([e] halt ())
* [(shift e)]k = [e] halt (\c x, c (k x))
*/
static pic_value
pic_cont_reset(pic_state *pic)
{
pic_value thunk;
pic_get_args(pic, "l", &thunk);
return pic_call(pic, thunk, 0);
}
static pic_value
shift_call(pic_state *pic)
{
pic_value x;
struct context cxt;
pic_get_args(pic, "o", &x);
CONTEXT_INIT(pic, &cxt, pic_closure_ref(pic, 0), 1, &x);
pic_vm(pic, &cxt);
return pic_protect(pic, cxt.fp->regs[1]);
}
static pic_value
pic_cont_shift(pic_state *pic)
{
pic_value f, k;
pic_get_args(pic, "l", &f);
k = pic_lambda(pic, shift_call, 1, pic->cxt->fp->regs[1]);
CONTEXT_INITK(pic, pic->cxt, f, pic->halt, 1, &k);
return pic_invalid_value(pic);
}
static pic_value
cont_call(pic_state *pic)
{
int argc;
pic_value *argv, k, dyn_env;
struct context *cxt, *c;
int i;
pic_get_args(pic, "*", &argc, &argv);
cxt = pic_data(pic, pic_closure_ref(pic, 0));
k = pic_closure_ref(pic, 1);
dyn_env = pic_closure_ref(pic, 2);
/* check if continuation is alive */
for (c = pic->cxt; c != NULL; c = c->prev) {
@@ -30,20 +71,9 @@ cont_call(pic_state *pic)
pic_error(pic, "calling dead escape continuation", 0);
}
k = pic_closure_ref(pic, 1);
dyn_env = pic_closure_ref(pic, 2);
CONTEXT_INIT(pic, cxt, k, argc, argv);
#define MKCALLK(argc) \
(cxt->tmpcode[0] = OP_CALL, cxt->tmpcode[1] = (argc), cxt->tmpcode)
cxt->pc = MKCALLK(argc);
cxt->sp = pic_make_frame_unsafe(pic, argc + 2);
cxt->sp->regs[0] = k;
for (i = 0; i < argc; ++i) {
cxt->sp->regs[i + 1] = argv[i];
}
pic->cxt = cxt;
pic->dyn_env = dyn_env;
longjmp(cxt->jmp, 1);
@@ -60,12 +90,11 @@ pic_make_cont(pic_state *pic, pic_value k)
static pic_value
pic_cont_callcc(pic_state *pic)
{
pic_value f, args[1];
pic_value f;
pic_get_args(pic, "l", &f);
args[0] = pic_make_cont(pic, pic->cxt->fp->regs[1]);
return pic_applyk(pic, f, 1, args);
return pic_callk(pic, f, 1, pic_make_cont(pic, pic->cxt->fp->regs[1]));
}
void
@@ -73,6 +102,8 @@ pic_init_cont(pic_state *pic)
{
pic_defun(pic, "call-with-current-continuation", pic_cont_callcc);
pic_defun(pic, "call/cc", pic_cont_callcc);
pic_defun(pic, "shift", pic_cont_shift);
pic_defun(pic, "reset", pic_cont_reset);
}
#endif /* PIC_USE_CALCC */