Coverage Report

Created: 2019-02-15 18:59

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/include/clang/Sema/TypoCorrection.h
Line
Count
Source (jump to first uncovered line)
1
//===- TypoCorrection.h - Class for typo correction results -----*- C++ -*-===//
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 defines the TypoCorrection class, which stores the results of
10
// Sema's typo correction (Sema::CorrectTypo).
11
//
12
//===----------------------------------------------------------------------===//
13
14
#ifndef LLVM_CLANG_SEMA_TYPOCORRECTION_H
15
#define LLVM_CLANG_SEMA_TYPOCORRECTION_H
16
17
#include "clang/AST/Decl.h"
18
#include "clang/AST/DeclarationName.h"
19
#include "clang/Basic/LLVM.h"
20
#include "clang/Basic/PartialDiagnostic.h"
21
#include "clang/Basic/SourceLocation.h"
22
#include "clang/Sema/DeclSpec.h"
23
#include "llvm/ADT/ArrayRef.h"
24
#include "llvm/ADT/SmallVector.h"
25
#include "llvm/Support/Casting.h"
26
#include <cstddef>
27
#include <limits>
28
#include <string>
29
#include <utility>
30
#include <vector>
31
32
namespace clang {
33
34
class DeclContext;
35
class IdentifierInfo;
36
class LangOptions;
37
class MemberExpr;
38
class NestedNameSpecifier;
39
class Sema;
40
41
/// Simple class containing the result of Sema::CorrectTypo
42
class TypoCorrection {
43
public:
44
  // "Distance" for unusable corrections
45
  static const unsigned InvalidDistance = std::numeric_limits<unsigned>::max();
46
47
  // The largest distance still considered valid (larger edit distances are
48
  // mapped to InvalidDistance by getEditDistance).
49
  static const unsigned MaximumDistance = 10000U;
50
51
  // Relative weightings of the "edit distance" components. The higher the
52
  // weight, the more of a penalty to fitness the component will give (higher
53
  // weights mean greater contribution to the total edit distance, with the
54
  // best correction candidates having the lowest edit distance).
55
  static const unsigned CharDistanceWeight = 100U;
56
  static const unsigned QualifierDistanceWeight = 110U;
57
  static const unsigned CallbackDistanceWeight = 150U;
58
59
  TypoCorrection(const DeclarationName &Name, NamedDecl *NameDecl,
60
                 NestedNameSpecifier *NNS = nullptr, unsigned CharDistance = 0,
61
                 unsigned QualifierDistance = 0)
62
      : CorrectionName(Name), CorrectionNameSpec(NNS),
63
30.7k
        CharDistance(CharDistance), QualifierDistance(QualifierDistance) {
64
30.7k
    if (NameDecl)
65
0
      CorrectionDecls.push_back(NameDecl);
66
30.7k
  }
67
68
  TypoCorrection(NamedDecl *Name, NestedNameSpecifier *NNS = nullptr,
69
                 unsigned CharDistance = 0)
70
      : CorrectionName(Name->getDeclName()), CorrectionNameSpec(NNS),
71
        CharDistance(CharDistance) {
72
    if (Name)
73
      CorrectionDecls.push_back(Name);
74
  }
75
76
  TypoCorrection(DeclarationName Name, NestedNameSpecifier *NNS = nullptr,
77
                 unsigned CharDistance = 0)
78
      : CorrectionName(Name), CorrectionNameSpec(NNS),
79
        CharDistance(CharDistance) {}
80
81
24.0k
  TypoCorrection() = default;
82
83
  /// Gets the DeclarationName of the typo correction
84
402
  DeclarationName getCorrection() const { return CorrectionName; }
85
86
236k
  IdentifierInfo *getCorrectionAsIdentifierInfo() const {
87
236k
    return CorrectionName.getAsIdentifierInfo();
88
236k
  }
89
90
  /// Gets the NestedNameSpecifier needed to use the typo correction
91
1.42k
  NestedNameSpecifier *getCorrectionSpecifier() const {
92
1.42k
    return CorrectionNameSpec;
93
1.42k
  }
94
95
86.0k
  void setCorrectionSpecifier(NestedNameSpecifier *NNS) {
96
86.0k
    CorrectionNameSpec = NNS;
97
86.0k
    ForceSpecifierReplacement = (NNS != nullptr);
98
86.0k
  }
99
100
3.05k
  void WillReplaceSpecifier(bool ForceReplacement) {
101
3.05k
    ForceSpecifierReplacement = ForceReplacement;
102
3.05k
  }
103
104
6.03k
  bool WillReplaceSpecifier() const {
105
6.03k
    return ForceSpecifierReplacement;
106
6.03k
  }
107
108
86.0k
  void setQualifierDistance(unsigned ED) {
109
86.0k
    QualifierDistance = ED;
110
86.0k
  }
111
112
89.7k
  void setCallbackDistance(unsigned ED) {
113
89.7k
    CallbackDistance = ED;
114
89.7k
  }
115
116
  // Convert the given weighted edit distance to a roughly equivalent number of
117
  // single-character edits (typically for comparison to the length of the
118
  // string being edited).
119
93.9k
  static unsigned NormalizeEditDistance(unsigned ED) {
120
93.9k
    if (ED > MaximumDistance)
121
0
      return InvalidDistance;
122
93.9k
    return (ED + CharDistanceWeight / 2) / CharDistanceWeight;
123
93.9k
  }
124
125
  /// Gets the "edit distance" of the typo correction from the typo.
126
  /// If Normalized is true, scale the distance down by the CharDistanceWeight
127
  /// to return the edit distance in terms of single-character edits.
128
106k
  unsigned getEditDistance(bool Normalized = true) const {
129
106k
    if (CharDistance > MaximumDistance || QualifierDistance > MaximumDistance ||
130
106k
        CallbackDistance > MaximumDistance)
131
1.36k
      return InvalidDistance;
132
104k
    unsigned ED =
133
104k
        CharDistance * CharDistanceWeight +
134
104k
        QualifierDistance * QualifierDistanceWeight +
135
104k
        CallbackDistance * CallbackDistanceWeight;
136
104k
    if (ED > MaximumDistance)
137
0
      return InvalidDistance;
138
104k
    // Half the CharDistanceWeight is added to ED to simulate rounding since
139
104k
    // integer division truncates the value (i.e. round-to-nearest-int instead
140
104k
    // of round-to-zero).
141
104k
    return Normalized ? 
NormalizeEditDistance(ED)90.5k
:
ED14.3k
;
142
104k
  }
143
144
  /// Get the correction declaration found by name lookup (before we
145
  /// looked through using shadow declarations and the like).
146
18.0k
  NamedDecl *getFoundDecl() const {
147
18.0k
    return hasCorrectionDecl() ? 
*(CorrectionDecls.begin())8.00k
:
nullptr10.0k
;
148
18.0k
  }
149
150
  /// Gets the pointer to the declaration of the typo correction
151
16.3k
  NamedDecl *getCorrectionDecl() const {
152
16.3k
    auto *D = getFoundDecl();
153
16.3k
    return D ? 
D->getUnderlyingDecl()6.34k
:
nullptr10.0k
;
154
16.3k
  }
155
  template <class DeclClass>
156
816
  DeclClass *getCorrectionDeclAs() const {
157
816
    return dyn_cast_or_null<DeclClass>(getCorrectionDecl());
158
816
  }
clang::FieldDecl* clang::TypoCorrection::getCorrectionDeclAs<clang::FieldDecl>() const
Line
Count
Source
156
233
  DeclClass *getCorrectionDeclAs() const {
157
233
    return dyn_cast_or_null<DeclClass>(getCorrectionDecl());
158
233
  }
clang::VarDecl* clang::TypoCorrection::getCorrectionDeclAs<clang::VarDecl>() const
Line
Count
Source
156
19
  DeclClass *getCorrectionDeclAs() const {
157
19
    return dyn_cast_or_null<DeclClass>(getCorrectionDecl());
158
19
  }
clang::NamespaceDecl* clang::TypoCorrection::getCorrectionDeclAs<clang::NamespaceDecl>() const
Line
Count
Source
156
15
  DeclClass *getCorrectionDeclAs() const {
157
15
    return dyn_cast_or_null<DeclClass>(getCorrectionDecl());
158
15
  }
clang::ObjCInterfaceDecl* clang::TypoCorrection::getCorrectionDeclAs<clang::ObjCInterfaceDecl>() const
Line
Count
Source
156
110
  DeclClass *getCorrectionDeclAs() const {
157
110
    return dyn_cast_or_null<DeclClass>(getCorrectionDecl());
158
110
  }
clang::FunctionDecl* clang::TypoCorrection::getCorrectionDeclAs<clang::FunctionDecl>() const
Line
Count
Source
156
79
  DeclClass *getCorrectionDeclAs() const {
157
79
    return dyn_cast_or_null<DeclClass>(getCorrectionDecl());
158
79
  }
clang::TypeDecl* clang::TypoCorrection::getCorrectionDeclAs<clang::TypeDecl>() const
Line
Count
Source
156
7
  DeclClass *getCorrectionDeclAs() const {
157
7
    return dyn_cast_or_null<DeclClass>(getCorrectionDecl());
158
7
  }
clang::ObjCProtocolDecl* clang::TypoCorrection::getCorrectionDeclAs<clang::ObjCProtocolDecl>() const
Line
Count
Source
156
10
  DeclClass *getCorrectionDeclAs() const {
157
10
    return dyn_cast_or_null<DeclClass>(getCorrectionDecl());
158
10
  }
clang::ImplicitParamDecl* clang::TypoCorrection::getCorrectionDeclAs<clang::ImplicitParamDecl>() const
Line
Count
Source
156
302
  DeclClass *getCorrectionDeclAs() const {
157
302
    return dyn_cast_or_null<DeclClass>(getCorrectionDecl());
158
302
  }
clang::ObjCIvarDecl* clang::TypoCorrection::getCorrectionDeclAs<clang::ObjCIvarDecl>() const
Line
Count
Source
156
22
  DeclClass *getCorrectionDeclAs() const {
157
22
    return dyn_cast_or_null<DeclClass>(getCorrectionDecl());
158
22
  }
clang::ObjCPropertyDecl* clang::TypoCorrection::getCorrectionDeclAs<clang::ObjCPropertyDecl>() const
Line
Count
Source
156
19
  DeclClass *getCorrectionDeclAs() const {
157
19
    return dyn_cast_or_null<DeclClass>(getCorrectionDecl());
158
19
  }
159
160
  /// Clears the list of NamedDecls.
161
86.0k
  void ClearCorrectionDecls() {
162
86.0k
    CorrectionDecls.clear();
163
86.0k
  }
164
165
  /// Clears the list of NamedDecls before adding the new one.
166
308
  void setCorrectionDecl(NamedDecl *CDecl) {
167
308
    CorrectionDecls.clear();
168
308
    addCorrectionDecl(CDecl);
169
308
  }
170
171
  /// Clears the list of NamedDecls and adds the given set.
172
374
  void setCorrectionDecls(ArrayRef<NamedDecl*> Decls) {
173
374
    CorrectionDecls.clear();
174
374
    CorrectionDecls.insert(CorrectionDecls.begin(), Decls.begin(), Decls.end());
175
374
  }
176
177
  /// Add the given NamedDecl to the list of NamedDecls that are the
178
  /// declarations associated with the DeclarationName of this TypoCorrection
179
  void addCorrectionDecl(NamedDecl *CDecl);
180
181
  std::string getAsString(const LangOptions &LO) const;
182
183
954
  std::string getQuoted(const LangOptions &LO) const {
184
954
    return "'" + getAsString(LO) + "'";
185
954
  }
186
187
  /// Returns whether this TypoCorrection has a non-empty DeclarationName
188
18.4k
  explicit operator bool() const { return bool(CorrectionName); }
189
190
  /// Mark this TypoCorrection as being a keyword.
191
  /// Since addCorrectionDeclsand setCorrectionDecl don't allow NULL to be
192
  /// added to the list of the correction's NamedDecl pointers, NULL is added
193
  /// as the only element in the list to mark this TypoCorrection as a keyword.
194
106
  void makeKeyword() {
195
106
    CorrectionDecls.clear();
196
106
    CorrectionDecls.push_back(nullptr);
197
106
    ForceSpecifierReplacement = true;
198
106
  }
199
200
  // Check if this TypoCorrection is a keyword by checking if the first
201
  // item in CorrectionDecls is NULL.
202
33.2k
  bool isKeyword() const {
203
33.2k
    return !CorrectionDecls.empty() && 
CorrectionDecls.front() == nullptr18.1k
;
204
33.2k
  }
205
206
  // Check if this TypoCorrection is the given keyword.
207
  template<std::size_t StrLen>
208
8
  bool isKeyword(const char (&Str)[StrLen]) const {
209
8
    return isKeyword() && 
getCorrectionAsIdentifierInfo()->isStr(Str)5
;
210
8
  }
211
212
  // Returns true if the correction either is a keyword or has a known decl.
213
26.7k
  bool isResolved() const { return !CorrectionDecls.empty(); }
214
215
74
  bool isOverloaded() const {
216
74
    return CorrectionDecls.size() > 1;
217
74
  }
218
219
  void setCorrectionRange(CXXScopeSpec *SS,
220
35.0k
                          const DeclarationNameInfo &TypoName) {
221
35.0k
    CorrectionRange = TypoName.getSourceRange();
222
35.0k
    if (ForceSpecifierReplacement && 
SS2.79k
&&
!SS->isEmpty()2.28k
)
223
541
      CorrectionRange.setBegin(SS->getBeginLoc());
224
35.0k
  }
225
226
4.91k
  SourceRange getCorrectionRange() const {
227
4.91k
    return CorrectionRange;
228
4.91k
  }
229
230
  using decl_iterator = SmallVectorImpl<NamedDecl *>::iterator;
231
232
4.88k
  decl_iterator begin() {
233
4.88k
    return isKeyword() ? 
CorrectionDecls.end()143
:
CorrectionDecls.begin()4.74k
;
234
4.88k
  }
235
236
4.49k
  decl_iterator end() { return CorrectionDecls.end(); }
237
238
  using const_decl_iterator = SmallVectorImpl<NamedDecl *>::const_iterator;
239
240
1.91k
  const_decl_iterator begin() const {
241
1.91k
    return isKeyword() ? 
CorrectionDecls.end()0
: CorrectionDecls.begin();
242
1.91k
  }
243
244
1.91k
  const_decl_iterator end() const { return CorrectionDecls.end(); }
245
246
  /// Returns whether this typo correction is correcting to a
247
  /// declaration that was declared in a module that has not been imported.
248
9.67k
  bool requiresImport() const { return RequiresImport; }
249
4.31k
  void setRequiresImport(bool Req) { RequiresImport = Req; }
250
251
  /// Extra diagnostics are printed after the first diagnostic for the typo.
252
  /// This can be used to attach external notes to the diag.
253
  void addExtraDiagnostic(PartialDiagnostic PD) {
254
    ExtraDiagnostics.push_back(std::move(PD));
255
  }
256
743
  ArrayRef<PartialDiagnostic> getExtraDiagnostics() const {
257
743
    return ExtraDiagnostics;
258
743
  }
259
260
private:
261
18.0k
  bool hasCorrectionDecl() const {
262
18.0k
    return (!isKeyword() && 
!CorrectionDecls.empty()17.8k
);
263
18.0k
  }
264
265
  // Results.
266
  DeclarationName CorrectionName;
267
  NestedNameSpecifier *CorrectionNameSpec = nullptr;
268
  SmallVector<NamedDecl *, 1> CorrectionDecls;
269
  unsigned CharDistance = 0;
270
  unsigned QualifierDistance = 0;
271
  unsigned CallbackDistance = 0;
272
  SourceRange CorrectionRange;
273
  bool ForceSpecifierReplacement = false;
274
  bool RequiresImport = false;
275
276
  std::vector<PartialDiagnostic> ExtraDiagnostics;
277
};
278
279
/// Base class for callback objects used by Sema::CorrectTypo to check
280
/// the validity of a potential typo correction.
281
class CorrectionCandidateCallback {
282
public:
283
  static const unsigned InvalidDistance = TypoCorrection::InvalidDistance;
284
285
  explicit CorrectionCandidateCallback(IdentifierInfo *Typo = nullptr,
286
                                       NestedNameSpecifier *TypoNNS = nullptr)
287
21.9M
      : Typo(Typo), TypoNNS(TypoNNS) {}
288
289
21.9M
  virtual ~CorrectionCandidateCallback() = default;
290
291
  /// Simple predicate used by the default RankCandidate to
292
  /// determine whether to return an edit distance of 0 or InvalidDistance.
293
  /// This can be overridden by validators that only need to determine if a
294
  /// candidate is viable, without ranking potentially viable candidates.
295
  /// Only ValidateCandidate or RankCandidate need to be overridden by a
296
  /// callback wishing to check the viability of correction candidates.
297
  /// The default predicate always returns true if the candidate is not a type
298
  /// name or keyword, true for types if WantTypeSpecifiers is true, and true
299
  /// for keywords if WantTypeSpecifiers, WantExpressionKeywords,
300
  /// WantCXXNamedCasts, WantRemainingKeywords, or WantObjCSuper is true.
301
  virtual bool ValidateCandidate(const TypoCorrection &candidate);
302
303
  /// Method used by Sema::CorrectTypo to assign an "edit distance" rank
304
  /// to a candidate (where a lower value represents a better candidate), or
305
  /// returning InvalidDistance if the candidate is not at all viable. For
306
  /// validation callbacks that only need to determine if a candidate is viable,
307
  /// the default RankCandidate returns either 0 or InvalidDistance depending
308
  /// whether ValidateCandidate returns true or false.
309
3.66k
  virtual unsigned RankCandidate(const TypoCorrection &candidate) {
310
3.66k
    return (!MatchesTypo(candidate) && 
ValidateCandidate(candidate)3.65k
)
311
3.66k
               ? 
02.29k
312
3.66k
               : 
InvalidDistance1.36k
;
313
3.66k
  }
314
315
5.05k
  void setTypoName(IdentifierInfo *II) { Typo = II; }
316
0
  void setTypoNNS(NestedNameSpecifier *NNS) { TypoNNS = NNS; }
317
318
  // Flags for context-dependent keywords. WantFunctionLikeCasts is only
319
  // used/meaningful when WantCXXNamedCasts is false.
320
  // TODO: Expand these to apply to non-keywords or possibly remove them.
321
  bool WantTypeSpecifiers = true;
322
  bool WantExpressionKeywords = true;
323
  bool WantCXXNamedCasts = true;
324
  bool WantFunctionLikeCasts = true;
325
  bool WantRemainingKeywords = true;
326
  bool WantObjCSuper = false;
327
  // Temporary hack for the one case where a CorrectTypoContext enum is used
328
  // when looking up results.
329
  bool IsObjCIvarLookup = false;
330
  bool IsAddressOfOperand = false;
331
332
protected:
333
3.66k
  bool MatchesTypo(const TypoCorrection &candidate) {
334
3.66k
    return Typo && 
candidate.isResolved()498
&&
!candidate.requiresImport()494
&&
335
3.66k
           
candidate.getCorrectionAsIdentifierInfo() == Typo438
&&
336
3.66k
           // FIXME: This probably does not return true when both
337
3.66k
           // NestedNameSpecifiers have the same textual representation.
338
3.66k
           
candidate.getCorrectionSpecifier() == TypoNNS229
;
339
3.66k
  }
340
341
  IdentifierInfo *Typo;
342
  NestedNameSpecifier *TypoNNS;
343
};
344
345
/// Simple template class for restricting typo correction candidates
346
/// to ones having a single Decl* of the given type.
347
template <class C>
348
class DeclFilterCCC : public CorrectionCandidateCallback {
349
public:
350
114
  bool ValidateCandidate(const TypoCorrection &candidate) override {
351
114
    return candidate.getCorrectionDeclAs<C>();
352
114
  }
clang::DeclFilterCCC<clang::ObjCInterfaceDecl>::ValidateCandidate(clang::TypoCorrection const&)
Line
Count
Source
350
1
  bool ValidateCandidate(const TypoCorrection &candidate) override {
351
1
    return candidate.getCorrectionDeclAs<C>();
352
1
  }
clang::DeclFilterCCC<clang::FunctionDecl>::ValidateCandidate(clang::TypoCorrection const&)
Line
Count
Source
350
79
  bool ValidateCandidate(const TypoCorrection &candidate) override {
351
79
    return candidate.getCorrectionDeclAs<C>();
352
79
  }
clang::DeclFilterCCC<clang::ObjCProtocolDecl>::ValidateCandidate(clang::TypoCorrection const&)
Line
Count
Source
350
1
  bool ValidateCandidate(const TypoCorrection &candidate) override {
351
1
    return candidate.getCorrectionDeclAs<C>();
352
1
  }
clang::DeclFilterCCC<clang::ObjCIvarDecl>::ValidateCandidate(clang::TypoCorrection const&)
Line
Count
Source
350
13
  bool ValidateCandidate(const TypoCorrection &candidate) override {
351
13
    return candidate.getCorrectionDeclAs<C>();
352
13
  }
clang::DeclFilterCCC<clang::ObjCPropertyDecl>::ValidateCandidate(clang::TypoCorrection const&)
Line
Count
Source
350
19
  bool ValidateCandidate(const TypoCorrection &candidate) override {
351
19
    return candidate.getCorrectionDeclAs<C>();
352
19
  }
clang::DeclFilterCCC<clang::VarDecl>::ValidateCandidate(clang::TypoCorrection const&)
Line
Count
Source
350
1
  bool ValidateCandidate(const TypoCorrection &candidate) override {
351
1
    return candidate.getCorrectionDeclAs<C>();
352
1
  }
353
};
354
355
// Callback class to limit the allowed keywords and to only accept typo
356
// corrections that are keywords or whose decls refer to functions (or template
357
// functions) that accept the given number of arguments.
358
class FunctionCallFilterCCC : public CorrectionCandidateCallback {
359
public:
360
  FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
361
                        bool HasExplicitTemplateArgs,
362
                        MemberExpr *ME = nullptr);
363
364
  bool ValidateCandidate(const TypoCorrection &candidate) override;
365
366
private:
367
  unsigned NumArgs;
368
  bool HasExplicitTemplateArgs;
369
  DeclContext *CurContext;
370
  MemberExpr *MemberFn;
371
};
372
373
// Callback class that effectively disabled typo correction
374
class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
375
public:
376
0
  NoTypoCorrectionCCC() {
377
0
    WantTypeSpecifiers = false;
378
0
    WantExpressionKeywords = false;
379
0
    WantCXXNamedCasts = false;
380
0
    WantFunctionLikeCasts = false;
381
0
    WantRemainingKeywords = false;
382
0
  }
383
384
0
  bool ValidateCandidate(const TypoCorrection &candidate) override {
385
0
    return false;
386
0
  }
387
};
388
389
} // namespace clang
390
391
#endif // LLVM_CLANG_SEMA_TYPOCORRECTION_H