picrin/lib/var.c

92 lines
1.8 KiB
C
Raw Normal View History

2014-08-25 00:38:09 -04:00
/**
* See Copyright Notice in picrin.h
*/
#include "picrin.h"
2017-05-05 23:53:20 -04:00
#include "value.h"
2017-03-28 10:09:40 -04:00
#include "object.h"
#include "state.h"
2014-08-25 00:38:09 -04:00
2017-03-31 01:39:01 -04:00
/* implementated by deep binding */
2014-08-25 00:38:09 -04:00
2015-06-08 09:28:17 -04:00
static pic_value
var_call(pic_state *pic)
{
2016-02-19 10:03:16 -05:00
pic_value self, val;
2015-06-08 09:28:17 -04:00
int n;
2014-08-25 00:38:09 -04:00
n = pic_get_args(pic, "&|o", &self, &val);
2014-08-25 00:38:09 -04:00
2015-06-08 09:28:17 -04:00
if (n == 0) {
2017-03-31 01:39:01 -04:00
pic_value env, it;
pic_for_each(env, pic->dyn_env, it) {
2017-04-29 11:23:38 -04:00
if (pic_attr_has(pic, env, self)) {
return pic_attr_ref(pic, env, self);
2017-03-31 01:39:01 -04:00
}
}
PIC_UNREACHABLE(); /* logic flaw */
2015-06-08 09:28:17 -04:00
} else {
2017-03-31 01:39:01 -04:00
pic_value conv;
2017-03-31 01:39:01 -04:00
conv = pic_closure_ref(pic, 0);
if (! pic_false_p(pic, conv)) {
val = pic_call(pic, conv, 1, val);
}
2017-04-29 11:23:38 -04:00
pic_attr_set(pic, pic_car(pic, pic->dyn_env), self, val);
2016-02-23 06:50:26 -05:00
return pic_undef_value(pic);
}
2014-08-25 00:38:09 -04:00
}
2016-02-19 10:03:16 -05:00
pic_value
pic_make_var(pic_state *pic, pic_value init, pic_value conv)
2014-08-25 00:38:09 -04:00
{
pic_value var, env = pic->dyn_env;
2014-08-25 00:38:09 -04:00
2017-03-31 01:39:01 -04:00
var = pic_lambda(pic, var_call, 1, conv);
while (1) {
if (pic_nil_p(pic, pic_cdr(pic, env))) { /* top dyn env */
if (! pic_false_p(pic, conv)) {
init = pic_call(pic, conv, 1, init);
}
2017-04-29 11:23:38 -04:00
pic_attr_set(pic, pic_car(pic, env), var, init);
break;
}
env = pic_cdr(pic, env);
}
2017-03-31 01:39:01 -04:00
return var;
2014-08-25 00:38:09 -04:00
}
static pic_value
pic_var_make_parameter(pic_state *pic)
2014-08-25 00:38:09 -04:00
{
2016-02-19 10:03:16 -05:00
pic_value init, conv = pic_false_value(pic);
2014-08-25 00:38:09 -04:00
pic_get_args(pic, "o|l", &init, &conv);
2014-08-25 00:38:09 -04:00
2016-02-19 10:03:16 -05:00
return pic_make_var(pic, init, conv);
2014-08-25 00:38:09 -04:00
}
2015-06-08 09:28:17 -04:00
static pic_value
pic_var_current_dynamic_environment(pic_state *pic)
2015-06-08 09:28:17 -04:00
{
pic_value dyn_env;
int n;
2015-06-08 09:28:17 -04:00
n = pic_get_args(pic, "|o", &dyn_env);
2015-06-08 09:28:17 -04:00
if (n == 0) {
return pic->dyn_env;
} else {
pic->dyn_env = dyn_env;
return pic_undef_value(pic);
2016-02-23 06:50:26 -05:00
}
2015-06-08 09:28:17 -04:00
}
2014-08-25 00:38:09 -04:00
void
pic_init_var(pic_state *pic)
{
2014-08-31 22:37:52 -04:00
pic_defun(pic, "make-parameter", pic_var_make_parameter);
pic_defun(pic, "current-dynamic-environment", pic_var_current_dynamic_environment);
2014-08-25 00:38:09 -04:00
}