84 lines
1.8 KiB
C
84 lines
1.8 KiB
C
#include "scanner.h"
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <sysexits.h>
|
|
#include <string.h>
|
|
#include <errno.h>
|
|
|
|
void RunFile(const char*);
|
|
void RunPrompt(void);
|
|
char* GetFileContents(const char*);
|
|
|
|
int main(int argc, char** argv) {
|
|
if (argc > 2) {
|
|
printf("Useage: clox [script]\n");
|
|
exit(EX_USAGE);
|
|
} else if (argc == 2) {
|
|
RunFile(argv[1]);
|
|
} else {
|
|
RunPrompt();
|
|
}
|
|
}
|
|
|
|
void Print(TokenList* list) {
|
|
char lexeme[100];
|
|
|
|
for(int i = 0; i < list->size; i++) {
|
|
if (list->tokens[i]->type == EndOF) {
|
|
printf("EOF\n");\
|
|
return;
|
|
}
|
|
|
|
printf("[Line %d] ", list->tokens[i]->line);
|
|
for(int j = 0; j < list->tokens[i]->length; j++) {
|
|
printf("%c", list->tokens[i]->lexeme[j]);
|
|
}
|
|
printf("\n");
|
|
}
|
|
}
|
|
|
|
void RunFile(const char* path) {
|
|
printf("Running '%s'\n", path);
|
|
char* contents = GetFileContents(path);
|
|
TokenList* tokens = ScanTokens(contents);
|
|
Print(tokens);
|
|
|
|
DestroyTokenList(tokens);
|
|
free(contents);
|
|
}
|
|
|
|
char* GetFileContents(const char* path) {
|
|
FILE *script = fopen(path, "r");
|
|
|
|
if (!script) {
|
|
fprintf(stderr, "Failed to open script '%s'. %s.\n", path, strerror(errno));
|
|
return NULL;
|
|
}
|
|
|
|
size_t length;
|
|
char* content = NULL;
|
|
|
|
size_t bytes_read = getdelim(&content, &length, '\0', script);
|
|
|
|
fclose(script);
|
|
|
|
if (bytes_read < 0) {
|
|
fprintf(stderr, "Failed to read '%s'. %s.\n", path, strerror(errno));
|
|
return NULL;
|
|
}
|
|
|
|
return content;
|
|
}
|
|
|
|
void RunPrompt(void) {
|
|
printf("> ");
|
|
char input[256];
|
|
|
|
while(fgets(input, sizeof input, stdin) != NULL) {
|
|
if (strcmp(input, "q\n") == 0) break;
|
|
|
|
printf("E_NOT_IMPLEMENTED\n");
|
|
|
|
printf("> ");
|
|
}
|
|
} |