crafting-interpreters/clox/src/main.c

79 lines
1.4 KiB
C
Raw Normal View History

2021-08-02 18:09:03 -07:00
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
2021-07-08 02:24:24 -07:00
#include "chunk.h"
2021-07-22 01:09:11 -07:00
#include "common.h"
2021-07-08 02:24:24 -07:00
#include "debug.h"
2021-07-22 01:09:11 -07:00
#include "vm.h"
2021-08-02 18:09:03 -07:00
static void repl() {
char line[1024];
for (;;) {
printf("> ");
2021-07-08 02:24:24 -07:00
2021-08-02 18:09:03 -07:00
if (!fgets(line, sizeof(line), stdin)) {
printf("\n");
break;
}
2021-07-08 02:24:24 -07:00
2021-08-02 18:09:03 -07:00
interpret(line);
}
}
2021-07-29 23:56:42 -07:00
2021-08-02 18:09:03 -07:00
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);
}
2021-07-29 23:56:42 -07:00
2021-08-02 18:09:03 -07:00
fseek(file, 0L, SEEK_END);
size_t fileSize = ftell(file);
rewind(file);
2021-07-29 23:56:42 -07:00
2021-08-02 18:09:03 -07:00
char *buffer = (char *)malloc(fileSize + 1);
if (buffer == NULL) {
fprintf(stderr, "Not enough memory to read \"%s\".\n", path);
exit(74);
}
2021-07-29 23:56:42 -07:00
2021-08-02 18:09:03 -07:00
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();
2021-07-08 02:24:24 -07:00
2021-08-02 18:09:03 -07:00
if (argc == 1) {
repl();
} else if (argc = 2) {
runFile(argv[1]);
} else {
fprintf(stderr, "Usage: clox [path]\n");
exit(64);
}
2021-07-08 02:24:24 -07:00
2021-07-22 01:09:11 -07:00
freeVM();
2021-07-08 02:24:24 -07:00
return 0;
}