(Somewhat adapted) code and solutions from the book "Build Your Own Lisp" http://www.buildyourownlisp.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

413 lines
9.3 KiB

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <assert.h>
  4. #include "../mpc/mpc.h"
  5. /* If we are on Windows compile these functions */
  6. #ifdef _WIN32
  7. #include <string.h>
  8. static char buffer[2048];
  9. /* Fake readline function */
  10. char* readline(char* prompt) {
  11. fputs(prompt, stdout);
  12. fgets(buffer, 2048, stdin);
  13. char* cpy = malloc(strlen(buffer)+1);
  14. assert(cpy != NULL)
  15. strcpy(cpy, buffer);
  16. cpy[strlen(cpy)-1] = '\0';
  17. return cpy;
  18. }
  19. /* Fake add_history function */
  20. void add_history(char* unused) {}
  21. /* Otherwise include the editline headers
  22. could use __APPLE__ for detection of OSX */
  23. #else
  24. #include <editline/readline.h>
  25. #endif
  26. /* Include type and function declarations */
  27. #include "lispy.h"
  28. /* Construct a pointer to a new number lval */
  29. lval* lval_num(long x) {
  30. lval* v = malloc(sizeof(lval));
  31. assert(v != NULL);
  32. v->type = LVAL_NUM;
  33. v->num = x;
  34. return v;
  35. }
  36. /* Construct a pointer to a new error lval */
  37. lval* lval_err(char* m) {
  38. lval* v = malloc(sizeof(lval));
  39. assert(v != NULL);
  40. v->type = LVAL_ERR;
  41. v->err = malloc(strlen(m)+1);
  42. assert(v->err != NULL);
  43. strcpy(v->err, m);
  44. return v;
  45. }
  46. /* Construct a pointer to a new symbol lval */
  47. lval* lval_sym(char* s) {
  48. lval* v = malloc(sizeof(lval));
  49. assert(v != NULL);
  50. v->type = LVAL_SYM;
  51. v->sym = malloc(strlen(s)+1);
  52. assert(v->sym != NULL);
  53. strcpy(v->sym, s);
  54. return v;
  55. }
  56. /* Construct a pointer to a new empty sexpr lval */
  57. lval* lval_sexpr(void) {
  58. lval* v = malloc(sizeof(lval));
  59. assert(v != NULL);
  60. v->type = LVAL_SEXPR;
  61. v->count = 0;
  62. v->cell = NULL;
  63. return v;
  64. }
  65. /* Free memory of an lval and all its members */
  66. void lval_del(lval* v) {
  67. switch (v->type) {
  68. /* Do nothing special for number type */
  69. case LVAL_NUM:
  70. break;
  71. /* For err or sym free the string data */
  72. case LVAL_ERR:
  73. free(v->err);
  74. break;
  75. case LVAL_SYM:
  76. free(v->sym);
  77. break;
  78. /* If sexpr then delete all elements inside */
  79. case LVAL_SEXPR:
  80. for (size_t i = 0; i < v->count; i++) {
  81. lval_del(v->cell[i]);
  82. }
  83. /* Also free the memory allocated to contain
  84. the pointers */
  85. free(v->cell);
  86. break;
  87. }
  88. /* Free the memory allocated for the lval struct itself */
  89. free(v);
  90. }
  91. lval* lval_read_num(mpc_ast_t* t) {
  92. errno = 0;
  93. long x = strtol(t->contents, NULL, 10);
  94. return errno != ERANGE ? lval_num(x)
  95. : lval_err("Invalid number");
  96. }
  97. lval* lval_read(mpc_ast_t* t) {
  98. /* If symbol or number return conversion to that type */
  99. if (strstr(t->tag, "number")) {
  100. return lval_read_num(t);
  101. }
  102. if (strstr(t->tag, "symbol")) {
  103. return lval_sym(t->contents);
  104. }
  105. /* If root (>) or sexpr then create empty list */
  106. lval* x = NULL;
  107. if (strcmp(t->tag, ">") == 0 || strstr(t->tag, "sexpr")) {
  108. x = lval_sexpr();
  109. }
  110. /* Fill this list with any valid expression
  111. contained within */
  112. for (size_t i = 0; i < t->children_num; i++) {
  113. if (strcmp(t->children[i]->contents, "(") == 0) {
  114. continue;
  115. }
  116. if (strcmp(t->children[i]->contents, ")") == 0) {
  117. continue;
  118. }
  119. if (strcmp(t->children[i]->contents, "{") == 0) {
  120. continue;
  121. }
  122. if (strcmp(t->children[i]->contents, "}") == 0) {
  123. continue;
  124. }
  125. if (strcmp(t->children[i]->tag, "regex") == 0) {
  126. continue;
  127. }
  128. x = lval_add(x, lval_read(t->children[i]));
  129. }
  130. return x;
  131. }
  132. lval* lval_add(lval* v, lval* x) {
  133. v->count++;
  134. v->cell = realloc(v->cell, sizeof(lval*) * v->count);
  135. assert(v->cell != NULL);
  136. v->cell[v->count-1] = x;
  137. return v;
  138. }
  139. void lval_expr_print(lval* v, char open, char close) {
  140. /* Opening char */
  141. putchar(open);
  142. for (size_t i = 0; i < v->count; i++) {
  143. /* Print value contained within */
  144. lval_print(v->cell[i]);
  145. /* Don't print trailing space if last element */
  146. if (i != (v->count-1)) {
  147. putchar(' ');
  148. }
  149. }
  150. /* Opening char */
  151. putchar(close);
  152. }
  153. /* Print an lval */
  154. void lval_print(lval* v) {
  155. switch (v->type) {
  156. /* In the case the type is a number print it
  157. Then break out of the switch */
  158. case LVAL_NUM:
  159. printf("%li", v->num);
  160. break;
  161. /* In the case the type is an error */
  162. case LVAL_ERR:
  163. printf("Error: %s", v->err);
  164. break;
  165. case LVAL_SYM:
  166. printf("%s", v->sym);
  167. break;
  168. case LVAL_SEXPR:
  169. lval_expr_print(v, '(', ')');
  170. break;
  171. }
  172. }
  173. /* Print an lval followed by a newline */
  174. void lval_println(lval* v) {
  175. lval_print(v);
  176. putchar('\n');
  177. }
  178. lval* lval_eval_sexpr(lval* v) {
  179. /* Evaluate children */
  180. for (size_t i = 0; i < v->count; i++) {
  181. v->cell[i] = lval_eval(v->cell[i]);
  182. }
  183. /* Error checking */
  184. for (size_t i = 0; i < v->count; i++) {
  185. if (v->cell[i]->type == LVAL_ERR) {
  186. return lval_take(v, i);
  187. }
  188. }
  189. /* Empty expression */
  190. if (v->count == 0) {
  191. return v;
  192. }
  193. /* Single expression */
  194. if (v->count == 1) {
  195. return lval_take(v, 0);
  196. }
  197. /* Ensure first element is symbol */
  198. lval* f = lval_pop(v, 0);
  199. if (f->type != LVAL_SYM) {
  200. lval_del(f);
  201. lval_del(v);
  202. return lval_err("S-expression does not start with symbol!");
  203. }
  204. /* Call builtin with operator */
  205. lval* result = builtin_op(v, f->sym);
  206. lval_del(f);
  207. return result;
  208. }
  209. lval* lval_eval(lval* v) {
  210. /* Evaluate sexpressions */
  211. if (v->type == LVAL_SEXPR) {
  212. return lval_eval_sexpr(v);
  213. }
  214. /* All other lval types remain the same */
  215. return v;
  216. }
  217. lval* lval_pop(lval* v, size_t i) {
  218. /* Fine the item at i */
  219. lval* x = v->cell[i];
  220. /* Shift memory after the item at i over the top */
  221. memmove(&v->cell[i], &v->cell[i+1],
  222. sizeof(lval*) * (v->count-i-1));
  223. /* Decrease the count of items in the list */
  224. v->count--;
  225. /* Reallocate the memory used */
  226. v->cell = realloc(v->cell, sizeof(lval*) * v->count);
  227. assert(v->cell != NULL);
  228. return x;
  229. }
  230. lval* lval_take(lval* v, size_t i) {
  231. lval* x = lval_pop(v, i);
  232. lval_del(v);
  233. return x;
  234. }
  235. lval* builtin_op(lval* a, char* op) {
  236. /* Ensure all arguments are numbers */
  237. for (size_t i = 0; i < a->count; i++) {
  238. if (a->cell[i]->type != LVAL_NUM) {
  239. lval_del(a);
  240. return lval_err("Cannot operate on non-number!");
  241. }
  242. }
  243. /* Pop the 1st element */
  244. lval* x = lval_pop(a, 0);
  245. /* If no arguments and sub then perform unary negation */
  246. if (strcmp(op, "-") == 0 && a->count == 0) {
  247. x->num = -x->num;
  248. }
  249. /* While there are still elements remaining */
  250. while (a->count > 0) {
  251. /* Pop the next element */
  252. lval* y = lval_pop(a, 0);
  253. if (strcmp(op, "+") == 0) {x->num += y->num;}
  254. if (strcmp(op, "-") == 0) {x->num -= y->num;}
  255. if (strcmp(op, "*") == 0) {x->num *= y->num;}
  256. if (strcmp(op, "/") == 0) {
  257. /* If second operand is zero return error */
  258. if (y->num == 0) {
  259. lval_del(x);
  260. lval_del(y);
  261. x = lval_err("Division by zero!");
  262. break;
  263. }
  264. x->num /= y->num;
  265. }
  266. if (strcmp(op, "%") == 0) {x->num %= y->num;}
  267. if (strcmp(op, "^") == 0) {x->num = (pow(x->num, y->num));}
  268. if (strcmp(op, "min") == 0) {x->num = min(x->num, y->num);}
  269. if (strcmp(op, "max") == 0) {x->num = max(x->num, y->num);}
  270. }
  271. lval_del(a);
  272. return x;
  273. }
  274. long min(long x, long y) {
  275. if (x <= y) {
  276. return x;
  277. } else {
  278. return y;
  279. }
  280. }
  281. long max(long x, long y) {
  282. if (x >= y) {
  283. return x;
  284. } else {
  285. return y;
  286. }
  287. }
  288. int main(int argc, char const *argv[]) {
  289. /* Create some parsers */
  290. mpc_parser_t* Number = mpc_new("number");
  291. mpc_parser_t* Symbol = mpc_new("symbol");
  292. mpc_parser_t* Sexpr = mpc_new("sexpr");
  293. mpc_parser_t* Expr = mpc_new("expr");
  294. mpc_parser_t* Lispy = mpc_new("lispy");
  295. /* Define them with the following language */
  296. mpca_lang(MPCA_LANG_DEFAULT, parser,
  297. Number, Symbol, Sexpr, Expr, Lispy);
  298. /* Print version and exit information */
  299. puts(lispy_version);
  300. puts("Press Ctrl+c to exit\n");
  301. /* In a never ending loop */
  302. while (1) {
  303. /* Output our prompt and get input */
  304. char* input = readline("lispy> ");
  305. /* Add input to history */
  306. add_history(input);
  307. /* Attempt to parse the user input */
  308. mpc_result_t r;
  309. if (mpc_parse("<stdin>", input, Lispy, &r)) {
  310. /* On success evaluate the user input */
  311. lval* x = lval_eval(lval_read(r.output));
  312. lval_println(x);
  313. lval_del(x);
  314. } else {
  315. /* Otherwise print the error */
  316. mpc_err_print(r.error);
  317. mpc_err_delete(r.error);
  318. }
  319. /* Free retrieved input */
  320. free(input);
  321. }
  322. /* Undefine and delete our parsers */
  323. mpc_cleanup(5, Number, Symbol, Sexpr, Expr, Lispy);
  324. return 0;
  325. }