diff --git a/src/Scanner.cpp b/src/Scanner.cpp index 7387059..fd290c6 100644 --- a/src/Scanner.cpp +++ b/src/Scanner.cpp @@ -1,5 +1,6 @@ #include "Scanner.h" #include +#include int Scanner::process_const_table(int index) { return 0; @@ -34,7 +35,45 @@ int Scanner::process_identifier_table(int index) { } int Scanner::process_key_table(int index) { - return 0; + int max_len = 0; + int found_key = -1; // 存储找到的关键字编号 + + // 遍历关键字表 + for (const auto& pair : m_tables.KeyTable) { + const std::string& keyword = pair.second; + int len = keyword.length(); + + // 检查剩余长度是否足够 + if (index + len > m_source_code.length()) { + continue; + } + + // 比较子串是否匹配关键字 + if (m_source_code.substr(index, len) == keyword) { + // 检查关键字后是否紧跟字母/数字/下划线 + if (index + len < m_source_code.length()) { + char next_char = m_source_code[index + len]; + if (isalnum(next_char) || next_char == '_') { + continue; // 是标识符的一部分,跳过 + } + } + + // 更新最长匹配(解决"float32"和"float64"的冲突) + if (len > max_len) { + max_len = len; + found_key = pair.first; + } + } + } + + // 找到有效关键字 + if (max_len > 0) { + Token token({ found_key, KEY_TABLE }); + m_token_list.push_back(token); + return max_len; + } + + return 0; // 未识别到关键字 } int Scanner::process_punct_table(int index) { diff --git a/unit/scanner_test.cpp b/unit/scanner_test.cpp index 1246e77..47e7119 100644 --- a/unit/scanner_test.cpp +++ b/unit/scanner_test.cpp @@ -5,7 +5,7 @@ #include "Tbs.h" #include using std::string,std::vector; - +// TEST_CASE("Scanner test identifier table") { Tbs tables; std::string src = "abcvljl laadfs fafarwrw"; @@ -27,4 +27,15 @@ TEST_CASE("Scanner test Punct table") { for (auto e : scan.get_token_list()) { std::cout<