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

80 lines
2.3 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\" | '+' | '-' | '*' | '/' | '%' | \
  10. '^' | \"min\" | \"max\" ; \
  11. sexpr : '(' <expr>* ')' ; \
  12. qexpr : '{' <expr>* '}' ; \
  13. expr : <number> | <symbol> | <sexpr> | <qexpr>; \
  14. lispy : /^/ <expr>* /$/ ; \
  15. ";
  16. /* Declare new lval struct */
  17. typedef struct lval {
  18. int type;
  19. /* only one of the two number/decimal is valid in a
  20. lval instance, so we can use an anonymous union */
  21. union {
  22. long num;
  23. double dec;
  24. };
  25. /* Error & symbol types have some string data */
  26. char* err;
  27. char* sym;
  28. /* Counter & pointer to a list of lval */
  29. size_t count;
  30. struct lval** cell;
  31. } lval;
  32. /* Create enumeration of possible lval types */
  33. enum lval_types {LVAL_NUM, LVAL_DEC, LVAL_SYM, LVAL_SEXPR,
  34. LVAL_QEXPR, LVAL_ERR};
  35. /* lval constructor functions */
  36. lval* lval_num(long x);
  37. lval* lval_dec(double x);
  38. lval* lval_err(char* m);
  39. lval* lval_sym(char* s);
  40. lval* lval_sexpr(void);
  41. lval* lval_qexpr(void);
  42. /* lval destructor function */
  43. void lval_del(lval* v);
  44. /* lval manipulating functions */
  45. lval* lval_add(lval* v, lval* x);
  46. lval* lval_pop(lval* v, size_t i);
  47. lval* lval_take(lval* v, size_t i);
  48. lval* lval_read_num(mpc_ast_t* t);
  49. lval* lval_read(mpc_ast_t* t);
  50. lval* lval_eval_sexpr(lval* v);
  51. lval* lval_eval(lval* v);
  52. /* lval print functions */
  53. void lval_expr_print(lval* v, char open, char close);
  54. void lval_print(lval* v);
  55. void lval_println(lval* v);
  56. /* language built-in operators and functions */
  57. long min(long x, long y);
  58. long max(long x, long y);
  59. lval* builtin(lval* a, char* func);
  60. lval* builtin_op(lval* a, char* op);
  61. lval* builtin_head(lval* a);
  62. lval* builtin_tail(lval* a);
  63. lval* builtin_list(lval* a);
  64. lval* builtin_eval(lval* a);
  65. lval* builtin_join(lval* a);
  66. lval* lval_join(lval* x, lval* y);