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 
PDiag(unsigned DiagID)25 inline PartialDiagnostic Sema::PDiag(unsigned DiagID) {
26   return PartialDiagnostic(DiagID, Context.getDiagAllocator());
27 }
28 
29 inline bool
FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo & FTI)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
FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo & FTI)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.
IsVariableAConstantExpression(VarDecl * Var,ASTContext & Context)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.
MarkVarDeclODRUsed(VarDecl * Var,SourceLocation Loc,Sema & SemaRef,const unsigned * const FunctionScopeIndexToStopAt)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.
getDLLAttr(Decl * D)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:
TypoCorrectionConsumer(Sema & SemaRef,const DeclarationNameInfo & TypoName,Sema::LookupNameKind LookupKind,Scope * S,CXXScopeSpec * SS,std::unique_ptr<CorrectionCandidateCallback> CCC,DeclContext * MemberContext,bool EnteringContext)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         SavedTCIndex(0), 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 
includeHiddenDecls()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 
empty()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.
getBestEditDistance(bool Normalized)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().
getCurrentCorrection()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).
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).
resetCorrectionStream()179   void resetCorrectionStream() {
180     CurrentTCIndex = 0;
181   }
182 
183   /// \brief Return whether the end of the stream of corrections has been
184   /// reached.
finished()185   bool finished() {
186     return CorrectionResults.empty() &&
187            CurrentTCIndex >= ValidatedCorrections.size();
188   }
189 
190   /// \brief Save the current position in the correction stream (overwriting any
191   /// previously saved position).
saveCurrentPosition()192   void saveCurrentPosition() {
193     SavedTCIndex = CurrentTCIndex;
194   }
195 
196   /// \brief Restore the saved position in the correction stream.
restoreSavedPosition()197   void restoreSavedPosition() {
198     CurrentTCIndex = SavedTCIndex;
199   }
200 
getContext()201   ASTContext &getContext() const { return SemaRef.Context; }
getLookupResult()202   const LookupResult &getLookupResult() const { return Result; }
203 
isAddressOfOperand()204   bool isAddressOfOperand() const { return CorrectionValidator->IsAddressOfOperand; }
getSS()205   const CXXScopeSpec *getSS() const { return SS.get(); }
getScope()206   Scope *getScope() const { return S; }
207 
208 private:
209   class NamespaceSpecifierSet {
210     struct SpecifierInfo {
211       DeclContext* DeclCtx;
212       NestedNameSpecifier* NameSpecifier;
213       unsigned EditDistance;
214     };
215 
216     typedef SmallVector<DeclContext*, 4> DeclContextList;
217     typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
218 
219     ASTContext &Context;
220     DeclContextList CurContextChain;
221     std::string CurNameSpecifier;
222     SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
223     SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
224     bool isSorted;
225 
226     SpecifierInfoList Specifiers;
227     llvm::SmallSetVector<unsigned, 4> Distances;
228     llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
229 
230     /// \brief Helper for building the list of DeclContexts between the current
231     /// context and the top of the translation unit
232     static DeclContextList buildContextChain(DeclContext *Start);
233 
234     void sortNamespaces();
235 
236     unsigned buildNestedNameSpecifier(DeclContextList &DeclChain,
237                                       NestedNameSpecifier *&NNS);
238 
239    public:
240     NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
241                           CXXScopeSpec *CurScopeSpec);
242 
243     /// \brief Add the DeclContext (a namespace or record) to the set, computing
244     /// the corresponding NestedNameSpecifier and its distance in the process.
245     void addNameSpecifier(DeclContext *Ctx);
246 
247     typedef SpecifierInfoList::iterator iterator;
begin()248     iterator begin() {
249       if (!isSorted) sortNamespaces();
250       return Specifiers.begin();
251     }
end()252     iterator end() { return Specifiers.end(); }
253   };
254 
255   void addName(StringRef Name, NamedDecl *ND,
256                NestedNameSpecifier *NNS = nullptr, bool isKeyword = false);
257 
258   /// \brief Find any visible decls for the given typo correction candidate.
259   /// If none are found, it to the set of candidates for which qualified lookups
260   /// will be performed to find possible nested name specifier changes.
261   bool resolveCorrection(TypoCorrection &Candidate);
262 
263   /// \brief Perform qualified lookups on the queued set of typo correction
264   /// candidates and add the nested name specifier changes to each candidate if
265   /// a lookup succeeds (at which point the candidate will be returned to the
266   /// main pool of potential corrections).
267   void performQualifiedLookups();
268 
269   /// \brief The name written that is a typo in the source.
270   IdentifierInfo *Typo;
271 
272   /// \brief The results found that have the smallest edit distance
273   /// found (so far) with the typo name.
274   ///
275   /// The pointer value being set to the current DeclContext indicates
276   /// whether there is a keyword with this name.
277   TypoEditDistanceMap CorrectionResults;
278 
279   SmallVector<TypoCorrection, 4> ValidatedCorrections;
280   size_t CurrentTCIndex;
281   size_t SavedTCIndex;
282 
283   Sema &SemaRef;
284   Scope *S;
285   std::unique_ptr<CXXScopeSpec> SS;
286   std::unique_ptr<CorrectionCandidateCallback> CorrectionValidator;
287   DeclContext *MemberContext;
288   LookupResult Result;
289   NamespaceSpecifierSet Namespaces;
290   SmallVector<TypoCorrection, 2> QualifiedResults;
291   bool EnteringContext;
292   bool SearchNamespaces;
293 };
294 
TypoExprState()295 inline Sema::TypoExprState::TypoExprState() {}
296 
TypoExprState(TypoExprState && other)297 inline Sema::TypoExprState::TypoExprState(TypoExprState &&other) LLVM_NOEXCEPT {
298   *this = std::move(other);
299 }
300 
301 inline Sema::TypoExprState &Sema::TypoExprState::operator=(
302     Sema::TypoExprState &&other) LLVM_NOEXCEPT {
303   Consumer = std::move(other.Consumer);
304   DiagHandler = std::move(other.DiagHandler);
305   RecoveryHandler = std::move(other.RecoveryHandler);
306   return *this;
307 }
308 
309 } // end namespace clang
310 
311 #endif
312