mumble.c (42895B)
1 // #include <editline/history.h> 2 // #include <editline/readline.h> 3 #include <editline.h> 4 #include <stdio.h> 5 #include <stdlib.h> 6 #include <string.h> 7 8 #include "mpc/mpc.h" 9 #define LISPVAL_ASSERT(cond, err) \ 10 if (!(cond)) { \ 11 return lispval_err(err); \ 12 } 13 int VERBOSE = 0; 14 #define printfln(...) \ 15 do { \ 16 if (VERBOSE == 2) { \ 17 printf("\n@ %s (%d): ", __FILE__, __LINE__); \ 18 printf(__VA_ARGS__); \ 19 } else { \ 20 printf("%s", "\n"); \ 21 printf(__VA_ARGS__); \ 22 } \ 23 } while (0) 24 // Types 25 26 // Types: Forward declarations 27 // I don't understand how this works 28 // and in particular why lispval is repeated twice after the typedef struct 29 // See: <https://buildyourownlisp.com/chapter11_variables> 30 // <https://web.archive.org/web/20230226023546/https://buildyourownlisp.com/chapter11_variables> 31 struct lispval; 32 struct lispenv; 33 typedef struct lispval lispval; 34 typedef struct lispenv lispenv; 35 typedef lispval* (*lispbuiltin)(lispval*, lispenv*); 36 // this defines the lispbuiltin type 37 // which seems to be a pointer to a function which takes in a lispenv* 38 // and a lispval* and returns a lispval* 39 40 // Types 41 enum { 42 LISPVAL_NUM, 43 LISPVAL_ERR, 44 LISPVAL_SYM, 45 LISPVAL_BUILTIN_FUNC, 46 LISPVAL_USER_FUNC, 47 LISPVAL_SEXPR, 48 LISPVAL_QEXPR, 49 }; 50 int LARGEST_LISPVAL = LISPVAL_QEXPR; // for checking out of bounds. 51 52 typedef struct lispval { 53 int type; 54 55 // Basic types 56 double num; 57 char* err; 58 char* sym; 59 60 // Functions 61 // Built-in 62 lispbuiltin builtin_func; 63 char* builtin_func_name; 64 // User-defined 65 lispenv* env; 66 lispval* variables; 67 lispval* manipulation; 68 69 // Expression 70 int count; 71 struct lispval** cell; // list of lisval* 72 } lispval; 73 74 // Function types 75 void print_lispval_tree(lispval* v, int indent_level); 76 lispenv* new_lispenv(); 77 void destroy_lispenv(lispenv* env); 78 lispval* clone_lispval(lispval* old); 79 lispval* evaluate_lispval(lispval* l, lispenv* env); 80 81 // Constructors 82 lispval* lispval_num(double x) 83 { 84 if (VERBOSE) 85 printfln("Allocating num"); 86 lispval* v = malloc(sizeof(lispval)); 87 v->type = LISPVAL_NUM; 88 v->count = 0; 89 v->num = x; 90 if (VERBOSE) 91 printfln("Allocated num"); 92 if (VERBOSE > 1) 93 print_lispval_tree(v, 2); 94 return v; 95 } 96 97 lispval* lispval_err(char* message) 98 { 99 if (VERBOSE) 100 printfln("Allocating err"); 101 lispval* v = malloc(sizeof(lispval)); 102 v->type = LISPVAL_ERR; 103 v->count = 0; 104 v->err = malloc(strlen(message) + 1); 105 strcpy(v->err, message); 106 if (VERBOSE) 107 printfln("Allocated err"); 108 if (VERBOSE > 1) 109 print_lispval_tree(v, 2); 110 return v; 111 } 112 113 lispval* lispval_sym(char* symbol) 114 { 115 if (VERBOSE) 116 printfln("Allocating sym"); 117 lispval* v = malloc(sizeof(lispval)); 118 v->type = LISPVAL_SYM; 119 v->count = 0; 120 v->sym = malloc(strlen(symbol) + 1); 121 strcpy(v->sym, symbol); 122 if (VERBOSE) 123 printfln("Allocated sym"); 124 if (VERBOSE > 1) 125 print_lispval_tree(v, 2); 126 return v; 127 } 128 129 lispval* lispval_builtin_func(lispbuiltin func, char* builtin_func_name) 130 { 131 if (VERBOSE) 132 printfln("Allocating func name:%s, pointer: %p", builtin_func_name, func); 133 lispval* v = malloc(sizeof(lispval)); 134 v->type = LISPVAL_BUILTIN_FUNC; 135 v->count = 0; 136 v->builtin_func_name = malloc(strlen(builtin_func_name) + 1); 137 strcpy(v->builtin_func_name, builtin_func_name); 138 v->builtin_func = func; 139 if (VERBOSE) 140 printfln("Allocated func"); 141 if (VERBOSE > 1) 142 print_lispval_tree(v, 2); 143 return v; 144 } 145 146 lispval* lispval_lambda_func(lispval* variables, lispval* manipulation, lispenv* env) 147 { 148 /* correct idiom for calling this: 149 lispval* variables = clone_lispval(v->cell[0]); 150 lispval* manipulation = clone_lispval(v->cell[1]); 151 lispenv* env = NULL; // clone_lispval(blah) 152 lispval* lambda = lispval_lambda_func(variables, manipulation, NULL); 153 */ 154 if (VERBOSE) { 155 printfln("Allocating user-defined function"); 156 } 157 lispval* v = malloc(sizeof(lispval)); 158 v->type = LISPVAL_USER_FUNC; 159 v->builtin_func = NULL; 160 v->env = (env == NULL ? new_lispenv() : env); 161 v->variables = variables; 162 v->manipulation = manipulation; 163 // Previously: unclear how to garbage-collect this. Maybe add to a list and collect at the end? 164 // Now: Hah! Lambda functions are just added to the environment, so they will just 165 // be destroyed when it is destroyed. 166 // But no! in def {id} (@ {x} {x}), there is a copy of a lambda function in 167 // the arguments to def. Aarg! 168 if (VERBOSE) { 169 printfln("Allocated user-defined function"); 170 } 171 if (VERBOSE > 1) 172 print_lispval_tree(v, 2); 173 return v; 174 } 175 176 lispval* lispval_sexpr(void) 177 { 178 if (VERBOSE) 179 printfln("Allocating sexpr"); 180 lispval* v = malloc(sizeof(lispval)); 181 v->type = LISPVAL_SEXPR; 182 v->count = 0; 183 v->cell = NULL; 184 if (VERBOSE) 185 printfln("Allocated sexpr"); 186 if (VERBOSE > 1) 187 print_lispval_tree(v, 2); 188 return v; 189 } 190 191 lispval* lispval_qexpr(void) 192 { 193 if (VERBOSE) 194 printfln("Allocating qexpr"); 195 lispval* v = malloc(sizeof(lispval)); 196 v->type = LISPVAL_QEXPR; 197 v->count = 0; 198 v->cell = NULL; 199 if (VERBOSE > 1) 200 print_lispval_tree(v, 2); 201 return v; 202 } 203 204 // Destructor 205 void delete_lispval(lispval* v) 206 { 207 if (v == NULL || v->type > LARGEST_LISPVAL) 208 return; 209 // print_lispval_tree(v, 0); 210 if (VERBOSE) 211 printfln("\nDeleting object of type %i", v->type); 212 switch (v->type) { 213 case LISPVAL_NUM: 214 if (VERBOSE) 215 printfln("Freeing num"); 216 if (v != NULL) 217 free(v); 218 if (VERBOSE) 219 printfln("Freed num"); 220 break; 221 case LISPVAL_ERR: 222 if (VERBOSE) 223 printfln("Freeing err"); 224 if (v->err != NULL) 225 free(v->err); 226 v->err = NULL; 227 if (v != NULL) 228 free(v); 229 if (VERBOSE) 230 printfln("Freed err"); 231 break; 232 case LISPVAL_SYM: 233 if (VERBOSE) 234 printfln("Freeing sym"); 235 if (v->sym != NULL) 236 free(v->sym); 237 v->sym = NULL; 238 if (v != NULL) 239 free(v); 240 if (VERBOSE) 241 printfln("Freed sym"); 242 break; 243 case LISPVAL_BUILTIN_FUNC: 244 if (v->builtin_func_name != NULL) { 245 if (VERBOSE) { 246 printfln("Freeing builtin func"); 247 } 248 free(v->builtin_func_name); 249 v->builtin_func_name = NULL; 250 } 251 if (v != NULL) 252 free(v); 253 if (VERBOSE) 254 printfln("Freed builtin func"); 255 // Don't do anything with v->func for now 256 // Though we could delete the pointer to the function later 257 // free(v->func); 258 break; 259 case LISPVAL_USER_FUNC: 260 if(VERBOSE) printfln("This shouldn't fire until the end, unless we are deleting the operands of a builtin function. E.g,. in def {id} (@ {x} {x}), there is a lambda function in the arguments, which should get collected."); 261 // for now, do nothing 262 if (VERBOSE) 263 printfln("Freeing user-defined func"); 264 if (v->env != NULL) { 265 destroy_lispenv(v->env); 266 // ^ free(v->env) is not necessary; taken care of by destroy_lispenv 267 v->env = NULL; 268 } 269 if (v->variables != NULL) { 270 // not deleting these for now. 271 // delete_lispval(v->variables); 272 // free(v->variables) 273 // v->variables = NULL; 274 } 275 if (v->manipulation != NULL) { 276 // not deleting these for now. 277 // delete_lispval(v->manipulation); 278 // free(v->manipulation); 279 // v->manipulation = NULL; 280 } 281 if (v != NULL) 282 free(v); 283 if (VERBOSE) 284 printfln("Freed user-defined func"); 285 // Don't do anything with v->func for now 286 // Though we could delete the pointer to the function later 287 // 288 // free(v->func); 289 /* 290 */ 291 break; 292 case LISPVAL_SEXPR: 293 case LISPVAL_QEXPR: 294 if (VERBOSE) 295 printfln("Freeing sexpr|qexpr"); 296 if (VERBOSE) 297 printfln("Freed sexpr|qexpr cells"); 298 for (int i = 0; i < v->count; i++) { 299 if (v->cell[i] != NULL) 300 delete_lispval(v->cell[i]); 301 v->cell[i] = NULL; 302 } 303 if (VERBOSE) 304 printfln("Setting v->count to 0"); 305 v->count = 0; 306 307 if (VERBOSE) 308 printfln("Freeing v->cell"); 309 if (v->cell != NULL) 310 free(v->cell); 311 v->cell = NULL; 312 313 if (VERBOSE) 314 printfln("Freeing the v pointer"); 315 if (v != NULL) 316 free(v); 317 if (VERBOSE) 318 printfln("Freed sexpr|qexpr"); 319 break; 320 default: 321 if (VERBOSE) 322 printfln("Error: Unknown expression type for pointer %p of type %i. This is probably indicative that you are trying to delete a previously deleted object", v, v->type); 323 } 324 // v = NULL; this is only our local pointer, sadly. 325 } 326 327 // Environment 328 struct lispenv { 329 int count; 330 char** syms; // list of strings 331 lispval** vals; // list of pointers to vals 332 lispenv* parent; 333 }; 334 335 lispenv* new_lispenv() 336 { 337 lispenv* e = malloc(sizeof(lispenv)); 338 e->count = 0; 339 e->syms = NULL; 340 e->vals = NULL; 341 e->parent = NULL; 342 return e; 343 } 344 345 void destroy_lispenv(lispenv* env) 346 { 347 for (int i = 0; i < env->count; i++) { 348 free(env->syms[i]); 349 free(env->vals[i]); 350 // to do: delete_lispval(vals[i])? 351 env->syms[i] = NULL; 352 env->vals[i] = NULL; 353 } 354 free(env->syms); 355 env->syms = NULL; 356 free(env->vals); 357 env->vals = NULL; 358 free(env); 359 env = NULL; 360 // parent is it's own environment 361 // so it isn't destroyed 362 } 363 364 lispval* get_from_lispenv(char* sym, lispenv* env) 365 { 366 for (int i = 0; i < env->count; i++) { 367 if (strcmp(env->syms[i], sym) == 0) { 368 return clone_lispval(env->vals[i]); 369 // return env->vals[i]; 370 // to do: make sure that the clone is deleted. 371 } 372 } 373 374 if (env->parent != NULL) { 375 return get_from_lispenv(sym, env->parent); 376 } else { 377 if (VERBOSE) 378 printfln("Unbound symbol %s", sym); 379 return lispval_err("Error: unbound symbol"); 380 } 381 // and this explains shadowing! 382 } 383 384 void insert_in_current_lispenv(char* sym, lispval* v, lispenv* env) 385 { 386 int found = 0; 387 for (int i = 0; i < env->count; i++) { 388 if (strcmp(env->syms[i], sym) == 0) { 389 delete_lispval(env->vals[i]); 390 env->vals[i] = clone_lispval(v); 391 found = 1; 392 } 393 } 394 if (found == 0) { 395 // Expand memory *for the arrays* 396 env->count++; 397 env->syms = realloc(env->syms, sizeof(char*) * env->count); 398 env->vals = realloc(env->vals, sizeof(lispval*) * env->count); 399 400 // Copy contents over 401 env->vals[env->count - 1] = clone_lispval(v); 402 env->syms[env->count - 1] = malloc(strlen(sym) + 1); 403 strcpy(env->syms[env->count - 1], sym); 404 } 405 } 406 407 void insert_in_parentmost_lispenv(char* sym, lispval* v, lispenv* env) 408 { 409 // note that you could have two chains of envs, though hopefully not. 410 while (env->parent != NULL) { 411 env = env->parent; 412 } 413 insert_in_current_lispenv(sym, v, env); 414 } 415 416 lispenv* clone_lispenv(lispenv* origin_env) 417 { 418 lispenv* new_env = malloc(sizeof(lispenv)); 419 new_env->count = origin_env->count; 420 new_env->parent = origin_env->parent; 421 422 new_env->syms = malloc(sizeof(char*) * origin_env->count); 423 new_env->vals = malloc(sizeof(lispval*) * origin_env->count); 424 425 for (int i = 0; i < origin_env->count; i++) { 426 new_env->syms[i] = malloc(strlen(origin_env->syms[i]) + 1); 427 strcpy(new_env->syms[i], origin_env->syms[i]); 428 new_env->vals[i] = clone_lispval(origin_env->vals[i]); 429 } 430 return new_env; 431 } 432 433 // Read ast into a lispval object 434 lispval* lispval_append_child(lispval* parent, lispval* child) 435 { 436 parent->count = parent->count + 1; 437 parent->cell = realloc(parent->cell, sizeof(lispval) * parent->count); 438 parent->cell[parent->count - 1] = child; 439 return parent; 440 } 441 lispval* read_lispval_num(mpc_ast_t* t) 442 { 443 errno = 0; 444 double x = strtod(t->contents, NULL); 445 return errno != ERANGE ? lispval_num(x) 446 : lispval_err("Error: Invalid number."); 447 } 448 449 lispval* read_lispval(mpc_ast_t* t) 450 { 451 // Non-ignorable children 452 // Relevant for the edge-case of considering the case where you 453 // only have one top level item in brackets 454 int c = 0; 455 int c_index = -1; 456 for (int i = 0; i < t->children_num; i++) { 457 mpc_ast_t* child = t->children[i]; 458 if ((strcmp(child->tag, "regex") != 0) || (strcmp(child->contents, "") != 0) || child->children_num != 0) { 459 c++; 460 c_index = i; 461 } 462 } 463 if (VERBOSE) 464 printfln("Non ignorable children: %i", c); 465 466 if (strstr(t->tag, "number")) { 467 return read_lispval_num(t); 468 } else if (strstr(t->tag, "symbol")) { 469 return lispval_sym(t->contents); 470 } else if ((strcmp(t->tag, ">") == 0) && (c == 1)) { 471 return read_lispval(t->children[c_index]); 472 } else if ((strcmp(t->tag, ">") == 0) || strstr(t->tag, "sexpr") || strstr(t->tag, "qexpr")) { 473 lispval* x; 474 if ((strcmp(t->tag, ">") == 0) || strstr(t->tag, "sexpr")) { 475 x = lispval_sexpr(); 476 } else if (strstr(t->tag, "qexpr")) { 477 x = lispval_qexpr(); 478 } else { 479 return lispval_err("Error: Unreachable code state reached."); 480 } 481 482 for (int i = 0; i < (t->children_num); i++) { 483 if (strcmp(t->children[i]->contents, "(") == 0) { 484 continue; 485 } else if (strcmp(t->children[i]->contents, ")") == 0) { 486 continue; 487 } else if (strcmp(t->children[i]->contents, "{") == 0) { 488 continue; 489 } else if (strcmp(t->children[i]->contents, "}") == 0) { 490 continue; 491 } else if (strcmp(t->children[i]->tag, "regex") == 0) { 492 continue; 493 } else { 494 x = lispval_append_child(x, read_lispval(t->children[i])); 495 } 496 } 497 return x; 498 } else { 499 lispval* err = lispval_err("Unknown AST type."); 500 return err; 501 } 502 } 503 504 // Print 505 void print_env(lispenv* env) 506 { 507 printfln("Environment: "); 508 for (int i = 0; i < env->count; i++) { 509 printfln("Value for symbol %s: ", env->syms[i]); 510 print_lispval_tree(env->vals[i], 2); 511 } 512 } 513 void print_lispval_tree(lispval* v, int indent_level) 514 { 515 char* indent = malloc(sizeof(char) * (indent_level + 1)); 516 for (int i = 0; i < indent_level; i++) { 517 indent[i] = ' '; 518 } 519 indent[indent_level] = '\0'; 520 521 switch (v->type) { 522 case LISPVAL_NUM: 523 printfln("%sNumber: %f", indent, v->num); 524 break; 525 case LISPVAL_ERR: 526 printfln("%s%s", indent, v->err); 527 break; 528 case LISPVAL_SYM: 529 printfln("%sSymbol: %s", indent, v->sym); 530 break; 531 case LISPVAL_BUILTIN_FUNC: 532 printfln("%sFunction, name: %s, pointer: %p", indent, v->builtin_func_name, v->builtin_func); 533 break; 534 case LISPVAL_USER_FUNC: 535 printfln("%sUser-defined function: %p", indent, v->env); // Identify it with its environment? 536 print_lispval_tree(v->variables, indent_level + 2); 537 print_lispval_tree(v->manipulation, indent_level + 2); 538 break; 539 case LISPVAL_SEXPR: 540 printfln("%sSExpr, with %d children:", indent, v->count); 541 for (int i = 0; i < v->count; i++) { 542 print_lispval_tree(v->cell[i], indent_level + 2); 543 } 544 break; 545 case LISPVAL_QEXPR: 546 printfln("%sQExpr, with %d children:", indent, v->count); 547 for (int i = 0; i < v->count; i++) { 548 print_lispval_tree(v->cell[i], indent_level + 2); 549 } 550 break; 551 default: 552 if (VERBOSE) 553 printfln("Error: unknown lispval type\n"); 554 // printfln("%s", v->sym); 555 } 556 if (VERBOSE > 1) 557 printfln("Freeing indent"); 558 if (indent != NULL) 559 free(indent); 560 indent = NULL; 561 if (VERBOSE > 1) 562 printfln("Freed indent"); 563 } 564 565 void print_lispval_parenthesis(lispval* v) 566 { 567 switch (v->type) { 568 case LISPVAL_NUM: 569 printf("%f ", v->num); 570 break; 571 case LISPVAL_ERR: 572 printf("%s ", v->err); 573 break; 574 case LISPVAL_SYM: 575 printf("%s ", v->sym); 576 break; 577 case LISPVAL_BUILTIN_FUNC: 578 printf("<function, name: %s, pointer: %p> ", v->builtin_func_name, v->builtin_func); 579 break; 580 case LISPVAL_USER_FUNC: 581 printf("<user-defined function, pointer: %p> ", v->env); 582 break; 583 case LISPVAL_SEXPR: 584 printf("( "); 585 for (int i = 0; i < v->count; i++) { 586 print_lispval_parenthesis(v->cell[i]); 587 } 588 printf(") "); 589 break; 590 case LISPVAL_QEXPR: 591 printf("{ "); 592 for (int i = 0; i < v->count; i++) { 593 print_lispval_parenthesis(v->cell[i]); 594 } 595 printf("} "); 596 break; 597 default: 598 if (VERBOSE) 599 printfln("Error: unknown lispval type\n"); 600 // printfln("%s", v->sym); 601 } 602 } 603 604 void print_ast(mpc_ast_t* ast, int indent_level) 605 { 606 char* indent = malloc(sizeof(char) * (indent_level + 1)); // ""; 607 for (int i = 0; i < indent_level; i++) { 608 indent[i] = ' '; 609 } 610 indent[indent_level] = '\0'; 611 printfln("%sTag: %s", indent, ast->tag); 612 printfln("%sContents: %s", indent, 613 strcmp(ast->contents, "") ? ast->contents : "None"); 614 printfln("%sNumber of children: %i", indent, ast->children_num); 615 /* Print the children */ 616 for (int i = 0; i < ast->children_num; i++) { 617 mpc_ast_t* child_i = ast->children[i]; 618 printfln("%sChild #%d", indent, i); 619 print_ast(child_i, indent_level + 2); 620 } 621 free(indent); 622 indent = NULL; 623 } 624 625 // Cloners 626 lispval* clone_lispval(lispval* old) 627 { 628 lispval* new; 629 switch (old->type) { 630 case LISPVAL_NUM: 631 new = lispval_num(old->num); 632 break; 633 case LISPVAL_ERR: 634 new = lispval_err(old->err); 635 break; 636 case LISPVAL_SYM: 637 new = lispval_sym(old->sym); 638 break; 639 case LISPVAL_BUILTIN_FUNC: 640 new = lispval_builtin_func(old->builtin_func, old->builtin_func_name); 641 break; 642 case LISPVAL_USER_FUNC: 643 if(VERBOSE) printfln("Cloning function. This generally shouldn't be happening, given that I've decided to just add functions to the environment and just clean them when the environment is cleaned. One situation where it should happen is in def {id} (@ {x} {x}), there is a lambda function in the arguments, which should get collected. "); 644 lispval* variables = clone_lispval(old->variables); 645 lispval* manipulation = clone_lispval(old->manipulation); 646 lispenv* env = clone_lispenv(old->env); 647 new = lispval_lambda_func(variables, manipulation, env); 648 // new = lispval_lambda_func(old->variables, old->manipulation, old->env); 649 // Also, fun to notice how these choices around implementation would determine tricky behaviour details around variable shadowing. 650 break; 651 case LISPVAL_SEXPR: 652 new = lispval_sexpr(); 653 break; 654 case LISPVAL_QEXPR: 655 new = lispval_qexpr(); 656 break; 657 default: 658 return lispval_err("Error: Cloning element of unknown type."); 659 } 660 661 if ((old->type == LISPVAL_QEXPR || old->type == LISPVAL_SEXPR) && (old->count > 0)) { 662 for (int i = 0; i < old->count; i++) { 663 lispval* temp_child = old->cell[i]; 664 lispval* child = clone_lispval(temp_child); 665 lispval_append_child(new, child); 666 } 667 } 668 return new; 669 } 670 671 // Operations 672 // Ops for q-expressions 673 lispval* builtin_head(lispval* v, lispenv* e) 674 { 675 // printfln("Entering builtin_head with v->count = %d and v->cell[0]->type = %d\n", v->count, v->cell[0]->type); 676 // head { 1 2 3 } 677 // But actually, that gets processd into head ({ 1 2 3 }), hence the v->cell[0]->cell[0]; 678 LISPVAL_ASSERT(v->count == 1, "Error: function head passed too many arguments"); 679 LISPVAL_ASSERT(v->cell[0]->type == LISPVAL_QEXPR, "Error: Argument passed to head is not a q-expr, i.e., a bracketed list."); 680 LISPVAL_ASSERT(v->cell[0]->count != 0, "Error: Argument passed to head is {}"); 681 lispval* result = clone_lispval(v->cell[0]->cell[0]); 682 return result; 683 // Returns something that should be freed later: yes. 684 // Returns something that doesn't share pointers with the input: yes. 685 } 686 687 lispval* builtin_tail(lispval* v, lispenv* env) 688 { 689 // tail { 1 2 3 } 690 LISPVAL_ASSERT(v->count == 1, "Error: function tail passed too many arguments"); 691 692 lispval* old = v->cell[0]; 693 LISPVAL_ASSERT(old->type == LISPVAL_QEXPR, "Error: Argument passed to tail is not a q-expr, i.e., a bracketed list."); 694 LISPVAL_ASSERT(old->count != 0, "Error: Argument passed to tail is {}"); 695 696 lispval* new = lispval_qexpr(); 697 if (old->count == 1) { 698 return new; 699 } else if (old->count > 1 && old->type == LISPVAL_QEXPR) { 700 for (int i = 1; i < (old->count); i++) { 701 // lispval_append_child(new, clone_lispval(old->cell[i])); 702 lispval_append_child(new, clone_lispval(old->cell[i])); 703 } 704 return new; 705 } else { 706 delete_lispval(new); 707 return lispval_err("Error: Unreachable point reached in tail function"); 708 } 709 710 // Returns something that should be freed later: yes. 711 // Returns something that doesn't share pointers with the input: yes. 712 } 713 714 lispval* builtin_list(lispval* v, lispenv* e) 715 { 716 // list ( 1 2 3 ) 717 LISPVAL_ASSERT(v->count == 1, "Error: function list passed too many arguments"); 718 lispval* old = v->cell[0]; 719 LISPVAL_ASSERT(old->type == LISPVAL_SEXPR, "Error: Argument passed to list is not an s-expr, i.e., a list with parenthesis."); 720 lispval* new = clone_lispval(old); 721 new->type = LISPVAL_QEXPR; 722 return new; 723 // Returns something that should be freed later: yes. 724 // Returns something that is independent of the input: yes. 725 } 726 727 lispval* builtin_len(lispval* v, lispenv* e) 728 { 729 // len { 1 2 3 } 730 LISPVAL_ASSERT(v->count == 1, "Error: function len passed too many arguments"); 731 732 lispval* source = v->cell[0]; 733 LISPVAL_ASSERT(source->type == LISPVAL_QEXPR, "Error: Argument passed to len is not a q-expr, i.e., a bracketed list."); 734 lispval* new = lispval_num(source->count); 735 return new; 736 // Returns something that should be freed later: yes. 737 // Returns something that doesn't share pointers with the input: yes. 738 } 739 740 lispval* builtin_eval(lispval* v, lispenv* env) 741 { 742 // eval { + 1 2 3 } 743 // not sure how this will end up working, but we'll see 744 LISPVAL_ASSERT(v->count == 1, "Error: function eval passed too many arguments"); 745 lispval* old = v->cell[0]; 746 LISPVAL_ASSERT(old->type == LISPVAL_QEXPR || old->type == LISPVAL_QEXPR, "Error: Argument passed to eval is not a q-expr, i.e., a bracketed list."); 747 lispval* temp = clone_lispval(old); 748 temp->type = LISPVAL_SEXPR; 749 lispval* answer = evaluate_lispval(temp, env); 750 answer = evaluate_lispval(answer, env); 751 // ^ needed to make this example work: 752 // (eval {head {+ -}}) 1 2 3 753 // though I'm not sure why 754 delete_lispval(temp); 755 return answer; 756 // Returns something that should be freed later: probably. 757 // Returns something that is independent of the input: depends on the output of evaluate_lispval. 758 } 759 760 lispval* builtin_join(lispval* l, lispenv* e) 761 { 762 // return lispval_err("Error: Join not ready yet."); 763 // join { {1 2} {3 4} } 764 print_lispval_parenthesis(l); 765 LISPVAL_ASSERT(l->count == 1, "Error: function join passed too many arguments"); 766 lispval* old = l->cell[0]; 767 LISPVAL_ASSERT(old->type == LISPVAL_QEXPR, "Error: function join not passed q-expression"); 768 lispval* result = lispval_qexpr(); 769 for (int i = 0; i < old->count; i++) { 770 lispval* temp = old->cell[i]; 771 LISPVAL_ASSERT(temp->type == LISPVAL_QEXPR, "Error: function join not passed a q expression with other q-expressions"); 772 773 for (int j = 0; j < temp->count; j++) { 774 lispval_append_child(result, clone_lispval(temp->cell[j])); 775 } 776 } 777 return result; 778 // Returns something that should be freed later: yes. 779 // Returns something that is independent of the input: yes. 780 } 781 782 // Define a variable 783 lispval* builtin_def(lispval* v, lispenv* env) 784 { 785 // Takes two arguments: argument: def {a} 1; def {init} (@ {x y} {x}) 786 lispval* symbol_wrapper = v->cell[0]; 787 lispval* value = v->cell[1]; 788 789 insert_in_current_lispenv(symbol_wrapper->cell[0]->sym, value, env); 790 lispval* source = v->cell[0]; 791 return lispval_sexpr(); // () 792 LISPVAL_ASSERT(v->count == 1, "Error: function def passed too many arguments"); 793 LISPVAL_ASSERT(source->type == LISPVAL_QEXPR, "Error: Argument passed to def is not a q-expr, i.e., a bracketed list."); 794 LISPVAL_ASSERT(source->count == 2, "Error: Argument passed to def should be a q expr with two q expressions as children: def { { a b } { 1 2 } } "); 795 LISPVAL_ASSERT(source->cell[0]->type == LISPVAL_QEXPR, "Error: Argument passed to def should be a q expr with two q expressions as children: def { { a b } { 1 2 } } "); 796 LISPVAL_ASSERT(source->cell[1]->type == LISPVAL_QEXPR || source->cell[1]->type == LISPVAL_SEXPR, "Error: Argument passed to def should be a q expr with two q expressions as children: def { { a b } { 1 2 } } "); 797 LISPVAL_ASSERT(source->cell[0]->count == source->cell[1]->count, "Error: In function \"def\" both subarguments should have the same length"); 798 799 lispval* symbols = source->cell[0]; 800 lispval* values = source->cell[1]; 801 for (int i = 0; i < symbols->count; i++) { 802 LISPVAL_ASSERT(symbols->cell[i]->type == LISPVAL_SYM, "Error: in function def, the first list of items should be of type symbol: def { { a b } { 1 2 } }"); 803 if (VERBOSE) 804 print_lispval_tree(symbols, 0); 805 if (VERBOSE) 806 print_lispval_tree(values, 0); 807 if (VERBOSE) 808 printf("\n"); 809 insert_in_current_lispenv(symbols->cell[i]->sym, clone_lispval(values->cell[i]), env); 810 } 811 return lispval_sexpr(); // () 812 } 813 814 // A builtin for defining a function 815 lispval* builtin_define_lambda(lispval* v, lispenv* env) 816 { 817 // @ { {x y} { + x y } } 818 // def { {plus} {{@ {x y} {+ x y}} }} 819 // (eval plus) 1 2 820 // (@ { {x y} { + x y } }) 1 2 821 LISPVAL_ASSERT(v->count == 2, "Lambda definition requires two arguments; try (@ {x y} { + x y }) "); 822 LISPVAL_ASSERT(v->cell[0]->type == LISPVAL_QEXPR, "Lambda definition (@) requires that the first sub-arg be a q-expression; try @ {x y} { + x y }"); 823 LISPVAL_ASSERT(v->cell[1]->type == LISPVAL_QEXPR, "Lambda definition (@) requires that the second sub-arg be a q-expression; try @ {x y} { + x y }"); 824 825 lispval* variables = clone_lispval(v->cell[0]); 826 lispval* manipulation = clone_lispval(v->cell[1]); 827 828 for (int i = 0; i > variables->count; i++) { 829 LISPVAL_ASSERT(variables->cell[i]->type == LISPVAL_SYM, "First argument in function definition must only be symbols. Try @ { {x y} { + x y } }"); 830 } 831 lispenv* new_env = clone_lispenv(env); 832 // So env at the time of creation! 833 lispval* lambda = lispval_lambda_func(variables, manipulation, new_env); 834 return lambda; 835 } 836 837 // Conditionals 838 839 lispval* builtin_ifelse(lispval* v, lispenv* e) 840 { 841 // ifelse 1 {a} b 842 LISPVAL_ASSERT(v->count == 3, "Error: function ifelse passed too many arguments. Try ifelse choice result alternative, e.g., if (1 (a) {b})"); 843 844 lispval* choice = v->cell[0]; 845 lispval* result = v->cell[1]; 846 lispval* alternative = v->cell[2]; 847 848 if( choice->type == LISPVAL_NUM && choice->num == 0){ 849 lispval* answer = clone_lispval(alternative); 850 if(answer->type == LISPVAL_QEXPR){ 851 answer->type = LISPVAL_SEXPR; 852 answer = evaluate_lispval(answer, e); 853 } 854 return answer; 855 }else { 856 lispval* answer = clone_lispval(result); 857 if(answer->type == LISPVAL_QEXPR){ 858 // answer = builtin_eval(answer, e); 859 answer->type = LISPVAL_SEXPR; 860 answer = evaluate_lispval(answer, e); 861 } 862 return answer; 863 } 864 } 865 866 // Comparators: =, > (also potentially <, >=, <=, <=) 867 // For numbers. 868 869 lispval* builtin_equal(lispval* v, lispenv* e) 870 { 871 // ifelse 1 {a} b 872 LISPVAL_ASSERT(v->count == 2, "Error: function = takes two numeric arguments. Try (= 1 2)"); 873 874 lispval* a = v->cell[0]; 875 lispval* b = v->cell[1]; 876 877 LISPVAL_ASSERT(a->type == LISPVAL_NUM, "Error: Functio = only takes numeric arguments."); 878 LISPVAL_ASSERT(b->type == LISPVAL_NUM, "Error: Functio = only takes numeric arguments."); 879 880 if(a->num == b->num){ 881 return lispval_num(1); 882 }else { 883 return lispval_num(0); 884 } 885 } 886 887 888 lispval* builtin_greater_than(lispval* v, lispenv* e) 889 { 890 // ifelse 1 {a} b 891 LISPVAL_ASSERT(v->count == 2, "Error: function = takes two numeric arguments. Try (= 1 2)"); 892 893 lispval* a = v->cell[0]; 894 lispval* b = v->cell[1]; 895 896 LISPVAL_ASSERT(a->type == LISPVAL_NUM, "Error: Functio = only takes numeric arguments."); 897 LISPVAL_ASSERT(b->type == LISPVAL_NUM, "Error: Functio = only takes numeric arguments."); 898 899 if(a->num > b->num){ 900 return lispval_num(1); 901 }else { 902 return lispval_num(0); 903 } 904 } 905 906 907 // Simple math ops 908 lispval* builtin_math_ops(char* op, lispval* v, lispenv* e) 909 { 910 // For now, ensure all args are numbers 911 for (int i = 0; i < v->count; i++) { 912 if (v->cell[i]->type != LISPVAL_NUM) { 913 return lispval_err("Error: Operating on non-numbers. This can be caused by an input like (+ 1 2 (3 * 4)). Because the (3 * 4) doesn't have the correct operation order, it isn't simplified, and then + can't sum over it."); 914 } 915 } 916 // Check how many elements 917 if (v->count == 0) { 918 return lispval_err("Error: No numbers on which to operate!"); 919 } else if (v->count == 1) { 920 if (strcmp(op, "-") == 0) { 921 return lispval_num(-v->cell[0]->num); 922 } else { 923 return lispval_err("Error: Non minus unary operation"); 924 } 925 } else if (v->count >= 2) { 926 lispval* x = clone_lispval(v->cell[0]); 927 928 for (int i = 1; i < v->count; i++) { 929 lispval* y = v->cell[i]; 930 if (strcmp(op, "+") == 0) { 931 x->num += y->num; 932 } 933 if (strcmp(op, "-") == 0) { 934 x->num -= y->num; 935 } 936 if (strcmp(op, "*") == 0) { 937 x->num *= y->num; 938 } 939 940 if (strcmp(op, "/") == 0) { 941 if (y->num == 0) { 942 delete_lispval(x); 943 delete_lispval(y); 944 return lispval_err("Error: Division By Zero!"); 945 } 946 x->num /= y->num; 947 } 948 } 949 return x; 950 } else { 951 return lispval_err("Error: Incorrect number of args. Perhaps a lispval->count was wrongly initialized?"); 952 } 953 // Returns something that should be freed later: yes. 954 // Returns something that is independent of the input: yes. 955 } 956 957 // Fit the simple math ops using the above code 958 lispval* builtin_add(lispval* v, lispenv* env) 959 { 960 return builtin_math_ops("+", v, env); 961 } 962 963 lispval* builtin_substract(lispval* v, lispenv* env) 964 { 965 return builtin_math_ops("-", v, env); 966 } 967 968 lispval* builtin_multiply(lispval* v, lispenv* env) 969 { 970 return builtin_math_ops("*", v, env); 971 } 972 973 lispval* builtin_divide(lispval* v, lispenv* env) 974 { 975 return builtin_math_ops("/", v, env); 976 } 977 978 // Add builtins to an env 979 void lispenv_add_builtin(char* builtin_func_name, lispbuiltin func, lispenv* env) 980 { 981 if (VERBOSE) 982 printfln("Adding func: name: %s, pointer: %p", builtin_func_name, func); 983 lispval* f = lispval_builtin_func(func, builtin_func_name); 984 if (VERBOSE) 985 print_lispval_tree(f, 0); 986 insert_in_current_lispenv(builtin_func_name, f, env); 987 delete_lispval(f); 988 } 989 void lispenv_add_builtins(lispenv* env) 990 { 991 // Math functions 992 lispenv_add_builtin("+", builtin_add, env); 993 lispenv_add_builtin("-", builtin_substract, env); 994 lispenv_add_builtin("*", builtin_multiply, env); 995 lispenv_add_builtin("/", builtin_divide, env); 996 997 // 998 /* List Functions */ 999 lispenv_add_builtin("list", builtin_list, env); 1000 lispenv_add_builtin("head", builtin_head, env); 1001 lispenv_add_builtin("tail", builtin_tail, env); 1002 lispenv_add_builtin("eval", builtin_eval, env); 1003 lispenv_add_builtin("join", builtin_join, env); 1004 lispenv_add_builtin("len", builtin_len, env); 1005 lispenv_add_builtin("def", builtin_def, env); 1006 lispenv_add_builtin("@", builtin_define_lambda, env); 1007 lispenv_add_builtin("ifelse", builtin_ifelse, env); 1008 lispenv_add_builtin("if", builtin_ifelse, env); 1009 lispenv_add_builtin("=", builtin_equal, env); 1010 lispenv_add_builtin(">", builtin_greater_than, env); 1011 } 1012 1013 // Evaluate the lispval 1014 lispval* evaluate_lispval(lispval* l, lispenv* env) 1015 { 1016 if (VERBOSE) 1017 printfln("Evaluating lispval"); 1018 // Check if this is neither an s-expression nor a symbol; otherwise return as is. 1019 if (VERBOSE) 1020 printfln("%s", ""); 1021 if (l->type != LISPVAL_SEXPR && l->type != LISPVAL_SYM) 1022 return l; 1023 1024 // Check if this is a symbol 1025 if (VERBOSE) 1026 printfln("Checking if this is a symbol"); 1027 if (l->type == LISPVAL_SYM) { 1028 // Unclear how I want to structure this so as to not get memory errors. 1029 lispval* answer = get_from_lispenv(l->sym, env); 1030 delete_lispval(l); 1031 // fixes memory bug! I guess that if I just return get_from_lispenv, 1032 // then it gets lost along the way? Not sure. 1033 return answer; 1034 } 1035 1036 // Evaluate the children if needed 1037 if (VERBOSE) 1038 printfln("%s", "Evaluating children"); 1039 for (int i = 0; i < l->count; i++) { 1040 if (l->cell[i]->type == LISPVAL_SEXPR || l->cell[i]->type == LISPVAL_SYM) { 1041 // l->cell[i] = 1042 if (VERBOSE) 1043 printfln("%s", ""); 1044 lispval* new = evaluate_lispval(l->cell[i], env); 1045 // delete_lispval(l->cell[i]); 1046 // ^ gave me a "double free" error. 1047 l->cell[i] = new; 1048 if (VERBOSE) 1049 printfln("%s", ""); 1050 } 1051 } 1052 // Check if any are errors. 1053 if (VERBOSE) 1054 printfln("Checking for errors in children"); 1055 lispval* err = NULL; 1056 for (int i = 0; i < l->count; i++) { 1057 if (l->cell[i]->type == LISPVAL_ERR) { 1058 err = clone_lispval(l->cell[i]); 1059 } 1060 } 1061 if (err != NULL) { 1062 /* 1063 for (int i = 0; i < l->count; i++) { 1064 delete_lispval(l->cell[i]); 1065 } 1066 */ 1067 if (VERBOSE) 1068 printfln("Returning error"); 1069 return err; 1070 } 1071 1072 // Check if the first element is an operation. 1073 if (VERBOSE) 1074 printfln("Checking if first element is a function"); 1075 if (l->count >= 2 && ((l->cell[0])->type == LISPVAL_BUILTIN_FUNC)) { 1076 1077 if (VERBOSE) 1078 printfln("Passed check"); 1079 if (VERBOSE) 1080 printfln("Operating on:"); 1081 if (VERBOSE) 1082 print_lispval_tree(l, 4); 1083 1084 // Ok, do this properly now. 1085 if (VERBOSE) 1086 printfln("Constructing function and operands"); 1087 1088 lispval* f = clone_lispval(l->cell[0]); 1089 lispval* operands = lispval_sexpr(); 1090 1091 for (int i = 1; i < l->count; i++) { 1092 lispval_append_child(operands, l->cell[i]); 1093 } 1094 if (VERBOSE) 1095 printfln("Applying function to operands"); 1096 // lispval* answer = lispval_num(42); 1097 lispval* answer = f->builtin_func(operands, env); 1098 if (VERBOSE) 1099 printfln("Applied function to operands"); 1100 1101 if (VERBOSE) 1102 printfln("Cleaning up"); 1103 delete_lispval(f); 1104 delete_lispval(operands); 1105 // delete_lispval(temp); 1106 if (VERBOSE) 1107 printfln("Cleaned up. Returning"); 1108 return answer; 1109 } 1110 1111 if (l->count >= 2 && ((l->cell[0])->type == LISPVAL_USER_FUNC)) { 1112 lispval* f = l->cell[0]; // clone_lispval(l->cell[0]); 1113 if (VERBOSE) { 1114 printfln("Evaluating user-defined function"); 1115 print_lispval_tree(f, 2); 1116 printfln("Expected %d variables, found %d variables.", f->variables->count, l->count - 1); 1117 } 1118 1119 lispenv* evaluation_env = new_lispenv(); 1120 evaluation_env->parent = env; 1121 1122 LISPVAL_ASSERT(f->variables->count == (l->count - 1), "Error: Incorrect number of variables given to user-defined function"); 1123 if (VERBOSE) { 1124 printfln("Number of variables match"); 1125 printfln("Function vars:"); 1126 print_lispval_tree(f->variables, 2); 1127 printfln("Function manipulation:"); 1128 print_lispval_tree(f->manipulation, 2); 1129 } 1130 1131 for (int i = 0; i < f->variables->count; i++) { 1132 insert_in_current_lispenv(f->variables->cell[i]->sym, l->cell[i + 1], evaluation_env); 1133 } 1134 if (VERBOSE) { 1135 printfln("Evaluation environment: "); 1136 print_env(evaluation_env); 1137 } 1138 lispval* temp_expression = clone_lispval(f->manipulation); 1139 temp_expression->type = LISPVAL_SEXPR; 1140 lispval* answer = evaluate_lispval(temp_expression, evaluation_env); 1141 // delete_lispval(temp_expression); 1142 destroy_lispenv(evaluation_env); 1143 // lispval* answer = builtin_eval(f->manipulation, f->env); 1144 // destroy_lispenv(f->env); 1145 return answer; 1146 } 1147 1148 return l; 1149 } 1150 // Increase or decrease verbosity level manually 1151 int modify_verbosity(char* command) 1152 { 1153 if (strcmp("VERBOSE=0", command) == 0) { 1154 VERBOSE = 0; 1155 return 1; 1156 } 1157 if (strcmp("VERBOSE=1", command) == 0) { 1158 VERBOSE = 1; 1159 printfln("VERBOSE=1"); 1160 return 1; 1161 } 1162 if (strcmp("VERBOSE=2", command) == 0) { 1163 printfln("VERBOSE=2"); 1164 VERBOSE = 2; 1165 return 1; 1166 } 1167 return 0; 1168 } 1169 1170 // Main 1171 int main(int argc, char** argv) 1172 { 1173 // Info 1174 printfln("%s", "Mumble version 0.0.2\n"); 1175 printfln("%s", "Press Ctrl+C to exit\n"); 1176 1177 /* Create Some Parsers */ 1178 mpc_parser_t* Number = mpc_new("number"); 1179 mpc_parser_t* Symbol = mpc_new("symbol"); 1180 mpc_parser_t* Sexpr = mpc_new("sexpr"); 1181 mpc_parser_t* Qexpr = mpc_new("qexpr"); 1182 mpc_parser_t* Expr = mpc_new("expr"); 1183 mpc_parser_t* Mumble = mpc_new("mumble"); 1184 1185 /* Define them with the following Language */ 1186 mpca_lang(MPCA_LANG_DEFAULT, " \ 1187 number : /-?[0-9]+\\.?([0-9]+)?/ ; \ 1188 symbol : /[a-zA-Z0-9_+\\-*\\/\\\\=<>!&@]+/ ; \ 1189 sexpr : '(' <expr>* ')' ; \ 1190 qexpr : '{' <expr>* '}' ; \ 1191 expr : <number> | <symbol> | <sexpr> | <qexpr>; \ 1192 mumble : /^/ <expr>* /$/ ; \ 1193 ", 1194 Number, Symbol, Sexpr, Qexpr, Expr, Mumble); 1195 1196 // Create an environment 1197 if (VERBOSE) 1198 printfln("Creating lispenv"); 1199 lispenv* env = new_lispenv(); 1200 if (VERBOSE) 1201 printfln("Created lispenv"); 1202 if (VERBOSE) 1203 printfln("Adding builtins"); 1204 lispenv_add_builtins(env); 1205 if (VERBOSE) 1206 printfln("Added builtins"); 1207 if (VERBOSE) 1208 printfln("Environment contents: %i", env->count); 1209 if (VERBOSE) 1210 printfln(" env->syms[0]: %s", env->syms[0]); 1211 if (VERBOSE) 1212 print_lispval_tree(env->vals[0], 2); 1213 if (VERBOSE) 1214 printfln("\n"); 1215 1216 // Initialize a repl 1217 int loop = 1; 1218 while (loop) { 1219 char* input = readline("mumble> "); 1220 if (input == NULL) { 1221 break; 1222 } else { 1223 if (modify_verbosity(input)) { 1224 continue; 1225 } 1226 /* Attempt to Parse the user Input */ 1227 mpc_result_t result; 1228 if (mpc_parse("<stdin>", input, Mumble, &result)) { 1229 /* On Success Print the AST */ 1230 // mpc_ast_print(result.output); 1231 /* Load AST from output */ 1232 mpc_ast_t* ast = result.output; 1233 1234 // Print AST if VERBOSE 1235 if (VERBOSE) { 1236 printfln("Printing AST"); 1237 print_ast(ast, 0); 1238 } 1239 // Evaluate the AST 1240 // lispval result = evaluate_ast(ast); 1241 lispval* l = read_lispval(ast); 1242 if (VERBOSE) { 1243 printfln("\nPrinting initially parsed lispvalue"); 1244 printfln("Tree printing: "); 1245 print_lispval_tree(l, 2); 1246 printfln("Parenthesis printing: "); 1247 print_lispval_parenthesis(l); 1248 } 1249 1250 // Eval the lispval in that environment. 1251 1252 lispval* answer = evaluate_lispval(l, env); 1253 { 1254 if (VERBOSE) 1255 printfln("Result: "); 1256 print_lispval_parenthesis(answer); 1257 if (VERBOSE) 1258 print_lispval_tree(answer, 0); 1259 printf("\n"); 1260 } 1261 delete_lispval(answer); 1262 if (VERBOSE > 1) 1263 printfln("variable \"answer\" after deletion: %p ", answer); 1264 // delete_lispval(answer); // do this twice, just to see. 1265 //if(VERBOSE) printfln("Deleting this lispval:"); 1266 // if(VERBOSE) print_lispval_tree(l,2); 1267 1268 // delete_lispval(l); 1269 // if(VERBOSE) printfln("Deleted that ^ lispval"); 1270 // ^ I do not understand how the memory in l is freed. 1271 // delete the ast 1272 mpc_ast_delete(ast); 1273 } else { 1274 /* Otherwise Print the Error */ 1275 mpc_err_print(result.error); 1276 mpc_err_delete(result.error); 1277 } 1278 add_history(input); 1279 // can't add if input is NULL 1280 } 1281 printf("%s", ""); 1282 free(input); 1283 input = NULL; 1284 } 1285 1286 // Clear the history 1287 rl_uninitialize(); 1288 // rl_free_line_state(); 1289 // Clean up environment 1290 destroy_lispenv(env); 1291 1292 /* Undefine and Delete our Parsers */ 1293 mpc_cleanup(6, Number, Symbol, Sexpr, Qexpr, Expr, Mumble); 1294 1295 return 0; 1296 }