Parsing Expressions


Because we’re now thinking in S-Expressions, and not Polish Notation we need to update our parser. The syntax for S-Expressions is simple. It is just a number of other Expressions between parentheses, where an Expression can be a Number, Operator, or other S-Expression . We can modify our existing parse rules to reflect this. We also are going to rename our operator rule to symbol. This is in anticipation of adding more operators, variables and functions later.

  1. mpc_parser_t* Number = mpc_new("number");
  2. mpc_parser_t* Symbol = mpc_new("symbol");
  3. mpc_parser_t* Sexpr = mpc_new("sexpr");
  4. mpc_parser_t* Expr = mpc_new("expr");
  5. mpc_parser_t* Lispy = mpc_new("lispy");
  6. mpca_lang(MPCA_LANG_DEFAULT,
  7. " \
  8. number : /-?[0-9]+/ ; \
  9. symbol : '+' | '-' | '*' | '/' ; \
  10. sexpr : '(' <expr>* ')' ; \
  11. expr : <number> | <symbol> | <sexpr> ; \
  12. lispy : /^/ <expr>* /$/ ; \
  13. ",
  14. Number, Symbol, Sexpr, Expr, Lispy);

We should also remember to cleanup these rules on exit.

  1. mpc_cleanup(5, Number, Symbol, Sexpr, Expr, Lispy);