From 76fb52c60c22f1048f8ae1d84de836ffa656dfb6 Mon Sep 17 00:00:00 2001 From: overflowerror Date: Sat, 18 May 2024 11:15:03 +0200 Subject: [PATCH] feat: Includes are relative to input file --- compiler/src/main.c | 3 +++ compiler/src/preprocessor.c | 23 ++++++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/compiler/src/main.c b/compiler/src/main.c index 7e4b286..295c6e1 100644 --- a/compiler/src/main.c +++ b/compiler/src/main.c @@ -10,6 +10,8 @@ #define EXIT_ARGS_ERROR (3) +const char* input_filename = NULL; + extern FILE* yyin; extern int yyparse(void); extern int yydebug; @@ -58,6 +60,7 @@ int main(int argc, char** argv) { if (!input) { panic("fopen"); } + input_filename = argv[optind]; if (!output) { output = fopen("m.gen.bf", "w+"); diff --git a/compiler/src/preprocessor.c b/compiler/src/preprocessor.c index 8c6e57a..2b89999 100644 --- a/compiler/src/preprocessor.c +++ b/compiler/src/preprocessor.c @@ -2,6 +2,7 @@ #include #include #include +#include #include "y.tab.h" @@ -18,6 +19,8 @@ int yylex(void); extern char* yytext; extern YYSTYPE yylval; +extern const char* input_filename; + static void handle_include(void) { int token = yylex(); @@ -26,12 +29,30 @@ static void handle_include(void) { panic("preprocessor syntax error"); } - const char* filename = yylval.str; + char* input = strdup(input_filename); + char* relative_path = strdup(dirname(input)); + free(input); + + char* filename = strdup(yylval.str); + + if (filename[0] != '/') { + strbuf_t buffer = strbuf_from(relative_path); + strbuf_append_c(buffer, '/'); + strbuf_append(buffer, filename); + free(filename); + filename = strdup(buffer); + strbuf_free(buffer); + } + + free(relative_path); + FILE* file = fopen(filename, "r"); if (file == NULL) { panic("file not found"); } + free(filename); + push_file_to_yy_stack(file); }