main.c (2103B)
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* contents = NULL; 22 const char* filename = NULL; 23 const char* flag = NULL; 24 25 filename = argv[1]; 26 switch (argc) { 27 case 2: 28 filename = argv[1]; 29 break; 30 case 3: 31 // --quiet, --exec 32 flag = argv[1]; 33 filename = argv[2]; 34 break; 35 36 default: 37 panic("unsupported arguments"); 38 } 39 40 contents = readfile(filename); 41 42 bool quiet_flag = flag == NULL ? false : (strcmp(flag, "--quiet") == 0); 43 bool exec_flag = flag == NULL ? false : (strcmp(flag, "--exec") == 0); 44 45 if (contents == NULL) { panic("error reading file: %s", filename); } 46 47 printf("--- lex --- \n"); 48 49 Lexer lex; 50 lexer_lex(&lex, filename, contents); 51 // lexer_print(&lex); 52 53 Parser par = parser_init(&lex); 54 55 printf("--- par --- \n"); 56 57 Ast ast; 58 parser_parse(&ast, &par); 59 ast_print(&ast); 60 61 printf("--- sem --- \n"); 62 63 Scope program_scope = scope_init(ast.node); 64 scope_program(&program_scope, &ast); 65 scope_print(&program_scope, &ast); 66 67 printf("--- gen --- \n"); 68 69 Gen gen = gen_init(&program_scope, contents, ast.node, quiet_flag); 70 gen_next(&gen, ast.node); 71 72 gcc_jit_result* result; 73 74 /* Compile the code. */ 75 result = gcc_jit_context_compile(gen.ctx); 76 if (!result) { panic("compilation failed"); } 77 78 /* Extract the generated code from "result". */ 79 if (exec_flag) { 80 printf("--- exec start --- \n"); 81 82 typedef int (*fn_type)(void); 83 fn_type starting_func = (fn_type)gcc_jit_result_get_code(result, "main"); 84 85 if (!starting_func) { 86 fprintf(stderr, "NULL gcc_jit_result_get_code\n"); 87 exit(1); 88 } 89 starting_func(); 90 91 printf("--- exec end --- \n"); 92 } 93 94 fflush(stdout); 95 96 gcc_jit_context_set_bool_option(gen.ctx, GCC_JIT_BOOL_OPTION_DUMP_INITIAL_GIMPLE, 0); 97 gcc_jit_context_compile_to_file(gen.ctx, GCC_JIT_OUTPUT_KIND_EXECUTABLE, "out"); 98 99 gcc_jit_context_release(gen.ctx); 100 gcc_jit_result_release(result); 101 }