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 /// Retrieve the depth and index of a template parameter.
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());
109 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
110 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
112 const auto *TTP = cast<TemplateTemplateParmDecl>(ND);
113 return std::make_pair(TTP->getDepth(), TTP->getIndex());
116 /// Retrieve the depth and index of an unexpanded parameter pack.
117 inline std::pair<unsigned, unsigned>
118 getDepthAndIndex(UnexpandedParameterPack UPP) {
119 if (const auto *TTP = UPP.first.dyn_cast<const TemplateTypeParmType *>())
120 return std::make_pair(TTP->getDepth(), TTP->getIndex());
122 return getDepthAndIndex(UPP.first.get<NamedDecl *>());
125 class TypoCorrectionConsumer : public VisibleDeclConsumer {
126 typedef SmallVector<TypoCorrection, 1> TypoResultList;
127 typedef llvm::StringMap<TypoResultList> TypoResultsMap;
128 typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
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());
150 bool includeHiddenDecls() const override { return true; }
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);
160 return CorrectionResults.empty() && ValidatedCorrections.size() == 1;
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];
169 /// Return the edit distance of the corrections that have the
170 /// closest/best edit distance from the original typop.
171 unsigned getBestEditDistance(bool Normalized) {
172 if (CorrectionResults.empty())
173 return (std::numeric_limits<unsigned>::max)();
175 unsigned BestED = CorrectionResults.begin()->first;
176 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
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.
184 addNamespaces(const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces);
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
191 const TypoCorrection &getNextCorrection();
193 /// Get the last correction returned by getNextCorrection().
194 const TypoCorrection &getCurrentCorrection() {
195 return CurrentTCIndex < ValidatedCorrections.size()
196 ? ValidatedCorrections[CurrentTCIndex]
197 : ValidatedCorrections[0]; // The empty correction.
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).
204 const TypoCorrection &peekNextCorrection() {
205 auto Current = CurrentTCIndex;
206 const TypoCorrection &TC = getNextCorrection();
207 CurrentTCIndex = Current;
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).
214 void resetCorrectionStream() {
218 /// Return whether the end of the stream of corrections has been
221 return CorrectionResults.empty() &&
222 CurrentTCIndex >= ValidatedCorrections.size();
225 /// Save the current position in the correction stream (overwriting any
226 /// previously saved position).
227 void saveCurrentPosition() {
228 SavedTCIndex = CurrentTCIndex;
231 /// Restore the saved position in the correction stream.
232 void restoreSavedPosition() {
233 CurrentTCIndex = SavedTCIndex;
236 ASTContext &getContext() const { return SemaRef.Context; }
237 const LookupResult &getLookupResult() const { return Result; }
239 bool isAddressOfOperand() const { return CorrectionValidator->IsAddressOfOperand; }
240 const CXXScopeSpec *getSS() const { return SS.get(); }
241 Scope *getScope() const { return S; }
242 CorrectionCandidateCallback *getCorrectionValidator() const {
243 return CorrectionValidator.get();
247 class NamespaceSpecifierSet {
248 struct SpecifierInfo {
249 DeclContext* DeclCtx;
250 NestedNameSpecifier* NameSpecifier;
251 unsigned EditDistance;
254 typedef SmallVector<DeclContext*, 4> DeclContextList;
255 typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
258 DeclContextList CurContextChain;
259 std::string CurNameSpecifier;
260 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
261 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
263 std::map<unsigned, SpecifierInfoList> DistanceMap;
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);
269 unsigned buildNestedNameSpecifier(DeclContextList &DeclChain,
270 NestedNameSpecifier *&NNS);
273 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
274 CXXScopeSpec *CurScopeSpec);
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);
280 /// Provides flat iteration over specifiers, sorted by distance.
282 : public llvm::iterator_facade_base<iterator, std::forward_iterator_tag,
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;
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());
299 iterator &operator++() {
301 if (Inner == Outer->second.end() && Outer != OuterBack) {
303 Inner = Outer->second.begin();
308 SpecifierInfo &operator*() { return *Inner; }
309 bool operator==(const iterator &RHS) const { return Inner == RHS.Inner; }
312 iterator begin() { return iterator(*this, /*IsAtEnd=*/false); }
313 iterator end() { return iterator(*this, /*IsAtEnd=*/true); }
316 void addName(StringRef Name, NamedDecl *ND,
317 NestedNameSpecifier *NNS = nullptr, bool isKeyword = false);
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);
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();
330 /// The name written that is a typo in the source.
331 IdentifierInfo *Typo;
333 /// The results found that have the smallest edit distance
334 /// found (so far) with the typo name.
336 /// The pointer value being set to the current DeclContext indicates
337 /// whether there is a keyword with this name.
338 TypoEditDistanceMap CorrectionResults;
340 SmallVector<TypoCorrection, 4> ValidatedCorrections;
341 size_t CurrentTCIndex;
346 std::unique_ptr<CXXScopeSpec> SS;
347 std::unique_ptr<CorrectionCandidateCallback> CorrectionValidator;
348 DeclContext *MemberContext;
350 NamespaceSpecifierSet Namespaces;
351 SmallVector<TypoCorrection, 2> QualifiedResults;
352 bool EnteringContext;
353 bool SearchNamespaces;
356 inline Sema::TypoExprState::TypoExprState() {}
358 inline Sema::TypoExprState::TypoExprState(TypoExprState &&other) noexcept {
359 *this = std::move(other);
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);
370 } // end namespace clang