| 1 | /* |
| 2 | * Open Chinese Convert |
| 3 | * |
| 4 | * Copyright 2010-2026 Carbo Kuo and contributors |
| 5 | * |
| 6 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | * you may not use this file except in compliance with the License. |
| 8 | * You may obtain a copy of the License at |
| 9 | * |
| 10 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | * |
| 12 | * Unless required by applicable law or agreed to in writing, software |
| 13 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | * See the License for the specific language governing permissions and |
| 16 | * limitations under the License. |
| 17 | */ |
| 18 | |
| 19 | #include "PrefixMatch.hpp" |
| 20 | #include "Dict.hpp" |
| 21 | #include "DictGroup.hpp" |
| 22 | #include "Lexicon.hpp" |
| 23 | #include "UTF8Util.hpp" |
| 24 | |
| 25 | #include <cstdint> |
| 26 | #include <mutex> |
| 27 | #include <unordered_map> |
| 28 | #include <utility> |
| 29 | #include <vector> |
| 30 | |
| 31 | using namespace opencc; |
| 32 | |
| 33 | namespace { |
| 34 | |
| 35 | size_t Utf8CharLength(const char* str, size_t len) { |
| 36 | if (len == 0) { |
| 37 | return 0; |
| 38 | } |
| 39 | const size_t charLen = UTF8Util::NextCharLength(str); |
| 40 | return charLen <= len ? charLen : 0; |
| 41 | } |
| 42 | |
| 43 | uint32_t Utf8CharKey(const char* str, size_t charLen) { |
| 44 | uint32_t key = static_cast<uint32_t>(charLen); |
| 45 | for (size_t i = 0; i < charLen; i++) { |
| 46 | key = (key << 8) | static_cast<unsigned char>(str[i]); |
| 47 | } |
| 48 | return key; |
| 49 | } |
| 50 | |
| 51 | } // namespace |
| 52 | |
| 53 | class PrefixMatch::Tables { |
| 54 | public: |
| 55 | class Matcher; |
| 56 | std::unique_ptr<Matcher> matcher; |
| 57 | }; |
| 58 | |
| 59 | namespace { |
| 60 | |
| 61 | struct CacheEntry { |
| 62 | std::vector<std::weak_ptr<const Dict>> dicts; |
| 63 | std::weak_ptr<const PrefixMatch::Tables> tables; |
| 64 | }; |
| 65 | |
| 66 | bool SameOwner(const std::weak_ptr<const Dict>& cached, |
| 67 | const std::weak_ptr<const Dict>& current) { |
| 68 | return !cached.owner_before(current) && !current.owner_before(cached); |
| 69 | } |
| 70 | |
| 71 | bool SameDicts(const CacheEntry& cached, |
| 72 | const std::vector<std::weak_ptr<const Dict>>& current) { |
| 73 | if (cached.dicts.size() != current.size()) { |
| 74 | return false; |
| 75 | } |
| 76 | for (size_t i = 0; i < current.size(); i++) { |
| 77 | if (cached.dicts[i].expired() || !SameOwner(cached.dicts[i], current[i])) { |
| 78 | return false; |
| 79 | } |
| 80 | } |
| 81 | return true; |
| 82 | } |
| 83 | |
| 84 | bool HasExpiredDict(const CacheEntry& cached) { |
| 85 | if (cached.tables.expired()) { |
| 86 | return true; |
| 87 | } |
| 88 | for (const std::weak_ptr<const Dict>& dict : cached.dicts) { |
| 89 | if (dict.expired()) { |
| 90 | return true; |
| 91 | } |
| 92 | } |
| 93 | return false; |
| 94 | } |
| 95 | |
| 96 | void PruneExpiredPrefixMatchCache( |
| 97 | std::unordered_map<std::string, std::vector<CacheEntry>>* cache) { |
| 98 | for (std::unordered_map<std::string, std::vector<CacheEntry>>::iterator it = |
| 99 | cache->begin(); |
| 100 | it != cache->end();) { |
| 101 | std::vector<CacheEntry>& entries = it->second; |
| 102 | for (std::vector<CacheEntry>::iterator entry = entries.begin(); |
| 103 | entry != entries.end();) { |
| 104 | if (HasExpiredDict(*entry)) { |
| 105 | entry = entries.erase(entry); |
| 106 | } else { |
| 107 | ++entry; |
| 108 | } |
| 109 | } |
| 110 | if (entries.empty()) { |
| 111 | it = cache->erase(it); |
| 112 | } else { |
| 113 | ++it; |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | void Unreachable() { |
| 119 | #if defined(_MSC_VER) |
| 120 | __assume(false); |
| 121 | #elif defined(__GNUC__) || defined(__clang__) |
| 122 | __builtin_unreachable(); |
| 123 | #endif |
| 124 | } |
| 125 | |
| 126 | } // namespace |
| 127 | |
| 128 | class PrefixMatch::Tables::Matcher { |
| 129 | public: |
| 130 | struct Candidate { |
| 131 | bool hasValue = false; |
| 132 | size_t keyLength = 0; |
| 133 | const std::string* key = nullptr; |
| 134 | const std::string* value = nullptr; |
| 135 | }; |
| 136 | |
| 137 | virtual ~Matcher() {} |
| 138 | |
| 139 | virtual Candidate MatchPrefixCandidate(const char* word, |
| 140 | size_t len) const = 0; |
| 141 | }; |
| 142 | |
| 143 | class LeafMatcher : public PrefixMatch::Tables::Matcher { |
| 144 | private: |
| 145 | struct StoredCandidate { |
| 146 | bool hasValue = false; |
| 147 | size_t keyLength = 0; |
| 148 | std::string key; |
| 149 | std::string value; |
| 150 | }; |
| 151 | |
| 152 | struct Node { |
| 153 | StoredCandidate candidate; |
| 154 | std::unordered_map<uint32_t, std::unique_ptr<Node>> children; |
| 155 | }; |
| 156 | |
| 157 | public: |
| 158 | LeafMatcher() {} |
| 159 | |
| 160 | void AddDict(const DictPtr& dict) { |
| 161 | const LexiconPtr lexicon = dict->GetLexicon(); |
| 162 | for (const std::unique_ptr<DictEntry>& item : *lexicon) { |
| 163 | AddEntry(item->Key(), item->GetDefault()); |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | Candidate MatchPrefixCandidate(const char* word, size_t len) const override { |
| 168 | const Node* node = &root; |
| 169 | const StoredCandidate* matchedCandidate = nullptr; |
| 170 | for (const char* pstr = word; pstr < word + len;) { |
| 171 | const size_t remainingLength = word + len - pstr; |
| 172 | const size_t charLength = Utf8CharLength(pstr, remainingLength); |
| 173 | if (charLength == 0) { |
| 174 | break; |
| 175 | } |
| 176 | const auto child = node->children.find(Utf8CharKey(pstr, charLength)); |
| 177 | if (child == node->children.end()) { |
| 178 | break; |
| 179 | } |
| 180 | pstr += charLength; |
| 181 | node = child->second.get(); |
| 182 | if (node->candidate.hasValue && |
| 183 | (matchedCandidate == nullptr || |
| 184 | node->candidate.keyLength > matchedCandidate->keyLength)) { |
| 185 | matchedCandidate = &node->candidate; |
| 186 | } |
| 187 | } |
| 188 | if (matchedCandidate == nullptr) { |
| 189 | return Candidate{}; |
| 190 | } |
| 191 | return Candidate{true, matchedCandidate->keyLength, |
| 192 | &matchedCandidate->key, &matchedCandidate->value}; |
| 193 | } |
| 194 | |
| 195 | private: |
| 196 | void AddEntry(const std::string& key, const std::string& value) { |
| 197 | Node* node = &root; |
| 198 | for (const char* pstr = key.c_str(); *pstr != '\0';) { |
| 199 | const size_t remainingLength = key.c_str() + key.length() - pstr; |
| 200 | const size_t charLength = Utf8CharLength(pstr, remainingLength); |
| 201 | if (charLength == 0) { |
| 202 | break; |
| 203 | } |
| 204 | std::unique_ptr<Node>& child = |
| 205 | node->children[Utf8CharKey(pstr, charLength)]; |
| 206 | if (child == nullptr) { |
| 207 | child.reset(new Node); |
| 208 | } |
| 209 | node = child.get(); |
| 210 | pstr += charLength; |
| 211 | } |
| 212 | if (!node->candidate.hasValue) { |
| 213 | node->candidate.hasValue = true; |
| 214 | node->candidate.keyLength = key.length(); |
| 215 | node->candidate.key = key; |
| 216 | node->candidate.value = value; |
| 217 | } |
| 218 | } |
| 219 | |
| 220 | Node root; |
| 221 | }; |
| 222 | |
| 223 | class GroupMatcher : public PrefixMatch::Tables::Matcher { |
| 224 | public: |
| 225 | explicit GroupMatcher(DictGroupMatchPolicy _matchPolicy) |
| 226 | : matchPolicy(_matchPolicy) {} |
| 227 | |
| 228 | void AddChild(std::unique_ptr<Matcher> child) { |
| 229 | children.push_back(std::move(child)); |
| 230 | } |
| 231 | |
| 232 | Candidate MatchPrefixCandidate(const char* word, size_t len) const override { |
| 233 | switch (matchPolicy) { |
| 234 | case DictGroupMatchPolicy::ShortCircuit: |
| 235 | return MatchPrefixShortCircuit(word, len); |
| 236 | case DictGroupMatchPolicy::Union: |
| 237 | return MatchPrefixUnion(word, len); |
| 238 | } |
| 239 | Unreachable(); |
| 240 | return Candidate{}; |
| 241 | } |
| 242 | |
| 243 | private: |
| 244 | Candidate MatchPrefixShortCircuit(const char* word, size_t len) const { |
| 245 | for (const std::unique_ptr<Matcher>& child : children) { |
| 246 | const Candidate candidate = child->MatchPrefixCandidate(word, len); |
| 247 | if (candidate.hasValue) { |
| 248 | return candidate; |
| 249 | } |
| 250 | } |
| 251 | return Candidate{}; |
| 252 | } |
| 253 | |
| 254 | Candidate MatchPrefixUnion(const char* word, size_t len) const { |
| 255 | Candidate best; |
| 256 | for (const std::unique_ptr<Matcher>& child : children) { |
| 257 | const Candidate candidate = child->MatchPrefixCandidate(word, len); |
| 258 | if (candidate.hasValue && |
| 259 | (!best.hasValue || candidate.keyLength > best.keyLength)) { |
| 260 | best = candidate; |
| 261 | } |
| 262 | } |
| 263 | return best; |
| 264 | } |
| 265 | |
| 266 | std::vector<std::unique_ptr<Matcher>> children; |
| 267 | const DictGroupMatchPolicy matchPolicy; |
| 268 | }; |
| 269 | |
| 270 | // Returns true if dict is a leaf dict, or if the entire subtree rooted at dict |
| 271 | // consists only of union groups and leaf dicts (no short_circuit anywhere). |
| 272 | // Union is associative, so such a tree is semantically equivalent to a single |
| 273 | // flat union of all its leaf dicts: the longest match across all leaves wins, |
| 274 | // which is exactly what a single LeafMatcher trie computes. |
| 275 | bool CanFlattenAsUnion(const DictPtr& dict) { |
| 276 | const std::list<DictPtr>* items = dict->GetDictGroupItems(); |
| 277 | if (items == nullptr) { |
| 278 | return true; |
| 279 | } |
| 280 | if (dict->GetMatchPolicy() != DictGroupMatchPolicy::Union) { |
| 281 | return false; |
| 282 | } |
| 283 | for (const DictPtr& child : *items) { |
| 284 | if (!CanFlattenAsUnion(child)) { |
| 285 | return false; |
| 286 | } |
| 287 | } |
| 288 | return true; |
| 289 | } |
| 290 | |
| 291 | void CollectAllLeafDicts(const DictPtr& dict, LeafMatcher* out) { |
| 292 | const std::list<DictPtr>* items = dict->GetDictGroupItems(); |
| 293 | if (items == nullptr) { |
| 294 | out->AddDict(dict); |
| 295 | return; |
| 296 | } |
| 297 | for (const DictPtr& child : *items) { |
| 298 | CollectAllLeafDicts(child, out); |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | std::unique_ptr<PrefixMatch::Tables::Matcher> BuildMatcher( |
| 303 | const DictPtr& dict) { |
| 304 | const std::list<DictPtr>* dictGroupItems = dict->GetDictGroupItems(); |
| 305 | if (dictGroupItems != nullptr) { |
| 306 | // If the entire subtree is a pure union of leaf dicts, merge all entries |
| 307 | // into a single LeafMatcher. One trie traversal finds the longest match |
| 308 | // across all dicts, which equals union semantics, and eliminates the |
| 309 | // overhead of GroupMatcher dispatch and multiple traversals. |
| 310 | if (CanFlattenAsUnion(dict)) { |
| 311 | std::unique_ptr<LeafMatcher> leaf(new LeafMatcher); |
| 312 | CollectAllLeafDicts(dict, leaf.get()); |
| 313 | return std::move(leaf); |
| 314 | } |
| 315 | |
| 316 | std::unique_ptr<GroupMatcher> group( |
| 317 | new GroupMatcher(dict->GetMatchPolicy())); |
| 318 | for (const DictPtr& child : *dictGroupItems) { |
| 319 | group->AddChild(BuildMatcher(child)); |
| 320 | } |
| 321 | return std::move(group); |
| 322 | } |
| 323 | |
| 324 | std::unique_ptr<LeafMatcher> leaf(new LeafMatcher); |
| 325 | leaf->AddDict(dict); |
| 326 | return std::move(leaf); |
| 327 | } |
| 328 | |
| 329 | PrefixMatch::PrefixMatch(const DictPtr& dict) { |
| 330 | // Try to unwrap single dict group |
| 331 | DictPtr actualDict = dict; |
| 332 | while (actualDict) { |
| 333 | const std::list<DictPtr>* items = actualDict->GetDictGroupItems(); |
| 334 | if (items != nullptr && items->size() == 1) { |
| 335 | actualDict = items->front(); |
| 336 | } else { |
| 337 | break; |
| 338 | } |
| 339 | } |
| 340 | |
| 341 | if (actualDict && actualDict->SupportsFastPrefixMatch()) { |
| 342 | singleDict = actualDict; |
| 343 | return; |
| 344 | } |
| 345 | |
| 346 | static std::mutex cacheMutex; |
| 347 | static std::unordered_map<std::string, std::vector<CacheEntry>> cache; |
| 348 | |
| 349 | std::string cacheKey; |
| 350 | AppendCacheKey(dict, &cacheKey); |
| 351 | std::vector<std::weak_ptr<const Dict>> leafDicts; |
| 352 | CollectLeafDicts(dict, &leafDicts); |
| 353 | |
| 354 | { |
| 355 | std::lock_guard<std::mutex> lock(cacheMutex); |
| 356 | PruneExpiredPrefixMatchCache(&cache); |
| 357 | const auto cached = cache.find(cacheKey); |
| 358 | if (cached != cache.end()) { |
| 359 | for (const CacheEntry& entry : cached->second) { |
| 360 | if (SameDicts(entry, leafDicts)) { |
| 361 | tables = entry.tables.lock(); |
| 362 | if (tables != nullptr) { |
| 363 | return; |
| 364 | } |
| 365 | } |
| 366 | } |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | std::shared_ptr<Tables> built(new Tables); |
| 371 | built->matcher = BuildMatcher(dict); |
| 372 | |
| 373 | std::lock_guard<std::mutex> lock(cacheMutex); |
| 374 | PruneExpiredPrefixMatchCache(&cache); |
| 375 | std::vector<CacheEntry>& entries = cache[cacheKey]; |
| 376 | for (std::vector<CacheEntry>::iterator it = entries.begin(); |
| 377 | it != entries.end();) { |
| 378 | if (HasExpiredDict(*it)) { |
| 379 | it = entries.erase(it); |
| 380 | } else if (SameDicts(*it, leafDicts)) { |
| 381 | tables = it->tables.lock(); |
| 382 | if (tables != nullptr) { |
| 383 | return; |
| 384 | } |
| 385 | it = entries.erase(it); |
| 386 | } else { |
| 387 | ++it; |
| 388 | } |
| 389 | } |
| 390 | tables = built; |
| 391 | CacheEntry entry; |
| 392 | entry.dicts = std::move(leafDicts); |
| 393 | entry.tables = tables; |
| 394 | entries.push_back(std::move(entry)); |
| 395 | } |
| 396 | |
| 397 | PrefixMatch::~PrefixMatch() {} |
| 398 | |
| 399 | PrefixMatch::Match PrefixMatch::MatchPrefix(const char* word, |
| 400 | size_t len) const { |
| 401 | if (singleDict != nullptr) { |
| 402 | struct MatchCache { |
| 403 | std::string key; |
| 404 | std::string value; |
| 405 | }; |
| 406 | // key/value pointers are valid until the next MatchPrefix() call on this |
| 407 | // thread. |
| 408 | static thread_local MatchCache matchCache; |
| 409 | const PrefixMatchView pv = singleDict->MatchPrefixValue(word, len); |
| 410 | if (pv.matched) { |
| 411 | matchCache.key = std::string(pv.key); |
| 412 | matchCache.value = std::string(pv.value); |
| 413 | return Match{true, pv.keyLength, &matchCache.key, &matchCache.value}; |
| 414 | } |
| 415 | return Match{false, 0, nullptr, nullptr}; |
| 416 | } |
| 417 | |
| 418 | const Tables::Matcher::Candidate candidate = |
| 419 | tables->matcher->MatchPrefixCandidate(word, len); |
| 420 | if (candidate.hasValue) { |
| 421 | return Match{true, candidate.keyLength, candidate.key, candidate.value}; |
| 422 | } |
| 423 | return Match{false, 0, nullptr, nullptr}; |
| 424 | } |
| 425 | |
| 426 | PrefixMatchView PrefixMatch::MatchPrefixView(const char* word, |
| 427 | size_t len) const { |
| 428 | if (singleDict != nullptr) { |
| 429 | return singleDict->MatchPrefixValue(word, len); |
| 430 | } |
| 431 | const Tables::Matcher::Candidate candidate = |
| 432 | tables->matcher->MatchPrefixCandidate(word, len); |
| 433 | if (candidate.hasValue) { |
| 434 | return {true, candidate.keyLength, |
| 435 | std::string_view(*candidate.key), |
| 436 | std::string_view(*candidate.value)}; |
| 437 | } |
| 438 | return {false, 0, std::string_view(), std::string_view()}; |
| 439 | } |
| 440 | |
| 441 | void PrefixMatch::AppendCacheKey(const DictPtr& dict, std::string* output) { |
| 442 | const std::list<DictPtr>* dictGroupItems = dict->GetDictGroupItems(); |
| 443 | if (dictGroupItems != nullptr) { |
| 444 | output->push_back('['); |
| 445 | const DictGroupMatchPolicy matchPolicy = dict->GetMatchPolicy(); |
| 446 | switch (matchPolicy) { |
| 447 | case DictGroupMatchPolicy::ShortCircuit: |
| 448 | output->append("short_circuit:"); |
| 449 | break; |
| 450 | case DictGroupMatchPolicy::Union: |
| 451 | output->append("union:"); |
| 452 | break; |
| 453 | } |
| 454 | for (const DictPtr& child : *dictGroupItems) { |
| 455 | AppendCacheKey(child, output); |
| 456 | } |
| 457 | output->push_back(']'); |
| 458 | return; |
| 459 | } |
| 460 | |
| 461 | const uintptr_t dictKey = reinterpret_cast<uintptr_t>(dict.get()); |
| 462 | output->append(reinterpret_cast<const char*>(&dictKey), sizeof(dictKey)); |
| 463 | output->push_back(';'); |
| 464 | } |
| 465 | |
| 466 | void PrefixMatch::CollectLeafDicts( |
| 467 | const DictPtr& dict, std::vector<std::weak_ptr<const Dict>>* output) { |
| 468 | const std::list<DictPtr>* dictGroupItems = dict->GetDictGroupItems(); |
| 469 | if (dictGroupItems != nullptr) { |
| 470 | for (const DictPtr& child : *dictGroupItems) { |
| 471 | CollectLeafDicts(child, output); |
| 472 | } |
| 473 | return; |
| 474 | } |
| 475 | output->push_back(dict); |
| 476 | } |