clang  6.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 
106  typedef llvm::StringMap<TypoResultList> TypoResultsMap;
107  typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
108 
109 public:
111  const DeclarationNameInfo &TypoName,
112  Sema::LookupNameKind LookupKind,
113  Scope *S, CXXScopeSpec *SS,
114  std::unique_ptr<CorrectionCandidateCallback> CCC,
115  DeclContext *MemberContext,
116  bool EnteringContext)
117  : Typo(TypoName.getName().getAsIdentifierInfo()), CurrentTCIndex(0),
118  SavedTCIndex(0), SemaRef(SemaRef), S(S),
119  SS(SS ? llvm::make_unique<CXXScopeSpec>(*SS) : nullptr),
120  CorrectionValidator(std::move(CCC)), MemberContext(MemberContext),
121  Result(SemaRef, TypoName, LookupKind),
122  Namespaces(SemaRef.Context, SemaRef.CurContext, SS),
123  EnteringContext(EnteringContext), SearchNamespaces(false) {
124  Result.suppressDiagnostics();
125  // Arrange for ValidatedCorrections[0] to always be an empty correction.
126  ValidatedCorrections.push_back(TypoCorrection());
127  }
128 
129  bool includeHiddenDecls() const override { return true; }
130 
131  // Methods for adding potential corrections to the consumer.
132  void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
133  bool InBaseClass) override;
134  void FoundName(StringRef Name);
135  void addKeywordResult(StringRef Keyword);
136  void addCorrection(TypoCorrection Correction);
137 
138  bool empty() const {
139  return CorrectionResults.empty() && ValidatedCorrections.size() == 1;
140  }
141 
142  /// \brief Return the list of TypoCorrections for the given identifier from
143  /// the set of corrections that have the closest edit distance, if any.
144  TypoResultList &operator[](StringRef Name) {
145  return CorrectionResults.begin()->second[Name];
146  }
147 
148  /// \brief Return the edit distance of the corrections that have the
149  /// closest/best edit distance from the original typop.
150  unsigned getBestEditDistance(bool Normalized) {
151  if (CorrectionResults.empty())
153 
154  unsigned BestED = CorrectionResults.begin()->first;
155  return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
156  }
157 
158  /// \brief Set-up method to add to the consumer the set of namespaces to use
159  /// in performing corrections to nested name specifiers. This method also
160  /// implicitly adds all of the known classes in the current AST context to the
161  /// to the consumer for correcting nested name specifiers.
162  void
163  addNamespaces(const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces);
164 
165  /// \brief Return the next typo correction that passes all internal filters
166  /// and is deemed valid by the consumer's CorrectionCandidateCallback,
167  /// starting with the corrections that have the closest edit distance. An
168  /// empty TypoCorrection is returned once no more viable corrections remain
169  /// in the consumer.
170  const TypoCorrection &getNextCorrection();
171 
172  /// \brief Get the last correction returned by getNextCorrection().
174  return CurrentTCIndex < ValidatedCorrections.size()
175  ? ValidatedCorrections[CurrentTCIndex]
176  : ValidatedCorrections[0]; // The empty correction.
177  }
178 
179  /// \brief Return the next typo correction like getNextCorrection, but keep
180  /// the internal state pointed to the current correction (i.e. the next time
181  /// getNextCorrection is called, it will return the same correction returned
182  /// by peekNextcorrection).
184  auto Current = CurrentTCIndex;
185  const TypoCorrection &TC = getNextCorrection();
186  CurrentTCIndex = Current;
187  return TC;
188  }
189 
190  /// \brief Reset the consumer's position in the stream of viable corrections
191  /// (i.e. getNextCorrection() will return each of the previously returned
192  /// corrections in order before returning any new corrections).
194  CurrentTCIndex = 0;
195  }
196 
197  /// \brief Return whether the end of the stream of corrections has been
198  /// reached.
199  bool finished() {
200  return CorrectionResults.empty() &&
201  CurrentTCIndex >= ValidatedCorrections.size();
202  }
203 
204  /// \brief Save the current position in the correction stream (overwriting any
205  /// previously saved position).
207  SavedTCIndex = CurrentTCIndex;
208  }
209 
210  /// \brief Restore the saved position in the correction stream.
212  CurrentTCIndex = SavedTCIndex;
213  }
214 
215  ASTContext &getContext() const { return SemaRef.Context; }
216  const LookupResult &getLookupResult() const { return Result; }
217 
218  bool isAddressOfOperand() const { return CorrectionValidator->IsAddressOfOperand; }
219  const CXXScopeSpec *getSS() const { return SS.get(); }
220  Scope *getScope() const { return S; }
222  return CorrectionValidator.get();
223  }
224 
225 private:
226  class NamespaceSpecifierSet {
227  struct SpecifierInfo {
228  DeclContext* DeclCtx;
229  NestedNameSpecifier* NameSpecifier;
230  unsigned EditDistance;
231  };
232 
233  typedef SmallVector<DeclContext*, 4> DeclContextList;
234  typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
235 
237  DeclContextList CurContextChain;
238  std::string CurNameSpecifier;
239  SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
240  SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
241 
242  std::map<unsigned, SpecifierInfoList> DistanceMap;
243 
244  /// \brief Helper for building the list of DeclContexts between the current
245  /// context and the top of the translation unit
246  static DeclContextList buildContextChain(DeclContext *Start);
247 
248  unsigned buildNestedNameSpecifier(DeclContextList &DeclChain,
249  NestedNameSpecifier *&NNS);
250 
251  public:
252  NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
253  CXXScopeSpec *CurScopeSpec);
254 
255  /// \brief Add the DeclContext (a namespace or record) to the set, computing
256  /// the corresponding NestedNameSpecifier and its distance in the process.
257  void addNameSpecifier(DeclContext *Ctx);
258 
259  /// \brief Provides flat iteration over specifiers, sorted by distance.
260  class iterator
261  : public llvm::iterator_facade_base<iterator, std::forward_iterator_tag,
262  SpecifierInfo> {
263  /// Always points to the last element in the distance map.
264  const std::map<unsigned, SpecifierInfoList>::iterator OuterBack;
265  /// Iterator on the distance map.
266  std::map<unsigned, SpecifierInfoList>::iterator Outer;
267  /// Iterator on an element in the distance map.
268  SpecifierInfoList::iterator Inner;
269 
270  public:
271  iterator(NamespaceSpecifierSet &Set, bool IsAtEnd)
272  : OuterBack(std::prev(Set.DistanceMap.end())),
273  Outer(Set.DistanceMap.begin()),
274  Inner(!IsAtEnd ? Outer->second.begin() : OuterBack->second.end()) {
275  assert(!Set.DistanceMap.empty());
276  }
277 
279  ++Inner;
280  if (Inner == Outer->second.end() && Outer != OuterBack) {
281  ++Outer;
282  Inner = Outer->second.begin();
283  }
284  return *this;
285  }
286 
287  SpecifierInfo &operator*() { return *Inner; }
288  bool operator==(const iterator &RHS) const { return Inner == RHS.Inner; }
289  };
290 
291  iterator begin() { return iterator(*this, /*IsAtEnd=*/false); }
292  iterator end() { return iterator(*this, /*IsAtEnd=*/true); }
293  };
294 
295  void addName(StringRef Name, NamedDecl *ND,
296  NestedNameSpecifier *NNS = nullptr, bool isKeyword = false);
297 
298  /// \brief Find any visible decls for the given typo correction candidate.
299  /// If none are found, it to the set of candidates for which qualified lookups
300  /// will be performed to find possible nested name specifier changes.
301  bool resolveCorrection(TypoCorrection &Candidate);
302 
303  /// \brief Perform qualified lookups on the queued set of typo correction
304  /// candidates and add the nested name specifier changes to each candidate if
305  /// a lookup succeeds (at which point the candidate will be returned to the
306  /// main pool of potential corrections).
307  void performQualifiedLookups();
308 
309  /// \brief The name written that is a typo in the source.
310  IdentifierInfo *Typo;
311 
312  /// \brief The results found that have the smallest edit distance
313  /// found (so far) with the typo name.
314  ///
315  /// The pointer value being set to the current DeclContext indicates
316  /// whether there is a keyword with this name.
317  TypoEditDistanceMap CorrectionResults;
318 
319  SmallVector<TypoCorrection, 4> ValidatedCorrections;
320  size_t CurrentTCIndex;
321  size_t SavedTCIndex;
322 
323  Sema &SemaRef;
324  Scope *S;
325  std::unique_ptr<CXXScopeSpec> SS;
326  std::unique_ptr<CorrectionCandidateCallback> CorrectionValidator;
327  DeclContext *MemberContext;
329  NamespaceSpecifierSet Namespaces;
330  SmallVector<TypoCorrection, 2> QualifiedResults;
331  bool EnteringContext;
332  bool SearchNamespaces;
333 };
334 
335 inline Sema::TypoExprState::TypoExprState() {}
336 
337 inline Sema::TypoExprState::TypoExprState(TypoExprState &&other) noexcept {
338  *this = std::move(other);
339 }
340 
341 inline Sema::TypoExprState &Sema::TypoExprState::
342 operator=(Sema::TypoExprState &&other) noexcept {
343  Consumer = std::move(other.Consumer);
344  DiagHandler = std::move(other.DiagHandler);
345  RecoveryHandler = std::move(other.RecoveryHandler);
346  return *this;
347 }
348 
349 } // end namespace clang
350 
351 #endif
Defines the clang::ASTContext interface.
void MarkVarDeclODRUsed(VarDecl *Var, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt)
Definition: SemaInternal.h:70
A (possibly-)qualified type.
Definition: Type.h:653
ASTConsumer & Consumer
Definition: Sema.h:317
Simple class containing the result of Sema::CorrectTypo.
DominatorTree GraphTraits specialization so the DominatorTree can be iterable by generic graph iterat...
Definition: Dominators.h:26
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
CorrectionCandidateCallback * getCorrectionValidator() const
Definition: SemaInternal.h:221
const Expr * getAnyInitializer() const
getAnyInitializer - Get the initializer for this variable, no matter which declaration it is attached...
Definition: Decl.h:1203
TypoResultList & operator[](StringRef Name)
Return the list of TypoCorrections for the given identifier from the set of corrections that have the...
Definition: SemaInternal.h:144
void saveCurrentPosition()
Save the current position in the correction stream (overwriting any previously saved position)...
Definition: SemaInternal.h:206
Consumes visible declarations found when searching for all visible names within a given scope or cont...
Definition: Lookup.h:763
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:807
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:199
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:1097
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:14516
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:149
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
Definition: Format.h:1900
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
Represents the results of name lookup.
Definition: Lookup.h:32
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:39
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:314
bool hasAttr() const
Definition: DeclBase.h:535
ASTContext & getContext() const
Definition: SemaInternal.h:215
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:274
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:2161
void restoreSavedPosition()
Restore the saved position in the correction stream.
Definition: SemaInternal.h:211
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1266
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:2990
const CXXScopeSpec * getSS() const
Definition: SemaInternal.h:219
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:2088
PartialDiagnostic::StorageAllocator & getDiagAllocator()
Definition: ASTContext.h:667
The result type of a method or function.
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:1973
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:110
#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:605
const LookupResult & getLookupResult() const
Definition: SemaInternal.h:216
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
This declaration is only a declaration.
Definition: Decl.h:1139
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:1252
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with &#39;,...)&#39;, this is true.
Definition: DeclSpec.h:1232
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:2277
T * getAttr() const
Definition: DeclBase.h:531
const TypoCorrection & peekNextCorrection()
Return the next typo correction like getNextCorrection, but keep the internal state pointed to the cu...
Definition: SemaInternal.h:183
iterator(NamespaceSpecifierSet &Set, bool IsAtEnd)
Definition: SemaInternal.h:271
char __ovld __cnfn max(char x, char y)
Returns y if x < y, otherwise it returns x.
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:401
Provides flat iteration over specifiers, sorted by distance.
Definition: SemaInternal.h:260
bool includeHiddenDecls() const override
Determine whether hidden declarations (from unimported modules) should be given to this consumer...
Definition: SemaInternal.h:129
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:328
const TypoCorrection & getCurrentCorrection()
Get the last correction returned by getNextCorrection().
Definition: SemaInternal.h:173
unsigned getBestEditDistance(bool Normalized)
Return the edit distance of the corrections that have the closest/best edit distance from the origina...
Definition: SemaInternal.h:150
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1127
void resetCorrectionStream()
Reset the consumer&#39;s position in the stream of viable corrections (i.e.
Definition: SemaInternal.h:193
ASTContext & Context
Definition: Sema.h:316
NamedDecl - This represents a decl with a name.
Definition: Decl.h:245
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1349
bool hasInit() const
Definition: Decl.cpp:2111
ParamInfo * Params
Params - This is a pointer to a new[]&#39;d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1306
bool isExternallyVisible() const
Definition: Decl.h:371