1 //===--- SemaInternal.h - Internal Sema Interfaces --------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides common API and #includes for the internal
10 // implementation of Sema.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_CLANG_SEMA_SEMAINTERNAL_H
15 #define LLVM_CLANG_SEMA_SEMAINTERNAL_H
16
17 #include "clang/AST/ASTContext.h"
18 #include "clang/Sema/Lookup.h"
19 #include "clang/Sema/Sema.h"
20 #include "clang/Sema/SemaDiagnostic.h"
21
22 namespace clang {
23
PDiag(unsigned DiagID)24 inline PartialDiagnostic Sema::PDiag(unsigned DiagID) {
25 return PartialDiagnostic(DiagID, Context.getDiagAllocator());
26 }
27
28 inline bool
FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo & FTI)29 FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI) {
30 return FTI.NumParams == 1 && !FTI.isVariadic &&
31 FTI.Params[0].Ident == nullptr && FTI.Params[0].Param &&
32 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType();
33 }
34
35 inline bool
FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo & FTI)36 FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI) {
37 // Assume FTI is well-formed.
38 return FTI.NumParams && !FTIHasSingleVoidParameter(FTI);
39 }
40
41 // Helper function to check whether D's attributes match current CUDA mode.
42 // Decls with mismatched attributes and related diagnostics may have to be
43 // ignored during this CUDA compilation pass.
DeclAttrsMatchCUDAMode(const LangOptions & LangOpts,Decl * D)44 inline bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D) {
45 if (!LangOpts.CUDA || !D)
46 return true;
47 bool isDeviceSideDecl = D->hasAttr<CUDADeviceAttr>() ||
48 D->hasAttr<CUDASharedAttr>() ||
49 D->hasAttr<CUDAGlobalAttr>();
50 return isDeviceSideDecl == LangOpts.CUDAIsDevice;
51 }
52
53 /// Return a DLL attribute from the declaration.
getDLLAttr(Decl * D)54 inline InheritableAttr *getDLLAttr(Decl *D) {
55 assert(!(D->hasAttr<DLLImportAttr>() && D->hasAttr<DLLExportAttr>()) &&
56 "A declaration cannot be both dllimport and dllexport.");
57 if (auto *Import = D->getAttr<DLLImportAttr>())
58 return Import;
59 if (auto *Export = D->getAttr<DLLExportAttr>())
60 return Export;
61 return nullptr;
62 }
63
64 /// Retrieve the depth and index of a template parameter.
getDepthAndIndex(NamedDecl * ND)65 inline std::pair<unsigned, unsigned> getDepthAndIndex(NamedDecl *ND) {
66 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
67 return std::make_pair(TTP->getDepth(), TTP->getIndex());
68
69 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
70 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
71
72 const auto *TTP = cast<TemplateTemplateParmDecl>(ND);
73 return std::make_pair(TTP->getDepth(), TTP->getIndex());
74 }
75
76 /// Retrieve the depth and index of an unexpanded parameter pack.
77 inline std::pair<unsigned, unsigned>
getDepthAndIndex(UnexpandedParameterPack UPP)78 getDepthAndIndex(UnexpandedParameterPack UPP) {
79 if (const auto *TTP = UPP.first.dyn_cast<const TemplateTypeParmType *>())
80 return std::make_pair(TTP->getDepth(), TTP->getIndex());
81
82 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
83 }
84
85 class TypoCorrectionConsumer : public VisibleDeclConsumer {
86 typedef SmallVector<TypoCorrection, 1> TypoResultList;
87 typedef llvm::StringMap<TypoResultList> TypoResultsMap;
88 typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
89
90 public:
TypoCorrectionConsumer(Sema & SemaRef,const DeclarationNameInfo & TypoName,Sema::LookupNameKind LookupKind,Scope * S,CXXScopeSpec * SS,std::unique_ptr<CorrectionCandidateCallback> CCC,DeclContext * MemberContext,bool EnteringContext)91 TypoCorrectionConsumer(Sema &SemaRef,
92 const DeclarationNameInfo &TypoName,
93 Sema::LookupNameKind LookupKind,
94 Scope *S, CXXScopeSpec *SS,
95 std::unique_ptr<CorrectionCandidateCallback> CCC,
96 DeclContext *MemberContext,
97 bool EnteringContext)
98 : Typo(TypoName.getName().getAsIdentifierInfo()), CurrentTCIndex(0),
99 SavedTCIndex(0), SemaRef(SemaRef), S(S),
100 SS(SS ? std::make_unique<CXXScopeSpec>(*SS) : nullptr),
101 CorrectionValidator(std::move(CCC)), MemberContext(MemberContext),
102 Result(SemaRef, TypoName, LookupKind),
103 Namespaces(SemaRef.Context, SemaRef.CurContext, SS),
104 EnteringContext(EnteringContext), SearchNamespaces(false) {
105 Result.suppressDiagnostics();
106 // Arrange for ValidatedCorrections[0] to always be an empty correction.
107 ValidatedCorrections.push_back(TypoCorrection());
108 }
109
includeHiddenDecls()110 bool includeHiddenDecls() const override { return true; }
111
112 // Methods for adding potential corrections to the consumer.
113 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
114 bool InBaseClass) override;
115 void FoundName(StringRef Name);
116 void addKeywordResult(StringRef Keyword);
117 void addCorrection(TypoCorrection Correction);
118
empty()119 bool empty() const {
120 return CorrectionResults.empty() && ValidatedCorrections.size() == 1;
121 }
122
123 /// Return the list of TypoCorrections for the given identifier from
124 /// the set of corrections that have the closest edit distance, if any.
125 TypoResultList &operator[](StringRef Name) {
126 return CorrectionResults.begin()->second[Name];
127 }
128
129 /// Return the edit distance of the corrections that have the
130 /// closest/best edit distance from the original typop.
getBestEditDistance(bool Normalized)131 unsigned getBestEditDistance(bool Normalized) {
132 if (CorrectionResults.empty())
133 return (std::numeric_limits<unsigned>::max)();
134
135 unsigned BestED = CorrectionResults.begin()->first;
136 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
137 }
138
139 /// Set-up method to add to the consumer the set of namespaces to use
140 /// in performing corrections to nested name specifiers. This method also
141 /// implicitly adds all of the known classes in the current AST context to the
142 /// to the consumer for correcting nested name specifiers.
143 void
144 addNamespaces(const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces);
145
146 /// Return the next typo correction that passes all internal filters
147 /// and is deemed valid by the consumer's CorrectionCandidateCallback,
148 /// starting with the corrections that have the closest edit distance. An
149 /// empty TypoCorrection is returned once no more viable corrections remain
150 /// in the consumer.
151 const TypoCorrection &getNextCorrection();
152
153 /// Get the last correction returned by getNextCorrection().
getCurrentCorrection()154 const TypoCorrection &getCurrentCorrection() {
155 return CurrentTCIndex < ValidatedCorrections.size()
156 ? ValidatedCorrections[CurrentTCIndex]
157 : ValidatedCorrections[0]; // The empty correction.
158 }
159
160 /// Return the next typo correction like getNextCorrection, but keep
161 /// the internal state pointed to the current correction (i.e. the next time
162 /// getNextCorrection is called, it will return the same correction returned
163 /// by peekNextcorrection).
peekNextCorrection()164 const TypoCorrection &peekNextCorrection() {
165 auto Current = CurrentTCIndex;
166 const TypoCorrection &TC = getNextCorrection();
167 CurrentTCIndex = Current;
168 return TC;
169 }
170
171 /// Reset the consumer's position in the stream of viable corrections
172 /// (i.e. getNextCorrection() will return each of the previously returned
173 /// corrections in order before returning any new corrections).
resetCorrectionStream()174 void resetCorrectionStream() {
175 CurrentTCIndex = 0;
176 }
177
178 /// Return whether the end of the stream of corrections has been
179 /// reached.
finished()180 bool finished() {
181 return CorrectionResults.empty() &&
182 CurrentTCIndex >= ValidatedCorrections.size();
183 }
184
185 /// Save the current position in the correction stream (overwriting any
186 /// previously saved position).
saveCurrentPosition()187 void saveCurrentPosition() {
188 SavedTCIndex = CurrentTCIndex;
189 }
190
191 /// Restore the saved position in the correction stream.
restoreSavedPosition()192 void restoreSavedPosition() {
193 CurrentTCIndex = SavedTCIndex;
194 }
195
getContext()196 ASTContext &getContext() const { return SemaRef.Context; }
getLookupResult()197 const LookupResult &getLookupResult() const { return Result; }
198
isAddressOfOperand()199 bool isAddressOfOperand() const { return CorrectionValidator->IsAddressOfOperand; }
getSS()200 const CXXScopeSpec *getSS() const { return SS.get(); }
getScope()201 Scope *getScope() const { return S; }
getCorrectionValidator()202 CorrectionCandidateCallback *getCorrectionValidator() const {
203 return CorrectionValidator.get();
204 }
205
206 private:
207 class NamespaceSpecifierSet {
208 struct SpecifierInfo {
209 DeclContext* DeclCtx;
210 NestedNameSpecifier* NameSpecifier;
211 unsigned EditDistance;
212 };
213
214 typedef SmallVector<DeclContext*, 4> DeclContextList;
215 typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
216
217 ASTContext &Context;
218 DeclContextList CurContextChain;
219 std::string CurNameSpecifier;
220 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
221 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
222
223 std::map<unsigned, SpecifierInfoList> DistanceMap;
224
225 /// Helper for building the list of DeclContexts between the current
226 /// context and the top of the translation unit
227 static DeclContextList buildContextChain(DeclContext *Start);
228
229 unsigned buildNestedNameSpecifier(DeclContextList &DeclChain,
230 NestedNameSpecifier *&NNS);
231
232 public:
233 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
234 CXXScopeSpec *CurScopeSpec);
235
236 /// Add the DeclContext (a namespace or record) to the set, computing
237 /// the corresponding NestedNameSpecifier and its distance in the process.
238 void addNameSpecifier(DeclContext *Ctx);
239
240 /// Provides flat iteration over specifiers, sorted by distance.
241 class iterator
242 : public llvm::iterator_facade_base<iterator, std::forward_iterator_tag,
243 SpecifierInfo> {
244 /// Always points to the last element in the distance map.
245 const std::map<unsigned, SpecifierInfoList>::iterator OuterBack;
246 /// Iterator on the distance map.
247 std::map<unsigned, SpecifierInfoList>::iterator Outer;
248 /// Iterator on an element in the distance map.
249 SpecifierInfoList::iterator Inner;
250
251 public:
iterator(NamespaceSpecifierSet & Set,bool IsAtEnd)252 iterator(NamespaceSpecifierSet &Set, bool IsAtEnd)
253 : OuterBack(std::prev(Set.DistanceMap.end())),
254 Outer(Set.DistanceMap.begin()),
255 Inner(!IsAtEnd ? Outer->second.begin() : OuterBack->second.end()) {
256 assert(!Set.DistanceMap.empty());
257 }
258
259 iterator &operator++() {
260 ++Inner;
261 if (Inner == Outer->second.end() && Outer != OuterBack) {
262 ++Outer;
263 Inner = Outer->second.begin();
264 }
265 return *this;
266 }
267
268 SpecifierInfo &operator*() { return *Inner; }
269 bool operator==(const iterator &RHS) const { return Inner == RHS.Inner; }
270 };
271
begin()272 iterator begin() { return iterator(*this, /*IsAtEnd=*/false); }
end()273 iterator end() { return iterator(*this, /*IsAtEnd=*/true); }
274 };
275
276 void addName(StringRef Name, NamedDecl *ND,
277 NestedNameSpecifier *NNS = nullptr, bool isKeyword = false);
278
279 /// Find any visible decls for the given typo correction candidate.
280 /// If none are found, it to the set of candidates for which qualified lookups
281 /// will be performed to find possible nested name specifier changes.
282 bool resolveCorrection(TypoCorrection &Candidate);
283
284 /// Perform qualified lookups on the queued set of typo correction
285 /// candidates and add the nested name specifier changes to each candidate if
286 /// a lookup succeeds (at which point the candidate will be returned to the
287 /// main pool of potential corrections).
288 void performQualifiedLookups();
289
290 /// The name written that is a typo in the source.
291 IdentifierInfo *Typo;
292
293 /// The results found that have the smallest edit distance
294 /// found (so far) with the typo name.
295 ///
296 /// The pointer value being set to the current DeclContext indicates
297 /// whether there is a keyword with this name.
298 TypoEditDistanceMap CorrectionResults;
299
300 SmallVector<TypoCorrection, 4> ValidatedCorrections;
301 size_t CurrentTCIndex;
302 size_t SavedTCIndex;
303
304 Sema &SemaRef;
305 Scope *S;
306 std::unique_ptr<CXXScopeSpec> SS;
307 std::unique_ptr<CorrectionCandidateCallback> CorrectionValidator;
308 DeclContext *MemberContext;
309 LookupResult Result;
310 NamespaceSpecifierSet Namespaces;
311 SmallVector<TypoCorrection, 2> QualifiedResults;
312 bool EnteringContext;
313 bool SearchNamespaces;
314 };
315
TypoExprState()316 inline Sema::TypoExprState::TypoExprState() {}
317
TypoExprState(TypoExprState && other)318 inline Sema::TypoExprState::TypoExprState(TypoExprState &&other) noexcept {
319 *this = std::move(other);
320 }
321
322 inline Sema::TypoExprState &Sema::TypoExprState::
323 operator=(Sema::TypoExprState &&other) noexcept {
324 Consumer = std::move(other.Consumer);
325 DiagHandler = std::move(other.DiagHandler);
326 RecoveryHandler = std::move(other.RecoveryHandler);
327 return *this;
328 }
329
330 } // end namespace clang
331
332 #endif
333