diff --git a/src/env.c b/src/env.c index 1dc2b10..d68fff4 100644 --- a/src/env.c +++ b/src/env.c @@ -72,22 +72,56 @@ struct Environment envForLambda(const Object *params, const Object *arg_forms, return env; } +// Determine if a given symbol exists in the given environment chain +// +// Modifies `env` to the environment that the symbol was found in, only if the +// symbol was found +// +// Returns the index of the symbol in the environment, if found. Otherwise, -1 +int findInEnv(struct Environment **env, const char *name) +{ + struct Environment *temp_env = *env; + while(temp_env) { + for(int i = 0; i < temp_env->size; i++) { + if(temp_env->strings[i] == NULL) { + break; + } + if(strcmp(temp_env->strings[i], name) == 0) { + *env = temp_env; + return i; + } + } + temp_env = temp_env->outer; + } + return -1; +} + // TODO Maybe extend environment using a new outer, instead of realloc void addToEnv(struct Environment *env, const char *name, const Object obj) { + // int sym_pos = findInEnv(&env, name); + // if(sym_pos != -1) { + // Object o = cloneObject(obj); + // cleanObject(&env->objects[sym_pos]); + // env->objects[sym_pos] = o; + // return; + // } + int i; struct Environment *temp_env = env; while(temp_env) { for(i = 0; i < temp_env->size; i++) { if(temp_env->strings[i] == NULL) { + //printf("Add new object\n"); temp_env->strings[i] = calloc(sizeof(char), strlen(name) + 1); strncpy(temp_env->strings[i], name, strlen(name)); temp_env->objects[i] = cloneObject(obj); return; } if(strcmp(temp_env->strings[i], name) == 0) { + Object o = cloneObject(obj); cleanObject(&temp_env->objects[i]); - temp_env->objects[i] = cloneObject(obj); + temp_env->objects[i] = o; return; } }