#include "scanner.h" #include "parser.h" #include "expr.h" #include "interpreter.h" #include #include #include #include #include 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) { for(int i = 0; i < list->size; i++) { if (list->tokens[i]->type == EndOF) { printf("[Line %d] EOF\n", list->tokens[i]->line);\ return; } printf("[Line %d] %s\n", list->tokens[i]->line, list->tokens[i]->lexeme); } } void RunFile(const char* path) { printf("Running '%s'\n", path); char* contents = GetFileContents(path); TokenList* tokens = ScanTokens(contents); free(contents); Print(tokens); printf("TREE:\n"); Expr* tree = GenerateExpressionTree(tokens); PrintExpressionTree(tree); printf("\n"); Interpret(tree); FreeExpressionTree(tree); DestroyTokenList(tokens); } 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("> "); } }