From b131e343bb8a2b126a5370138d826d87d74fce30 Mon Sep 17 00:00:00 2001 From: Tom Willemse Date: Mon, 2 Aug 2021 18:09:03 -0700 Subject: Chapter 16.1 --- clox/src/main.c | 82 +++++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 62 insertions(+), 20 deletions(-) (limited to 'clox/src/main.c') diff --git a/clox/src/main.c b/clox/src/main.c index d1e747f..c95c7ba 100644 --- a/clox/src/main.c +++ b/clox/src/main.c @@ -1,36 +1,78 @@ +#include +#include +#include + #include "chunk.h" #include "common.h" #include "debug.h" #include "vm.h" -int main(int argc, const char *argv[]) { - initVM(); +static void repl() { + char line[1024]; + for (;;) { + printf("> "); - Chunk chunk; - initChunk(&chunk); + if (!fgets(line, sizeof(line), stdin)) { + printf("\n"); + break; + } - int constant = addConstant(&chunk, 1.2); - writeChunk(&chunk, OP_CONSTANT, 123); - writeChunk(&chunk, constant, 123); + interpret(line); + } +} - constant = addConstant(&chunk, 3.4); - writeChunk(&chunk, OP_CONSTANT, 123); - writeChunk(&chunk, constant, 123); +static char *readFile(const char *path) { + FILE *file = fopen(path, "rb"); + if (file == NULL) { + fprintf(stderr, "Could not open file \"%s\".\n", path); + exit(74); + } - writeChunk(&chunk, OP_ADD, 123); + fseek(file, 0L, SEEK_END); + size_t fileSize = ftell(file); + rewind(file); - constant = addConstant(&chunk, 5.6); - writeChunk(&chunk, OP_CONSTANT, 123); - writeChunk(&chunk, constant, 123); + char *buffer = (char *)malloc(fileSize + 1); + if (buffer == NULL) { + fprintf(stderr, "Not enough memory to read \"%s\".\n", path); + exit(74); + } - writeChunk(&chunk, OP_DIVIDE, 123); - writeChunk(&chunk, OP_NEGATE, 123); + size_t bytesRead = fread(buffer, sizeof(char), fileSize, file); + if (bytesRead < fileSize) { + fprintf(stderr, "Could not read file \"%s\".\n", path); + exit(74); + } + + buffer[bytesRead] = '\0'; + + fclose(file); + return buffer; +} + +static void runFile(const char *path) { + char *source = readFile(path); + InterpretResult result = interpret(source); + free(source); + + if (result == INTERPRET_COMPILE_ERROR) + exit(65); + if (result == INTERPRET_RUNTIME_ERROR) + exit(70); +} + +int main(int argc, const char *argv[]) { + initVM(); - writeChunk(&chunk, OP_RETURN, 123); + if (argc == 1) { + repl(); + } else if (argc = 2) { + runFile(argv[1]); + } else { + fprintf(stderr, "Usage: clox [path]\n"); + exit(64); + } - disassembleChunk(&chunk, "test chunk"); - interpret(&chunk); freeVM(); - freeChunk(&chunk); return 0; } -- cgit v1.2.3-54-g00ecf