]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/include/clang/Sema/SemaInternal.h
Merge ^/head r277956 through r277974.
[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 // Directly mark a variable odr-used. Given a choice, prefer to use 
52 // MarkVariableReferenced since it does additional checks and then 
53 // calls MarkVarDeclODRUsed.
54 // If the variable must be captured:
55 //  - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
56 //  - else capture it in the DeclContext that maps to the 
57 //    *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.  
58 inline void MarkVarDeclODRUsed(VarDecl *Var,
59     SourceLocation Loc, Sema &SemaRef,
60     const unsigned *const FunctionScopeIndexToStopAt) {
61   // Keep track of used but undefined variables.
62   // FIXME: We shouldn't suppress this warning for static data members.
63   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
64     !Var->isExternallyVisible() &&
65     !(Var->isStaticDataMember() && Var->hasInit())) {
66       SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
67       if (old.isInvalid()) old = Loc;
68   }
69   QualType CaptureType, DeclRefType;
70   SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit, 
71     /*EllipsisLoc*/ SourceLocation(),
72     /*BuildAndDiagnose*/ true, 
73     CaptureType, DeclRefType, 
74     FunctionScopeIndexToStopAt);
75
76   Var->markUsed(SemaRef.Context);
77 }
78
79 /// Return a DLL attribute from the declaration.
80 inline InheritableAttr *getDLLAttr(Decl *D) {
81   assert(!(D->hasAttr<DLLImportAttr>() && D->hasAttr<DLLExportAttr>()) &&
82          "A declaration cannot be both dllimport and dllexport.");
83   if (auto *Import = D->getAttr<DLLImportAttr>())
84     return Import;
85   if (auto *Export = D->getAttr<DLLExportAttr>())
86     return Export;
87   return nullptr;
88 }
89
90 class TypoCorrectionConsumer : public VisibleDeclConsumer {
91   typedef SmallVector<TypoCorrection, 1> TypoResultList;
92   typedef llvm::StringMap<TypoResultList> TypoResultsMap;
93   typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
94
95 public:
96   TypoCorrectionConsumer(Sema &SemaRef,
97                          const DeclarationNameInfo &TypoName,
98                          Sema::LookupNameKind LookupKind,
99                          Scope *S, CXXScopeSpec *SS,
100                          std::unique_ptr<CorrectionCandidateCallback> CCC,
101                          DeclContext *MemberContext,
102                          bool EnteringContext)
103       : Typo(TypoName.getName().getAsIdentifierInfo()), CurrentTCIndex(0),
104         SemaRef(SemaRef), S(S),
105         SS(SS ? llvm::make_unique<CXXScopeSpec>(*SS) : nullptr),
106         CorrectionValidator(std::move(CCC)), MemberContext(MemberContext),
107         Result(SemaRef, TypoName, LookupKind),
108         Namespaces(SemaRef.Context, SemaRef.CurContext, SS),
109         EnteringContext(EnteringContext), SearchNamespaces(false) {
110     Result.suppressDiagnostics();
111     // Arrange for ValidatedCorrections[0] to always be an empty correction.
112     ValidatedCorrections.push_back(TypoCorrection());
113   }
114
115   bool includeHiddenDecls() const override { return true; }
116
117   // Methods for adding potential corrections to the consumer.
118   void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
119                  bool InBaseClass) override;
120   void FoundName(StringRef Name);
121   void addKeywordResult(StringRef Keyword);
122   void addCorrection(TypoCorrection Correction);
123
124   bool empty() const {
125     return CorrectionResults.empty() && ValidatedCorrections.size() == 1;
126   }
127
128   /// \brief Return the list of TypoCorrections for the given identifier from
129   /// the set of corrections that have the closest edit distance, if any.
130   TypoResultList &operator[](StringRef Name) {
131     return CorrectionResults.begin()->second[Name];
132   }
133
134   /// \brief Return the edit distance of the corrections that have the
135   /// closest/best edit distance from the original typop.
136   unsigned getBestEditDistance(bool Normalized) {
137     if (CorrectionResults.empty())
138       return (std::numeric_limits<unsigned>::max)();
139
140     unsigned BestED = CorrectionResults.begin()->first;
141     return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
142   }
143
144   /// \brief Set-up method to add to the consumer the set of namespaces to use
145   /// in performing corrections to nested name specifiers. This method also
146   /// implicitly adds all of the known classes in the current AST context to the
147   /// to the consumer for correcting nested name specifiers.
148   void
149   addNamespaces(const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces);
150
151   /// \brief Return the next typo correction that passes all internal filters
152   /// and is deemed valid by the consumer's CorrectionCandidateCallback,
153   /// starting with the corrections that have the closest edit distance. An
154   /// empty TypoCorrection is returned once no more viable corrections remain
155   /// in the consumer.
156   const TypoCorrection &getNextCorrection();
157
158   /// \brief Get the last correction returned by getNextCorrection().
159   const TypoCorrection &getCurrentCorrection() {
160     return CurrentTCIndex < ValidatedCorrections.size()
161                ? ValidatedCorrections[CurrentTCIndex]
162                : ValidatedCorrections[0];  // The empty correction.
163   }
164
165   /// \brief Return the next typo correction like getNextCorrection, but keep
166   /// the internal state pointed to the current correction (i.e. the next time
167   /// getNextCorrection is called, it will return the same correction returned
168   /// by peekNextcorrection).
169   const TypoCorrection &peekNextCorrection() {
170     auto Current = CurrentTCIndex;
171     const TypoCorrection &TC = getNextCorrection();
172     CurrentTCIndex = Current;
173     return TC;
174   }
175
176   /// \brief 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).
179   void resetCorrectionStream() {
180     CurrentTCIndex = 0;
181   }
182
183   /// \brief 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   ASTContext &getContext() const { return SemaRef.Context; }
191   const LookupResult &getLookupResult() const { return Result; }
192
193   bool isAddressOfOperand() const { return CorrectionValidator->IsAddressOfOperand; }
194   const CXXScopeSpec *getSS() const { return SS.get(); }
195   Scope *getScope() const { return S; }
196
197 private:
198   class NamespaceSpecifierSet {
199     struct SpecifierInfo {
200       DeclContext* DeclCtx;
201       NestedNameSpecifier* NameSpecifier;
202       unsigned EditDistance;
203     };
204
205     typedef SmallVector<DeclContext*, 4> DeclContextList;
206     typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
207
208     ASTContext &Context;
209     DeclContextList CurContextChain;
210     std::string CurNameSpecifier;
211     SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
212     SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
213     bool isSorted;
214
215     SpecifierInfoList Specifiers;
216     llvm::SmallSetVector<unsigned, 4> Distances;
217     llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
218
219     /// \brief Helper for building the list of DeclContexts between the current
220     /// context and the top of the translation unit
221     static DeclContextList buildContextChain(DeclContext *Start);
222
223     void sortNamespaces();
224
225     unsigned buildNestedNameSpecifier(DeclContextList &DeclChain,
226                                       NestedNameSpecifier *&NNS);
227
228    public:
229     NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
230                           CXXScopeSpec *CurScopeSpec);
231
232     /// \brief Add the DeclContext (a namespace or record) to the set, computing
233     /// the corresponding NestedNameSpecifier and its distance in the process.
234     void addNameSpecifier(DeclContext *Ctx);
235
236     typedef SpecifierInfoList::iterator iterator;
237     iterator begin() {
238       if (!isSorted) sortNamespaces();
239       return Specifiers.begin();
240     }
241     iterator end() { return Specifiers.end(); }
242   };
243
244   void addName(StringRef Name, NamedDecl *ND,
245                NestedNameSpecifier *NNS = nullptr, bool isKeyword = false);
246
247   /// \brief Find any visible decls for the given typo correction candidate.
248   /// If none are found, it to the set of candidates for which qualified lookups
249   /// will be performed to find possible nested name specifier changes.
250   bool resolveCorrection(TypoCorrection &Candidate);
251
252   /// \brief Perform qualified lookups on the queued set of typo correction
253   /// candidates and add the nested name specifier changes to each candidate if
254   /// a lookup succeeds (at which point the candidate will be returned to the
255   /// main pool of potential corrections).
256   void performQualifiedLookups();
257
258   /// \brief The name written that is a typo in the source.
259   IdentifierInfo *Typo;
260
261   /// \brief The results found that have the smallest edit distance
262   /// found (so far) with the typo name.
263   ///
264   /// The pointer value being set to the current DeclContext indicates
265   /// whether there is a keyword with this name.
266   TypoEditDistanceMap CorrectionResults;
267
268   SmallVector<TypoCorrection, 4> ValidatedCorrections;
269   size_t CurrentTCIndex;
270
271   Sema &SemaRef;
272   Scope *S;
273   std::unique_ptr<CXXScopeSpec> SS;
274   std::unique_ptr<CorrectionCandidateCallback> CorrectionValidator;
275   DeclContext *MemberContext;
276   LookupResult Result;
277   NamespaceSpecifierSet Namespaces;
278   SmallVector<TypoCorrection, 2> QualifiedResults;
279   bool EnteringContext;
280   bool SearchNamespaces;
281 };
282
283 inline Sema::TypoExprState::TypoExprState() {}
284
285 inline Sema::TypoExprState::TypoExprState(TypoExprState &&other) LLVM_NOEXCEPT {
286   *this = std::move(other);
287 }
288
289 inline Sema::TypoExprState &Sema::TypoExprState::operator=(
290     Sema::TypoExprState &&other) LLVM_NOEXCEPT {
291   Consumer = std::move(other.Consumer);
292   DiagHandler = std::move(other.DiagHandler);
293   RecoveryHandler = std::move(other.RecoveryHandler);
294   return *this;
295 }
296
297 } // end namespace clang
298
299 #endif