#include "pebblisp.h" #include "tokens.h" #include #include #include #ifndef STANDALONE #undef printf #define printf(...) APP_LOG(APP_LOG_LEVEL_DEBUG, __VA_ARGS__) #endif Object evalDefArgs(const Object *argForms, struct Environment *env) { const Object *newSymbol = argForms; const char *name = newSymbol->name; const Object newValue = eval(newSymbol->forward, env); addToEnv(env, name, newValue); return *newSymbol; } Object evalIfArgs(const Object *argForms, struct Environment *env) { return eval(argForms, env).number? eval(argForms->forward, env) : eval(argForms->forward->forward, env); } Object evalLambdaArgs(const Object *argForms) { // params // body return constructLambda(argForms, argForms? argForms->forward : NULL); } Object evalMapArgs(const Object *argForms, struct Environment *env) { if(!argForms) return errorObject(NULL_MAP_ARGS); const Object lambda = eval(argForms, env); const Object *inputList = argForms->forward; if(lambda.type != TYPE_LAMBDA || inputList->type != TYPE_LIST) return errorObject(BAD_TYPE); Object list = listObject(); FOR_POINTER_IN_LIST(inputList) { // Create a new list for each element, // since lambda evaluation looks for a list Object tempList = startList(cloneObject(*POINTER)); Object *params = &lambda.lambda->params; struct Environment newEnv = envForLambda(params, &tempList, env); // Add the lambda evaluation to the list nf_addToList(&list, eval(&lambda.lambda->body, &newEnv)); deleteEnv(&newEnv); cleanObject(&tempList); } return list; } 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 Object *ptr = itemAt(src, i + 1); // Skip the first destList[i] = eval(ptr, env); } } Object eval(const Object *obj, struct Environment *env) { // printf("eval():\n"); // printObj(obj); switch(obj->type) { case TYPE_NUMBER: case TYPE_BOOL: return *obj; // Return as is case TYPE_STRING: return copyString(*obj); 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 const Object builtIn = evalBuiltIns(first_form, first_form->forward, env); if(builtIn.type != TYPE_ERROR) { return builtIn; } } 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++) { Object toClean = func_eval; func_eval = first_eval.func(func_eval, rest[i], env); //if(i != length - 1) cleanObject(&toClean); cleanObject(&rest[i]); } 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 { Object list = listObject(); FOR_POINTER_IN_LIST(obj) { nf_addToList(&list, eval(POINTER, env)); } return list; } } case TYPE_LAMBDA: return errorObject(UNEXPECTED_FORM); default: return *obj; } } Result result(Object obj, struct Slice *slices) { return (Result) { .obj = obj, .slices = slices }; } Object catObjects(const Object obj1, const Object obj2, struct Environment *env) { Object evalObj1 = eval(&obj1, env); Object evalObj2 = eval(&obj2, env); char str1[100] = ""; char str2[100] = ""; stringObj(str1, &evalObj1); stringObj(str2, &evalObj2); cleanObject(&evalObj1); cleanObject(&evalObj2); int length = strlen(str1) + strlen(str2) + 1; Object o = newObject(TYPE_STRING); o.string = calloc(sizeof(char), length); strcat(o.string, str1); strcat(o.string, str2); return o; } Object _basicOp(const Object *obj1, const Object *obj2, const char op, struct Environment *env) { const int n1 = obj1->number; const int n2 = obj2->number; switch(op){ case '+': if(obj1->type == TYPE_STRING || obj2->type == TYPE_STRING) return catObjects(*obj1, *obj2, env); return numberObject(n1 + n2); 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; } Object basicOp(const Object *obj1, const Object *obj2, const char op, struct Environment *env) { int lists = (obj1->type == TYPE_LIST) + (obj2->type == TYPE_LIST); if(lists == 0) { return _basicOp(obj1, obj2, op, env); } else if(lists == 1) { // Single operand is applied to each element in list const Object *listObj = (obj1->type == TYPE_LIST)? obj1 : obj2; const Object *singleObj = (obj1->type == TYPE_LIST)? obj2 : obj1; Object newList = listObject(); FOR_POINTER_IN_LIST(listObj) { Object adding = eval(POINTER, env); nf_addToList(&newList, _basicOp(&adding, singleObj, op, env)); } return newList; } else { // 2 lists with the op applied to matching indices of both lists if(listLength(obj1) == listLength(obj2)) { Object newList = listObject(); FOR_POINTERS_IN_LISTS(obj1, obj2) { const Object ev1 = eval(P1, env); const Object ev2 = eval(P2, env); nf_addToList(&newList, _basicOp(&ev1, &ev2, op, env)); } return newList; } else { return errorObject(LISTS_NOT_SAME_SIZE); } } } #define BASIC_OP(_name, _char) \ Object _name(Object obj1, Object obj2, struct Environment *env) \ { return basicOp(&obj1, &obj2, _char, env); } BASIC_OP(add, '+'); BASIC_OP(sub, '-'); BASIC_OP(mul, '*'); BASIC_OP(dvi, '/'); BASIC_OP(mod, '%'); BASIC_OP(equ, '='); BASIC_OP(gth, '>'); BASIC_OP(lth, '<'); #undef BASIC_OP 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) { if(!s) { printf("NULL SLICE\n"); return; } printf("Debug Slice\n text:'"); for(int i = 0; i < s->length; i++) { printf("%c", s->text[i]); if(s->text[i] == '\0') printf("NULLCHAR\n"); } printf("'\n"); printf(" length: %d\n", s->length); } Result parse(struct Slice *slices) { struct Slice *token = slices; if(token && token->text) { struct Slice *rest = &slices[1]; if(token->text[0] == '(') { // todo check for null rest return readSeq(rest); } else { // todo error on missing close paren return result(parseAtom(token), rest); } } else { return result(errorObject(NULL_PARSE), NULL); } } Result readSeq(struct Slice *tokens) { Object res = listObject(); for(;;) { struct Slice *next = tokens; 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 parseDecimal(struct Slice *s) { int num = 0; for(int i = 0; i < s->length; i++) { if(!isDigit(s->text[i])) { return errorObject(SYMBOLS_CANT_START_WITH_DIGITS); } num *= 10; num += s->text[i] - '0'; } return numberObject(num); } Object parseAtom(struct Slice *s) { if(isDigit(s->text[0])) { if(s->text[0] != '0' || s->length == 1) return parseDecimal(s); else { return errorObject(UNSUPPORTED_NUMBER_TYPE); } } else if (s->length == 1 && (s->text[0] == 'T' || s->text[0] == 't')) { return boolObject(1); } else if (s->length == 1 && (s->text[0] == 'F' || s->text[0] == 'f')) { return boolObject(0); } else if (s->text[0] == '"') { return objFromSlice(s->text, s->length); } else { Object o = symbolObject(); copySlice(o.name, s); return o; } } 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 int i = 0; int parens = 0; Object obj = numberObject(0); struct Slice *tok = tokens; if(tok[i].text[0] != '(') { Object parsed = parse(tok).obj; obj = eval(&parsed, env); cleanObject(&parsed); } else { while(tok[i].text != NULL) { if(tok[i].text[0] == '(') { parens++; } else if(tok[i].text[0] == ')') { parens--; if(parens == 0) { cleanObject(&obj); Object parsed = parse(tok).obj; tok = &tok[i + 1]; i = -1; obj = eval(&parsed, env); cleanObject(&parsed); } } i++; } } free(tokens); return obj; } #ifdef STANDALONE void repl(struct Environment *env) { char input[200] = ""; while(input[0] != 'q') { printf("pebblisp>> "); fgets(input, 100, stdin); Object obj = parseEval(input, env); printAndClean(&obj); } } int main(int argc, const char* argv[]) { struct Environment env = defaultEnv(); if(argc >= 2) { Object r = numberObject(0); for(int i = 1; i < argc; i++) { r = parseEval(argv[i], &env); printAndClean(&r); } } else { repl(&env); } deleteEnv(&env); } #endif