Created
August 8, 2024 02:23
-
-
Save Aragami1408/906f6d53102eb8aee967b738a98869ba to your computer and use it in GitHub Desktop.
c compiler driver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <string.h> | |
#include "common.h" | |
#include "options.h" | |
#include "utils.h" | |
#include "lexer.h" | |
#include "parser.h" | |
#include "ast.h" | |
Lexer *lexer = NULL; | |
Token *tokens = NULL; | |
usize tokens_len = 0; | |
Parser *parser = NULL; | |
AST *global_ast = NULL; | |
usize asts_len = 0; | |
#ifndef NDEBUG | |
void lexer_log() { | |
if (lexer == NULL) { | |
fprintf(stderr, "The lexer hasn't been properly initialized\n"); | |
exit(1); | |
} | |
printf("LEXER DEBUG\n"); | |
printf("-----------\n"); | |
printf("Token list: \n"); | |
for (int i = 0; i < tokens_len; i++) { | |
Token token = tokens[i]; | |
print_token(&token); | |
if (token.type == TOKEN_ERROR || token.type == TOKEN_EOF) { | |
break; | |
} | |
} | |
} | |
void parser_log() { | |
printf("PARSER DEBUG\n"); | |
printf("------------\n"); | |
printf("Program(\n"); | |
for (int i = 0; i < asts_len; i++) { | |
AST ast = global_ast[i]; | |
printf("\t"); | |
ast_print(&ast); | |
printf("\n"); | |
} | |
printf("\n)"); | |
} | |
#endif | |
int main(int argc, char **argv) { | |
if (argc == 1) { | |
printf("higancc: fatal error: no input files\n"); | |
printf("compilation terminated\n"); | |
return 1; | |
} | |
Options opts = Options_parse(argc, argv); | |
const char *buffer = read_file(argv[argc-1]); | |
lexer = Lexer_init(buffer); | |
tokens = Lexer_scanTokens(lexer, &tokens_len); | |
parser = Parser_init(tokens); | |
global_ast = Parser_parse(parser, &asts_len); | |
for (int i = 0; i < tokens_len; i++) { | |
Token token = tokens[i]; | |
if (token.type == TOKEN_ERROR) { | |
fprintf(stderr, "[LEXER ERROR - line %d] %.*s\n", token.line, token.length, token.start); | |
exit(1); | |
} | |
} | |
if (opts.lexer) { | |
lexer_log(); | |
} | |
if (opts.parser) { | |
parser_log(); | |
} | |
if (opts.emit_assembly) { | |
printf("Here's the Assembly: \n"); | |
} | |
if (opts.output_file) { | |
printf("Compile to '%s'\n", opts.output_file); | |
} | |
Lexer_free(lexer); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment