1 //===--- SemaInternal.h - Internal Sema Interfaces --------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides common API and #includes for the internal
11 // implementation of Sema.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_SEMA_SEMAINTERNAL_H
16 #define LLVM_CLANG_SEMA_SEMAINTERNAL_H
18 #include "clang/AST/ASTContext.h"
19 #include "clang/Sema/Lookup.h"
20 #include "clang/Sema/Sema.h"
21 #include "clang/Sema/SemaDiagnostic.h"
25 inline PartialDiagnostic Sema::PDiag(unsigned DiagID) {
26 return PartialDiagnostic(DiagID, Context.getDiagAllocator());
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();
37 FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI) {
38 // Assume FTI is well-formed.
39 return FTI.NumParams && !FTIHasSingleVoidParameter(FTI);
42 // This requires the variable to be non-dependent and the initializer
43 // to not be value dependent.
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();
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.
54 inline bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D) {
55 if (!LangOpts.CUDA || !D)
57 bool isDeviceSideDecl = D->hasAttr<CUDADeviceAttr>() ||
58 D->hasAttr<CUDASharedAttr>() ||
59 D->hasAttr<CUDAGlobalAttr>();
60 return isDeviceSideDecl == LangOpts.CUDAIsDevice;
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.
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()];
83 QualType CaptureType, DeclRefType;
84 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
85 /*EllipsisLoc*/ SourceLocation(),
86 /*BuildAndDiagnose*/ true,
87 CaptureType, DeclRefType,
88 FunctionScopeIndexToStopAt);
90 Var->markUsed(SemaRef.Context);
93 /// Return a DLL attribute from the declaration.
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>())
99 if (auto *Export = D->getAttr<DLLExportAttr>())
104 class TypoCorrectionConsumer : public VisibleDeclConsumer {
105 typedef SmallVector<TypoCorrection, 1> TypoResultList;
106 typedef llvm::StringMap<TypoResultList> TypoResultsMap;
107 typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
110 TypoCorrectionConsumer(Sema &SemaRef,
111 const DeclarationNameInfo &TypoName,
112 Sema::LookupNameKind LookupKind,
113 Scope *S, CXXScopeSpec *SS,
114 std::unique_ptr<CorrectionCandidateCallback> CCC,
115 DeclContext *MemberContext,
116 bool EnteringContext)
117 : Typo(TypoName.getName().getAsIdentifierInfo()), CurrentTCIndex(0),
118 SavedTCIndex(0), SemaRef(SemaRef), S(S),
119 SS(SS ? llvm::make_unique<CXXScopeSpec>(*SS) : nullptr),
120 CorrectionValidator(std::move(CCC)), MemberContext(MemberContext),
121 Result(SemaRef, TypoName, LookupKind),
122 Namespaces(SemaRef.Context, SemaRef.CurContext, SS),
123 EnteringContext(EnteringContext), SearchNamespaces(false) {
124 Result.suppressDiagnostics();
125 // Arrange for ValidatedCorrections[0] to always be an empty correction.
126 ValidatedCorrections.push_back(TypoCorrection());
129 bool includeHiddenDecls() const override { return true; }
131 // Methods for adding potential corrections to the consumer.
132 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
133 bool InBaseClass) override;
134 void FoundName(StringRef Name);
135 void addKeywordResult(StringRef Keyword);
136 void addCorrection(TypoCorrection Correction);
139 return CorrectionResults.empty() && ValidatedCorrections.size() == 1;
142 /// \brief Return the list of TypoCorrections for the given identifier from
143 /// the set of corrections that have the closest edit distance, if any.
144 TypoResultList &operator[](StringRef Name) {
145 return CorrectionResults.begin()->second[Name];
148 /// \brief Return the edit distance of the corrections that have the
149 /// closest/best edit distance from the original typop.
150 unsigned getBestEditDistance(bool Normalized) {
151 if (CorrectionResults.empty())
152 return (std::numeric_limits<unsigned>::max)();
154 unsigned BestED = CorrectionResults.begin()->first;
155 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
158 /// \brief Set-up method to add to the consumer the set of namespaces to use
159 /// in performing corrections to nested name specifiers. This method also
160 /// implicitly adds all of the known classes in the current AST context to the
161 /// to the consumer for correcting nested name specifiers.
163 addNamespaces(const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces);
165 /// \brief Return the next typo correction that passes all internal filters
166 /// and is deemed valid by the consumer's CorrectionCandidateCallback,
167 /// starting with the corrections that have the closest edit distance. An
168 /// empty TypoCorrection is returned once no more viable corrections remain
170 const TypoCorrection &getNextCorrection();
172 /// \brief Get the last correction returned by getNextCorrection().
173 const TypoCorrection &getCurrentCorrection() {
174 return CurrentTCIndex < ValidatedCorrections.size()
175 ? ValidatedCorrections[CurrentTCIndex]
176 : ValidatedCorrections[0]; // The empty correction.
179 /// \brief Return the next typo correction like getNextCorrection, but keep
180 /// the internal state pointed to the current correction (i.e. the next time
181 /// getNextCorrection is called, it will return the same correction returned
182 /// by peekNextcorrection).
183 const TypoCorrection &peekNextCorrection() {
184 auto Current = CurrentTCIndex;
185 const TypoCorrection &TC = getNextCorrection();
186 CurrentTCIndex = Current;
190 /// \brief Reset the consumer's position in the stream of viable corrections
191 /// (i.e. getNextCorrection() will return each of the previously returned
192 /// corrections in order before returning any new corrections).
193 void resetCorrectionStream() {
197 /// \brief Return whether the end of the stream of corrections has been
200 return CorrectionResults.empty() &&
201 CurrentTCIndex >= ValidatedCorrections.size();
204 /// \brief Save the current position in the correction stream (overwriting any
205 /// previously saved position).
206 void saveCurrentPosition() {
207 SavedTCIndex = CurrentTCIndex;
210 /// \brief Restore the saved position in the correction stream.
211 void restoreSavedPosition() {
212 CurrentTCIndex = SavedTCIndex;
215 ASTContext &getContext() const { return SemaRef.Context; }
216 const LookupResult &getLookupResult() const { return Result; }
218 bool isAddressOfOperand() const { return CorrectionValidator->IsAddressOfOperand; }
219 const CXXScopeSpec *getSS() const { return SS.get(); }
220 Scope *getScope() const { return S; }
221 CorrectionCandidateCallback *getCorrectionValidator() const {
222 return CorrectionValidator.get();
226 class NamespaceSpecifierSet {
227 struct SpecifierInfo {
228 DeclContext* DeclCtx;
229 NestedNameSpecifier* NameSpecifier;
230 unsigned EditDistance;
233 typedef SmallVector<DeclContext*, 4> DeclContextList;
234 typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
237 DeclContextList CurContextChain;
238 std::string CurNameSpecifier;
239 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
240 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
242 std::map<unsigned, SpecifierInfoList> DistanceMap;
244 /// \brief Helper for building the list of DeclContexts between the current
245 /// context and the top of the translation unit
246 static DeclContextList buildContextChain(DeclContext *Start);
248 unsigned buildNestedNameSpecifier(DeclContextList &DeclChain,
249 NestedNameSpecifier *&NNS);
252 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
253 CXXScopeSpec *CurScopeSpec);
255 /// \brief Add the DeclContext (a namespace or record) to the set, computing
256 /// the corresponding NestedNameSpecifier and its distance in the process.
257 void addNameSpecifier(DeclContext *Ctx);
259 /// \brief Provides flat iteration over specifiers, sorted by distance.
261 : public llvm::iterator_facade_base<iterator, std::forward_iterator_tag,
263 /// Always points to the last element in the distance map.
264 const std::map<unsigned, SpecifierInfoList>::iterator OuterBack;
265 /// Iterator on the distance map.
266 std::map<unsigned, SpecifierInfoList>::iterator Outer;
267 /// Iterator on an element in the distance map.
268 SpecifierInfoList::iterator Inner;
271 iterator(NamespaceSpecifierSet &Set, bool IsAtEnd)
272 : OuterBack(std::prev(Set.DistanceMap.end())),
273 Outer(Set.DistanceMap.begin()),
274 Inner(!IsAtEnd ? Outer->second.begin() : OuterBack->second.end()) {
275 assert(!Set.DistanceMap.empty());
278 iterator &operator++() {
280 if (Inner == Outer->second.end() && Outer != OuterBack) {
282 Inner = Outer->second.begin();
287 SpecifierInfo &operator*() { return *Inner; }
288 bool operator==(const iterator &RHS) const { return Inner == RHS.Inner; }
291 iterator begin() { return iterator(*this, /*IsAtEnd=*/false); }
292 iterator end() { return iterator(*this, /*IsAtEnd=*/true); }
295 void addName(StringRef Name, NamedDecl *ND,
296 NestedNameSpecifier *NNS = nullptr, bool isKeyword = false);
298 /// \brief Find any visible decls for the given typo correction candidate.
299 /// If none are found, it to the set of candidates for which qualified lookups
300 /// will be performed to find possible nested name specifier changes.
301 bool resolveCorrection(TypoCorrection &Candidate);
303 /// \brief Perform qualified lookups on the queued set of typo correction
304 /// candidates and add the nested name specifier changes to each candidate if
305 /// a lookup succeeds (at which point the candidate will be returned to the
306 /// main pool of potential corrections).
307 void performQualifiedLookups();
309 /// \brief The name written that is a typo in the source.
310 IdentifierInfo *Typo;
312 /// \brief The results found that have the smallest edit distance
313 /// found (so far) with the typo name.
315 /// The pointer value being set to the current DeclContext indicates
316 /// whether there is a keyword with this name.
317 TypoEditDistanceMap CorrectionResults;
319 SmallVector<TypoCorrection, 4> ValidatedCorrections;
320 size_t CurrentTCIndex;
325 std::unique_ptr<CXXScopeSpec> SS;
326 std::unique_ptr<CorrectionCandidateCallback> CorrectionValidator;
327 DeclContext *MemberContext;
329 NamespaceSpecifierSet Namespaces;
330 SmallVector<TypoCorrection, 2> QualifiedResults;
331 bool EnteringContext;
332 bool SearchNamespaces;
335 inline Sema::TypoExprState::TypoExprState() {}
337 inline Sema::TypoExprState::TypoExprState(TypoExprState &&other) noexcept {
338 *this = std::move(other);
341 inline Sema::TypoExprState &Sema::TypoExprState::
342 operator=(Sema::TypoExprState &&other) noexcept {
343 Consumer = std::move(other.Consumer);
344 DiagHandler = std::move(other.DiagHandler);
345 RecoveryHandler = std::move(other.RecoveryHandler);
349 } // end namespace clang