From 84abd5e5ebb5cbb8f354ec32d7a9638b4bae8efb Mon Sep 17 00:00:00 2001 From: tmeissner Date: Thu, 2 May 2019 20:17:08 +0200 Subject: [PATCH] Add chapter 6 --- chapter_06/Makefile | 13 +++++++ chapter_06/parsing.c | 84 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 97 insertions(+) create mode 100644 chapter_06/Makefile create mode 100644 chapter_06/parsing.c diff --git a/chapter_06/Makefile b/chapter_06/Makefile new file mode 100644 index 0000000..2a86146 --- /dev/null +++ b/chapter_06/Makefile @@ -0,0 +1,13 @@ +MPC_DIR := ../mpc + + +all: parsing + + +%: %.c + cc -std=c11 -Wall $@.c ${MPC_DIR}/mpc.c -ledit -o $@ + + +.PHONY: clean +clean: + rm -rf parsing diff --git a/chapter_06/parsing.c b/chapter_06/parsing.c new file mode 100644 index 0000000..e14848e --- /dev/null +++ b/chapter_06/parsing.c @@ -0,0 +1,84 @@ +#include +#include +#include "../mpc/mpc.h" + + +/* If we are on Windows compile these functions */ +#ifdef _WIN32 +#include +#include + +static char buffer[2048]; + +/* Fake readline function */ +char* readline(char* prompt) { + fputs(prompt, stdout); + fgets(buffer, 2048, stdin); + char* cpy = malloc(strlen(buffer)+1); + assert(cpy != NULL) + strcpy(cpy, buffer); + cpy[strlen(cpy)-1] = '\0'; + return cpy; +} + +/* Fake add_history function */ +void add_history(char* unused) {} + +/* Otherwise include the editline headers + could use __APPLE__ for detection of OSX */ +#else +#include +#endif + + +int main(int argc, char const *argv[]) +{ + /* Create some parsers */ + mpc_parser_t* Number = mpc_new("number"); + mpc_parser_t* Operator = mpc_new("operator"); + mpc_parser_t* Expr = mpc_new("expr"); + mpc_parser_t* Lispy = mpc_new("lispy"); + + /* Define them with the following language */ + mpca_lang(MPCA_LANG_DEFAULT, + " \ + number : /-?[0-9]+/ ; \ + operator : '+' | '-' | '*' | '/' ; \ + expr : | '(' + ')' ; \ + lispy : /^/ + /$/ ; \ + ", + Number, Operator, Expr, Lispy); + + /* Print version and exit information */ + puts("Lispy version 0.0.0.0.1"); + puts("Press Ctrl+c to exit\n"); + + /* In a never ending loop */ + while (1) { + /* Output our prompt and get input */ + char* input = readline("lispy> "); + + /* Add input to history */ + add_history(input); + + /* Attempt to parse the user input */ + mpc_result_t r; + if (mpc_parse("", input, Lispy, &r)) { + /* On success print the AST */ + mpc_ast_print(r.output); + mpc_ast_delete(r.output); + } else { + /* Otherwise print the error */ + mpc_err_print(r.error); + mpc_err_delete(r.error); + } + + /* Free retrieved input */ + free(input); + } + + /* Undefine and delete our parsers */ + mpc_cleanup(4, Number, Operator, Expr, Lispy); + + return 0; +}