clox/tests/01_main.c

76 lines
1.5 KiB
C
Raw Normal View History

2024-08-31 17:41:43 +00:00
#include "../include/common.h"
#include "../include/chunk.h"
#include "../include/debug.h"
2024-09-01 22:43:28 +00:00
#include "../include/vm.h"
2024-09-08 20:57:08 +00:00
#include <stdio.h>
#include <stdlib.h>
2024-08-31 17:41:43 +00:00
2024-09-08 20:57:08 +00:00
static void repl(){
char line[1024];
for(;;){
printf("_> ");
if(!fgets(line,sizeof(line),stdin)){
printf("\n");
break;
}
interpret(line);
}
}
2024-09-01 22:43:28 +00:00
2024-09-08 20:57:08 +00: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);
}
2024-09-02 22:15:41 +00:00
2024-09-08 20:57:08 +00:00
fseek(file, 0L, SEEK_END);
size_t fileSize = ftell(file);
rewind(file);
2024-09-02 22:15:41 +00:00
2024-09-08 20:57:08 +00:00
char *buffer = (char *)malloc(fileSize+1);
if(buffer == NULL){
fprintf(stderr,"Out of memory for \"%s\".\n",path);
exit(74);
}
2024-09-02 22:15:41 +00:00
2024-09-08 20:57:08 +00:00
size_t bytesRead = fread(buffer, sizeof(char), fileSize, file);
if(bytesRead < fileSize){
fprintf(stderr,"Could not read file \"%s\".\n",path);
exit(74);
}
2024-09-02 22:15:41 +00:00
2024-09-08 20:57:08 +00:00
buffer[bytesRead] = '\0';
fclose(file);
return buffer;
2024-09-02 22:15:41 +00:00
2024-09-08 20:57:08 +00:00
}
2024-08-31 17:41:43 +00:00
2024-09-08 20:57:08 +00:00
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, char *argv[]){
initVM();
2024-08-31 17:41:43 +00:00
2024-09-08 20:57:08 +00:00
if(argc == 1){
repl();
} else if(argc == 2){
runFile(argv[1]);
} else {
fprintf(stderr,"Usage: Clox [path]\n");
exit(64);
}
freeVM();
2024-08-31 17:41:43 +00:00
return 0;
}