picrin/src/proc.c

111 lines
2.2 KiB
C
Raw Normal View History

2014-01-17 06:58:31 -05:00
/**
* See Copyright Notice in picrin.h
*/
2013-10-21 04:35:14 -04:00
#include "picrin.h"
2013-12-03 09:40:50 -05:00
#include "picrin/pair.h"
2013-10-21 04:35:14 -04:00
#include "picrin/proc.h"
#include "picrin/irep.h"
struct pic_proc *
2014-01-08 08:44:53 -05:00
pic_proc_new(pic_state *pic, pic_func_t cfunc)
2013-10-21 04:35:14 -04:00
{
struct pic_proc *proc;
proc = (struct pic_proc *)pic_obj_alloc(pic, sizeof(struct pic_proc), PIC_TT_PROC);
2014-01-08 08:44:53 -05:00
proc->cfunc_p = true;
proc->u.cfunc = cfunc;
proc->env = NULL;
2013-10-21 04:35:14 -04:00
return proc;
}
struct pic_proc *
2014-01-08 08:44:53 -05:00
pic_proc_new_irep(pic_state *pic, struct pic_irep *irep, struct pic_env *env)
2013-10-21 04:35:14 -04:00
{
struct pic_proc *proc;
proc = (struct pic_proc *)pic_obj_alloc(pic, sizeof(struct pic_proc), PIC_TT_PROC);
2014-01-08 08:44:53 -05:00
proc->cfunc_p = false;
proc->u.irep = irep;
proc->env = env;
2013-10-21 04:35:14 -04:00
return proc;
}
2013-10-24 11:37:20 -04:00
void
pic_proc_cv_init(pic_state *pic, struct pic_proc *proc, size_t cv_size)
{
struct pic_env *env;
if (proc->env != NULL) {
pic_error(pic, "env slot already in use");
}
env = (struct pic_env *)pic_obj_alloc(pic, sizeof(struct pic_env), PIC_TT_ENV);
env->valuec = cv_size;
env->values = (pic_value *)pic_calloc(pic, cv_size, sizeof(pic_value));
env->up = NULL;
proc->env = env;
}
int
pic_proc_cv_size(pic_state *pic, struct pic_proc *proc)
{
return proc->env ? proc->env->valuec : 0;
}
pic_value
pic_proc_cv_ref(pic_state *pic, struct pic_proc *proc, size_t i)
{
if (proc->env == NULL) {
pic_error(pic, "no closed env");
}
return proc->env->values[i];
}
void
pic_proc_cv_set(pic_state *pic, struct pic_proc *proc, size_t i, pic_value v)
{
if (proc->env == NULL) {
pic_error(pic, "no closed env");
}
proc->env->values[i] = v;
}
2013-10-24 11:37:20 -04:00
static pic_value
pic_proc_proc_p(pic_state *pic)
{
pic_value v;
pic_get_args(pic, "o", &v);
return pic_bool_value(pic_proc_p(v));
}
2013-11-09 10:41:59 -05:00
static pic_value
pic_proc_apply(pic_state *pic)
{
2014-01-08 06:53:28 -05:00
struct pic_proc *proc;
pic_value *args, v;
2013-12-03 09:40:50 -05:00
size_t argc;
int i;
2013-11-09 10:41:59 -05:00
2014-01-08 06:53:28 -05:00
pic_get_args(pic, "l*", &proc, &argc, &args);
2013-11-09 10:41:59 -05:00
2013-12-03 09:40:50 -05:00
if (argc == 0) {
pic_error(pic, "apply: wrong number of arguments");
}
v = args[argc - 1];
for (i = argc - 2; i >= 0; --i) {
v = pic_cons(pic, args[i], v);
}
2014-01-08 06:53:28 -05:00
return pic_apply(pic, proc, v);
2013-11-09 10:41:59 -05:00
}
2013-10-24 11:37:20 -04:00
void
pic_init_proc(pic_state *pic)
{
pic_defun(pic, "procedure?", pic_proc_proc_p);
2013-11-09 10:41:59 -05:00
pic_defun(pic, "apply", pic_proc_apply);
2013-10-24 11:37:20 -04:00
}