main.c (1669B)
1 #include <stdint.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <string.h> 5 6 #include "file.h" 7 #include "utils.h" 8 #include "lexer.h" 9 #include "parser.h" 10 #include "sem.h" 11 #include "gen.h" 12 13 int 14 main(int argc, char* argv[]) 15 { 16 if (argc < 2) { 17 printf("Usage: %s <file>\n", argv[0]); 18 return 1; 19 } 20 21 const char* filename = argv[1]; 22 const char* contents = readfile(filename); 23 24 if (contents == NULL) { panic("error reading file: %s", filename); } 25 26 printf("--- lex --- \n"); 27 28 Lexer lex; 29 lexer_lex(&lex, filename, contents); 30 // lexer_print(&lex); 31 32 Parser par = parser_init(&lex); 33 34 printf("--- par --- \n"); 35 36 Ast ast; 37 parser_parse(&ast, &par); 38 // ast_print(&ast); 39 40 printf("--- sem --- \n"); 41 42 Scope program_scope = scope_init(ast.node); 43 scope_build(&program_scope, &ast); 44 scope_print(&program_scope, &ast); 45 46 printf("--- gen --- \n"); 47 48 Gen gen = gen_init(&program_scope, contents); 49 gen_next(&gen, ast.node); 50 51 gcc_jit_result* result; 52 53 /* Compile the code. */ 54 result = gcc_jit_context_compile(gen.ctx); 55 if (!result) { panic("compilation failed"); } 56 57 /* Extract the generated code from "result". */ 58 if (argv[2] != NULL && strcmp(argv[2], "--exec") == 0) { 59 printf("--- exec start --- \n"); 60 61 typedef int (*fn_type)(void); 62 fn_type starting_func = (fn_type)gcc_jit_result_get_code(result, "main"); 63 64 if (!starting_func) { 65 fprintf(stderr, "NULL gcc_jit_result_get_code\n"); 66 exit(1); 67 } 68 int main_ret = starting_func(); 69 70 printf("--- exec end: %d --- \n", main_ret); 71 } 72 73 fflush(stdout); 74 75 gcc_jit_context_compile_to_file(gen.ctx, GCC_JIT_OUTPUT_KIND_EXECUTABLE, "out"); 76 77 gcc_jit_context_release(gen.ctx); 78 gcc_jit_result_release(result); 79 }