clang  9.0.0svn
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 // This requires the variable to be non-dependent and the initializer
42 // to not be value dependent.
44  const VarDecl *DefVD = nullptr;
45  return !isa<ParmVarDecl>(Var) &&
46  Var->isUsableInConstantExpressions(Context) &&
47  Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE();
48 }
49 
50 // Helper function to check whether D's attributes match current CUDA mode.
51 // Decls with mismatched attributes and related diagnostics may have to be
52 // ignored during this CUDA compilation pass.
54  if (!LangOpts.CUDA || !D)
55  return true;
56  bool isDeviceSideDecl = D->hasAttr<CUDADeviceAttr>() ||
57  D->hasAttr<CUDASharedAttr>() ||
58  D->hasAttr<CUDAGlobalAttr>();
59  return isDeviceSideDecl == LangOpts.CUDAIsDevice;
60 }
61 
62 // Directly mark a variable odr-used. Given a choice, prefer to use
63 // MarkVariableReferenced since it does additional checks and then
64 // calls MarkVarDeclODRUsed.
65 // If the variable must be captured:
66 // - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
67 // - else capture it in the DeclContext that maps to the
68 // *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
69 inline void MarkVarDeclODRUsed(VarDecl *Var,
70  SourceLocation Loc, Sema &SemaRef,
71  const unsigned *const FunctionScopeIndexToStopAt) {
72  // Keep track of used but undefined variables.
73  // FIXME: We shouldn't suppress this warning for static data members.
74  if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
75  (!Var->isExternallyVisible() || Var->isInline() ||
76  SemaRef.isExternalWithNoLinkageType(Var)) &&
77  !(Var->isStaticDataMember() && Var->hasInit())) {
78  SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
79  if (old.isInvalid())
80  old = Loc;
81  }
82  QualType CaptureType, DeclRefType;
84  /*EllipsisLoc*/ SourceLocation(),
85  /*BuildAndDiagnose*/ true,
86  CaptureType, DeclRefType,
87  FunctionScopeIndexToStopAt);
88 
89  Var->markUsed(SemaRef.Context);
90 }
91 
92 /// Return a DLL attribute from the declaration.
94  assert(!(D->hasAttr<DLLImportAttr>() && D->hasAttr<DLLExportAttr>()) &&
95  "A declaration cannot be both dllimport and dllexport.");
96  if (auto *Import = D->getAttr<DLLImportAttr>())
97  return Import;
98  if (auto *Export = D->getAttr<DLLExportAttr>())
99  return Export;
100  return nullptr;
101 }
102 
103 /// Retrieve the depth and index of a template parameter.
104 inline std::pair<unsigned, unsigned> getDepthAndIndex(NamedDecl *ND) {
105  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
106  return std::make_pair(TTP->getDepth(), TTP->getIndex());
107 
108  if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
109  return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
110 
111  const auto *TTP = cast<TemplateTemplateParmDecl>(ND);
112  return std::make_pair(TTP->getDepth(), TTP->getIndex());
113 }
114 
115 /// Retrieve the depth and index of an unexpanded parameter pack.
116 inline std::pair<unsigned, unsigned>
118  if (const auto *TTP = UPP.first.dyn_cast<const TemplateTypeParmType *>())
119  return std::make_pair(TTP->getDepth(), TTP->getIndex());
120 
121  return getDepthAndIndex(UPP.first.get<NamedDecl *>());
122 }
123 
126  typedef llvm::StringMap<TypoResultList> TypoResultsMap;
127  typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
128 
129 public:
131  const DeclarationNameInfo &TypoName,
132  Sema::LookupNameKind LookupKind,
133  Scope *S, CXXScopeSpec *SS,
134  std::unique_ptr<CorrectionCandidateCallback> CCC,
136  bool EnteringContext)
137  : Typo(TypoName.getName().getAsIdentifierInfo()), CurrentTCIndex(0),
138  SavedTCIndex(0), SemaRef(SemaRef), S(S),
139  SS(SS ? llvm::make_unique<CXXScopeSpec>(*SS) : nullptr),
140  CorrectionValidator(std::move(CCC)), MemberContext(MemberContext),
141  Result(SemaRef, TypoName, LookupKind),
142  Namespaces(SemaRef.Context, SemaRef.CurContext, SS),
143  EnteringContext(EnteringContext), SearchNamespaces(false) {
144  Result.suppressDiagnostics();
145  // Arrange for ValidatedCorrections[0] to always be an empty correction.
146  ValidatedCorrections.push_back(TypoCorrection());
147  }
148 
149  bool includeHiddenDecls() const override { return true; }
150 
151  // Methods for adding potential corrections to the consumer.
152  void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
153  bool InBaseClass) override;
154  void FoundName(StringRef Name);
155  void addKeywordResult(StringRef Keyword);
156  void addCorrection(TypoCorrection Correction);
157 
158  bool empty() const {
159  return CorrectionResults.empty() && ValidatedCorrections.size() == 1;
160  }
161 
162  /// Return the list of TypoCorrections for the given identifier from
163  /// the set of corrections that have the closest edit distance, if any.
164  TypoResultList &operator[](StringRef Name) {
165  return CorrectionResults.begin()->second[Name];
166  }
167 
168  /// Return the edit distance of the corrections that have the
169  /// closest/best edit distance from the original typop.
170  unsigned getBestEditDistance(bool Normalized) {
171  if (CorrectionResults.empty())
173 
174  unsigned BestED = CorrectionResults.begin()->first;
175  return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
176  }
177 
178  /// Set-up method to add to the consumer the set of namespaces to use
179  /// in performing corrections to nested name specifiers. This method also
180  /// implicitly adds all of the known classes in the current AST context to the
181  /// to the consumer for correcting nested name specifiers.
182  void
183  addNamespaces(const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces);
184 
185  /// Return the next typo correction that passes all internal filters
186  /// and is deemed valid by the consumer's CorrectionCandidateCallback,
187  /// starting with the corrections that have the closest edit distance. An
188  /// empty TypoCorrection is returned once no more viable corrections remain
189  /// in the consumer.
190  const TypoCorrection &getNextCorrection();
191 
192  /// Get the last correction returned by getNextCorrection().
194  return CurrentTCIndex < ValidatedCorrections.size()
195  ? ValidatedCorrections[CurrentTCIndex]
196  : ValidatedCorrections[0]; // The empty correction.
197  }
198 
199  /// Return the next typo correction like getNextCorrection, but keep
200  /// the internal state pointed to the current correction (i.e. the next time
201  /// getNextCorrection is called, it will return the same correction returned
202  /// by peekNextcorrection).
204  auto Current = CurrentTCIndex;
205  const TypoCorrection &TC = getNextCorrection();
206  CurrentTCIndex = Current;
207  return TC;
208  }
209 
210  /// Reset the consumer's position in the stream of viable corrections
211  /// (i.e. getNextCorrection() will return each of the previously returned
212  /// corrections in order before returning any new corrections).
214  CurrentTCIndex = 0;
215  }
216 
217  /// Return whether the end of the stream of corrections has been
218  /// reached.
219  bool finished() {
220  return CorrectionResults.empty() &&
221  CurrentTCIndex >= ValidatedCorrections.size();
222  }
223 
224  /// Save the current position in the correction stream (overwriting any
225  /// previously saved position).
227  SavedTCIndex = CurrentTCIndex;
228  }
229 
230  /// Restore the saved position in the correction stream.
232  CurrentTCIndex = SavedTCIndex;
233  }
234 
235  ASTContext &getContext() const { return SemaRef.Context; }
236  const LookupResult &getLookupResult() const { return Result; }
237 
238  bool isAddressOfOperand() const { return CorrectionValidator->IsAddressOfOperand; }
239  const CXXScopeSpec *getSS() const { return SS.get(); }
240  Scope *getScope() const { return S; }
242  return CorrectionValidator.get();
243  }
244 
245 private:
246  class NamespaceSpecifierSet {
247  struct SpecifierInfo {
248  DeclContext* DeclCtx;
249  NestedNameSpecifier* NameSpecifier;
250  unsigned EditDistance;
251  };
252 
253  typedef SmallVector<DeclContext*, 4> DeclContextList;
254  typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
255 
257  DeclContextList CurContextChain;
258  std::string CurNameSpecifier;
259  SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
260  SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
261 
262  std::map<unsigned, SpecifierInfoList> DistanceMap;
263 
264  /// Helper for building the list of DeclContexts between the current
265  /// context and the top of the translation unit
266  static DeclContextList buildContextChain(DeclContext *Start);
267 
268  unsigned buildNestedNameSpecifier(DeclContextList &DeclChain,
269  NestedNameSpecifier *&NNS);
270 
271  public:
272  NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
273  CXXScopeSpec *CurScopeSpec);
274 
275  /// Add the DeclContext (a namespace or record) to the set, computing
276  /// the corresponding NestedNameSpecifier and its distance in the process.
277  void addNameSpecifier(DeclContext *Ctx);
278 
279  /// Provides flat iteration over specifiers, sorted by distance.
280  class iterator
281  : public llvm::iterator_facade_base<iterator, std::forward_iterator_tag,
282  SpecifierInfo> {
283  /// Always points to the last element in the distance map.
284  const std::map<unsigned, SpecifierInfoList>::iterator OuterBack;
285  /// Iterator on the distance map.
286  std::map<unsigned, SpecifierInfoList>::iterator Outer;
287  /// Iterator on an element in the distance map.
288  SpecifierInfoList::iterator Inner;
289 
290  public:
291  iterator(NamespaceSpecifierSet &Set, bool IsAtEnd)
292  : OuterBack(std::prev(Set.DistanceMap.end())),
293  Outer(Set.DistanceMap.begin()),
294  Inner(!IsAtEnd ? Outer->second.begin() : OuterBack->second.end()) {
295  assert(!Set.DistanceMap.empty());
296  }
297 
299  ++Inner;
300  if (Inner == Outer->second.end() && Outer != OuterBack) {
301  ++Outer;
302  Inner = Outer->second.begin();
303  }
304  return *this;
305  }
306 
307  SpecifierInfo &operator*() { return *Inner; }
308  bool operator==(const iterator &RHS) const { return Inner == RHS.Inner; }
309  };
310 
311  iterator begin() { return iterator(*this, /*IsAtEnd=*/false); }
312  iterator end() { return iterator(*this, /*IsAtEnd=*/true); }
313  };
314 
315  void addName(StringRef Name, NamedDecl *ND,
316  NestedNameSpecifier *NNS = nullptr, bool isKeyword = false);
317 
318  /// Find any visible decls for the given typo correction candidate.
319  /// If none are found, it to the set of candidates for which qualified lookups
320  /// will be performed to find possible nested name specifier changes.
321  bool resolveCorrection(TypoCorrection &Candidate);
322 
323  /// Perform qualified lookups on the queued set of typo correction
324  /// candidates and add the nested name specifier changes to each candidate if
325  /// a lookup succeeds (at which point the candidate will be returned to the
326  /// main pool of potential corrections).
327  void performQualifiedLookups();
328 
329  /// The name written that is a typo in the source.
330  IdentifierInfo *Typo;
331 
332  /// The results found that have the smallest edit distance
333  /// found (so far) with the typo name.
334  ///
335  /// The pointer value being set to the current DeclContext indicates
336  /// whether there is a keyword with this name.
337  TypoEditDistanceMap CorrectionResults;
338 
339  SmallVector<TypoCorrection, 4> ValidatedCorrections;
340  size_t CurrentTCIndex;
341  size_t SavedTCIndex;
342 
343  Sema &SemaRef;
344  Scope *S;
345  std::unique_ptr<CXXScopeSpec> SS;
346  std::unique_ptr<CorrectionCandidateCallback> CorrectionValidator;
349  NamespaceSpecifierSet Namespaces;
350  SmallVector<TypoCorrection, 2> QualifiedResults;
351  bool EnteringContext;
352  bool SearchNamespaces;
353 };
354 
355 inline Sema::TypoExprState::TypoExprState() {}
356 
357 inline Sema::TypoExprState::TypoExprState(TypoExprState &&other) noexcept {
358  *this = std::move(other);
359 }
360 
361 inline Sema::TypoExprState &Sema::TypoExprState::
362 operator=(Sema::TypoExprState &&other) noexcept {
363  Consumer = std::move(other.Consumer);
364  DiagHandler = std::move(other.DiagHandler);
365  RecoveryHandler = std::move(other.RecoveryHandler);
366  return *this;
367 }
368 
369 } // end namespace clang
370 
371 #endif
Defines the clang::ASTContext interface.
void MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt)
Definition: SemaInternal.h:69
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl * >, SourceLocation > UnexpandedParameterPack
Definition: Sema.h:226
A (possibly-)qualified type.
Definition: Type.h:634
ASTConsumer & Consumer
Definition: Sema.h:359
Simple class containing the result of Sema::CorrectTypo.
DominatorTree GraphTraits specialization so the DominatorTree can be iterable by generic graph iterat...
Definition: Dominators.h:29
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
CorrectionCandidateCallback * getCorrectionValidator() const
Definition: SemaInternal.h:241
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to...
Definition: Decl.h:1209
TypoResultList & operator[](StringRef Name)
Return the list of TypoCorrections for the given identifier from the set of corrections that have the...
Definition: SemaInternal.h:164
void saveCurrentPosition()
Save the current position in the correction stream (overwriting any previously saved position)...
Definition: SemaInternal.h:226
Consumes visible declarations found when searching for all visible names within a given scope or cont...
Definition: Lookup.h:765
Represents a variable declaration or definition.
Definition: Decl.h:812
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
bool finished()
Return whether the end of the stream of corrections has been reached.
Definition: SemaInternal.h:219
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:1169
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
Definition: SemaExpr.cpp:15363
std::string getName(ArrayRef< StringRef > Parts) const
Get the platform-specific name separator.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:36
One of these records is kept for each identifier that is lexed.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
Definition: Format.h:2071
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:49
Represents the results of name lookup.
Definition: Lookup.h:46
bool FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:29
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
static unsigned NormalizeEditDistance(unsigned ED)
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:62
const LangOptions & LangOpts
Definition: Sema.h:356
bool hasAttr() const
Definition: DeclBase.h:533
ASTContext & getContext() const
Definition: SemaInternal.h:235
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:312
bool isUsableInConstantExpressions(ASTContext &C) const
Determine whether this variable&#39;s value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2213
std::pair< unsigned, unsigned > getDepthAndIndex(NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:104
void restoreSavedPosition()
Restore the saved position in the correction stream.
Definition: SemaInternal.h:231
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1287
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:3114
const CXXScopeSpec * getSS() const
Definition: SemaInternal.h:239
bool IsVariableAConstantExpression(VarDecl *Var, ASTContext &Context)
Definition: SemaInternal.h:43
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2140
PartialDiagnostic::StorageAllocator & getDiagAllocator()
Definition: ASTContext.h:685
The result type of a method or function.
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2025
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:130
#define false
Definition: stdbool.h:33
Encodes a location in the source.
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:93
bool isExternalWithNoLinkageType(ValueDecl *VD)
Determine if VD, which must be a variable or function, is an external symbol that nonetheless can&#39;t b...
Definition: Sema.cpp:615
const LookupResult & getLookupResult() const
Definition: SemaInternal.h:236
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
This declaration is only a declaration.
Definition: Decl.h:1146
Dataflow Directional Tag Classes.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1265
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with &#39;,...)&#39;, this is true.
Definition: DeclSpec.h:1257
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
Definition: SemaInternal.h:53
bool checkInitIsICE() const
Determine whether the value of the initializer attached to this declaration is an integral constant e...
Definition: Decl.cpp:2329
T * getAttr() const
Definition: DeclBase.h:529
const TypoCorrection & peekNextCorrection()
Return the next typo correction like getNextCorrection, but keep the internal state pointed to the cu...
Definition: SemaInternal.h:203
iterator(NamespaceSpecifierSet &Set, bool IsAtEnd)
Definition: SemaInternal.h:291
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:411
Provides flat iteration over specifiers, sorted by distance.
Definition: SemaInternal.h:280
bool includeHiddenDecls() const override
Determine whether hidden declarations (from unimported modules) should be given to this consumer...
Definition: SemaInternal.h:149
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:370
const TypoCorrection & getCurrentCorrection()
Get the last correction returned by getNextCorrection().
Definition: SemaInternal.h:193
__DEVICE__ int max(int __a, int __b)
unsigned getBestEditDistance(bool Normalized)
Return the edit distance of the corrections that have the closest/best edit distance from the origina...
Definition: SemaInternal.h:170
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1134
void resetCorrectionStream()
Reset the consumer&#39;s position in the stream of viable corrections (i.e.
Definition: SemaInternal.h:213
ASTContext & Context
Definition: Sema.h:358
This represents a decl that may have a name.
Definition: Decl.h:248
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1363
bool hasInit() const
Definition: Decl.cpp:2163
ParamInfo * Params
Params - This is a pointer to a new[]&#39;d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1312
bool isExternallyVisible() const
Definition: Decl.h:379