aboutsummaryrefslogtreecommitdiffstats
path: root/clox/src/main.c
diff options
context:
space:
mode:
authorGravatar Tom Willemse2021-08-02 18:09:03 -0700
committerGravatar Tom Willemse2021-08-02 18:09:03 -0700
commitb131e343bb8a2b126a5370138d826d87d74fce30 (patch)
tree06cd5d22c8eeac088e5393199357c4e8d34eb8f6 /clox/src/main.c
parent9b60cf334cdb030759c54f700d5c122338c5b3a8 (diff)
downloadcrafting-interpreters-b131e343bb8a2b126a5370138d826d87d74fce30.tar.gz
crafting-interpreters-b131e343bb8a2b126a5370138d826d87d74fce30.zip
Chapter 16.1
Diffstat (limited to 'clox/src/main.c')
-rw-r--r--clox/src/main.c82
1 files changed, 62 insertions, 20 deletions
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 <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
#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;
}