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
225 std::map<unsigned, SpecifierInfoList> DistanceMap;
226
227 /// \brief Helper for building the list of DeclContexts between the current
228 /// context and the top of the translation unit
229 static DeclContextList buildContextChain(DeclContext *Start);
230
231 unsigned buildNestedNameSpecifier(DeclContextList &DeclChain,
232 NestedNameSpecifier *&NNS);
233
234 public:
235 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
236 CXXScopeSpec *CurScopeSpec);
237
238 /// \brief Add the DeclContext (a namespace or record) to the set, computing
239 /// the corresponding NestedNameSpecifier and its distance in the process.
240 void addNameSpecifier(DeclContext *Ctx);
241
242 /// \brief Provides flat iteration over specifiers, sorted by distance.
243 class iterator
244 : public llvm::iterator_facade_base<iterator, std::forward_iterator_tag,
245 SpecifierInfo> {
246 /// Always points to the last element in the distance map.
247 const std::map<unsigned, SpecifierInfoList>::iterator OuterBack;
248 /// Iterator on the distance map.
249 std::map<unsigned, SpecifierInfoList>::iterator Outer;
250 /// Iterator on an element in the distance map.
251 SpecifierInfoList::iterator Inner;
252
253 public:
iterator(NamespaceSpecifierSet & Set,bool IsAtEnd)254 iterator(NamespaceSpecifierSet &Set, bool IsAtEnd)
255 : OuterBack(std::prev(Set.DistanceMap.end())),
256 Outer(Set.DistanceMap.begin()),
257 Inner(!IsAtEnd ? Outer->second.begin() : OuterBack->second.end()) {
258 assert(!Set.DistanceMap.empty());
259 }
260
261 iterator &operator++() {
262 ++Inner;
263 if (Inner == Outer->second.end() && Outer != OuterBack) {
264 ++Outer;
265 Inner = Outer->second.begin();
266 }
267 return *this;
268 }
269
270 SpecifierInfo &operator*() { return *Inner; }
271 bool operator==(const iterator &RHS) const { return Inner == RHS.Inner; }
272 };
273
begin()274 iterator begin() { return iterator(*this, /*IsAtEnd=*/false); }
end()275 iterator end() { return iterator(*this, /*IsAtEnd=*/true); }
276 };
277
278 void addName(StringRef Name, NamedDecl *ND,
279 NestedNameSpecifier *NNS = nullptr, bool isKeyword = false);
280
281 /// \brief Find any visible decls for the given typo correction candidate.
282 /// If none are found, it to the set of candidates for which qualified lookups
283 /// will be performed to find possible nested name specifier changes.
284 bool resolveCorrection(TypoCorrection &Candidate);
285
286 /// \brief Perform qualified lookups on the queued set of typo correction
287 /// candidates and add the nested name specifier changes to each candidate if
288 /// a lookup succeeds (at which point the candidate will be returned to the
289 /// main pool of potential corrections).
290 void performQualifiedLookups();
291
292 /// \brief The name written that is a typo in the source.
293 IdentifierInfo *Typo;
294
295 /// \brief The results found that have the smallest edit distance
296 /// found (so far) with the typo name.
297 ///
298 /// The pointer value being set to the current DeclContext indicates
299 /// whether there is a keyword with this name.
300 TypoEditDistanceMap CorrectionResults;
301
302 SmallVector<TypoCorrection, 4> ValidatedCorrections;
303 size_t CurrentTCIndex;
304 size_t SavedTCIndex;
305
306 Sema &SemaRef;
307 Scope *S;
308 std::unique_ptr<CXXScopeSpec> SS;
309 std::unique_ptr<CorrectionCandidateCallback> CorrectionValidator;
310 DeclContext *MemberContext;
311 LookupResult Result;
312 NamespaceSpecifierSet Namespaces;
313 SmallVector<TypoCorrection, 2> QualifiedResults;
314 bool EnteringContext;
315 bool SearchNamespaces;
316 };
317
TypoExprState()318 inline Sema::TypoExprState::TypoExprState() {}
319
TypoExprState(TypoExprState && other)320 inline Sema::TypoExprState::TypoExprState(TypoExprState &&other) LLVM_NOEXCEPT {
321 *this = std::move(other);
322 }
323
324 inline Sema::TypoExprState &Sema::TypoExprState::operator=(
325 Sema::TypoExprState &&other) LLVM_NOEXCEPT {
326 Consumer = std::move(other.Consumer);
327 DiagHandler = std::move(other.DiagHandler);
328 RecoveryHandler = std::move(other.RecoveryHandler);
329 return *this;
330 }
331
332 } // end namespace clang
333
334 #endif
335