From 70f6d61cca2bad85f817e4079dfaf380f820d585 Mon Sep 17 00:00:00 2001 From: Bob Nystrom Date: Thu, 31 Oct 2013 22:25:00 -0700 Subject: [PATCH] Start hacking in a REPL. --- src/main.c | 44 +++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 41 insertions(+), 3 deletions(-) diff --git a/src/main.c b/src/main.c index 37ba26e2..7b9bb4c8 100644 --- a/src/main.c +++ b/src/main.c @@ -1,10 +1,14 @@ #include #include #include +#include #include "compiler.h" #include "vm.h" +// TODO(bob): Don't hardcode this. +#define MAX_LINE 1024 + void failIf(int condition, int exitCode, const char* format, ...) { if (!condition) return; @@ -39,11 +43,10 @@ char* readFile(const char* path, size_t* length) return buffer; } -int main(int argc, const char * argv[]) +int runFile(const char* path) { - // TODO(bob): Validate command line arguments. size_t length; - char* source = readFile(argv[1], &length); + char* source = readFile(path, &length); VM* vm = newVM(); ObjBlock* block = compile(vm, source, length); @@ -62,3 +65,38 @@ int main(int argc, const char * argv[]) return exitCode; } + +int runRepl() +{ + VM* vm = newVM(); + + for (;;) + { + printf("> "); + char line[MAX_LINE]; + fgets(line, MAX_LINE, stdin); + // TODO(bob): Handle failure. + size_t length = strlen(line); + ObjBlock* block = compile(vm, line, length); + + if (block != NULL) + { + Value result = interpret(vm, block); + printf("= "); + printValue(result); + printf("\n"); + } + } + + freeVM(vm); + return 0; +} + +int main(int argc, const char* argv[]) +{ + if (argc == 1) return runRepl(); + if (argc == 2) return runFile(argv[1]); + + fprintf(stderr, "Usage: wren [file]"); + return 1; +}