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

84 lines
2.4 KiB

  1. #define LASSERT(args, cond, err) \
  2. if (!(cond)) { lval_del(args); return lval_err(err); }
  3. static char* lispy_version = "Lispy version 0.0.0.0.6";
  4. /* Parser language defintion */
  5. static char* parser =
  6. " \
  7. number : /-?[0-9]+([.][0-9]*|[0-9]*)/ ; \
  8. symbol : \"list\" | \"head\" | \"tail\" | \"join\" | \
  9. \"eval\" | \"len\" | \"init\" | \"cons\" | \
  10. '+' | '-' | '*' | '/' | '%' | \
  11. '^' | \"min\" | \"max\" ; \
  12. sexpr : '(' <expr>* ')' ; \
  13. qexpr : '{' <expr>* '}' ; \
  14. expr : <number> | <symbol> | <sexpr> | <qexpr>; \
  15. lispy : /^/ <expr>* /$/ ; \
  16. ";
  17. /* Declare new lval struct */
  18. typedef struct lval {
  19. int type;
  20. /* only one of the two number/decimal is valid in a
  21. lval instance, so we can use an anonymous union */
  22. union {
  23. long num;
  24. double dec;
  25. };
  26. /* Error & symbol types have some string data */
  27. char* err;
  28. char* sym;
  29. /* Counter & pointer to a list of lval */
  30. size_t count;
  31. struct lval** cell;
  32. } lval;
  33. /* Create enumeration of possible lval types */
  34. enum lval_types {LVAL_NUM, LVAL_DEC, LVAL_SYM, LVAL_SEXPR,
  35. LVAL_QEXPR, LVAL_ERR};
  36. /* lval constructor functions */
  37. lval* lval_num(long x);
  38. lval* lval_dec(double x);
  39. lval* lval_err(char* m);
  40. lval* lval_sym(char* s);
  41. lval* lval_sexpr(void);
  42. lval* lval_qexpr(void);
  43. /* lval destructor function */
  44. void lval_del(lval* v);
  45. /* lval manipulating functions */
  46. lval* lval_add(lval* v, lval* x);
  47. lval* lval_pop(lval* v, size_t i);
  48. lval* lval_take(lval* v, size_t i);
  49. lval* lval_read_num(mpc_ast_t* t);
  50. lval* lval_read(mpc_ast_t* t);
  51. lval* lval_eval_sexpr(lval* v);
  52. lval* lval_eval(lval* v);
  53. /* lval print functions */
  54. void lval_expr_print(lval* v, char open, char close);
  55. void lval_print(lval* v);
  56. void lval_println(lval* v);
  57. /* language built-in operators and functions */
  58. long min(long x, long y);
  59. long max(long x, long y);
  60. lval* builtin(lval* a, char* func);
  61. lval* builtin_op(lval* a, char* op);
  62. lval* builtin_head(lval* a);
  63. lval* builtin_tail(lval* a);
  64. lval* builtin_list(lval* a);
  65. lval* builtin_eval(lval* a);
  66. lval* builtin_join(lval* a);
  67. lval* lval_join(lval* x, lval* y);
  68. lval* builtin_cons(lval* a);
  69. lval* builtin_len(lval* a);
  70. lval* builtin_init(lval* a);