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 // Directly mark a variable odr-used. Given a choice, prefer to use
52 // MarkVariableReferenced since it does additional checks and then
53 // calls MarkVarDeclODRUsed.
54 // If the variable must be captured:
55 // - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
56 // - else capture it in the DeclContext that maps to the
57 // *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
58 inline void MarkVarDeclODRUsed(VarDecl *Var,
59 SourceLocation Loc, Sema &SemaRef,
60 const unsigned *const FunctionScopeIndexToStopAt) {
61 // Keep track of used but undefined variables.
62 // FIXME: We shouldn't suppress this warning for static data members.
63 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
64 !Var->isExternallyVisible() &&
65 !(Var->isStaticDataMember() && Var->hasInit())) {
66 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
67 if (old.isInvalid()) old = Loc;
69 QualType CaptureType, DeclRefType;
70 SemaRef.tryCaptureVariable(Var, Loc, Sema::TryCapture_Implicit,
71 /*EllipsisLoc*/ SourceLocation(),
72 /*BuildAndDiagnose*/ true,
73 CaptureType, DeclRefType,
74 FunctionScopeIndexToStopAt);
76 Var->markUsed(SemaRef.Context);
79 /// Return a DLL attribute from the declaration.
80 inline InheritableAttr *getDLLAttr(Decl *D) {
81 assert(!(D->hasAttr<DLLImportAttr>() && D->hasAttr<DLLExportAttr>()) &&
82 "A declaration cannot be both dllimport and dllexport.");
83 if (auto *Import = D->getAttr<DLLImportAttr>())
85 if (auto *Export = D->getAttr<DLLExportAttr>())
90 class TypoCorrectionConsumer : public VisibleDeclConsumer {
91 typedef SmallVector<TypoCorrection, 1> TypoResultList;
92 typedef llvm::StringMap<TypoResultList> TypoResultsMap;
93 typedef std::map<unsigned, TypoResultsMap> TypoEditDistanceMap;
96 TypoCorrectionConsumer(Sema &SemaRef,
97 const DeclarationNameInfo &TypoName,
98 Sema::LookupNameKind LookupKind,
99 Scope *S, CXXScopeSpec *SS,
100 std::unique_ptr<CorrectionCandidateCallback> CCC,
101 DeclContext *MemberContext,
102 bool EnteringContext)
103 : Typo(TypoName.getName().getAsIdentifierInfo()), CurrentTCIndex(0),
104 SavedTCIndex(0), SemaRef(SemaRef), S(S),
105 SS(SS ? llvm::make_unique<CXXScopeSpec>(*SS) : nullptr),
106 CorrectionValidator(std::move(CCC)), MemberContext(MemberContext),
107 Result(SemaRef, TypoName, LookupKind),
108 Namespaces(SemaRef.Context, SemaRef.CurContext, SS),
109 EnteringContext(EnteringContext), SearchNamespaces(false) {
110 Result.suppressDiagnostics();
111 // Arrange for ValidatedCorrections[0] to always be an empty correction.
112 ValidatedCorrections.push_back(TypoCorrection());
115 bool includeHiddenDecls() const override { return true; }
117 // Methods for adding potential corrections to the consumer.
118 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
119 bool InBaseClass) override;
120 void FoundName(StringRef Name);
121 void addKeywordResult(StringRef Keyword);
122 void addCorrection(TypoCorrection Correction);
125 return CorrectionResults.empty() && ValidatedCorrections.size() == 1;
128 /// \brief Return the list of TypoCorrections for the given identifier from
129 /// the set of corrections that have the closest edit distance, if any.
130 TypoResultList &operator[](StringRef Name) {
131 return CorrectionResults.begin()->second[Name];
134 /// \brief Return the edit distance of the corrections that have the
135 /// closest/best edit distance from the original typop.
136 unsigned getBestEditDistance(bool Normalized) {
137 if (CorrectionResults.empty())
138 return (std::numeric_limits<unsigned>::max)();
140 unsigned BestED = CorrectionResults.begin()->first;
141 return Normalized ? TypoCorrection::NormalizeEditDistance(BestED) : BestED;
144 /// \brief Set-up method to add to the consumer the set of namespaces to use
145 /// in performing corrections to nested name specifiers. This method also
146 /// implicitly adds all of the known classes in the current AST context to the
147 /// to the consumer for correcting nested name specifiers.
149 addNamespaces(const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces);
151 /// \brief Return the next typo correction that passes all internal filters
152 /// and is deemed valid by the consumer's CorrectionCandidateCallback,
153 /// starting with the corrections that have the closest edit distance. An
154 /// empty TypoCorrection is returned once no more viable corrections remain
156 const TypoCorrection &getNextCorrection();
158 /// \brief Get the last correction returned by getNextCorrection().
159 const TypoCorrection &getCurrentCorrection() {
160 return CurrentTCIndex < ValidatedCorrections.size()
161 ? ValidatedCorrections[CurrentTCIndex]
162 : ValidatedCorrections[0]; // The empty correction.
165 /// \brief Return the next typo correction like getNextCorrection, but keep
166 /// the internal state pointed to the current correction (i.e. the next time
167 /// getNextCorrection is called, it will return the same correction returned
168 /// by peekNextcorrection).
169 const TypoCorrection &peekNextCorrection() {
170 auto Current = CurrentTCIndex;
171 const TypoCorrection &TC = getNextCorrection();
172 CurrentTCIndex = Current;
176 /// \brief Reset the consumer's position in the stream of viable corrections
177 /// (i.e. getNextCorrection() will return each of the previously returned
178 /// corrections in order before returning any new corrections).
179 void resetCorrectionStream() {
183 /// \brief Return whether the end of the stream of corrections has been
186 return CorrectionResults.empty() &&
187 CurrentTCIndex >= ValidatedCorrections.size();
190 /// \brief Save the current position in the correction stream (overwriting any
191 /// previously saved position).
192 void saveCurrentPosition() {
193 SavedTCIndex = CurrentTCIndex;
196 /// \brief Restore the saved position in the correction stream.
197 void restoreSavedPosition() {
198 CurrentTCIndex = SavedTCIndex;
201 ASTContext &getContext() const { return SemaRef.Context; }
202 const LookupResult &getLookupResult() const { return Result; }
204 bool isAddressOfOperand() const { return CorrectionValidator->IsAddressOfOperand; }
205 const CXXScopeSpec *getSS() const { return SS.get(); }
206 Scope *getScope() const { return S; }
209 class NamespaceSpecifierSet {
210 struct SpecifierInfo {
211 DeclContext* DeclCtx;
212 NestedNameSpecifier* NameSpecifier;
213 unsigned EditDistance;
216 typedef SmallVector<DeclContext*, 4> DeclContextList;
217 typedef SmallVector<SpecifierInfo, 16> SpecifierInfoList;
220 DeclContextList CurContextChain;
221 std::string CurNameSpecifier;
222 SmallVector<const IdentifierInfo*, 4> CurContextIdentifiers;
223 SmallVector<const IdentifierInfo*, 4> CurNameSpecifierIdentifiers;
226 SpecifierInfoList Specifiers;
227 llvm::SmallSetVector<unsigned, 4> Distances;
228 llvm::DenseMap<unsigned, SpecifierInfoList> DistanceMap;
230 /// \brief Helper for building the list of DeclContexts between the current
231 /// context and the top of the translation unit
232 static DeclContextList buildContextChain(DeclContext *Start);
234 void sortNamespaces();
236 unsigned buildNestedNameSpecifier(DeclContextList &DeclChain,
237 NestedNameSpecifier *&NNS);
240 NamespaceSpecifierSet(ASTContext &Context, DeclContext *CurContext,
241 CXXScopeSpec *CurScopeSpec);
243 /// \brief Add the DeclContext (a namespace or record) to the set, computing
244 /// the corresponding NestedNameSpecifier and its distance in the process.
245 void addNameSpecifier(DeclContext *Ctx);
247 typedef SpecifierInfoList::iterator iterator;
249 if (!isSorted) sortNamespaces();
250 return Specifiers.begin();
252 iterator end() { return Specifiers.end(); }
255 void addName(StringRef Name, NamedDecl *ND,
256 NestedNameSpecifier *NNS = nullptr, bool isKeyword = false);
258 /// \brief Find any visible decls for the given typo correction candidate.
259 /// If none are found, it to the set of candidates for which qualified lookups
260 /// will be performed to find possible nested name specifier changes.
261 bool resolveCorrection(TypoCorrection &Candidate);
263 /// \brief Perform qualified lookups on the queued set of typo correction
264 /// candidates and add the nested name specifier changes to each candidate if
265 /// a lookup succeeds (at which point the candidate will be returned to the
266 /// main pool of potential corrections).
267 void performQualifiedLookups();
269 /// \brief The name written that is a typo in the source.
270 IdentifierInfo *Typo;
272 /// \brief The results found that have the smallest edit distance
273 /// found (so far) with the typo name.
275 /// The pointer value being set to the current DeclContext indicates
276 /// whether there is a keyword with this name.
277 TypoEditDistanceMap CorrectionResults;
279 SmallVector<TypoCorrection, 4> ValidatedCorrections;
280 size_t CurrentTCIndex;
285 std::unique_ptr<CXXScopeSpec> SS;
286 std::unique_ptr<CorrectionCandidateCallback> CorrectionValidator;
287 DeclContext *MemberContext;
289 NamespaceSpecifierSet Namespaces;
290 SmallVector<TypoCorrection, 2> QualifiedResults;
291 bool EnteringContext;
292 bool SearchNamespaces;
295 inline Sema::TypoExprState::TypoExprState() {}
297 inline Sema::TypoExprState::TypoExprState(TypoExprState &&other) LLVM_NOEXCEPT {
298 *this = std::move(other);
301 inline Sema::TypoExprState &Sema::TypoExprState::operator=(
302 Sema::TypoExprState &&other) LLVM_NOEXCEPT {
303 Consumer = std::move(other.Consumer);
304 DiagHandler = std::move(other.DiagHandler);
305 RecoveryHandler = std::move(other.RecoveryHandler);
309 } // end namespace clang