clang  14.0.0git
SemaInternal.h
Go to the documentation of this file.
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"
21 
22 namespace clang {
23 
24 inline PartialDiagnostic Sema::PDiag(unsigned DiagID) {
25  return PartialDiagnostic(DiagID, Context.getDiagAllocator());
26 }
27 
28 inline bool
30  return FTI.NumParams == 1 && !FTI.isVariadic &&
31  FTI.Params[0].Ident == nullptr && FTI.Params[0].Param &&
32  cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType();
33 }
34 
35 inline bool
37  // Assume FTI is well-formed.
38  return FTI.NumParams && !FTIHasSingleVoidParameter(FTI);
39 }
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 inline bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D) {
45  if (!LangOpts.CUDA || !D)
46  return true;
47  bool isDeviceSideDecl = D->hasAttr<CUDADeviceAttr>() ||
48  D->hasAttr<CUDASharedAttr>() ||
49  D->hasAttr<CUDAGlobalAttr>();
50  return isDeviceSideDecl == LangOpts.CUDAIsDevice;
51 }
52 
53 /// Return a DLL attribute from the declaration.
55  assert(!(D->hasAttr<DLLImportAttr>() && D->hasAttr<DLLExportAttr>()) &&
56  "A declaration cannot be both dllimport and dllexport.");
57  if (auto *Import = D->getAttr<DLLImportAttr>())
58  return Import;
59  if (auto *Export = D->getAttr<DLLExportAttr>())
60  return Export;
61  return nullptr;
62 }
63 
64 /// Retrieve the depth and index of a template parameter.
65 inline std::pair<unsigned, unsigned> getDepthAndIndex(NamedDecl *ND) {
66  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
67  return std::make_pair(TTP->getDepth(), TTP->getIndex());
68 
69  if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
70  return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
71 
72  const auto *TTP = cast<TemplateTemplateParmDecl>(ND);
73  return std::make_pair(TTP->getDepth(), TTP->getIndex());
74 }
75 
76 /// Retrieve the depth and index of an unexpanded parameter pack.
77 inline std::pair<unsigned, unsigned>
79  if (const auto *TTP = UPP.first.dyn_cast<const TemplateTypeParmType *>())
80  return std::make_pair(TTP->getDepth(), TTP->getIndex());
81 
82  return getDepthAndIndex(UPP.first.get<NamedDecl *>());
83 }
84 
87  typedef llvm::StringMap<TypoResultList> TypoResultsMap;
88  typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
89 
90 public:
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  EnteringContext(EnteringContext), SearchNamespaces(false) {
105  Result.suppressDiagnostics();
106  // Arrange for ValidatedCorrections[0] to always be an empty correction.
107  ValidatedCorrections.push_back(TypoCorrection());
108  }
109 
110  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  bool empty() const {
120  return CorrectionResults.empty() && ValidatedCorrections.size() == 1;
121  }
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  TypoResultList &operator[](StringRef Name) {
126  return CorrectionResults.begin()->second[Name];
127  }
128 
129  /// Return the edit distance of the corrections that have the
130  /// closest/best edit distance from the original typop.
131  unsigned getBestEditDistance(bool Normalized) {
132  if (CorrectionResults.empty())
134 
135  unsigned BestED = CorrectionResults.begin()->first;
136  return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
137  }
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.
152 
153  /// Get the last correction returned by getNextCorrection().
155  return CurrentTCIndex < ValidatedCorrections.size()
156  ? ValidatedCorrections[CurrentTCIndex]
157  : ValidatedCorrections[0]; // The empty correction.
158  }
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).
165  auto Current = CurrentTCIndex;
166  const TypoCorrection &TC = getNextCorrection();
167  CurrentTCIndex = Current;
168  return TC;
169  }
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  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).
180  CurrentTCIndex = 0;
181  }
182 
183  /// Return whether the end of the stream of corrections has been
184  /// reached.
185  bool finished() {
186  return CorrectionResults.empty() &&
187  CurrentTCIndex >= ValidatedCorrections.size();
188  }
189 
190  /// Save the current position in the correction stream (overwriting any
191  /// previously saved position).
193  SavedTCIndex = CurrentTCIndex;
194  }
195 
196  /// Restore the saved position in the correction stream.
198  CurrentTCIndex = SavedTCIndex;
199  }
200 
201  ASTContext &getContext() const { return SemaRef.Context; }
202  const LookupResult &getLookupResult() const { return Result; }
203 
204  bool isAddressOfOperand() const { return CorrectionValidator->IsAddressOfOperand; }
205  const CXXScopeSpec *getSS() const { return SS.get(); }
206  Scope *getScope() const { return S; }
208  return CorrectionValidator.get();
209  }
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  Inner(!IsAtEnd ? Outer->second.begin() : OuterBack->second.end()) {
261  assert(!Set.DistanceMap.empty());
262  }
263 
265  ++Inner;
266  if (Inner == Outer->second.end() && Outer != OuterBack) {
267  ++Outer;
268  Inner = Outer->second.begin();
269  }
270  return *this;
271  }
272 
273  SpecifierInfo &operator*() { return *Inner; }
274  bool operator==(const iterator &RHS) const { return Inner == RHS.Inner; }
275  };
276 
277  iterator begin() { return iterator(*this, /*IsAtEnd=*/false); }
278  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 inline Sema::TypoExprState::TypoExprState() {}
322 
323 inline Sema::TypoExprState::TypoExprState(TypoExprState &&other) noexcept {
324  *this = std::move(other);
325 }
326 
327 inline Sema::TypoExprState &Sema::TypoExprState::
328 operator=(Sema::TypoExprState &&other) noexcept {
329  Consumer = std::move(other.Consumer);
330  DiagHandler = std::move(other.DiagHandler);
331  RecoveryHandler = std::move(other.RecoveryHandler);
332  return *this;
333 }
334 
335 } // end namespace clang
336 
337 #endif
clang::DeclaratorChunk::FunctionTypeInfo::NumParams
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1316
clang::TypoCorrectionConsumer::finished
bool finished()
Return whether the end of the stream of corrections has been reached.
Definition: SemaInternal.h:185
clang::TypoCorrectionConsumer::restoreSavedPosition
void restoreSavedPosition()
Restore the saved position in the correction stream.
Definition: SemaInternal.h:197
max
__DEVICE__ int max(int __a, int __b)
Definition: __clang_cuda_math.h:196
clang::TypoCorrectionConsumer::hasMadeAnyCorrectionProgress
bool hasMadeAnyCorrectionProgress() const
In the case of deeply invalid expressions, getNextCorrection() will never be called since the transfo...
Definition: SemaInternal.h:174
clang::TypoCorrectionConsumer::addNamespaces
void addNamespaces(const llvm::MapVector< NamespaceDecl *, bool > &KnownNamespaces)
Set-up method to add to the consumer the set of namespaces to use in performing corrections to nested...
Definition: SemaLookup.cpp:4331
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::DeclContext
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1347
clang::TypoCorrectionConsumer::getScope
Scope * getScope() const
Definition: SemaInternal.h:206
clang::Decl::hasAttr
bool hasAttr() const
Definition: DeclBase.h:547
clang::TypoCorrection
Simple class containing the result of Sema::CorrectTypo.
Definition: TypoCorrection.h:42
llvm::SmallVector
Definition: LLVM.h:38
Lookup.h
clang::TypoCorrectionConsumer::addKeywordResult
void addKeywordResult(StringRef Keyword)
Definition: SemaLookup.cpp:4257
clang::NamedDecl
This represents a decl that may have a name.
Definition: Decl.h:249
clang::NestedNameSpecifier
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
Definition: NestedNameSpecifier.h:50
clang::getDLLAttr
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:54
clang::LookupResult
Represents the results of name lookup.
Definition: Lookup.h:46
clang::TypoCorrectionConsumer::operator[]
TypoResultList & operator[](StringRef Name)
Return the list of TypoCorrections for the given identifier from the set of corrections that have the...
Definition: SemaInternal.h:125
clang::TypoCorrectionConsumer::includeHiddenDecls
bool includeHiddenDecls() const override
Determine whether hidden declarations (from unimported modules) should be given to this consumer.
Definition: SemaInternal.h:110
clang::Decl::getAttr
T * getAttr() const
Definition: DeclBase.h:543
clang::CXXScopeSpec
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:64
clang::TypoCorrectionConsumer::isAddressOfOperand
bool isAddressOfOperand() const
Definition: SemaInternal.h:204
clang::TypoCorrectionConsumer::peekNextCorrection
const TypoCorrection & peekNextCorrection()
Return the next typo correction like getNextCorrection, but keep the internal state pointed to the cu...
Definition: SemaInternal.h:164
clang::TypoCorrectionConsumer::getBestEditDistance
unsigned getBestEditDistance(bool Normalized)
Return the edit distance of the corrections that have the closest/best edit distance from the origina...
Definition: SemaInternal.h:131
clang::Sema::Context
ASTContext & Context
Definition: Sema.h:410
clang::InheritableAttr
Definition: Attr.h:142
clang::TypoCorrection::NormalizeEditDistance
static unsigned NormalizeEditDistance(unsigned ED)
Definition: TypoCorrection.h:119
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::iterator::operator++
iterator & operator++()
Definition: SemaInternal.h:264
clang::FTIHasNonVoidParameters
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:36
clang::TypoCorrectionConsumer::resetCorrectionStream
void resetCorrectionStream()
Reset the consumer's position in the stream of viable corrections (i.e.
Definition: SemaInternal.h:179
clang::TypoCorrectionConsumer::getCorrectionValidator
CorrectionCandidateCallback * getCorrectionValidator() const
Definition: SemaInternal.h:207
clang::UnexpandedParameterPack
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl * >, SourceLocation > UnexpandedParameterPack
Definition: Sema.h:241
clang::Scope
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
clang::TypoCorrectionConsumer::getCurrentCorrection
const TypoCorrection & getCurrentCorrection()
Get the last correction returned by getNextCorrection().
Definition: SemaInternal.h:154
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:212
clang::DeclaratorChunk::FunctionTypeInfo::isVariadic
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with ',...)',...
Definition: DeclSpec.h:1286
clang::DeclaratorChunk::FunctionTypeInfo
Definition: DeclSpec.h:1277
clang::TypoCorrectionConsumer::addCorrection
void addCorrection(TypoCorrection Correction)
Definition: SemaLookup.cpp:4286
clang::TypoCorrectionConsumer::empty
bool empty() const
Definition: SemaInternal.h:119
clang::TypoCorrectionConsumer
Definition: SemaInternal.h:85
clang::VisibleDeclConsumer
Consumes visible declarations found when searching for all visible names within a given scope or cont...
Definition: Lookup.h:764
clang::Sema::PDiag
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
ASTContext.h
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::iterator::iterator
iterator(NamespaceSpecifierSet &Set, bool IsAtEnd)
Definition: SemaInternal.h:257
getName
static std::string getName(const CallEvent &Call)
Definition: ReturnValueChecker.cpp:61
clang::DeclaratorChunk::FunctionTypeInfo::Params
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1341
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::iterator::operator==
bool operator==(const iterator &RHS) const
Definition: SemaInternal.h:274
Sema.h
clang::DeclaratorChunk::ParamInfo::Param
Decl * Param
Definition: DeclSpec.h:1255
clang::Sema::LookupNameKind
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:3985
clang::TemplateTypeParmType
Definition: Type.h:4765
clang::TypoCorrectionConsumer::FoundName
void FoundName(StringRef Name)
Definition: SemaLookup.cpp:4251
clang::LookupResult::suppressDiagnostics
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:583
false
#define false
Definition: stdbool.h:17
SemaDiagnostic.h
clang::TypoCorrectionConsumer::saveCurrentPosition
void saveCurrentPosition()
Save the current position in the correction stream (overwriting any previously saved position).
Definition: SemaInternal.h:192
clang::Decl
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:89
clang::Sema
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:354
clang::ASTContext::getDiagAllocator
PartialDiagnostic::DiagStorageAllocator & getDiagAllocator()
Definition: ASTContext.h:743
clang::TypoCorrectionConsumer::TypoCorrectionConsumer
TypoCorrectionConsumer(Sema &SemaRef, const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, std::unique_ptr< CorrectionCandidateCallback > CCC, DeclContext *MemberContext, bool EnteringContext)
Definition: SemaInternal.h:91
clang::TypoCorrectionConsumer::getSS
const CXXScopeSpec * getSS() const
Definition: SemaInternal.h:205
clang::PartialDiagnostic
Definition: PartialDiagnostic.h:34
clang::LangOptions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:58
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::iterator::operator*
SpecifierInfo & operator*()
Definition: SemaInternal.h:273
std
Definition: Format.h:4125
clang
Definition: CalledOnceCheck.h:17
clang::DeclAttrsMatchCUDAMode
bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
Definition: SemaInternal.h:44
clang::CorrectionCandidateCallback
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
Definition: TypoCorrection.h:281
clang::TypoCorrectionConsumer::getContext
ASTContext & getContext() const
Definition: SemaInternal.h:201
clang::FTIHasSingleVoidParameter
bool FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:29
clang::TypoCorrectionConsumer::getNextCorrection
const TypoCorrection & getNextCorrection()
Return the next typo correction that passes all internal filters and is deemed valid by the consumer'...
Definition: SemaLookup.cpp:4361
clang::TypoCorrectionConsumer::NamespaceSpecifierSet::iterator
Provides flat iteration over specifiers, sorted by distance.
Definition: SemaInternal.h:246
clang::getDepthAndIndex
std::pair< unsigned, unsigned > getDepthAndIndex(NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:65
clang::TypoCorrectionConsumer::FoundDecl
void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx, bool InBaseClass) override
Invoked each time Sema::LookupVisibleDecls() finds a declaration visible from the current scope or co...
Definition: SemaLookup.cpp:4230
clang::DeclarationNameInfo
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
Definition: DeclarationName.h:758
clang::DeclaratorChunk::ParamInfo::Ident
IdentifierInfo * Ident
Definition: DeclSpec.h:1253
clang::TypoCorrectionConsumer::getLookupResult
const LookupResult & getLookupResult() const
Definition: SemaInternal.h:202