🛰️航天仿真算法库 SpaceAST 0.0.1
载入中...
搜索中...
未找到
IdentifierTable.hpp
浏览该文件的文档.
1
20
21#pragma once
22
23#include "AstGlobal.h"
24#include "Identifier.hpp"
25#include <vector>
26#include <mutex>
27#include <algorithm>
28#include <unordered_map> // for std::unordered_map
29#include <memory> // for std::unique_ptr
30
31AST_NAMESPACE_BEGIN
32
33// #define _AST_ENABLE_IDENTIFIER_TABLE_MUTEX
34
35
37private:
38 // 使用哈希表存储符号
39 std::unordered_multimap<size_t, std::unique_ptr<Identifier>> table_;
40#ifdef _AST_ENABLE_IDENTIFIER_TABLE_MUTEX
41 mutable std::mutex mutex_;
42#endif
43
44 // 计算字符串的哈希值(DJB2哈希算法)
45 size_t compute_hash(const char* data, size_t length) const {
46 return Identifier::hash(data, length);
47 }
48
49public:
50 // 查找或创建符号
51 Identifier* intern(const char* data, size_t length) {
52 size_t hash = compute_hash(data, length);
53
54#ifdef _AST_ENABLE_IDENTIFIER_TABLE_MUTEX
55 std::lock_guard<std::mutex> lock(mutex_);
56#endif
57 // 查找现有符号
58 auto range = table_.equal_range(hash);
59 for (auto it = range.first; it != range.second; ++it) {
60 Identifier* sym = it->second.get();
61 if (sym->length() == length &&
62 memcmp(sym->data(), data, length) == 0) {
63 return sym; // 返回现有符号
64 }
65 // ++it;
66 }
67
68 // 创建新符号
69 size_t alloc_size = sizeof(Identifier) + length;
70 char* memory = new char[alloc_size];
71 Identifier* sym = new (memory) Identifier(static_cast<uint32_t>(length));
72 memcpy(sym->data(), data, length);
73 sym->data()[length] = '\0';
74
75 table_.emplace(hash, std::unique_ptr<Identifier>(sym));
76 return sym;
77 }
78
79 // 重载版本,接受C字符串
80 Identifier* intern(const char* str) {
81 return intern(str, strlen(str));
82 }
83
84 // 重载版本,接受std::string
85 Identifier* intern(const std::string& str) {
86 return intern(str.c_str(), str.length());
87 }
88
89 // 查找符号(不创建)
90 Identifier* lookup(const char* data, size_t length) const {
91 size_t hash = compute_hash(data, length);
92
93#ifdef _AST_ENABLE_IDENTIFIER_TABLE_MUTEX
94 std::lock_guard<std::mutex> lock(mutex_);
95#endif
96 auto range = table_.equal_range(hash);
97
98 for (auto it = range.first; it != range.second; ++it) {
99 Identifier* sym = it->second.get();
100 if (sym->length() == length &&
101 memcmp(sym->data(), data, length) == 0) {
102 return sym;
103 }
104 }
105
106 return nullptr;
107 }
108
109 // 获取符号数量
110 size_t size() const {
111#ifdef _AST_ENABLE_IDENTIFIER_TABLE_MUTEX
112 std::lock_guard<std::mutex> lock(mutex_);
113#endif
114 return table_.size();
115 }
116
117 // 清理符号表(移除所有符号)
118 void clear() {
119#ifdef _AST_ENABLE_IDENTIFIER_TABLE_MUTEX
120 std::lock_guard<std::mutex> lock(mutex_);
121#endif
122 table_.clear();
123 }
124};
125
126
127AST_NAMESPACE_END
定义 IdentifierTable.hpp:36
标识符类
定义 Identifier.hpp:37