From 7eb80b416dd7261fb50334a53d0ad48afcd8f04f Mon Sep 17 00:00:00 2001 From: Himbeer Date: Tue, 17 Sep 2024 10:37:23 +0200 Subject: Add token kind matching lexer function This function reads the next token, compares its kind to a parameter and returns a boolean indicating whether it matched. If it did not match, the token is pushed back into the lexer for later reuse. --- include/lex.h | 1 + src/lex.c | 11 +++++++++++ 2 files changed, 12 insertions(+) diff --git a/include/lex.h b/include/lex.h index 8b1fdf2..ba1596d 100644 --- a/include/lex.h +++ b/include/lex.h @@ -124,5 +124,6 @@ void lex_finish(struct lexer *lexer); enum lexical_token lex(struct lexer *lexer, struct token *out); void unlex(struct lexer *lexer, const struct token *in); +bool match(struct lexer *lexer, enum lexical_token token); #endif diff --git a/src/lex.c b/src/lex.c index 80c1c5b..89d1fc6 100644 --- a/src/lex.c +++ b/src/lex.c @@ -392,3 +392,14 @@ unlex(struct lexer *lexer, const struct token *in) assert(lexer->un.token == T_NONE); lexer->un = *in; } + +bool +match(struct lexer *lexer, enum lexical_token token) +{ + struct token tmp; + enum lexical_token kind = lex(lexer, &tmp); + if (kind != token) { + unlex(lexer, &tmp); + } + return kind == token; +} -- cgit v1.2.3