Debian Codegraph @

clang/lib/Basic/SimpleTypoCorrection.cpp

raw
1 //===- SimpleTypoCorrection.cpp - Basic typo correction utility -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the SimpleTypoCorrection class, which performs basic
10 // typo correction using string similarity based on edit distance.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Basic/SimpleTypoCorrection.h"
15 #include "clang/Basic/IdentifierTable.h"
16 #include "clang/Basic/LLVM.h"
17 #include "llvm/ADT/StringRef.h"
18
19 using namespace clang;
20
21 void SimpleTypoCorrection::add(const StringRef Candidate) {
22 if (Candidate.empty())
23 return;
24
25 unsigned MinPossibleEditDistance =
26 abs(static_cast<int>(Candidate.size()) - static_cast<int>(Typo.size()));
27
28 if (MinPossibleEditDistance > 0 && Typo.size() / MinPossibleEditDistance < 3)
29 return;
30
31 unsigned EditDistance = Typo.edit_distance(
32 Candidate, /*AllowReplacements*/ true, MaxEditDistance);
33
34 if (EditDistance < BestEditDistance) {
35 BestCandidate = Candidate;
36 BestEditDistance = EditDistance;
37 BestIndex = NextIndex;
38 }
39
40 ++NextIndex;
41 }
42
43 void SimpleTypoCorrection::add(const char *Candidate) {
44 if (Candidate)
45 add(StringRef(Candidate));
46 }
47
48 void SimpleTypoCorrection::add(const IdentifierInfo *Candidate) {
49 if (Candidate)
50 add(Candidate->getName());
51 }
52
53 unsigned SimpleTypoCorrection::getCorrectionIndex() const { return BestIndex; }
54
55 std::optional<StringRef> SimpleTypoCorrection::getCorrection() const {
56 if (hasCorrection())
57 return BestCandidate;
58 return std::nullopt;
59 }
60
61 bool SimpleTypoCorrection::hasCorrection() const {
62 return BestEditDistance <= MaxEditDistance;
63 }