Coverage Report

Created: 2023-05-31 04:38

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/include/clang/Sema/SemaInternal.h
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaInternal.h - Internal Sema Interfaces --------------*- 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 provides common API and #includes for the internal
10
// implementation of Sema.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#ifndef LLVM_CLANG_SEMA_SEMAINTERNAL_H
15
#define LLVM_CLANG_SEMA_SEMAINTERNAL_H
16
17
#include "clang/AST/ASTContext.h"
18
#include "clang/Sema/Lookup.h"
19
#include "clang/Sema/Sema.h"
20
#include "clang/Sema/SemaDiagnostic.h"
21
22
namespace clang {
23
24
2.18M
inline PartialDiagnostic Sema::PDiag(unsigned DiagID) {
25
2.18M
  return PartialDiagnostic(DiagID, Context.getDiagAllocator());
26
2.18M
}
27
28
inline bool
29
31.1M
FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI) {
30
31.1M
  return FTI.NumParams == 1 && 
!FTI.isVariadic3.43M
&&
31
31.1M
         
FTI.Params[0].Ident == nullptr3.41M
&&
FTI.Params[0].Param1.40M
&&
32
31.1M
         
cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType()1.40M
;
33
31.1M
}
34
35
inline bool
36
31.9M
FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI) {
37
  // Assume FTI is well-formed.
38
31.9M
  return FTI.NumParams && 
!FTIHasSingleVoidParameter(FTI)31.1M
;
39
31.9M
}
40
41
// Helper function to check whether D's attributes match current CUDA mode.
42
// Decls with mismatched attributes and related diagnostics may have to be
43
// ignored during this CUDA compilation pass.
44
59
inline bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D) {
45
59
  if (!LangOpts.CUDA || 
!D6
)
46
53
    return true;
47
6
  bool isDeviceSideDecl = D->hasAttr<CUDADeviceAttr>() ||
48
6
                          
D->hasAttr<CUDASharedAttr>()4
||
49
6
                          
D->hasAttr<CUDAGlobalAttr>()2
;
50
6
  return isDeviceSideDecl == LangOpts.CUDAIsDevice;
51
59
}
52
53
/// Return a DLL attribute from the declaration.
54
39.3M
inline InheritableAttr *getDLLAttr(Decl *D) {
55
39.3M
  assert(!(D->hasAttr<DLLImportAttr>() && D->hasAttr<DLLExportAttr>()) &&
56
39.3M
         "A declaration cannot be both dllimport and dllexport.");
57
39.3M
  if (auto *Import = D->getAttr<DLLImportAttr>())
58
9.78k
    return Import;
59
39.3M
  if (auto *Export = D->getAttr<DLLExportAttr>())
60
9.96k
    return Export;
61
39.3M
  return nullptr;
62
39.3M
}
63
64
/// Retrieve the depth and index of a template parameter.
65
134k
inline std::pair<unsigned, unsigned> getDepthAndIndex(NamedDecl *ND) {
66
134k
  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
67
79.1k
    return std::make_pair(TTP->getDepth(), TTP->getIndex());
68
69
55.1k
  if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
70
54.8k
    return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
71
72
225
  const auto *TTP = cast<TemplateTemplateParmDecl>(ND);
73
225
  return std::make_pair(TTP->getDepth(), TTP->getIndex());
74
55.1k
}
75
76
/// Retrieve the depth and index of an unexpanded parameter pack.
77
inline std::pair<unsigned, unsigned>
78
48.9k
getDepthAndIndex(UnexpandedParameterPack UPP) {
79
48.9k
  if (const auto *TTP = UPP.first.dyn_cast<const TemplateTypeParmType *>())
80
46.0k
    return std::make_pair(TTP->getDepth(), TTP->getIndex());
81
82
2.91k
  return getDepthAndIndex(UPP.first.get<NamedDecl *>());
83
48.9k
}
84
85
class TypoCorrectionConsumer : public VisibleDeclConsumer {
86
  typedef SmallVector<TypoCorrection, 1> TypoResultList;
87
  typedef llvm::StringMap<TypoResultList> TypoResultsMap;
88
  typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
89
90
public:
91
  TypoCorrectionConsumer(Sema &SemaRef,
92
                         const DeclarationNameInfo &TypoName,
93
                         Sema::LookupNameKind LookupKind,
94
                         Scope *S, CXXScopeSpec *SS,
95
                         std::unique_ptr<CorrectionCandidateCallback> CCC,
96
                         DeclContext *MemberContext,
97
                         bool EnteringContext)
98
      : Typo(TypoName.getName().getAsIdentifierInfo()), CurrentTCIndex(0),
99
        SavedTCIndex(0), SemaRef(SemaRef), S(S),
100
        SS(SS ? std::make_unique<CXXScopeSpec>(*SS) : nullptr),
101
        CorrectionValidator(std::move(CCC)), MemberContext(MemberContext),
102
        Result(SemaRef, TypoName, LookupKind),
103
        Namespaces(SemaRef.Context, SemaRef.CurContext, SS),
104
7.19k
        EnteringContext(EnteringContext), SearchNamespaces(false) {
105
7.19k
    Result.suppressDiagnostics();
106
    // Arrange for ValidatedCorrections[0] to always be an empty correction.
107
7.19k
    ValidatedCorrections.push_back(TypoCorrection());
108
7.19k
  }
109
110
838
  bool includeHiddenDecls() const override { return true; }
111
112
  // Methods for adding potential corrections to the consumer.
113
  void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
114
                 bool InBaseClass) override;
115
  void FoundName(StringRef Name);
116
  void addKeywordResult(StringRef Keyword);
117
  void addCorrection(TypoCorrection Correction);
118
119
7.13k
  bool empty() const {
120
7.13k
    return CorrectionResults.empty() && 
ValidatedCorrections.size() == 1214
;
121
7.13k
  }
122
123
  /// Return the list of TypoCorrections for the given identifier from
124
  /// the set of corrections that have the closest edit distance, if any.
125
0
  TypoResultList &operator[](StringRef Name) {
126
0
    return CorrectionResults.begin()->second[Name];
127
0
  }
128
129
  /// Return the edit distance of the corrections that have the
130
  /// closest/best edit distance from the original typop.
131
6.91k
  unsigned getBestEditDistance(bool Normalized) {
132
6.91k
    if (CorrectionResults.empty())
133
0
      return (std::numeric_limits<unsigned>::max)();
134
135
6.91k
    unsigned BestED = CorrectionResults.begin()->first;
136
6.91k
    return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : 
BestED0
;
137
6.91k
  }
138
139
  /// Set-up method to add to the consumer the set of namespaces to use
140
  /// in performing corrections to nested name specifiers. This method also
141
  /// implicitly adds all of the known classes in the current AST context to the
142
  /// to the consumer for correcting nested name specifiers.
143
  void
144
  addNamespaces(const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces);
145
146
  /// Return the next typo correction that passes all internal filters
147
  /// and is deemed valid by the consumer's CorrectionCandidateCallback,
148
  /// starting with the corrections that have the closest edit distance. An
149
  /// empty TypoCorrection is returned once no more viable corrections remain
150
  /// in the consumer.
151
  const TypoCorrection &getNextCorrection();
152
153
  /// Get the last correction returned by getNextCorrection().
154
4.09k
  const TypoCorrection &getCurrentCorrection() {
155
4.09k
    return CurrentTCIndex < ValidatedCorrections.size()
156
4.09k
               ? ValidatedCorrections[CurrentTCIndex]
157
4.09k
               : 
ValidatedCorrections[0]0
; // The empty correction.
158
4.09k
  }
159
160
  /// Return the next typo correction like getNextCorrection, but keep
161
  /// the internal state pointed to the current correction (i.e. the next time
162
  /// getNextCorrection is called, it will return the same correction returned
163
  /// by peekNextcorrection).
164
732
  const TypoCorrection &peekNextCorrection() {
165
732
    auto Current = CurrentTCIndex;
166
732
    const TypoCorrection &TC = getNextCorrection();
167
732
    CurrentTCIndex = Current;
168
732
    return TC;
169
732
  }
170
171
  /// In the case of deeply invalid expressions, `getNextCorrection()` will
172
  /// never be called since the transform never makes progress. If we don't
173
  /// detect this we risk trying to correct typos forever.
174
3.82k
  bool hasMadeAnyCorrectionProgress() const { return CurrentTCIndex != 0; }
175
176
  /// Reset the consumer's position in the stream of viable corrections
177
  /// (i.e. getNextCorrection() will return each of the previously returned
178
  /// corrections in order before returning any new corrections).
179
6.68k
  void resetCorrectionStream() {
180
6.68k
    CurrentTCIndex = 0;
181
6.68k
  }
182
183
  /// Return whether the end of the stream of corrections has been
184
  /// reached.
185
3.81k
  bool finished() {
186
3.81k
    return CorrectionResults.empty() &&
187
3.81k
           
CurrentTCIndex >= ValidatedCorrections.size()3.77k
;
188
3.81k
  }
189
190
  /// Save the current position in the correction stream (overwriting any
191
  /// previously saved position).
192
62
  void saveCurrentPosition() {
193
62
    SavedTCIndex = CurrentTCIndex;
194
62
  }
195
196
  /// Restore the saved position in the correction stream.
197
12
  void restoreSavedPosition() {
198
12
    CurrentTCIndex = SavedTCIndex;
199
12
  }
200
201
0
  ASTContext &getContext() const { return SemaRef.Context; }
202
1.00k
  const LookupResult &getLookupResult() const { return Result; }
203
204
81
  bool isAddressOfOperand() const { return CorrectionValidator->IsAddressOfOperand; }
205
504
  const CXXScopeSpec *getSS() const { return SS.get(); }
206
16
  Scope *getScope() const { return S; }
207
7.38k
  CorrectionCandidateCallback *getCorrectionValidator() const {
208
7.38k
    return CorrectionValidator.get();
209
7.38k
  }
210
211
private:
212
  class NamespaceSpecifierSet {
213
    struct SpecifierInfo {
214
      DeclContext* DeclCtx;
215
      NestedNameSpecifier* NameSpecifier;
216
      unsigned EditDistance;
217
    };
218
219
    typedef SmallVector<DeclContext*, 4> DeclContextList;
220
    typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
221
222
    ASTContext &Context;
223
    DeclContextList CurContextChain;
224
    std::string CurNameSpecifier;
225
    SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
226
    SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
227
228
    std::map<unsigned, SpecifierInfoList> DistanceMap;
229
230
    /// Helper for building the list of DeclContexts between the current
231
    /// context and the top of the translation unit
232
    static DeclContextList buildContextChain(DeclContext *Start);
233
234
    unsigned buildNestedNameSpecifier(DeclContextList &DeclChain,
235
                                      NestedNameSpecifier *&NNS);
236
237
   public:
238
    NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
239
                          CXXScopeSpec *CurScopeSpec);
240
241
    /// Add the DeclContext (a namespace or record) to the set, computing
242
    /// the corresponding NestedNameSpecifier and its distance in the process.
243
    void addNameSpecifier(DeclContext *Ctx);
244
245
    /// Provides flat iteration over specifiers, sorted by distance.
246
    class iterator
247
        : public llvm::iterator_facade_base<iterator, std::forward_iterator_tag,
248
                                            SpecifierInfo> {
249
      /// Always points to the last element in the distance map.
250
      const std::map<unsigned, SpecifierInfoList>::iterator OuterBack;
251
      /// Iterator on the distance map.
252
      std::map<unsigned, SpecifierInfoList>::iterator Outer;
253
      /// Iterator on an element in the distance map.
254
      SpecifierInfoList::iterator Inner;
255
256
    public:
257
      iterator(NamespaceSpecifierSet &Set, bool IsAtEnd)
258
          : OuterBack(std::prev(Set.DistanceMap.end())),
259
            Outer(Set.DistanceMap.begin()),
260
15.7k
            Inner(!IsAtEnd ? Outer->second.begin() : OuterBack->second.end()) {
261
15.7k
        assert(!Set.DistanceMap.empty());
262
15.7k
      }
263
264
211k
      iterator &operator++() {
265
211k
        ++Inner;
266
211k
        if (Inner == Outer->second.end() && 
Outer != OuterBack11.4k
) {
267
3.55k
          ++Outer;
268
3.55k
          Inner = Outer->second.begin();
269
3.55k
        }
270
211k
        return *this;
271
211k
      }
272
273
211k
      SpecifierInfo &operator*() { return *Inner; }
274
219k
      bool operator==(const iterator &RHS) const { return Inner == RHS.Inner; }
275
    };
276
277
7.86k
    iterator begin() { return iterator(*this, /*IsAtEnd=*/false); }
278
7.86k
    iterator end() { return iterator(*this, /*IsAtEnd=*/true); }
279
  };
280
281
  void addName(StringRef Name, NamedDecl *ND,
282
               NestedNameSpecifier *NNS = nullptr, bool isKeyword = false);
283
284
  /// Find any visible decls for the given typo correction candidate.
285
  /// If none are found, it to the set of candidates for which qualified lookups
286
  /// will be performed to find possible nested name specifier changes.
287
  bool resolveCorrection(TypoCorrection &Candidate);
288
289
  /// Perform qualified lookups on the queued set of typo correction
290
  /// candidates and add the nested name specifier changes to each candidate if
291
  /// a lookup succeeds (at which point the candidate will be returned to the
292
  /// main pool of potential corrections).
293
  void performQualifiedLookups();
294
295
  /// The name written that is a typo in the source.
296
  IdentifierInfo *Typo;
297
298
  /// The results found that have the smallest edit distance
299
  /// found (so far) with the typo name.
300
  ///
301
  /// The pointer value being set to the current DeclContext indicates
302
  /// whether there is a keyword with this name.
303
  TypoEditDistanceMap CorrectionResults;
304
305
  SmallVector<TypoCorrection, 4> ValidatedCorrections;
306
  size_t CurrentTCIndex;
307
  size_t SavedTCIndex;
308
309
  Sema &SemaRef;
310
  Scope *S;
311
  std::unique_ptr<CXXScopeSpec> SS;
312
  std::unique_ptr<CorrectionCandidateCallback> CorrectionValidator;
313
  DeclContext *MemberContext;
314
  LookupResult Result;
315
  NamespaceSpecifierSet Namespaces;
316
  SmallVector<TypoCorrection, 2> QualifiedResults;
317
  bool EnteringContext;
318
  bool SearchNamespaces;
319
};
320
321
4.18k
inline Sema::TypoExprState::TypoExprState() {}
322
323
8.41k
inline Sema::TypoExprState::TypoExprState(TypoExprState &&other) noexcept {
324
8.41k
  *this = std::move(other);
325
8.41k
}
326
327
inline Sema::TypoExprState &Sema::TypoExprState::
328
8.50k
operator=(Sema::TypoExprState &&other) noexcept {
329
8.50k
  Consumer = std::move(other.Consumer);
330
8.50k
  DiagHandler = std::move(other.DiagHandler);
331
8.50k
  RecoveryHandler = std::move(other.RecoveryHandler);
332
8.50k
  return *this;
333
8.50k
}
334
335
} // end namespace clang
336
337
#endif