#include "pebblisp.h" #include "tokens.h" #include #include #include #ifndef STANDALONE #undef printf #define printf(...) APP_LOG(APP_LOG_LEVEL_DEBUG, __VA_ARGS__) #endif void copySlice(char * dest, struct Slice *src) { if(!dest || !src) return; strncpy(dest, src->text, src->length); dest[(int)src->length] = '\0'; } void debugSlice(struct Slice *s) { printd("Debug Slice\n text:'"); for(int i = 0; i < s->length; i++) { printd("%c", s->text[i]); if(s->text[i] == '\0') printd("NULLCHAR\n"); } printd("'\n"); printd(" length: %d\n", s->length); } Object fetchFromEnvironment(const char *name, struct Environment *env) { if(!env) return errorObject(NULL_ENV); printd("Fetching '%s' from env\n", name); printEnv(env); for(int i = 0; i < env->size; i++) { if(strcmp(name, env->strings[i]) == 0) { return env->objects[i]; } } printd("Trying outer\n"); if(env->outer) { return fetchFromEnvironment(name, env->outer); } return errorObject(DID_NOT_FIND_SYMBOL); } Result parse(struct Slice *slices) { struct Slice *token = slices; struct Slice *rest; if(token->text != NULL) { rest = &slices[1]; } else { return result(errorObject(NULL_PARSE), NULL); } if(token->text[0] == '(') { // todo check for null rest return readSeq(rest); } else { // todo error on missing close paren return result(parseAtom(token), rest); } } Result readSeq(struct Slice *tokens) { Object res = listObject(); for(;;) { struct Slice *next = &tokens[0]; struct Slice *rest = next->text? &next[1] : NULL; if(next->text[0] == ')') { return result(res, rest); } Result r = parse(tokens); nf_addToList(&res, r.obj); tokens = r.slices; } } Object parseAtom(struct Slice *s) { if(isDigit(s->text[0])) { int num = 0; for(int i = 0; i < s->length; i++) { num *= 10; num += s->text[i] - '0'; } return numberObject(num); } else if (s->text[0] == 'T' && s->text[1] == '\0') { return boolObject(1); } else if (s->text[0] == 'F' && s->text[1] == '\0') { return boolObject(0); } else { Object o = symbolObject(); copySlice(o.name, s); return o; } } Object evalDefArgs(const Object *arg_forms, struct Environment *env) { const Object *first_form = &arg_forms[0]; const char *name = first_form->name; // Immediately adding the function to the env might allow recursion? Object second_eval = eval(first_form->forward, env); addToEnv(env, name, second_eval); return *first_form; } Object evalIfArgs(const Object *arg_forms, struct Environment *env) { return eval(arg_forms, env).number? eval(arg_forms->forward, env) : eval(arg_forms->forward->forward, env); } Object evalLambdaArgs(const Object *arg_forms) { // params // body return constructLambda(arg_forms, arg_forms? arg_forms->forward : NULL); } Object evalMapArgs(const Object *arg_forms, struct Environment *env) { if(!arg_forms) return errorObject(NULL_MAP_ARGS); const Object lambda = eval(&arg_forms[0], env); Object *oldList = (&arg_forms[0])->forward; if(lambda.type != TYPE_LAMBDA || oldList->type != TYPE_LIST) return errorObject(BAD_TYPE); Object list = listObject(); const Object *oldElement = oldList->list; while(oldElement != NULL) { // Create a new list for each element in the list, // since lambda evaluation looks for a list Object tempList = listObject(); Object listBack[1] = {*oldElement}; listBack[0].forward = NULL; tempList.list = listBack; struct Environment newEnv = envForLambda(&lambda.lambda->params, &tempList, env); const Object evalLambda = eval(&lambda.lambda->body, &newEnv); nf_addToList(&list, evalLambda); oldElement = oldElement->forward; } return list; } struct Environment envForLambda(const Object *params, const Object *arg_forms, struct Environment *outer) { printd("envForLambda()\n"); debugObj(arg_forms); int length = listLength(params); struct Environment env; env.outer = outer; env.strings = NULL; env.objects = NULL; env.size = length; if(length == 0) return env; env.strings = calloc(sizeof(char*), length + 1); env.objects = malloc(sizeof(Object) * length + 1); Object vs[length]; eval_forms(vs, arg_forms, outer); for(int i = 0; i < length; i++) { const char *n = itemAt(params, i)->name; addToEnv(&env, n, eval(&arg_forms[i], outer)); // May not need eval? // SHOULD BE `vs` not arg_forms??? } // Something is segfaulting, anyway // env.strings[length] = NULL; return env; } Object evalBuiltIns(const Object *first, const Object *rest, struct Environment *env) { if(strcmp(first->name, "def") == 0) { return evalDefArgs(rest, env); } else if(strcmp(first->name, "if") == 0) { return evalIfArgs(rest, env); } else if(strcmp(first->name, "fn") == 0) { return evalLambdaArgs(rest); } else if(strcmp(first->name, "map") == 0) { return evalMapArgs(rest, env); } return errorObject(BUILT_IN_NOT_FOUND); } void eval_forms(Object *destList, const Object *src, struct Environment *env) { int length = listLength(src) - 1; // Not counting first_form for(int i = 0; i < length; i++) { // Evaluates all in list destList[i] = eval(itemAt(src, i + 1), env); // Skip the first } } Object eval(const Object *obj, struct Environment *env) { printd("eval():\n"); debugObj(obj); switch(obj->type) { case TYPE_NUMBER: case TYPE_BOOL: return *obj; // Return as is case TYPE_SYMBOL: return fetchFromEnvironment(obj->name, env); case TYPE_LIST: { if(listLength(obj) == 0) return *obj; if(listLength(obj) == 1) return eval(obj->list, env); Object *first_form = obj->list; { // Try to eval built-ins Object built_in = evalBuiltIns(first_form, first_form->forward, env); // deleteList(obj); // Decreases indirectly lost memory, but fails on Pebble if(built_in.type != TYPE_ERROR) { return built_in; } } Object first_eval = eval(first_form, env); if(first_eval.type == TYPE_FUNC) { int length = listLength(obj) - 1; // Not counting first_form Object rest[length]; eval_forms(rest, obj, env); Object func_eval = rest[0]; for(int i = 1; i < length; i++) { func_eval = first_eval.func(func_eval, rest[i]); } // deleteList(obj); // Decreases indirectly lost memory, but fails on Pebble return func_eval; } else if (first_eval.type == TYPE_LAMBDA) { struct Environment newEnv = envForLambda(&first_eval.lambda->params, first_form->forward, env); Object ret = eval(&first_eval.lambda->body, &newEnv); deleteEnv(&newEnv); return ret; } else { return *obj; } } case TYPE_LAMBDA: return errorObject(UNEXPECTED_FORM); default: ; } return *obj; } Result result(Object obj, struct Slice *slices) { return (Result) { .obj = obj, .slices = slices }; } // todo could include and return a starting index for faster multi-adds // Maybe extend existing environment using a malloc'd outer, instead of realloc void addToEnv(struct Environment *env, const char *name, const Object obj) { int i; for(i = 0; i < env->size ; i++) { if(env->strings[i] == NULL) { env->strings[i] = calloc(sizeof(char), strlen(name) + 1); strncpy(env->strings[i], name, strlen(name)); env->objects[i] = obj; return; } if(strcmp(env->strings[i], name) == 0) { cleanObject(&env->objects[i]); env->objects[i] = obj; return; } } printd("Reallocating environment\n"); const int inc = 5; env->size += inc; env->strings = realloc(env->strings, sizeof(char*) * env->size); env->objects = realloc(env->objects, sizeof(Object) * env->size); for(int j = 0; j < inc; j++) { env->strings[i + j] = NULL; } env->strings[i] = malloc(strlen(name) + 1); strncpy(env->strings[i], name, strlen(name) + 1); env->objects[i] = obj; } void printEnv(struct Environment *env) { if(!env) { printf("NULL env\n"); return; } for(int i = 0; i < env->size; i++) { if(env->strings[i] == NULL) return; printd("env[%d]: '%s'\n ", i, env->strings[i]); debugObj(&env->objects[i]); } } Object basicOp(Object *obj1, Object *obj2, const char op) { const int n1 = obj1->number; const int n2 = obj2->number; switch(op){ case '+': return numberObject(n1 + n2); case '-': return numberObject(n1 - n2); case '*': return numberObject(n1 * n2); case '/': return numberObject(n1 / n2); case '=': return boolObject(n1 == n2); case '>': return boolObject(n1 > n2); case '<': return boolObject(n1 < n2); } return *obj1; } #define bopf(_name, _char) \ Object _name(Object obj1, Object obj2) \ { return basicOp(&obj1, &obj2, _char); } bopf(add, '+'); bopf(sub, '-'); bopf(mul, '*'); bopf(dvi, '/'); bopf(equ, '='); bopf(gth, '>'); bopf(lth, '<'); void addFunc(const char *name, Object (*func)(Object, Object), struct Environment *env) { Object o; o.type = TYPE_FUNC; o.forward = NULL; o.func = func; addToEnv(env, name, o); } void deleteEnv(struct Environment *e) { int i = 0; while(e->strings[i]) { free(e->strings[i]); cleanObject(&e->objects[i]); i++; } free(e->strings); e->strings = NULL; free(e->objects); e->objects = NULL; } struct Environment defaultEnv() { struct Environment e; e.outer = NULL; e.strings = calloc(sizeof(char*), MAX_ENV_ELM); e.size = MAX_ENV_ELM; // for(int i = 0; i < MAX_ENV_ELM; i++) { // e.strings[i] = NULL; // } e.objects = malloc(sizeof(Object) * MAX_ENV_ELM); addFunc("+", &add, &e); addFunc("-", &sub, &e); addFunc("*", &mul, &e); addFunc("/", &dvi, &e); addFunc("=", &equ, &e); addFunc(">", >h, &e); addFunc("<", <h, &e); return e; } Object parseEval(const char *input, struct Environment *env) { struct Slice *tokens = nf_tokenize(input); if(!tokens) return errorObject(MISMATCHED_PARENS); #ifdef DEBUG struct Slice *debug = tokens; if(debug) { while(debug->text) { char tok[MAX_TOK_LEN]; copySlice(tok, debug); //printd("slice: '%s'\n", tok); debug++; } } #endif Object parsed = parse(tokens).obj; free(tokens); Object ret = eval(&parsed, env); cleanObject(&parsed); return ret; } #ifdef STANDALONE int repl(struct Environment *env) { char input[100] = ""; while(input[0] != 'q') { printf("pebblisp>> "); fgets(input, 100, stdin); Object obj = parseEval(input, env); // printAndClean(&obj); printObj(&obj); // printEnv(env); } } int main(void) { struct Environment env = defaultEnv(); #ifndef NO_REPL repl(&env); #else Object r = parseEval("(def ad (fn (a) (+ 1 a)))", &env); printAndClean(&r); r = parseEval("(map ad (1 2 3))", &env); //printAndClean(&r); #endif deleteEnv(&env); } #endif