From fbfce55d3c7e5d0b71661b3f1ff9674fba6b8618 Mon Sep 17 00:00:00 2001 From: Bad Diode Date: Sat, 9 Oct 2021 12:54:15 +0200 Subject: Add support for file interpretaion or repl --- src/bootstrap/main.c | 93 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 89 insertions(+), 4 deletions(-) (limited to 'src/bootstrap/main.c') diff --git a/src/bootstrap/main.c b/src/bootstrap/main.c index 1494378..e0012eb 100755 --- a/src/bootstrap/main.c +++ b/src/bootstrap/main.c @@ -1,4 +1,5 @@ #include +#include #include #include #include @@ -695,9 +696,16 @@ eval(Object *root) { return NULL; } -int -main(void) { - init(); +void +print_usage(void) { + printf("Usage: %s [options] \n", BIN_NAME); + printf("\n"); + printf("\t-i\tInteractive mode (REPL).\n"); + printf("\n"); +} + +void +run_repl(void) { printf("BDL REPL (Press Ctrl-C to exit)\n"); while (true) { printf(REPL_PROMPT); @@ -725,5 +733,82 @@ main(void) { printf("\n"); } } - return 0; +} + +void +run_file(char *file_name) { +#if DEBUG + printf("Executing file: %s\n", file_name); +#endif + + // Load entire file into memory. + char * src = NULL; + FILE *fd = fopen(file_name, "r"); + if (!fd) { + fprintf(stderr, "couldn't open file: %s\n", file_name); + exit(-1); + } + fseek(fd, 0, SEEK_END); + size_t file_size = ftell(fd); + fseek(fd, 0, SEEK_SET); + src = malloc(file_size + 1); + fread(src, 1, file_size, fd); + src[file_size] = '\0'; + fclose(fd); + + Tokens tokens = tokenize((StringView){.start = src, .n = file_size}); +#if DEBUG + printf("N_TOKENS: %ld\n", tokens.n); + for (size_t i = 0; i < tokens.n; i++) { + printf("\tTYPE: %3d ", tokens.start[i].type); + printf("N: %3ld ", tokens.start[i].value.n); + printf("VALUE: "); + sv_write(tokens.start[i].value); + printf("\n"); + } +#endif + while (tokens.n) { + Object *ast = parse(&tokens); + if (ast) { +#if DEBUG + printf("AST: "); + display(ast); + printf("\n"); + printf("EVAL: "); +#endif + display(eval(ast)); + printf("\n"); + } + } + + free(src); +} + +int +main(int argc, char *argv[]) { + init(); + + int option; + while ((option = getopt(argc, argv, "i")) != -1) { + switch (option) { + case 'i': { + run_repl(); + return EXIT_SUCCESS; + } break; + default: { + print_usage(); + return EXIT_FAILURE; + } break; + } + } + + if (optind != argc - 1) { + fprintf(stderr, "%s: No input file given.\n", BIN_NAME); + print_usage(); + return EXIT_FAILURE; + } + char *file_name = argv[optind]; + run_file(file_name); + + return EXIT_SUCCESS; } -- cgit v1.2.1