Reference

{% collapse title=”variables.c” %}

  1. #include "mpc.h"
  2. #ifdef _WIN32
  3. static char buffer[2048];
  4. char* readline(char* prompt) {
  5. fputs(prompt, stdout);
  6. fgets(buffer, 2048, stdin);
  7. char* cpy = malloc(strlen(buffer)+1);
  8. strcpy(cpy, buffer);
  9. cpy[strlen(cpy)-1] = '\0';
  10. return cpy;
  11. }
  12. void add_history(char* unused) {}
  13. #else
  14. #include <editline/readline.h>
  15. #include <editline/history.h>
  16. #endif
  17. /* Forward Declarations */
  18. struct lval;
  19. struct lenv;
  20. typedef struct lval lval;
  21. typedef struct lenv lenv;
  22. /* Lisp Value */
  23. enum { LVAL_ERR, LVAL_NUM, LVAL_SYM,
  24. LVAL_FUN, LVAL_SEXPR, LVAL_QEXPR };
  25. typedef lval*(*lbuiltin)(lenv*, lval*);
  26. struct lval {
  27. int type;
  28. long num;
  29. char* err;
  30. char* sym;
  31. lbuiltin fun;
  32. int count;
  33. lval** cell;
  34. };
  35. lval* lval_num(long x) {
  36. lval* v = malloc(sizeof(lval));
  37. v->type = LVAL_NUM;
  38. v->num = x;
  39. return v;
  40. }
  41. lval* lval_err(char* fmt, ...) {
  42. lval* v = malloc(sizeof(lval));
  43. v->type = LVAL_ERR;
  44. /* Create a va list and initialize it */
  45. va_list va;
  46. va_start(va, fmt);
  47. /* Allocate 512 bytes of space */
  48. v->err = malloc(512);
  49. /* printf the error string with a maximum of 511 characters */
  50. vsnprintf(v->err, 511, fmt, va);
  51. /* Reallocate to number of bytes actually used */
  52. v->err = realloc(v->err, strlen(v->err)+1);
  53. /* Cleanup our va list */
  54. va_end(va);
  55. return v;
  56. }
  57. lval* lval_sym(char* s) {
  58. lval* v = malloc(sizeof(lval));
  59. v->type = LVAL_SYM;
  60. v->sym = malloc(strlen(s) + 1);
  61. strcpy(v->sym, s);
  62. return v;
  63. }
  64. lval* lval_fun(lbuiltin func) {
  65. lval* v = malloc(sizeof(lval));
  66. v->type = LVAL_FUN;
  67. v->fun = func;
  68. return v;
  69. }
  70. lval* lval_sexpr(void) {
  71. lval* v = malloc(sizeof(lval));
  72. v->type = LVAL_SEXPR;
  73. v->count = 0;
  74. v->cell = NULL;
  75. return v;
  76. }
  77. lval* lval_qexpr(void) {
  78. lval* v = malloc(sizeof(lval));
  79. v->type = LVAL_QEXPR;
  80. v->count = 0;
  81. v->cell = NULL;
  82. return v;
  83. }
  84. void lval_del(lval* v) {
  85. switch (v->type) {
  86. case LVAL_NUM: break;
  87. case LVAL_FUN: break;
  88. case LVAL_ERR: free(v->err); break;
  89. case LVAL_SYM: free(v->sym); break;
  90. case LVAL_QEXPR:
  91. case LVAL_SEXPR:
  92. for (int i = 0; i < v->count; i++) {
  93. lval_del(v->cell[i]);
  94. }
  95. free(v->cell);
  96. break;
  97. }
  98. free(v);
  99. }
  100. lval* lval_copy(lval* v) {
  101. lval* x = malloc(sizeof(lval));
  102. x->type = v->type;
  103. switch (v->type) {
  104. /* Copy Functions and Numbers Directly */
  105. case LVAL_FUN: x->fun = v->fun; break;
  106. case LVAL_NUM: x->num = v->num; break;
  107. /* Copy Strings using malloc and strcpy */
  108. case LVAL_ERR:
  109. x->err = malloc(strlen(v->err) + 1);
  110. strcpy(x->err, v->err); break;
  111. case LVAL_SYM:
  112. x->sym = malloc(strlen(v->sym) + 1);
  113. strcpy(x->sym, v->sym); break;
  114. /* Copy Lists by copying each sub-expression */
  115. case LVAL_SEXPR:
  116. case LVAL_QEXPR:
  117. x->count = v->count;
  118. x->cell = malloc(sizeof(lval*) * x->count);
  119. for (int i = 0; i < x->count; i++) {
  120. x->cell[i] = lval_copy(v->cell[i]);
  121. }
  122. break;
  123. }
  124. return x;
  125. }
  126. lval* lval_add(lval* v, lval* x) {
  127. v->count++;
  128. v->cell = realloc(v->cell, sizeof(lval*) * v->count);
  129. v->cell[v->count-1] = x;
  130. return v;
  131. }
  132. lval* lval_join(lval* x, lval* y) {
  133. for (int i = 0; i < y->count; i++) {
  134. x = lval_add(x, y->cell[i]);
  135. }
  136. free(y->cell);
  137. free(y);
  138. return x;
  139. }
  140. lval* lval_pop(lval* v, int i) {
  141. lval* x = v->cell[i];
  142. memmove(&v->cell[i], &v->cell[i+1],
  143. sizeof(lval*) * (v->count-i-1));
  144. v->count--;
  145. v->cell = realloc(v->cell, sizeof(lval*) * v->count);
  146. return x;
  147. }
  148. lval* lval_take(lval* v, int i) {
  149. lval* x = lval_pop(v, i);
  150. lval_del(v);
  151. return x;
  152. }
  153. void lval_print(lval* v);
  154. void lval_print_expr(lval* v, char open, char close) {
  155. putchar(open);
  156. for (int i = 0; i < v->count; i++) {
  157. lval_print(v->cell[i]);
  158. if (i != (v->count-1)) {
  159. putchar(' ');
  160. }
  161. }
  162. putchar(close);
  163. }
  164. void lval_print(lval* v) {
  165. switch (v->type) {
  166. case LVAL_FUN: printf("<function>"); break;
  167. case LVAL_NUM: printf("%li", v->num); break;
  168. case LVAL_ERR: printf("Error: %s", v->err); break;
  169. case LVAL_SYM: printf("%s", v->sym); break;
  170. case LVAL_SEXPR: lval_print_expr(v, '(', ')'); break;
  171. case LVAL_QEXPR: lval_print_expr(v, '{', '}'); break;
  172. }
  173. }
  174. void lval_println(lval* v) { lval_print(v); putchar('\n'); }
  175. char* ltype_name(int t) {
  176. switch(t) {
  177. case LVAL_FUN: return "Function";
  178. case LVAL_NUM: return "Number";
  179. case LVAL_ERR: return "Error";
  180. case LVAL_SYM: return "Symbol";
  181. case LVAL_SEXPR: return "S-Expression";
  182. case LVAL_QEXPR: return "Q-Expression";
  183. default: return "Unknown";
  184. }
  185. }
  186. /* Lisp Environment */
  187. struct lenv {
  188. int count;
  189. char** syms;
  190. lval** vals;
  191. };
  192. lenv* lenv_new(void) {
  193. /* Initialize struct */
  194. lenv* e = malloc(sizeof(lenv));
  195. e->count = 0;
  196. e->syms = NULL;
  197. e->vals = NULL;
  198. return e;
  199. }
  200. void lenv_del(lenv* e) {
  201. /* Iterate over all items in environment deleting them */
  202. for (int i = 0; i < e->count; i++) {
  203. free(e->syms[i]);
  204. lval_del(e->vals[i]);
  205. }
  206. /* Free allocated memory for lists */
  207. free(e->syms);
  208. free(e->vals);
  209. free(e);
  210. }
  211. lval* lenv_get(lenv* e, lval* k) {
  212. /* Iterate over all items in environment */
  213. for (int i = 0; i < e->count; i++) {
  214. /* Check if the stored string matches the symbol string */
  215. /* If it does, return a copy of the value */
  216. if (strcmp(e->syms[i], k->sym) == 0) {
  217. return lval_copy(e->vals[i]);
  218. }
  219. }
  220. /* If no symbol found return error */
  221. return lval_err("Unbound Symbol '%s'", k->sym);
  222. }
  223. void lenv_put(lenv* e, lval* k, lval* v) {
  224. /* Iterate over all items in environment */
  225. /* This is to see if variable already exists */
  226. for (int i = 0; i < e->count; i++) {
  227. /* If variable is found delete item at that position */
  228. /* And replace with variable supplied by user */
  229. if (strcmp(e->syms[i], k->sym) == 0) {
  230. lval_del(e->vals[i]);
  231. e->vals[i] = lval_copy(v);
  232. return;
  233. }
  234. }
  235. /* If no existing entry found allocate space for new entry */
  236. e->count++;
  237. e->vals = realloc(e->vals, sizeof(lval*) * e->count);
  238. e->syms = realloc(e->syms, sizeof(char*) * e->count);
  239. /* Copy contents of lval and symbol string into new location */
  240. e->vals[e->count-1] = lval_copy(v);
  241. e->syms[e->count-1] = malloc(strlen(k->sym)+1);
  242. strcpy(e->syms[e->count-1], k->sym);
  243. }
  244. /* Builtins */
  245. #define LASSERT(args, cond, fmt, ...) \
  246. if (!(cond)) { lval* err = lval_err(fmt, ##__VA_ARGS__); lval_del(args); return err; }
  247. #define LASSERT_TYPE(func, args, index, expect) \
  248. LASSERT(args, args->cell[index]->type == expect, \
  249. "Function '%s' passed incorrect type for argument %i. Got %s, Expected %s.", \
  250. func, index, ltype_name(args->cell[index]->type), ltype_name(expect))
  251. #define LASSERT_NUM(func, args, num) \
  252. LASSERT(args, args->count == num, \
  253. "Function '%s' passed incorrect number of arguments. Got %i, Expected %i.", \
  254. func, args->count, num)
  255. #define LASSERT_NOT_EMPTY(func, args, index) \
  256. LASSERT(args, args->cell[index]->count != 0, \
  257. "Function '%s' passed {} for argument %i.", func, index);
  258. lval* lval_eval(lenv* e, lval* v);
  259. lval* builtin_list(lenv* e, lval* a) {
  260. a->type = LVAL_QEXPR;
  261. return a;
  262. }
  263. lval* builtin_head(lenv* e, lval* a) {
  264. LASSERT_NUM("head", a, 1);
  265. LASSERT_TYPE("head", a, 0, LVAL_QEXPR);
  266. LASSERT_NOT_EMPTY("head", a, 0);
  267. lval* v = lval_take(a, 0);
  268. while (v->count > 1) { lval_del(lval_pop(v, 1)); }
  269. return v;
  270. }
  271. lval* builtin_tail(lenv* e, lval* a) {
  272. LASSERT_NUM("tail", a, 1);
  273. LASSERT_TYPE("tail", a, 0, LVAL_QEXPR);
  274. LASSERT_NOT_EMPTY("tail", a, 0);
  275. lval* v = lval_take(a, 0);
  276. lval_del(lval_pop(v, 0));
  277. return v;
  278. }
  279. lval* builtin_eval(lenv* e, lval* a) {
  280. LASSERT_NUM("eval", a, 1);
  281. LASSERT_TYPE("eval", a, 0, LVAL_QEXPR);
  282. lval* x = lval_take(a, 0);
  283. x->type = LVAL_SEXPR;
  284. return lval_eval(e, x);
  285. }
  286. lval* builtin_join(lenv* e, lval* a) {
  287. for (int i = 0; i < a->count; i++) {
  288. LASSERT_TYPE("join", a, i, LVAL_QEXPR);
  289. }
  290. lval* x = lval_pop(a, 0);
  291. while (a->count) {
  292. lval* y = lval_pop(a, 0);
  293. x = lval_join(x, y);
  294. }
  295. lval_del(a);
  296. return x;
  297. }
  298. lval* builtin_op(lenv* e, lval* a, char* op) {
  299. for (int i = 0; i < a->count; i++) {
  300. LASSERT_TYPE(op, a, i, LVAL_NUM);
  301. }
  302. lval* x = lval_pop(a, 0);
  303. if ((strcmp(op, "-") == 0) && a->count == 0) {
  304. x->num = -x->num;
  305. }
  306. while (a->count > 0) {
  307. lval* y = lval_pop(a, 0);
  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 (y->num == 0) {
  313. lval_del(x); lval_del(y);
  314. x = lval_err("Division By Zero.");
  315. break;
  316. }
  317. x->num /= y->num;
  318. }
  319. lval_del(y);
  320. }
  321. lval_del(a);
  322. return x;
  323. }
  324. lval* builtin_add(lenv* e, lval* a) {
  325. return builtin_op(e, a, "+");
  326. }
  327. lval* builtin_sub(lenv* e, lval* a) {
  328. return builtin_op(e, a, "-");
  329. }
  330. lval* builtin_mul(lenv* e, lval* a) {
  331. return builtin_op(e, a, "*");
  332. }
  333. lval* builtin_div(lenv* e, lval* a) {
  334. return builtin_op(e, a, "/");
  335. }
  336. lval* builtin_def(lenv* e, lval* a) {
  337. LASSERT_TYPE("def", a, 0, LVAL_QEXPR);
  338. /* First argument is symbol list */
  339. lval* syms = a->cell[0];
  340. /* Ensure all elements of first list are symbols */
  341. for (int i = 0; i < syms->count; i++) {
  342. LASSERT(a, (syms->cell[i]->type == LVAL_SYM),
  343. "Function 'def' cannot define non-symbol. "
  344. "Got %s, Expected %s.",
  345. ltype_name(syms->cell[i]->type), ltype_name(LVAL_SYM));
  346. }
  347. /* Check correct number of symbols and values */
  348. LASSERT(a, (syms->count == a->count-1),
  349. "Function 'def' passed too many arguments for symbols. "
  350. "Got %i, Expected %i.",
  351. syms->count, a->count-1);
  352. /* Assign copies of values to symbols */
  353. for (int i = 0; i < syms->count; i++) {
  354. lenv_put(e, syms->cell[i], a->cell[i+1]);
  355. }
  356. lval_del(a);
  357. return lval_sexpr();
  358. }
  359. void lenv_add_builtin(lenv* e, char* name, lbuiltin func) {
  360. lval* k = lval_sym(name);
  361. lval* v = lval_fun(func);
  362. lenv_put(e, k, v);
  363. lval_del(k); lval_del(v);
  364. }
  365. void lenv_add_builtins(lenv* e) {
  366. /* Variable Functions */
  367. lenv_add_builtin(e, "def", builtin_def);
  368. /* List Functions */
  369. lenv_add_builtin(e, "list", builtin_list);
  370. lenv_add_builtin(e, "head", builtin_head);
  371. lenv_add_builtin(e, "tail", builtin_tail);
  372. lenv_add_builtin(e, "eval", builtin_eval);
  373. lenv_add_builtin(e, "join", builtin_join);
  374. /* Mathematical Functions */
  375. lenv_add_builtin(e, "+", builtin_add);
  376. lenv_add_builtin(e, "-", builtin_sub);
  377. lenv_add_builtin(e, "*", builtin_mul);
  378. lenv_add_builtin(e, "/", builtin_div);
  379. }
  380. /* Evaluation */
  381. lval* lval_eval_sexpr(lenv* e, lval* v) {
  382. for (int i = 0; i < v->count; i++) {
  383. v->cell[i] = lval_eval(e, v->cell[i]);
  384. }
  385. for (int i = 0; i < v->count; i++) {
  386. if (v->cell[i]->type == LVAL_ERR) { return lval_take(v, i); }
  387. }
  388. if (v->count == 0) { return v; }
  389. if (v->count == 1) { return lval_take(v, 0); }
  390. /* Ensure first element is a function after evaluation */
  391. lval* f = lval_pop(v, 0);
  392. if (f->type != LVAL_FUN) {
  393. lval* err = lval_err(
  394. "S-Expression starts with incorrect type. "
  395. "Got %s, Expected %s.",
  396. ltype_name(f->type), ltype_name(LVAL_FUN));
  397. lval_del(f); lval_del(v);
  398. return err;
  399. }
  400. /* If so call function to get result */
  401. lval* result = f->fun(e, v);
  402. lval_del(f);
  403. return result;
  404. }
  405. lval* lval_eval(lenv* e, lval* v) {
  406. if (v->type == LVAL_SYM) {
  407. lval* x = lenv_get(e, v);
  408. lval_del(v);
  409. return x;
  410. }
  411. if (v->type == LVAL_SEXPR) { return lval_eval_sexpr(e, v); }
  412. return v;
  413. }
  414. /* Reading */
  415. lval* lval_read_num(mpc_ast_t* t) {
  416. errno = 0;
  417. long x = strtol(t->contents, NULL, 10);
  418. return errno != ERANGE ? lval_num(x) : lval_err("Invalid Number.");
  419. }
  420. lval* lval_read(mpc_ast_t* t) {
  421. if (strstr(t->tag, "number")) { return lval_read_num(t); }
  422. if (strstr(t->tag, "symbol")) { return lval_sym(t->contents); }
  423. lval* x = NULL;
  424. if (strcmp(t->tag, ">") == 0) { x = lval_sexpr(); }
  425. if (strstr(t->tag, "sexpr")) { x = lval_sexpr(); }
  426. if (strstr(t->tag, "qexpr")) { x = lval_qexpr(); }
  427. for (int i = 0; i < t->children_num; i++) {
  428. if (strcmp(t->children[i]->contents, "(") == 0) { continue; }
  429. if (strcmp(t->children[i]->contents, ")") == 0) { continue; }
  430. if (strcmp(t->children[i]->contents, "}") == 0) { continue; }
  431. if (strcmp(t->children[i]->contents, "{") == 0) { continue; }
  432. if (strcmp(t->children[i]->tag, "regex") == 0) { continue; }
  433. x = lval_add(x, lval_read(t->children[i]));
  434. }
  435. return x;
  436. }
  437. /* Main */
  438. int main(int argc, char** argv) {
  439. mpc_parser_t* Number = mpc_new("number");
  440. mpc_parser_t* Symbol = mpc_new("symbol");
  441. mpc_parser_t* Sexpr = mpc_new("sexpr");
  442. mpc_parser_t* Qexpr = mpc_new("qexpr");
  443. mpc_parser_t* Expr = mpc_new("expr");
  444. mpc_parser_t* Lispy = mpc_new("lispy");
  445. mpca_lang(MPCA_LANG_DEFAULT,
  446. " \
  447. number : /-?[0-9]+/ ; \
  448. symbol : /[a-zA-Z0-9_+\\-*\\/\\\\=<>!&]+/ ; \
  449. sexpr : '(' <expr>* ')' ; \
  450. qexpr : '{' <expr>* '}' ; \
  451. expr : <number> | <symbol> | <sexpr> | <qexpr> ; \
  452. lispy : /^/ <expr>* /$/ ; \
  453. ",
  454. Number, Symbol, Sexpr, Qexpr, Expr, Lispy);
  455. puts("Lispy Version 0.0.0.0.7");
  456. puts("Press Ctrl+c to Exit\n");
  457. lenv* e = lenv_new();
  458. lenv_add_builtins(e);
  459. while (1) {
  460. char* input = readline("lispy> ");
  461. add_history(input);
  462. mpc_result_t r;
  463. if (mpc_parse("<stdin>", input, Lispy, &r)) {
  464. lval* x = lval_eval(e, lval_read(r.output));
  465. lval_println(x);
  466. lval_del(x);
  467. mpc_ast_delete(r.output);
  468. } else {
  469. mpc_err_print(r.error);
  470. mpc_err_delete(r.error);
  471. }
  472. free(input);
  473. }
  474. lenv_del(e);
  475. mpc_cleanup(6, Number, Symbol, Sexpr, Qexpr, Expr, Lispy);
  476. return 0;
  477. }

{% endcollapse %}