clang 20.0.0git
SemaInternal.h
Go to the documentation of this file.
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
18#include "clang/Sema/Lookup.h"
19#include "clang/Sema/Sema.h"
21
22namespace clang {
23
24inline bool
26 return FTI.NumParams == 1 && !FTI.isVariadic &&
27 FTI.Params[0].Ident == nullptr && FTI.Params[0].Param &&
28 cast<ParmVarDecl>(FTI.Params[0].Param)->getType()->isVoidType();
29}
30
31inline bool
33 // Assume FTI is well-formed.
34 return FTI.NumParams && !FTIHasSingleVoidParameter(FTI);
35}
36
37// Helper function to check whether D's attributes match current CUDA mode.
38// Decls with mismatched attributes and related diagnostics may have to be
39// ignored during this CUDA compilation pass.
40inline bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D) {
41 if (!LangOpts.CUDA || !D)
42 return true;
43 bool isDeviceSideDecl = D->hasAttr<CUDADeviceAttr>() ||
44 D->hasAttr<CUDASharedAttr>() ||
45 D->hasAttr<CUDAGlobalAttr>();
46 return isDeviceSideDecl == LangOpts.CUDAIsDevice;
47}
48
49/// Return a DLL attribute from the declaration.
51 assert(!(D->hasAttr<DLLImportAttr>() && D->hasAttr<DLLExportAttr>()) &&
52 "A declaration cannot be both dllimport and dllexport.");
53 if (auto *Import = D->getAttr<DLLImportAttr>())
54 return Import;
55 if (auto *Export = D->getAttr<DLLExportAttr>())
56 return Export;
57 return nullptr;
58}
59
60/// Retrieve the depth and index of a template parameter.
61inline std::pair<unsigned, unsigned> getDepthAndIndex(NamedDecl *ND) {
62 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
63 return std::make_pair(TTP->getDepth(), TTP->getIndex());
64
65 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
66 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
67
68 const auto *TTP = cast<TemplateTemplateParmDecl>(ND);
69 return std::make_pair(TTP->getDepth(), TTP->getIndex());
70}
71
72/// Retrieve the depth and index of an unexpanded parameter pack.
73inline std::pair<unsigned, unsigned>
75 if (const auto *TTP = UPP.first.dyn_cast<const TemplateTypeParmType *>())
76 return std::make_pair(TTP->getDepth(), TTP->getIndex());
77
78 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
79}
80
83 typedef llvm::StringMap<TypoResultList> TypoResultsMap;
84 typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
85
86public:
88 const DeclarationNameInfo &TypoName,
89 Sema::LookupNameKind LookupKind,
90 Scope *S, CXXScopeSpec *SS,
91 std::unique_ptr<CorrectionCandidateCallback> CCC,
92 DeclContext *MemberContext,
93 bool EnteringContext)
94 : Typo(TypoName.getName().getAsIdentifierInfo()), CurrentTCIndex(0),
95 SavedTCIndex(0), SemaRef(SemaRef), S(S),
96 SS(SS ? std::make_unique<CXXScopeSpec>(*SS) : nullptr),
97 CorrectionValidator(std::move(CCC)), MemberContext(MemberContext),
98 Result(SemaRef, TypoName, LookupKind),
99 Namespaces(SemaRef.Context, SemaRef.CurContext, SS),
100 EnteringContext(EnteringContext), SearchNamespaces(false) {
101 Result.suppressDiagnostics();
102 // Arrange for ValidatedCorrections[0] to always be an empty correction.
103 ValidatedCorrections.push_back(TypoCorrection());
104 }
105
106 bool includeHiddenDecls() const override { return true; }
107
108 // Methods for adding potential corrections to the consumer.
109 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
110 bool InBaseClass) override;
111 void FoundName(StringRef Name);
112 void addKeywordResult(StringRef Keyword);
113 void addCorrection(TypoCorrection Correction);
114
115 bool empty() const {
116 return CorrectionResults.empty() && ValidatedCorrections.size() == 1;
117 }
118
119 /// Return the list of TypoCorrections for the given identifier from
120 /// the set of corrections that have the closest edit distance, if any.
121 TypoResultList &operator[](StringRef Name) {
122 return CorrectionResults.begin()->second[Name];
123 }
124
125 /// Return the edit distance of the corrections that have the
126 /// closest/best edit distance from the original typop.
127 unsigned getBestEditDistance(bool Normalized) {
128 if (CorrectionResults.empty())
129 return (std::numeric_limits<unsigned>::max)();
130
131 unsigned BestED = CorrectionResults.begin()->first;
132 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
133 }
134
135 /// Set-up method to add to the consumer the set of namespaces to use
136 /// in performing corrections to nested name specifiers. This method also
137 /// implicitly adds all of the known classes in the current AST context to the
138 /// to the consumer for correcting nested name specifiers.
139 void
140 addNamespaces(const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces);
141
142 /// Return the next typo correction that passes all internal filters
143 /// and is deemed valid by the consumer's CorrectionCandidateCallback,
144 /// starting with the corrections that have the closest edit distance. An
145 /// empty TypoCorrection is returned once no more viable corrections remain
146 /// in the consumer.
148
149 /// Get the last correction returned by getNextCorrection().
151 return CurrentTCIndex < ValidatedCorrections.size()
152 ? ValidatedCorrections[CurrentTCIndex]
153 : ValidatedCorrections[0]; // The empty correction.
154 }
155
156 /// Return the next typo correction like getNextCorrection, but keep
157 /// the internal state pointed to the current correction (i.e. the next time
158 /// getNextCorrection is called, it will return the same correction returned
159 /// by peekNextcorrection).
161 auto Current = CurrentTCIndex;
162 const TypoCorrection &TC = getNextCorrection();
163 CurrentTCIndex = Current;
164 return TC;
165 }
166
167 /// In the case of deeply invalid expressions, `getNextCorrection()` will
168 /// never be called since the transform never makes progress. If we don't
169 /// detect this we risk trying to correct typos forever.
170 bool hasMadeAnyCorrectionProgress() const { return CurrentTCIndex != 0; }
171
172 /// Reset the consumer's position in the stream of viable corrections
173 /// (i.e. getNextCorrection() will return each of the previously returned
174 /// corrections in order before returning any new corrections).
176 CurrentTCIndex = 0;
177 }
178
179 /// Return whether the end of the stream of corrections has been
180 /// reached.
181 bool finished() {
182 return CorrectionResults.empty() &&
183 CurrentTCIndex >= ValidatedCorrections.size();
184 }
185
186 /// Save the current position in the correction stream (overwriting any
187 /// previously saved position).
189 SavedTCIndex = CurrentTCIndex;
190 }
191
192 /// Restore the saved position in the correction stream.
194 CurrentTCIndex = SavedTCIndex;
195 }
196
197 ASTContext &getContext() const { return SemaRef.Context; }
198 const LookupResult &getLookupResult() const { return Result; }
199
200 bool isAddressOfOperand() const { return CorrectionValidator->IsAddressOfOperand; }
201 const CXXScopeSpec *getSS() const { return SS.get(); }
202 Scope *getScope() const { return S; }
204 return CorrectionValidator.get();
205 }
206
207private:
208 class NamespaceSpecifierSet {
209 struct SpecifierInfo {
210 DeclContext* DeclCtx;
211 NestedNameSpecifier* NameSpecifier;
212 unsigned EditDistance;
213 };
214
215 typedef SmallVector<DeclContext*, 4> DeclContextList;
216 typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
217
218 ASTContext &Context;
219 DeclContextList CurContextChain;
220 std::string CurNameSpecifier;
221 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
222 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
223
224 std::map<unsigned, SpecifierInfoList> DistanceMap;
225
226 /// Helper for building the list of DeclContexts between the current
227 /// context and the top of the translation unit
228 static DeclContextList buildContextChain(DeclContext *Start);
229
230 unsigned buildNestedNameSpecifier(DeclContextList &DeclChain,
231 NestedNameSpecifier *&NNS);
232
233 public:
234 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
235 CXXScopeSpec *CurScopeSpec);
236
237 /// Add the DeclContext (a namespace or record) to the set, computing
238 /// the corresponding NestedNameSpecifier and its distance in the process.
239 void addNameSpecifier(DeclContext *Ctx);
240
241 /// Provides flat iteration over specifiers, sorted by distance.
243 : public llvm::iterator_facade_base<iterator, std::forward_iterator_tag,
244 SpecifierInfo> {
245 /// Always points to the last element in the distance map.
246 const std::map<unsigned, SpecifierInfoList>::iterator OuterBack;
247 /// Iterator on the distance map.
248 std::map<unsigned, SpecifierInfoList>::iterator Outer;
249 /// Iterator on an element in the distance map.
250 SpecifierInfoList::iterator Inner;
251
252 public:
253 iterator(NamespaceSpecifierSet &Set, bool IsAtEnd)
254 : OuterBack(std::prev(Set.DistanceMap.end())),
255 Outer(Set.DistanceMap.begin()),
256 Inner(!IsAtEnd ? Outer->second.begin() : OuterBack->second.end()) {
257 assert(!Set.DistanceMap.empty());
258 }
259
261 ++Inner;
262 if (Inner == Outer->second.end() && Outer != OuterBack) {
263 ++Outer;
264 Inner = Outer->second.begin();
265 }
266 return *this;
267 }
268
269 SpecifierInfo &operator*() { return *Inner; }
270 bool operator==(const iterator &RHS) const { return Inner == RHS.Inner; }
271 };
272
273 iterator begin() { return iterator(*this, /*IsAtEnd=*/false); }
274 iterator end() { return iterator(*this, /*IsAtEnd=*/true); }
275 };
276
277 void addName(StringRef Name, NamedDecl *ND,
278 NestedNameSpecifier *NNS = nullptr, bool isKeyword = false);
279
280 /// Find any visible decls for the given typo correction candidate.
281 /// If none are found, it to the set of candidates for which qualified lookups
282 /// will be performed to find possible nested name specifier changes.
283 bool resolveCorrection(TypoCorrection &Candidate);
284
285 /// Perform qualified lookups on the queued set of typo correction
286 /// candidates and add the nested name specifier changes to each candidate if
287 /// a lookup succeeds (at which point the candidate will be returned to the
288 /// main pool of potential corrections).
289 void performQualifiedLookups();
290
291 /// The name written that is a typo in the source.
292 IdentifierInfo *Typo;
293
294 /// The results found that have the smallest edit distance
295 /// found (so far) with the typo name.
296 ///
297 /// The pointer value being set to the current DeclContext indicates
298 /// whether there is a keyword with this name.
299 TypoEditDistanceMap CorrectionResults;
300
301 SmallVector<TypoCorrection, 4> ValidatedCorrections;
302 size_t CurrentTCIndex;
303 size_t SavedTCIndex;
304
305 Sema &SemaRef;
306 Scope *S;
307 std::unique_ptr<CXXScopeSpec> SS;
308 std::unique_ptr<CorrectionCandidateCallback> CorrectionValidator;
309 DeclContext *MemberContext;
310 LookupResult Result;
311 NamespaceSpecifierSet Namespaces;
312 SmallVector<TypoCorrection, 2> QualifiedResults;
313 bool EnteringContext;
314 bool SearchNamespaces;
315};
316
318
320 *this = std::move(other);
321}
322
324operator=(Sema::TypoExprState &&other) noexcept {
325 Consumer = std::move(other.Consumer);
326 DiagHandler = std::move(other.DiagHandler);
327 RecoveryHandler = std::move(other.RecoveryHandler);
328 return *this;
329}
330
331} // end namespace clang
332
333#endif
Defines the clang::ASTContext interface.
const Decl * D
static std::string getName(const CallEvent &Call)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:186
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1425
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
T * getAttr() const
Definition: DeclBase.h:579
bool hasAttr() const
Definition: DeclBase.h:583
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:461
Represents the results of name lookup.
Definition: Lookup.h:46
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
This represents a decl that may have a name.
Definition: Decl.h:249
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:535
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:8995
ASTContext & Context
Definition: Sema.h:1002
ASTConsumer & Consumer
Definition: Sema.h:1003
Provides flat iteration over specifiers, sorted by distance.
Definition: SemaInternal.h:244
iterator(NamespaceSpecifierSet &Set, bool IsAtEnd)
Definition: SemaInternal.h:253
void resetCorrectionStream()
Reset the consumer's position in the stream of viable corrections (i.e.
Definition: SemaInternal.h:175
void addKeywordResult(StringRef Keyword)
void restoreSavedPosition()
Restore the saved position in the correction stream.
Definition: SemaInternal.h:193
const LookupResult & getLookupResult() const
Definition: SemaInternal.h:198
void addCorrection(TypoCorrection Correction)
const TypoCorrection & getCurrentCorrection()
Get the last correction returned by getNextCorrection().
Definition: SemaInternal.h:150
void saveCurrentPosition()
Save the current position in the correction stream (overwriting any previously saved position).
Definition: SemaInternal.h:188
const CXXScopeSpec * getSS() const
Definition: SemaInternal.h:201
TypoCorrectionConsumer(Sema &SemaRef, const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, std::unique_ptr< CorrectionCandidateCallback > CCC, DeclContext *MemberContext, bool EnteringContext)
Definition: SemaInternal.h:87
const TypoCorrection & peekNextCorrection()
Return the next typo correction like getNextCorrection, but keep the internal state pointed to the cu...
Definition: SemaInternal.h:160
bool includeHiddenDecls() const override
Determine whether hidden declarations (from unimported modules) should be given to this consumer.
Definition: SemaInternal.h:106
bool finished()
Return whether the end of the stream of corrections has been reached.
Definition: SemaInternal.h:181
unsigned getBestEditDistance(bool Normalized)
Return the edit distance of the corrections that have the closest/best edit distance from the origina...
Definition: SemaInternal.h:127
bool hasMadeAnyCorrectionProgress() const
In the case of deeply invalid expressions, getNextCorrection() will never be called since the transfo...
Definition: SemaInternal.h:170
const TypoCorrection & getNextCorrection()
Return the next typo correction that passes all internal filters and is deemed valid by the consumer'...
TypoResultList & operator[](StringRef Name)
Return the list of TypoCorrections for the given identifier from the set of corrections that have the...
Definition: SemaInternal.h:121
ASTContext & getContext() const
Definition: SemaInternal.h:197
void FoundName(StringRef Name)
void addNamespaces(const llvm::MapVector< NamespaceDecl *, bool > &KnownNamespaces)
Set-up method to add to the consumer the set of namespaces to use in performing corrections to nested...
CorrectionCandidateCallback * getCorrectionValidator() const
Definition: SemaInternal.h:203
Simple class containing the result of Sema::CorrectTypo.
static unsigned NormalizeEditDistance(unsigned ED)
Consumes visible declarations found when searching for all visible names within a given scope or cont...
Definition: Lookup.h:836
The JSON file list parser is used to communicate input to InstallAPI.
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:32
bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
Definition: SemaInternal.h:40
bool FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:25
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:50
std::pair< unsigned, unsigned > getDepthAndIndex(NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:61
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl * >, SourceLocation > UnexpandedParameterPack
Definition: Sema.h:258
#define false
Definition: stdbool.h:26
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with ',...)',...
Definition: DeclSpec.h:1365
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1425
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1400
const IdentifierInfo * Ident
Definition: DeclSpec.h:1331
TypoExprState & operator=(TypoExprState &&other) noexcept
Definition: SemaInternal.h:324