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

589 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_op(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_op(lval* a, char* op) {
  271. /* Ensure all arguments are numbers */
  272. for (size_t i = 0; i < a->count; i++) {
  273. if (a->cell[i]->type != LVAL_NUM && a->cell[i]->type != LVAL_DEC) {
  274. lval_del(a);
  275. return lval_err("Cannot operate on non-number/non-decimal!");
  276. }
  277. }
  278. /* Pop the 1st element */
  279. lval* x = lval_pop(a, 0);
  280. /* If no arguments and sub then perform unary negation */
  281. if (strcmp(op, "-") == 0 && a->count == 0) {
  282. if (x->type == LVAL_NUM) {
  283. x->num = -x->num;
  284. } else {
  285. x->dec = -x->dec;
  286. }
  287. }
  288. /* While there are still elements remaining */
  289. while (a->count > 0) {
  290. /* Pop the next element */
  291. lval* y = lval_pop(a, 0);
  292. if (x->type == LVAL_NUM && y->type == LVAL_NUM) {
  293. if (strcmp(op, "+") == 0) {x->num += y->num;}
  294. if (strcmp(op, "-") == 0) {x->num -= y->num;}
  295. if (strcmp(op, "*") == 0) {x->num *= y->num;}
  296. if (strcmp(op, "/") == 0) {
  297. /* If second operand is zero return error */
  298. if (y->num == 0) {
  299. lval_del(x);
  300. lval_del(y);
  301. x = lval_err("Division by zero!");
  302. break;
  303. }
  304. x->num /= y->num;
  305. }
  306. if (strcmp(op, "%") == 0) {x->num %= y->num;}
  307. if (strcmp(op, "^") == 0) {x->num = (pow(x->num, y->num));}
  308. if (strcmp(op, "min") == 0) {x->num = min(x->num, y->num);}
  309. if (strcmp(op, "max") == 0) {x->num = max(x->num, y->num);}
  310. } else {
  311. /* Cast integer number into double if necessary */
  312. double b = x->type == LVAL_NUM ? (double) x->num : x->dec;
  313. double c = y->type == LVAL_NUM ? (double) y->num : y->dec;
  314. /* Perform all operations on double */
  315. if (strcmp(op, "+") == 0) {b += c;}
  316. if (strcmp(op, "-") == 0) {b -= c;}
  317. if (strcmp(op, "*") == 0) {b *= c;}
  318. if (strcmp(op, "/") == 0) {
  319. /* If second operand is zero return error */
  320. if (c == 0) {
  321. lval_del(x);
  322. lval_del(y);
  323. x = lval_err("Division by zero!");
  324. break;
  325. }
  326. b /= c;
  327. }
  328. if (strcmp(op, "%") == 0) {b = fmod(b, c);}
  329. if (strcmp(op, "^") == 0) {b = (pow(b, c));}
  330. if (strcmp(op, "min") == 0) {b = fmin(b, c);}
  331. if (strcmp(op, "max") == 0) {b = fmax(b, c);}
  332. x->type = LVAL_DEC;
  333. x->dec = b;
  334. }
  335. }
  336. lval_del(a);
  337. return x;
  338. }
  339. lval* builtin_head(lval* a) {
  340. /* Check error conditions */
  341. LASSERT(a, a->count == 1,
  342. "Function 'head' passed too many arguments!");
  343. LASSERT(a, a->cell[0]->type == LVAL_QEXPR,
  344. "Function 'head' passed incorrect type!");
  345. LASSERT(a, a->cell[0]->count != 0,
  346. "Function 'head' passed {}!");
  347. /* Otherwise take first argument */
  348. lval* v = lval_take(a, 0);
  349. /* Delete all elements that are not head and return */
  350. while (v-> count > 1) {
  351. lval_del(lval_pop(v, 1));
  352. }
  353. return v;
  354. }
  355. lval* builtin_tail(lval* a) {
  356. /* Check error conditions */
  357. LASSERT(a, a->count == 1,
  358. "Function 'tail' passed too many arguments!");
  359. LASSERT(a, a->cell[0]->type == LVAL_QEXPR,
  360. "Function 'tail' passed incorrect type!");
  361. LASSERT(a, a->cell[0]->count != 0,
  362. "Function 'tail' passed {}!");
  363. /* Otherwise take first argument */
  364. lval* v = lval_take(a, 0);
  365. /* Delete first element and return */
  366. lval_del(lval_pop(v, 0));
  367. return v;
  368. }
  369. lval* builtin_list(lval* a) {
  370. a->type = LVAL_QEXPR;
  371. return a;
  372. }
  373. lval* builtin_eval(lval* a) {
  374. /* Check error conditions */
  375. LASSERT(a, a->count == 1,
  376. "Function 'eval' passed too many arguments!");
  377. LASSERT(a, a->cell[0]->type == LVAL_QEXPR,
  378. "Function 'eval' passed incorrect type!");
  379. lval* x = lval_take(a, 0);
  380. x->type = LVAL_SEXPR;
  381. return lval_eval(x);
  382. }
  383. lval* builtin_join(lval* a) {
  384. /* Check error conditions */
  385. for (size_t i = 0; i < a->count; i++) {
  386. LASSERT(a, a->cell[i]->type == LVAL_QEXPR,
  387. "Function 'join' passed incorrect type!");
  388. }
  389. lval* x = lval_pop(a, 0);
  390. while (a->count) {
  391. x = lval_join(x, lval_pop(a, 0));
  392. }
  393. lval_del(a);
  394. return x;
  395. }
  396. lval* lval_join(lval* x, lval* y) {
  397. /* For each cell in y add it to x */
  398. while (y->count) {
  399. x = lval_add(x, lval_pop(y, 0));
  400. }
  401. /* Delete the empty y and return x */
  402. lval_del(y);
  403. return x;
  404. }
  405. long min(long x, long y) {
  406. if (x <= y) {
  407. return x;
  408. } else {
  409. return y;
  410. }
  411. }
  412. long max(long x, long y) {
  413. if (x >= y) {
  414. return x;
  415. } else {
  416. return y;
  417. }
  418. }
  419. int main() {
  420. /* Create some parsers */
  421. mpc_parser_t* Number = mpc_new("number");
  422. mpc_parser_t* Symbol = mpc_new("symbol");
  423. mpc_parser_t* Sexpr = mpc_new("sexpr");
  424. mpc_parser_t* Qexpr = mpc_new("qexpr");
  425. mpc_parser_t* Expr = mpc_new("expr");
  426. mpc_parser_t* Lispy = mpc_new("lispy");
  427. /* Define them with the following language */
  428. mpca_lang(MPCA_LANG_DEFAULT, parser,
  429. Number, Symbol, Sexpr, Qexpr, Expr, Lispy);
  430. /* Print version and exit information */
  431. puts(lispy_version);
  432. puts("Press Ctrl+c to exit\n");
  433. /* In a never ending loop */
  434. while (1) {
  435. /* Output our prompt and get input */
  436. char* input = readline("lispy> ");
  437. /* Add input to history */
  438. add_history(input);
  439. /* Attempt to parse the user input */
  440. mpc_result_t r;
  441. if (mpc_parse("<stdin>", input, Lispy, &r)) {
  442. /* On success evaluate the user input */
  443. lval* x = lval_eval(lval_read(r.output));
  444. lval_println(x);
  445. lval_del(x);
  446. } else {
  447. /* Otherwise print the error */
  448. mpc_err_print(r.error);
  449. mpc_err_delete(r.error);
  450. }
  451. /* Free retrieved input */
  452. free(input);
  453. }
  454. /* Undefine and delete our parsers */
  455. mpc_cleanup(6, Number, Symbol, Sexpr, Qexpr, Expr, Lispy);
  456. return 0;
  457. }