Initial commit
This commit is contained in:
commit
b2edca2cb4
25 changed files with 3590 additions and 0 deletions
86
main.c
Normal file
86
main.c
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "common.h"
|
||||
#include "chunk.h"
|
||||
#include "debug.h"
|
||||
#include "vm.h"
|
||||
|
||||
static void repl()
|
||||
{
|
||||
char line[1024];
|
||||
for (;;) {
|
||||
printf("> ");
|
||||
if (!fgets(line, sizeof(line), stdin)) {
|
||||
printf("\n");
|
||||
break;
|
||||
}
|
||||
|
||||
interpret(line);
|
||||
}
|
||||
}
|
||||
|
||||
static char* readFile(const char* path)
|
||||
{
|
||||
FILE* file = fopen(path, "rb");
|
||||
if (file == nullptr) {
|
||||
fprintf(stderr, "Could not open file \"%s\".\n", path);
|
||||
exit(74);
|
||||
}
|
||||
|
||||
fseek(file, 0L, SEEK_END);
|
||||
auto fileSize = ftell(file);
|
||||
if (fileSize < 0) {
|
||||
fprintf(stderr, "Could not tell file size.");
|
||||
exit(74);
|
||||
}
|
||||
rewind(file);
|
||||
|
||||
char* buffer = (char*)malloc(fileSize + 1);
|
||||
if (buffer == nullptr) {
|
||||
fprintf(stderr, "Not enough memory to read \"%s\".\n", path);
|
||||
exit(74);
|
||||
}
|
||||
auto bytesRead = fread(buffer, sizeof(char), fileSize, file);
|
||||
if (bytesRead < (size_t)fileSize) {
|
||||
fprintf(stderr, "Could not read file \"%s\".\n", path);
|
||||
exit(74);
|
||||
}
|
||||
|
||||
fclose(file);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
static void runFile(const char* path)
|
||||
{
|
||||
char* source = readFile(path);
|
||||
auto 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();
|
||||
|
||||
if (argc == 1) {
|
||||
repl();
|
||||
} else if (argc == 2) {
|
||||
runFile(argv[1]);
|
||||
} else {
|
||||
fprintf(stderr, "Usage: %s [path]\n", argv[0]);
|
||||
exit(64);
|
||||
}
|
||||
|
||||
freeVM();
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Loading…
Add table
Add a link
Reference in a new issue