From ecc12f6f3b3039ede67e05e24e837a2392eebb42 Mon Sep 17 00:00:00 2001 From: Jacob Signorovitch Date: Sat, 2 Nov 2024 10:31:55 -0400 Subject: [PATCH] Begin bison-based parsing. --- .gitignore | 1 + Makefile | 13 ++++++++++++- src/grammar.y | 17 +++++++++++++++++ src/include/lexer.h | 3 +++ src/lexer.c | 4 ++++ 5 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 src/grammar.y diff --git a/.gitignore b/.gitignore index 16b9a79..57274f2 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ tags *.out .cache +build/* compile_commands.json diff --git a/Makefile b/Makefile index bc39823..cafa0f1 100644 --- a/Makefile +++ b/Makefile @@ -3,8 +3,10 @@ NAME = scl TARGET = $(NAME).out SRC_DIR = src +INC_DIR = $(SRC_DIR)/include BUILD_DIR = build OBJ_DIR = $(BUILD_DIR)/obj +GRAM_DIR = $(BUILD_DIR)/grammars TEST_DIR = test TEST_BUILD_DIR = $(BUILD_DIR)/test TEST_OBJ_DIR = $(TEST_BUILD_DIR)/obj @@ -36,13 +38,22 @@ run: $(TARGET) @ echo -e "$(WHITE_BOLD)Running... $(RESETCOLOR)./$(TARGET)" @ ./$(TARGET) +# Generate grammars with bison. +grammars: $(SRC_DIR)/grammar.y + @ mkdir -p $(GRAM_DIR) + @ echo -e "$(WHITE_BOLD)Generating grammars...$(RESETCOLOR) bison $< -o$(GRAM_DIR)/grammar.tab.c -H$(GRAM_DIR)/grammar.tab.h" + @ bison $< -o$(GRAM_DIR)/grammar.tab.c -H$(GRAM_DIR)/grammar.tab.h + # Link to final binary. $(TARGET): $(OBJ_FILES) @ echo -e "$(WHITE_BOLD)Linking $(WHITE)$(TARGET)$(WHITE_BOLD)...$(RESETCOLOR) $(CC) -o $(TARGET) $(OBJ_FILES) $(LDFLAGS)" @ $(LINK) -o $(TARGET) $(OBJ_FILES) $(LDFLAGS) +# Lexer depends on grammars. +$(OBJ_DIR)/lexer.o: grammars + # Compile project sources. -$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c $(SRC_DIR)/include/%.h +$(OBJ_DIR)/%.o: $(SRC_DIR)/%.c $(INC_DIR)/%.h @ mkdir -p $(OBJ_DIR) @ echo -e "$(WHITE_BOLD)Compiling $(WHITE)$<$(WHITE_BOLD)... $(RESETCOLOR)$(CC) $(CFLAGS) -c $< -o $@" @ $(CC) $(CFLAGS) -c $< -o $@ diff --git a/src/grammar.y b/src/grammar.y new file mode 100644 index 0000000..4025133 --- /dev/null +++ b/src/grammar.y @@ -0,0 +1,17 @@ +%union { + int intval; + char* strval; +} + +%token NUM +%token CALL +%token PLUS + +%% + +exp: + NUM {} + | exp PLUS exp {} + ; + +%% diff --git a/src/include/lexer.h b/src/include/lexer.h index abfc94f..fc0ca20 100644 --- a/src/include/lexer.h +++ b/src/include/lexer.h @@ -68,4 +68,7 @@ void lexer_print_i(Lexer* lexer, int ilvl); // Print a representation of a LexerState. void lexerstate_print_raw(LexerState s); +// Interface with bison. +int yylex(); + #endif diff --git a/src/lexer.c b/src/lexer.c index 680731a..6693afc 100644 --- a/src/lexer.c +++ b/src/lexer.c @@ -143,3 +143,7 @@ void lexerstate_print_raw(LexerState s) { log_dbgf("%d is not a valid LexerState (max: %d)", s, TOKEN_TYPE_MAX); } else printf("%s", lexerstate_names[s]); } + +int yylex() { + lexer_lex() +}