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