参考

{% collapse title=”parsing.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. int main(int argc, char** argv) {
  18. /* Create Some Parsers */
  19. mpc_parser_t* Number = mpc_new("number");
  20. mpc_parser_t* Operator = mpc_new("operator");
  21. mpc_parser_t* Expr = mpc_new("expr");
  22. mpc_parser_t* Lispy = mpc_new("lispy");
  23. /* Define them with the following Language */
  24. mpca_lang(MPCA_LANG_DEFAULT,
  25. " \
  26. number : /-?[0-9]+/ ; \
  27. operator : '+' | '-' | '*' | '/' ; \
  28. expr : <number> | '(' <operator> <expr>+ ')' ; \
  29. lispy : /^/ <operator> <expr>+ /$/ ; \
  30. ",
  31. Number, Operator, Expr, Lispy);
  32. puts("Lispy Version 0.0.0.0.2");
  33. puts("Press Ctrl+c to Exit\n");
  34. while (1) {
  35. char* input = readline("lispy> ");
  36. add_history(input);
  37. /* Attempt to parse the user input */
  38. mpc_result_t r;
  39. if (mpc_parse("<stdin>", input, Lispy, &r)) {
  40. /* On success print and delete the AST */
  41. mpc_ast_print(r.output);
  42. mpc_ast_delete(r.output);
  43. } else {
  44. /* Otherwise print and delete the Error */
  45. mpc_err_print(r.error);
  46. mpc_err_delete(r.error);
  47. }
  48. free(input);
  49. }
  50. /* Undefine and delete our parsers */
  51. mpc_cleanup(4, Number, Operator, Expr, Lispy);
  52. return 0;
  53. }

{% endcollapse %}