]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/Sema/SemaInternal.h
MFV r316893:
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / include / clang / Sema / SemaInternal.h
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"
21 #include "clang/Sema/SemaDiagnostic.h"
22
23 namespace clang {
24
25 inline PartialDiagnostic Sema::PDiag(unsigned DiagID) {
26   return PartialDiagnostic(DiagID, Context.getDiagAllocator());
27 }
28
29 inline bool
30 FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI) {
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
37 FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI) {
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.
44 inline bool IsVariableAConstantExpression(VarDecl *Var, ASTContext &Context) {
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.
54 inline bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D) {
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;
84   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 
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.
94 inline InheritableAttr *getDLLAttr(Decl *D) {
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 class TypoCorrectionConsumer : public VisibleDeclConsumer {
105   typedef SmallVector<TypoCorrection, 1> TypoResultList;
106   typedef llvm::StringMap<TypoResultList> TypoResultsMap;
107   typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
108
109 public:
110   TypoCorrectionConsumer(Sema &SemaRef,
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())
152       return (std::numeric_limits<unsigned>::max)();
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().
173   const TypoCorrection &getCurrentCorrection() {
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).
183   const TypoCorrection &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).
193   void resetCorrectionStream() {
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).
206   void saveCurrentPosition() {
207     SavedTCIndex = CurrentTCIndex;
208   }
209
210   /// \brief Restore the saved position in the correction stream.
211   void restoreSavedPosition() {
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; }
221   CorrectionCandidateCallback *getCorrectionValidator() const {
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
236     ASTContext &Context;
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
278       iterator &operator++() {
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;
328   LookupResult Result;
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