(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.

610 lines
14 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 decimal lval */
  37. lval* lval_dec(double x) {
  38. lval* v = malloc(sizeof(lval));
  39. assert(v != NULL);
  40. v->type = LVAL_DEC;
  41. v->dec = x;
  42. return v;
  43. }
  44. /* Construct a pointer to a new error lval */
  45. lval* lval_err(char* m) {
  46. lval* v = malloc(sizeof(lval));
  47. assert(v != NULL);
  48. v->type = LVAL_ERR;
  49. v->err = malloc(strlen(m)+1);
  50. assert(v->err != NULL);
  51. strcpy(v->err, m);
  52. return v;
  53. }
  54. /* Construct a pointer to a new symbol lval */
  55. lval* lval_sym(char* s) {
  56. lval* v = malloc(sizeof(lval));
  57. assert(v != NULL);
  58. v->type = LVAL_SYM;
  59. v->sym = malloc(strlen(s)+1);
  60. assert(v->sym != NULL);
  61. strcpy(v->sym, s);
  62. return v;
  63. }
  64. /* Construct a pointer to a new empty sexpr lval */
  65. lval* lval_sexpr(void) {
  66. lval* v = malloc(sizeof(lval));
  67. assert(v != NULL);
  68. v->type = LVAL_SEXPR;
  69. v->count = 0;
  70. v->cell = NULL;
  71. return v;
  72. }
  73. /* Construct a pointer to a new empty qexpr lval */
  74. lval* lval_qexpr(void) {
  75. lval* v = malloc(sizeof(lval));
  76. assert(v != NULL);
  77. v->type = LVAL_QEXPR;
  78. v->count = 0;
  79. v->cell = NULL;
  80. return v;
  81. }
  82. /* Free memory of an lval and all its members */
  83. void lval_del(lval* v) {
  84. switch (v->type) {
  85. /* Do nothing special for number / decimal type */
  86. case LVAL_NUM:
  87. case LVAL_DEC:
  88. break;
  89. /* For err or sym free the string data */
  90. case LVAL_ERR:
  91. free(v->err);
  92. break;
  93. case LVAL_SYM:
  94. free(v->sym);
  95. break;
  96. /* If sexpr then delete all elements inside */
  97. case LVAL_SEXPR:
  98. case LVAL_QEXPR:
  99. for (size_t i = 0; i < v->count; i++) {
  100. lval_del(v->cell[i]);
  101. }
  102. /* Also free the memory allocated to contain
  103. the pointers */
  104. free(v->cell);
  105. break;
  106. }
  107. /* Free the memory allocated for the lval struct itself */
  108. free(v);
  109. }
  110. lval* lval_read_num(mpc_ast_t* t) {
  111. errno = 0;
  112. if (strstr(t->contents, ".")) {
  113. double x = strtod(t->contents, NULL);
  114. return errno != ERANGE ? lval_dec(x)
  115. : lval_err("Invalid number");
  116. } else {
  117. long x = strtol(t->contents, NULL, 10);
  118. return errno != ERANGE ? lval_num(x)
  119. : lval_err("Invalid number");
  120. }
  121. }
  122. lval* lval_read(mpc_ast_t* t) {
  123. /* If symbol or number return conversion to that type */
  124. if (strstr(t->tag, "number")) {
  125. return lval_read_num(t);
  126. }
  127. if (strstr(t->tag, "symbol")) {
  128. return lval_sym(t->contents);
  129. }
  130. /* If root (>) or sexpr then create empty list */
  131. lval* x = NULL;
  132. if (strcmp(t->tag, ">") == 0 || strstr(t->tag, "sexpr")) {
  133. x = lval_sexpr();
  134. }
  135. /* If qexpr create then empty list */
  136. if (strstr(t->tag, "qexpr")) {
  137. x = lval_qexpr();
  138. }
  139. /* Fill this list with any valid expression
  140. contained within */
  141. for (size_t i = 0; i < (size_t) t->children_num; i++) {
  142. if (strcmp(t->children[i]->contents, "(") == 0) {
  143. continue;
  144. }
  145. if (strcmp(t->children[i]->contents, ")") == 0) {
  146. continue;
  147. }
  148. if (strcmp(t->children[i]->contents, "{") == 0) {
  149. continue;
  150. }
  151. if (strcmp(t->children[i]->contents, "}") == 0) {
  152. continue;
  153. }
  154. if (strcmp(t->children[i]->tag, "regex") == 0) {
  155. continue;
  156. }
  157. x = lval_add(x, lval_read(t->children[i]));
  158. }
  159. return x;
  160. }
  161. lval* lval_add(lval* v, lval* x) {
  162. v->count++;
  163. v->cell = realloc(v->cell, sizeof(lval*) * v->count);
  164. assert(v->cell != NULL);
  165. v->cell[v->count-1] = x;
  166. return v;
  167. }
  168. void lval_expr_print(lval* v, char open, char close) {
  169. /* Opening char */
  170. putchar(open);
  171. for (size_t i = 0; i < v->count; i++) {
  172. /* Print value contained within */
  173. lval_print(v->cell[i]);
  174. /* Don't print trailing space if last element */
  175. if (i != (v->count-1)) {
  176. putchar(' ');
  177. }
  178. }
  179. /* Opening char */
  180. putchar(close);
  181. }
  182. /* Print an lval */
  183. void lval_print(lval* v) {
  184. switch (v->type) {
  185. /* In the case the type is a number print it
  186. Then break out of the switch */
  187. case LVAL_NUM:
  188. printf("%li", v->num);
  189. break;
  190. case LVAL_DEC:
  191. printf("%.2f", v->dec);
  192. break;
  193. /* In the case the type is an error */
  194. case LVAL_ERR:
  195. printf("Error: %s", v->err);
  196. break;
  197. case LVAL_SYM:
  198. printf("%s", v->sym);
  199. break;
  200. case LVAL_SEXPR:
  201. lval_expr_print(v, '(', ')');
  202. break;
  203. case LVAL_QEXPR:
  204. lval_expr_print(v, '{', '}');
  205. break;
  206. }
  207. }
  208. /* Print an lval followed by a newline */
  209. void lval_println(lval* v) {
  210. lval_print(v);
  211. putchar('\n');
  212. }
  213. lval* lval_eval_sexpr(lval* v) {
  214. /* Evaluate children */
  215. for (size_t i = 0; i < v->count; i++) {
  216. v->cell[i] = lval_eval(v->cell[i]);
  217. }
  218. /* Error checking */
  219. for (size_t i = 0; i < v->count; i++) {
  220. if (v->cell[i]->type == LVAL_ERR) {
  221. return lval_take(v, i);
  222. }
  223. }
  224. /* Empty expression */
  225. if (v->count == 0) {
  226. return v;
  227. }
  228. /* Single expression */
  229. if (v->count == 1) {
  230. return lval_take(v, 0);
  231. }
  232. /* Ensure first element is symbol */
  233. lval* f = lval_pop(v, 0);
  234. if (f->type != LVAL_SYM) {
  235. lval_del(f);
  236. lval_del(v);
  237. return lval_err("S-expression does not start with symbol!");
  238. }
  239. /* Call builtin with operator */
  240. lval* result = builtin(v, f->sym);
  241. lval_del(f);
  242. return result;
  243. }
  244. lval* lval_eval(lval* v) {
  245. /* Evaluate sexpressions */
  246. if (v->type == LVAL_SEXPR) {
  247. return lval_eval_sexpr(v);
  248. }
  249. /* All other lval types remain the same */
  250. return v;
  251. }
  252. lval* lval_pop(lval* v, size_t i) {
  253. /* Fine the item at i */
  254. lval* x = v->cell[i];
  255. /* Shift memory after the item at i over the top */
  256. memmove(&v->cell[i], &v->cell[i+1],
  257. sizeof(lval*) * (v->count-i-1));
  258. /* Decrease the count of items in the list */
  259. v->count--;
  260. /* Reallocate the memory used */
  261. v->cell = realloc(v->cell, sizeof(lval*) * v->count);
  262. assert(v->cell != NULL);
  263. return x;
  264. }
  265. lval* lval_take(lval* v, size_t i) {
  266. lval* x = lval_pop(v, i);
  267. lval_del(v);
  268. return x;
  269. }
  270. lval* builtin(lval* a, char* func) {
  271. /* Check for builtin functions */
  272. if (strcmp("list", func) == 0) {return builtin_list(a);}
  273. if (strcmp("head", func) == 0) {return builtin_head(a);}
  274. if (strcmp("tail", func) == 0) {return builtin_tail(a);}
  275. if (strcmp("join", func) == 0) {return builtin_join(a);}
  276. if (strcmp("eval", func) == 0) {return builtin_eval(a);}
  277. /* Check for operators */
  278. if (strstr("+-*/%^", func) ||
  279. strcmp("min", func) == 0 || strcmp("max", func) == 0) {
  280. return builtin_op(a, func);
  281. }
  282. lval_del(a);
  283. return lval_err("Unknown function!");
  284. }
  285. lval* builtin_op(lval* a, char* op) {
  286. /* Ensure all arguments are numbers */
  287. for (size_t i = 0; i < a->count; i++) {
  288. if (a->cell[i]->type != LVAL_NUM && a->cell[i]->type != LVAL_DEC) {
  289. lval_del(a);
  290. return lval_err("Cannot operate on non-number/non-decimal!");
  291. }
  292. }
  293. /* Pop the 1st element */
  294. lval* x = lval_pop(a, 0);
  295. /* If no arguments and sub then perform unary negation */
  296. if (strcmp(op, "-") == 0 && a->count == 0) {
  297. if (x->type == LVAL_NUM) {
  298. x->num = -x->num;
  299. } else {
  300. x->dec = -x->dec;
  301. }
  302. }
  303. /* While there are still elements remaining */
  304. while (a->count > 0) {
  305. /* Pop the next element */
  306. lval* y = lval_pop(a, 0);
  307. if (x->type == LVAL_NUM && y->type == LVAL_NUM) {
  308. if (strcmp(op, "+") == 0) {x->num += y->num;}
  309. if (strcmp(op, "-") == 0) {x->num -= y->num;}
  310. if (strcmp(op, "*") == 0) {x->num *= y->num;}
  311. if (strcmp(op, "/") == 0) {
  312. /* If second operand is zero return error */
  313. if (y->num == 0) {
  314. lval_del(x);
  315. lval_del(y);
  316. x = lval_err("Division by zero!");
  317. break;
  318. }
  319. x->num /= y->num;
  320. }
  321. if (strcmp(op, "%") == 0) {x->num %= y->num;}
  322. if (strcmp(op, "^") == 0) {x->num = (pow(x->num, y->num));}
  323. if (strcmp(op, "min") == 0) {x->num = min(x->num, y->num);}
  324. if (strcmp(op, "max") == 0) {x->num = max(x->num, y->num);}
  325. } else {
  326. /* Cast integer number into double if necessary */
  327. double b = x->type == LVAL_NUM ? (double) x->num : x->dec;
  328. double c = y->type == LVAL_NUM ? (double) y->num : y->dec;
  329. /* Perform all operations on double */
  330. if (strcmp(op, "+") == 0) {b += c;}
  331. if (strcmp(op, "-") == 0) {b -= c;}
  332. if (strcmp(op, "*") == 0) {b *= c;}
  333. if (strcmp(op, "/") == 0) {
  334. /* If second operand is zero return error */
  335. if (c == 0) {
  336. lval_del(x);
  337. lval_del(y);
  338. x = lval_err("Division by zero!");
  339. break;
  340. }
  341. b /= c;
  342. }
  343. if (strcmp(op, "%") == 0) {b = fmod(b, c);}
  344. if (strcmp(op, "^") == 0) {b = (pow(b, c));}
  345. if (strcmp(op, "min") == 0) {b = fmin(b, c);}
  346. if (strcmp(op, "max") == 0) {b = fmax(b, c);}
  347. x->type = LVAL_DEC;
  348. x->dec = b;
  349. }
  350. }
  351. lval_del(a);
  352. return x;
  353. }
  354. lval* builtin_head(lval* a) {
  355. /* Check error conditions */
  356. LASSERT(a, a->count == 1,
  357. "Function 'head' passed too many arguments!");
  358. LASSERT(a, a->cell[0]->type == LVAL_QEXPR,
  359. "Function 'head' passed incorrect type!");
  360. LASSERT(a, a->cell[0]->count != 0,
  361. "Function 'head' passed {}!");
  362. /* Otherwise take first argument */
  363. lval* v = lval_take(a, 0);
  364. /* Delete all elements that are not head and return */
  365. while (v-> count > 1) {
  366. lval_del(lval_pop(v, 1));
  367. }
  368. return v;
  369. }
  370. lval* builtin_tail(lval* a) {
  371. /* Check error conditions */
  372. LASSERT(a, a->count == 1,
  373. "Function 'tail' passed too many arguments!");
  374. LASSERT(a, a->cell[0]->type == LVAL_QEXPR,
  375. "Function 'tail' passed incorrect type!");
  376. LASSERT(a, a->cell[0]->count != 0,
  377. "Function 'tail' passed {}!");
  378. /* Otherwise take first argument */
  379. lval* v = lval_take(a, 0);
  380. /* Delete first element and return */
  381. lval_del(lval_pop(v, 0));
  382. return v;
  383. }
  384. lval* builtin_list(lval* a) {
  385. a->type = LVAL_QEXPR;
  386. return a;
  387. }
  388. lval* builtin_eval(lval* a) {
  389. /* Check error conditions */
  390. LASSERT(a, a->count == 1,
  391. "Function 'eval' passed too many arguments!");
  392. LASSERT(a, a->cell[0]->type == LVAL_QEXPR,
  393. "Function 'eval' passed incorrect type!");
  394. lval* x = lval_take(a, 0);
  395. x->type = LVAL_SEXPR;
  396. return lval_eval(x);
  397. }
  398. lval* builtin_join(lval* a) {
  399. /* Check error conditions */
  400. for (size_t i = 0; i < a->count; i++) {
  401. LASSERT(a, a->cell[i]->type == LVAL_QEXPR,
  402. "Function 'join' passed incorrect type!");
  403. }
  404. lval* x = lval_pop(a, 0);
  405. while (a->count) {
  406. x = lval_join(x, lval_pop(a, 0));
  407. }
  408. lval_del(a);
  409. return x;
  410. }
  411. lval* lval_join(lval* x, lval* y) {
  412. /* For each cell in y add it to x */
  413. while (y->count) {
  414. x = lval_add(x, lval_pop(y, 0));
  415. }
  416. /* Delete the empty y and return x */
  417. lval_del(y);
  418. return x;
  419. }
  420. long min(long x, long y) {
  421. if (x <= y) {
  422. return x;
  423. } else {
  424. return y;
  425. }
  426. }
  427. long max(long x, long y) {
  428. if (x >= y) {
  429. return x;
  430. } else {
  431. return y;
  432. }
  433. }
  434. int main() {
  435. /* Create some parsers */
  436. mpc_parser_t* Number = mpc_new("number");
  437. mpc_parser_t* Symbol = mpc_new("symbol");
  438. mpc_parser_t* Sexpr = mpc_new("sexpr");
  439. mpc_parser_t* Qexpr = mpc_new("qexpr");
  440. mpc_parser_t* Expr = mpc_new("expr");
  441. mpc_parser_t* Lispy = mpc_new("lispy");
  442. /* Define them with the following language */
  443. mpca_lang(MPCA_LANG_DEFAULT, parser,
  444. Number, Symbol, Sexpr, Qexpr, Expr, Lispy);
  445. /* Print version and exit information */
  446. puts(lispy_version);
  447. puts("Press Ctrl+c to exit\n");
  448. /* In a never ending loop */
  449. while (1) {
  450. /* Output our prompt and get input */
  451. char* input = readline("lispy> ");
  452. /* Add input to history */
  453. add_history(input);
  454. /* Attempt to parse the user input */
  455. mpc_result_t r;
  456. if (mpc_parse("<stdin>", input, Lispy, &r)) {
  457. /* On success evaluate the user input */
  458. lval* x = lval_eval(lval_read(r.output));
  459. lval_println(x);
  460. lval_del(x);
  461. } else {
  462. /* Otherwise print the error */
  463. mpc_err_print(r.error);
  464. mpc_err_delete(r.error);
  465. }
  466. /* Free retrieved input */
  467. free(input);
  468. }
  469. /* Undefine and delete our parsers */
  470. mpc_cleanup(6, Number, Symbol, Sexpr, Qexpr, Expr, Lispy);
  471. return 0;
  472. }