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 // 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.
DeclAttrsMatchCUDAMode(const LangOptions & LangOpts,Decl * D)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.
MarkVarDeclODRUsed(VarDecl * Var,SourceLocation Loc,Sema & SemaRef,const unsigned * const FunctionScopeIndexToStopAt)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.
getDLLAttr(Decl * D)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 /// Retrieve the depth and index of a template parameter.
getDepthAndIndex(NamedDecl * ND)105 inline std::pair<unsigned, unsigned> getDepthAndIndex(NamedDecl *ND) {
106 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
107 return std::make_pair(TTP->getDepth(), TTP->getIndex());
108
109 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
110 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
111
112 const auto *TTP = cast<TemplateTemplateParmDecl>(ND);
113 return std::make_pair(TTP->getDepth(), TTP->getIndex());
114 }
115
116 /// Retrieve the depth and index of an unexpanded parameter pack.
117 inline std::pair<unsigned, unsigned>
getDepthAndIndex(UnexpandedParameterPack UPP)118 getDepthAndIndex(UnexpandedParameterPack UPP) {
119 if (const auto *TTP = UPP.first.dyn_cast<const TemplateTypeParmType *>())
120 return std::make_pair(TTP->getDepth(), TTP->getIndex());
121
122 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
123 }
124
125 class TypoCorrectionConsumer : public VisibleDeclConsumer {
126 typedef SmallVector<TypoCorrection, 1> TypoResultList;
127 typedef llvm::StringMap<TypoResultList> TypoResultsMap;
128 typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
129
130 public:
TypoCorrectionConsumer(Sema & SemaRef,const DeclarationNameInfo & TypoName,Sema::LookupNameKind LookupKind,Scope * S,CXXScopeSpec * SS,std::unique_ptr<CorrectionCandidateCallback> CCC,DeclContext * MemberContext,bool EnteringContext)131 TypoCorrectionConsumer(Sema &SemaRef,
132 const DeclarationNameInfo &TypoName,
133 Sema::LookupNameKind LookupKind,
134 Scope *S, CXXScopeSpec *SS,
135 std::unique_ptr<CorrectionCandidateCallback> CCC,
136 DeclContext *MemberContext,
137 bool EnteringContext)
138 : Typo(TypoName.getName().getAsIdentifierInfo()), CurrentTCIndex(0),
139 SavedTCIndex(0), SemaRef(SemaRef), S(S),
140 SS(SS ? llvm::make_unique<CXXScopeSpec>(*SS) : nullptr),
141 CorrectionValidator(std::move(CCC)), MemberContext(MemberContext),
142 Result(SemaRef, TypoName, LookupKind),
143 Namespaces(SemaRef.Context, SemaRef.CurContext, SS),
144 EnteringContext(EnteringContext), SearchNamespaces(false) {
145 Result.suppressDiagnostics();
146 // Arrange for ValidatedCorrections[0] to always be an empty correction.
147 ValidatedCorrections.push_back(TypoCorrection());
148 }
149
includeHiddenDecls()150 bool includeHiddenDecls() const override { return true; }
151
152 // Methods for adding potential corrections to the consumer.
153 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
154 bool InBaseClass) override;
155 void FoundName(StringRef Name);
156 void addKeywordResult(StringRef Keyword);
157 void addCorrection(TypoCorrection Correction);
158
empty()159 bool empty() const {
160 return CorrectionResults.empty() && ValidatedCorrections.size() == 1;
161 }
162
163 /// Return the list of TypoCorrections for the given identifier from
164 /// the set of corrections that have the closest edit distance, if any.
165 TypoResultList &operator[](StringRef Name) {
166 return CorrectionResults.begin()->second[Name];
167 }
168
169 /// Return the edit distance of the corrections that have the
170 /// closest/best edit distance from the original typop.
getBestEditDistance(bool Normalized)171 unsigned getBestEditDistance(bool Normalized) {
172 if (CorrectionResults.empty())
173 return (std::numeric_limits<unsigned>::max)();
174
175 unsigned BestED = CorrectionResults.begin()->first;
176 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
177 }
178
179 /// Set-up method to add to the consumer the set of namespaces to use
180 /// in performing corrections to nested name specifiers. This method also
181 /// implicitly adds all of the known classes in the current AST context to the
182 /// to the consumer for correcting nested name specifiers.
183 void
184 addNamespaces(const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces);
185
186 /// Return the next typo correction that passes all internal filters
187 /// and is deemed valid by the consumer's CorrectionCandidateCallback,
188 /// starting with the corrections that have the closest edit distance. An
189 /// empty TypoCorrection is returned once no more viable corrections remain
190 /// in the consumer.
191 const TypoCorrection &getNextCorrection();
192
193 /// Get the last correction returned by getNextCorrection().
getCurrentCorrection()194 const TypoCorrection &getCurrentCorrection() {
195 return CurrentTCIndex < ValidatedCorrections.size()
196 ? ValidatedCorrections[CurrentTCIndex]
197 : ValidatedCorrections[0]; // The empty correction.
198 }
199
200 /// Return the next typo correction like getNextCorrection, but keep
201 /// the internal state pointed to the current correction (i.e. the next time
202 /// getNextCorrection is called, it will return the same correction returned
203 /// by peekNextcorrection).
peekNextCorrection()204 const TypoCorrection &peekNextCorrection() {
205 auto Current = CurrentTCIndex;
206 const TypoCorrection &TC = getNextCorrection();
207 CurrentTCIndex = Current;
208 return TC;
209 }
210
211 /// Reset the consumer's position in the stream of viable corrections
212 /// (i.e. getNextCorrection() will return each of the previously returned
213 /// corrections in order before returning any new corrections).
resetCorrectionStream()214 void resetCorrectionStream() {
215 CurrentTCIndex = 0;
216 }
217
218 /// Return whether the end of the stream of corrections has been
219 /// reached.
finished()220 bool finished() {
221 return CorrectionResults.empty() &&
222 CurrentTCIndex >= ValidatedCorrections.size();
223 }
224
225 /// Save the current position in the correction stream (overwriting any
226 /// previously saved position).
saveCurrentPosition()227 void saveCurrentPosition() {
228 SavedTCIndex = CurrentTCIndex;
229 }
230
231 /// Restore the saved position in the correction stream.
restoreSavedPosition()232 void restoreSavedPosition() {
233 CurrentTCIndex = SavedTCIndex;
234 }
235
getContext()236 ASTContext &getContext() const { return SemaRef.Context; }
getLookupResult()237 const LookupResult &getLookupResult() const { return Result; }
238
isAddressOfOperand()239 bool isAddressOfOperand() const { return CorrectionValidator->IsAddressOfOperand; }
getSS()240 const CXXScopeSpec *getSS() const { return SS.get(); }
getScope()241 Scope *getScope() const { return S; }
getCorrectionValidator()242 CorrectionCandidateCallback *getCorrectionValidator() const {
243 return CorrectionValidator.get();
244 }
245
246 private:
247 class NamespaceSpecifierSet {
248 struct SpecifierInfo {
249 DeclContext* DeclCtx;
250 NestedNameSpecifier* NameSpecifier;
251 unsigned EditDistance;
252 };
253
254 typedef SmallVector<DeclContext*, 4> DeclContextList;
255 typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
256
257 ASTContext &Context;
258 DeclContextList CurContextChain;
259 std::string CurNameSpecifier;
260 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
261 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
262
263 std::map<unsigned, SpecifierInfoList> DistanceMap;
264
265 /// Helper for building the list of DeclContexts between the current
266 /// context and the top of the translation unit
267 static DeclContextList buildContextChain(DeclContext *Start);
268
269 unsigned buildNestedNameSpecifier(DeclContextList &DeclChain,
270 NestedNameSpecifier *&NNS);
271
272 public:
273 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
274 CXXScopeSpec *CurScopeSpec);
275
276 /// Add the DeclContext (a namespace or record) to the set, computing
277 /// the corresponding NestedNameSpecifier and its distance in the process.
278 void addNameSpecifier(DeclContext *Ctx);
279
280 /// Provides flat iteration over specifiers, sorted by distance.
281 class iterator
282 : public llvm::iterator_facade_base<iterator, std::forward_iterator_tag,
283 SpecifierInfo> {
284 /// Always points to the last element in the distance map.
285 const std::map<unsigned, SpecifierInfoList>::iterator OuterBack;
286 /// Iterator on the distance map.
287 std::map<unsigned, SpecifierInfoList>::iterator Outer;
288 /// Iterator on an element in the distance map.
289 SpecifierInfoList::iterator Inner;
290
291 public:
iterator(NamespaceSpecifierSet & Set,bool IsAtEnd)292 iterator(NamespaceSpecifierSet &Set, bool IsAtEnd)
293 : OuterBack(std::prev(Set.DistanceMap.end())),
294 Outer(Set.DistanceMap.begin()),
295 Inner(!IsAtEnd ? Outer->second.begin() : OuterBack->second.end()) {
296 assert(!Set.DistanceMap.empty());
297 }
298
299 iterator &operator++() {
300 ++Inner;
301 if (Inner == Outer->second.end() && Outer != OuterBack) {
302 ++Outer;
303 Inner = Outer->second.begin();
304 }
305 return *this;
306 }
307
308 SpecifierInfo &operator*() { return *Inner; }
309 bool operator==(const iterator &RHS) const { return Inner == RHS.Inner; }
310 };
311
begin()312 iterator begin() { return iterator(*this, /*IsAtEnd=*/false); }
end()313 iterator end() { return iterator(*this, /*IsAtEnd=*/true); }
314 };
315
316 void addName(StringRef Name, NamedDecl *ND,
317 NestedNameSpecifier *NNS = nullptr, bool isKeyword = false);
318
319 /// Find any visible decls for the given typo correction candidate.
320 /// If none are found, it to the set of candidates for which qualified lookups
321 /// will be performed to find possible nested name specifier changes.
322 bool resolveCorrection(TypoCorrection &Candidate);
323
324 /// Perform qualified lookups on the queued set of typo correction
325 /// candidates and add the nested name specifier changes to each candidate if
326 /// a lookup succeeds (at which point the candidate will be returned to the
327 /// main pool of potential corrections).
328 void performQualifiedLookups();
329
330 /// The name written that is a typo in the source.
331 IdentifierInfo *Typo;
332
333 /// The results found that have the smallest edit distance
334 /// found (so far) with the typo name.
335 ///
336 /// The pointer value being set to the current DeclContext indicates
337 /// whether there is a keyword with this name.
338 TypoEditDistanceMap CorrectionResults;
339
340 SmallVector<TypoCorrection, 4> ValidatedCorrections;
341 size_t CurrentTCIndex;
342 size_t SavedTCIndex;
343
344 Sema &SemaRef;
345 Scope *S;
346 std::unique_ptr<CXXScopeSpec> SS;
347 std::unique_ptr<CorrectionCandidateCallback> CorrectionValidator;
348 DeclContext *MemberContext;
349 LookupResult Result;
350 NamespaceSpecifierSet Namespaces;
351 SmallVector<TypoCorrection, 2> QualifiedResults;
352 bool EnteringContext;
353 bool SearchNamespaces;
354 };
355
TypoExprState()356 inline Sema::TypoExprState::TypoExprState() {}
357
TypoExprState(TypoExprState && other)358 inline Sema::TypoExprState::TypoExprState(TypoExprState &&other) noexcept {
359 *this = std::move(other);
360 }
361
362 inline Sema::TypoExprState &Sema::TypoExprState::
363 operator=(Sema::TypoExprState &&other) noexcept {
364 Consumer = std::move(other.Consumer);
365 DiagHandler = std::move(other.DiagHandler);
366 RecoveryHandler = std::move(other.RecoveryHandler);
367 return *this;
368 }
369
370 } // end namespace clang
371
372 #endif
373