diff options
author | Raghuram Subramani <raghus2247@gmail.com> | 2025-06-13 11:51:28 +0530 |
---|---|---|
committer | Raghuram Subramani <raghus2247@gmail.com> | 2025-06-13 11:51:28 +0530 |
commit | 528b1e05c982e2625aa4b30d62dbfa7a4e69f269 (patch) | |
tree | 565b789c772333af37b3cb65490359eec34ad869 | |
parent | e119cb100dadf8b3e3b6660029abf73d14cf209b (diff) |
lexer: move extract_lexeme() to its own function
-rw-r--r-- | include/lexer.h | 1 | ||||
-rw-r--r-- | src/lexer.cc | 21 |
2 files changed, 13 insertions, 9 deletions
diff --git a/include/lexer.h b/include/lexer.h index 4605142..86d1861 100644 --- a/include/lexer.h +++ b/include/lexer.h @@ -23,6 +23,7 @@ private: char peek(void); char peek_next(void); bool match(char c); + char *extract_lexeme(void); private: void string(void); diff --git a/src/lexer.cc b/src/lexer.cc index e09e187..129531d 100644 --- a/src/lexer.cc +++ b/src/lexer.cc @@ -145,13 +145,7 @@ Lexer::identifier(void) while (isalnum(peek())) advance(); - int token_length = m_current - m_start; - if (token_length == 0) - token_length++; - - char *lexeme; - asprintf(&lexeme, "%.*s", token_length, m_script + m_start); - + char *lexeme = extract_lexeme(); token_type_e type = IDENTIFIER; for (size_t i = 0; i < N_KEYWORDS; i++) { @@ -160,10 +154,11 @@ Lexer::identifier(void) } add_token(type); + free(lexeme); } -void -Lexer::add_token(token_type_e type) +char * +Lexer::extract_lexeme(void) { int token_length = m_current - m_start; if (token_length == 0) @@ -172,6 +167,14 @@ Lexer::add_token(token_type_e type) char *lexeme; asprintf(&lexeme, "%.*s", token_length, m_script + m_start); + return lexeme; +} + +void +Lexer::add_token(token_type_e type) +{ + char *lexeme = extract_lexeme(); + Token token; token.init(type, lexeme, m_line); m_tokens->add(&token); |