From 2a6c809031d39fb7f3b5b89dc76b5caeb938cebe Mon Sep 17 00:00:00 2001 From: Shautvast Date: Tue, 15 Oct 2024 17:11:52 +0200 Subject: [PATCH] more C code removed --- src/scanner.cpp | 20 ++++++++++++++++---- src/scanner.hpp | 35 ----------------------------------- 2 files changed, 16 insertions(+), 39 deletions(-) diff --git a/src/scanner.cpp b/src/scanner.cpp index 2cd497d..26a37bf 100644 --- a/src/scanner.cpp +++ b/src/scanner.cpp @@ -3,8 +3,20 @@ #include #include #include +#include #include +static const std::map keywords = { + {"and", Token::Type::AND}, {"class", Token::Type::CLASS}, + {"else", Token::Type::ELSE}, {"false", Token::Type::FALSE}, + {"for", Token::Type::FOR}, {"fun", Token::Type::FUN}, + {"if", Token::Type::IF}, {"nil", Token::Type::NIL}, + {"or", Token::Type::OR}, {"print", Token::Type::PRINT}, + {"return", Token::Type::RETURN}, {"super", Token::Type::SUPER}, + {"this", Token::Type::THIS}, {"true", Token::Type::TRUE}, + {"var", Token::Type::VAR}, {"while", Token::Type::WHILE}, +}; + Scanner::Scanner(std::string s) : had_error(false), current_pos(0), start(0), current_line(1), source(s), token_list(std::list()) {} @@ -117,11 +129,11 @@ void Scanner::identifier() { std::string text = source.substr(start + 1, current_pos - start); - const Token::Type *tokentype = get_keyword_token(text); - if (tokentype == NULL) { - add_token(Token::Type::IDENTIFIER); + auto it = keywords.find(text); + if (it != keywords.end()) { + add_token(it->second); } else { - add_token(*tokentype); + add_token(Token::Type::IDENTIFIER); } } diff --git a/src/scanner.hpp b/src/scanner.hpp index f4d27a8..bdd8690 100644 --- a/src/scanner.hpp +++ b/src/scanner.hpp @@ -39,38 +39,3 @@ public: void error(std::string message); void report(std::string where, std::string message); }; - -typedef struct { - const std::string key; - const Token::Type value; -} Item; - -static const Item keywords[] = { - {"and", Token::Type::AND}, {"class", Token::Type::CLASS}, - {"else", Token::Type::ELSE}, {"false", Token::Type::FALSE}, - {"for", Token::Type::FOR}, {"fun", Token::Type::FUN}, - {"if", Token::Type::IF}, {"nil", Token::Type::NIL}, - {"or", Token::Type::OR}, {"print", Token::Type::PRINT}, - {"return", Token::Type::RETURN}, {"super", Token::Type::SUPER}, - {"this", Token::Type::THIS}, {"true", Token::Type::TRUE}, - {"var", Token::Type::VAR}, {"while", Token::Type::WHILE}}; - -inline static const Token::Type *get_keyword_token(std::string key) { - int low = 0; - int high = sizeof(keywords) / sizeof(Item); - - while (low < high) { - int mid = (low + high) / 2; - - int c = keywords[mid].key.compare(key); - if (c == 0) { - return &keywords[mid].value; - } - if (c < 0) { - low = mid + 1; - } else { - high = mid; - } - } - return NULL; -}