17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclBase.h"
19#include "clang/AST/DeclarationName.h"
20#include "clang/AST/NestedNameSpecifier.h"
21#include "clang/AST/Type.h"
22#include "clang/Basic/Diagnostic.h"
23#include "clang/Basic/DiagnosticParse.h"
24#include "clang/Basic/DiagnosticSema.h"
25#include "clang/Basic/LangOptions.h"
26#include "clang/Basic/SourceLocation.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/TokenKinds.h"
29#include "clang/Lex/Lexer.h"
30#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Scope.h"
33#include "clang/Sema/Sema.h"
34#include "clang/Sema/TypoCorrection.h"
35#include "llvm/ADT/DenseMap.h"
36#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/StringExtras.h"
38#include "llvm/ADT/StringRef.h"
39#include "llvm/ADT/StringSet.h"
40#include "llvm/Support/Error.h"
41#include "llvm/Support/FormatVariadic.h"
52std::optional<llvm::StringRef> getArgStr(
const clang::Diagnostic &
Info,
54 switch (
Info.getArgKind(Index)) {
55 case DiagnosticsEngine::ak_c_string:
56 return llvm::StringRef(
Info.getArgCStr(Index));
57 case DiagnosticsEngine::ak_std_string:
58 return llvm::StringRef(
Info.getArgStdStr(Index));
64std::vector<Fix> only(std::optional<Fix> F) {
66 return {std::move(*F)};
73 const clang::Diagnostic &
Info)
const {
74 switch (
Info.getID()) {
84 case diag::err_array_incomplete_or_sizeless_type:
85 case diag::err_array_size_incomplete_type:
86 case diag::err_asm_incomplete_type:
87 case diag::err_bad_cast_incomplete:
88 case diag::err_call_function_incomplete_return:
89 case diag::err_call_incomplete_argument:
90 case diag::err_call_incomplete_return:
91 case diag::err_capture_of_incomplete_or_sizeless_type:
92 case diag::err_catch_incomplete:
93 case diag::err_catch_incomplete_ptr:
94 case diag::err_catch_incomplete_ref:
95 case diag::err_cconv_incomplete_param_type:
96 case diag::err_coroutine_promise_type_incomplete:
97 case diag::err_covariant_return_incomplete:
99 case diag::err_delete_incomplete_class_type:
100 case diag::err_dereference_incomplete_type:
101 case diag::err_exception_spec_incomplete_type:
102 case diag::err_field_incomplete_or_sizeless:
103 case diag::err_for_range_incomplete_type:
104 case diag::err_func_def_incomplete_result:
105 case diag::err_ice_incomplete_type:
106 case diag::err_illegal_message_expr_incomplete_type:
107 case diag::err_incomplete_base_class:
108 case diag::err_incomplete_enum:
109 case diag::err_incomplete_in_exception_spec:
110 case diag::err_incomplete_member_access:
111 case diag::err_incomplete_nested_name_spec:
112 case diag::err_incomplete_object_call:
113 case diag::err_incomplete_receiver_type:
114 case diag::err_incomplete_synthesized_property:
115 case diag::err_incomplete_type:
116 case diag::err_incomplete_type_objc_at_encode:
117 case diag::err_incomplete_type_used_in_type_trait_expr:
118 case diag::err_incomplete_typeid:
119 case diag::err_init_incomplete_type:
120 case diag::err_invalid_incomplete_type_use:
121 case diag::err_lambda_incomplete_result:
124 case diag::err_memptr_incomplete:
125 case diag::err_new_incomplete_or_sizeless_type:
126 case diag::err_objc_incomplete_boxed_expression_type:
127 case diag::err_objc_index_incomplete_class_type:
128 case diag::err_offsetof_incomplete_type:
129 case diag::err_omp_firstprivate_incomplete_type:
130 case diag::err_omp_incomplete_type:
131 case diag::err_omp_lastprivate_incomplete_type:
132 case diag::err_omp_linear_incomplete_type:
133 case diag::err_omp_private_incomplete_type:
134 case diag::err_omp_reduction_incomplete_type:
135 case diag::err_omp_section_incomplete_type:
136 case diag::err_omp_threadprivate_incomplete_type:
137 case diag::err_second_parameter_to_va_arg_incomplete:
138 case diag::err_sizeof_alignof_incomplete_or_sizeless_type:
139 case diag::err_subscript_incomplete_or_sizeless_type:
140 case diag::err_switch_incomplete_class_type:
141 case diag::err_temp_copy_incomplete:
143 case diag::err_template_nontype_parm_incomplete:
145 case diag::err_throw_incomplete:
146 case diag::err_throw_incomplete_ptr:
147 case diag::err_typecheck_arithmetic_incomplete_or_sizeless_type:
148 case diag::err_typecheck_cast_to_incomplete:
149 case diag::err_typecheck_decl_incomplete_type:
151 case diag::err_typecheck_incomplete_tag:
152 case diag::err_typecheck_incomplete_type_not_modifiable_lvalue:
153 case diag::err_typecheck_nonviable_condition_incomplete:
154 case diag::err_underlying_type_of_incomplete_enum:
155 case diag::ext_incomplete_in_exception_spec:
157 case diag::ext_typecheck_decl_incomplete_type:
158 case diag::warn_delete_incomplete:
159 case diag::warn_incomplete_encoded_type:
161 case diag::warn_return_value_udt_incomplete:
167 for (
unsigned Idx = 0; Idx <
Info.getNumArgs(); ++Idx) {
168 if (
Info.getArgKind(Idx) == DiagnosticsEngine::ak_qualtype) {
169 auto QT = QualType::getFromOpaquePtr((
void *)
Info.getRawArg(Idx));
170 if (
const Type *T = QT.getTypePtrOrNull()) {
171 if (T->isIncompleteType())
172 return fixIncompleteType(*T);
175 if (
auto * ET = llvm::dyn_cast<EnumType>(T))
176 if (!ET->getOriginalDecl()->getDefinition())
177 return fixIncompleteType(*T);
183 case diag::err_unknown_typename:
184 case diag::err_unknown_typename_suggest:
185 case diag::err_unknown_type_or_class_name_suggest:
186 case diag::err_expected_class_name:
187 case diag::err_typename_nested_not_found:
188 case diag::err_no_template:
189 case diag::err_no_template_suggest:
190 case diag::err_undeclared_use:
191 case diag::err_undeclared_use_suggest:
192 case diag::err_undeclared_var_use:
193 case diag::err_undeclared_var_use_suggest:
194 case diag::err_no_member:
195 case diag::err_no_member_suggest:
196 case diag::err_no_member_template:
197 case diag::err_no_member_template_suggest:
198 case diag::warn_implicit_function_decl:
199 case diag::ext_implicit_function_decl_c99:
200 dlog(
"Unresolved name at {0}, last typo was {1}",
201 Info.getLocation().printToString(
Info.getSourceManager()),
203 ? LastUnresolvedName->Loc.printToString(
Info.getSourceManager())
205 if (LastUnresolvedName) {
217 if (LastUnresolvedName->Loc ==
Info.getLocation())
218 return fixUnresolvedName();
224 case diag::err_implied_std_initializer_list_not_found:
225 return only(insertHeader(
"<initializer_list>"));
226 case diag::err_need_header_before_typeid:
227 return only(insertHeader(
"<typeinfo>"));
228 case diag::err_need_header_before_placement_new:
229 case diag::err_implicit_coroutine_std_nothrow_type_not_found:
230 return only(insertHeader(
"<new>"));
231 case diag::err_omp_implied_type_not_found:
232 case diag::err_omp_interop_type_not_found:
233 return only(insertHeader(
"<omp.h>"));
234 case diag::err_implied_coroutine_type_not_found:
235 return only(insertHeader(
"<coroutine>"));
236 case diag::err_implied_comparison_category_type_not_found:
237 return only(insertHeader(
"<compare>"));
238 case diag::note_include_header_or_declare:
239 if (
Info.getNumArgs() > 0)
240 if (
auto Header = getArgStr(
Info, 0))
241 return only(insertHeader((
"<" + *Header +
">").str(),
242 getArgStr(
Info, 1).value_or(
"")));
249std::optional<Fix> IncludeFixer::insertHeader(llvm::StringRef
Spelled,
251 tooling::IncludeDirective Directive)
const {
254 if (
auto Edit = Inserter->insert(
Spelled, Directive))
259 llvm::StringRef DirectiveSpelling =
260 Directive == tooling::IncludeDirective::Include ?
"Include" :
"Import";
264 F.
Message = llvm::formatv(
"{0} {1} for symbol {2}",
270std::vector<Fix> IncludeFixer::fixIncompleteType(
const Type &T)
const {
272 const TagDecl *TD = T.getAsTagDecl();
276 trace::Span Tracer(
"Fix include for incomplete type");
278 vlog(
"Trying to fix include for incomplete type {0}", TypeName);
283 std::optional<const SymbolSlab *>
Symbols = lookupCached(ID);
286 const SymbolSlab &Syms = **
Symbols;
287 std::vector<Fix> Fixes;
289 auto &Matched = *Syms.begin();
290 if (!Matched.IncludeHeaders.empty() && Matched.Definition &&
291 Matched.CanonicalDeclaration.FileURI == Matched.Definition.FileURI)
292 Fixes = fixesForSymbols(Syms);
297std::vector<Fix> IncludeFixer::fixesForSymbols(
const SymbolSlab &Syms)
const {
298 auto Inserted = [&](
const Symbol &Sym, llvm::StringRef Header)
299 -> llvm::Expected<std::pair<std::string, bool>> {
300 auto ResolvedDeclaring =
302 if (!ResolvedDeclaring)
303 return ResolvedDeclaring.takeError();
305 if (!ResolvedInserted)
306 return ResolvedInserted.takeError();
307 auto Spelled = Inserter->calculateIncludePath(*ResolvedInserted, File);
309 return error(
"Header not on include path");
310 return std::make_pair(
312 Inserter->shouldInsertInclude(*ResolvedDeclaring, *ResolvedInserted));
315 std::vector<Fix> Fixes;
319 llvm::StringSet<> InsertedHeaders;
320 for (
const auto &Sym : Syms) {
322 if ((Inc.Directive & Directive) == 0)
324 if (
auto ToInclude = Inserted(Sym, Inc.Header)) {
325 if (ToInclude->second) {
326 if (!InsertedHeaders.try_emplace(ToInclude->first).second)
329 insertHeader(ToInclude->first, (Sym.Scope + Sym.Name).str(),
331 ? tooling::IncludeDirective::Import
332 : tooling::IncludeDirective::Include))
333 Fixes.push_back(std::move(*
Fix));
336 vlog(
"Failed to calculate include insertion for {0} into {1}: {2}",
337 Inc.Header, File, ToInclude.takeError());
351 const LangOptions &LangOpts) {
354 SourceLocation NextLoc = SM.getTopMacroCallerLoc(Loc);
355 while (
auto CCTok = Lexer::findNextToken(NextLoc, SM, LangOpts)) {
356 if (!CCTok->is(tok::coloncolon))
358 auto IDTok = Lexer::findNextToken(CCTok->getLocation(), SM, LangOpts);
359 if (!IDTok || !IDTok->is(tok::raw_identifier))
361 Result.append((
"::" + IDTok->getRawIdentifier()).str());
362 NextLoc = IDTok->getLocation();
384 const SourceManager &SM) {
386 if (!SM.isWrittenInSameFile(SS.getBeginLoc(), SS.getEndLoc()))
388 SourceRange
Range(SM.getTopMacroCallerLoc(SS.getBeginLoc()), SM.getTopMacroCallerLoc(SS.getEndLoc()));
389 if (
Range.getBegin().isMacroID() ||
Range.getEnd().isMacroID())
398 const SourceManager &SM,
const DeclarationNameInfo &Unresolved,
399 CXXScopeSpec *SS,
const LangOptions &LangOpts,
bool UnresolvedIsSpecifier) {
401 Result.
Name = Unresolved.getAsString();
402 if (SS && SS->isNotEmpty()) {
403 NestedNameSpecifier Nested = SS->getScopeRep();
404 if (Nested.getKind() == NestedNameSpecifier::Kind::Global) {
406 }
else if (Nested.getKind() == NestedNameSpecifier::Kind::Namespace) {
407 const NamespaceBaseDecl *NSB = Nested.getAsNamespaceAndPrefix().Namespace;
408 if (
const auto *NS = dyn_cast<NamespaceDecl>(NSB)) {
420 if (!Spelling || llvm::StringRef(SpecifiedNS).ends_with(*Spelling)) {
435 if (UnresolvedIsSpecifier) {
446 if (
auto QualifiedByUnresolved =
460 Result.
Name = std::string(Split.second);
467std::vector<std::string>
469 Sema::LookupNameKind LookupKind) {
471 struct VisitedContextCollector :
public VisibleDeclConsumer {
472 VisitedContextCollector(std::vector<std::string> &Out) : Out(Out) {}
473 void EnteredContext(DeclContext *Ctx)
override {
474 if (llvm::isa<NamespaceDecl>(Ctx))
477 void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
478 bool InBaseClass)
override {}
479 std::vector<std::string> &Out;
482 std::vector<std::string> Scopes;
483 Scopes.push_back(
"");
484 VisitedContextCollector Collector(Scopes);
485 Sem.LookupVisibleDecls(S, LookupKind, Collector,
489 Scopes.erase(llvm::unique(Scopes), Scopes.end());
496 : LastUnresolvedName(LastUnresolvedName) {}
502 TypoCorrection
CorrectTypo(
const DeclarationNameInfo &Typo,
int LookupKind,
503 Scope *S, CXXScopeSpec *SS,
504 CorrectionCandidateCallback &CCC,
505 DeclContext *MemberContext,
bool EnteringContext,
506 const ObjCObjectPointerType *OPT)
override {
507 dlog(
"CorrectTypo: {0}", Typo.getAsString());
508 assert(SemaPtr &&
"Sema must have been set.");
509 if (SemaPtr->isSFINAEContext())
510 return TypoCorrection();
512 return clang::TypoCorrection();
515 SemaPtr->SourceMgr, Typo, SS, SemaPtr->LangOpts,
516 static_cast<Sema::LookupNameKind
>(LookupKind) ==
517 Sema::LookupNameKind::LookupNestedNameSpecifierName);
519 return TypoCorrection();
521 UnresolvedName Unresolved;
522 Unresolved.Name = Extracted->Name;
523 Unresolved.Loc = Typo.getBeginLoc();
524 if (!Extracted->ResolvedScope && !S)
525 return TypoCorrection();
527 if (Extracted->ResolvedScope)
528 Unresolved.Scopes.push_back(*Extracted->ResolvedScope);
531 *SemaPtr, Typo, S,
static_cast<Sema::LookupNameKind
>(LookupKind));
533 if (Extracted->UnresolvedScope) {
534 for (std::string &Scope : Unresolved.Scopes)
535 Scope += *Extracted->UnresolvedScope;
538 LastUnresolvedName = std::move(Unresolved);
542 return TypoCorrection();
546 Sema *SemaPtr =
nullptr;
548 std::optional<UnresolvedName> &LastUnresolvedName;
551llvm::IntrusiveRefCntPtr<ExternalSemaSource>
556std::vector<Fix> IncludeFixer::fixUnresolvedName()
const {
557 assert(LastUnresolvedName);
558 auto &Unresolved = *LastUnresolvedName;
559 vlog(
"Trying to fix unresolved name \"{0}\" in scopes: [{1}]",
560 Unresolved.Name, llvm::join(Unresolved.Scopes,
", "));
564 Req.
Query = Unresolved.Name;
565 Req.
Scopes = Unresolved.Scopes;
569 if (std::optional<const SymbolSlab *> Syms = fuzzyFindCached(Req))
570 return fixesForSymbols(**Syms);
575std::optional<const SymbolSlab *>
576IncludeFixer::fuzzyFindCached(
const FuzzyFindRequest &Req)
const {
577 auto ReqStr = llvm::formatv(
"{0}",
toJSON(Req)).str();
578 auto I = FuzzyFindCache.find(ReqStr);
579 if (I != FuzzyFindCache.end())
582 if (IndexRequestCount >= IndexRequestLimit)
586 SymbolSlab::Builder Matches;
587 Index.fuzzyFind(Req, [&](
const Symbol &Sym) {
588 if (Sym.Name != Req.Query)
590 if (!Sym.IncludeHeaders.empty())
593 auto Syms = std::move(Matches).build();
594 auto E = FuzzyFindCache.try_emplace(ReqStr, std::move(Syms));
595 return &E.first->second;
598std::optional<const SymbolSlab *>
599IncludeFixer::lookupCached(
const SymbolID &ID)
const {
603 auto I = LookupCache.find(ID);
604 if (I != LookupCache.end())
607 if (IndexRequestCount >= IndexRequestLimit)
612 SymbolSlab::Builder Matches;
613 Index.lookup(Req, [&](
const Symbol &Sym) { Matches.insert(Sym); });
614 auto Syms = std::move(Matches).build();
616 std::vector<Fix> Fixes;
618 auto &Matched = *Syms.begin();
619 if (!Matched.IncludeHeaders.empty() && Matched.Definition &&
620 Matched.CanonicalDeclaration.FileURI == Matched.Definition.FileURI)
621 Fixes = fixesForSymbols(Syms);
623 auto E = LookupCache.try_emplace(ID, std::move(Syms));
624 return &E.first->second;
static cl::opt< bool > Fix("fix", desc(R"(
Apply suggested fixes. Without -fix-errors
clang-tidy will bail out if any compilation
errors were found.
)"), cl::init(false), cl::cat(ClangTidyCategory))
#define SPAN_ATTACH(S, Name, Expr)
Attach a key-value pair to a Span event.
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, int LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT) override
void InitializeSema(Sema &S) override
UnresolvedNameRecorder(std::optional< UnresolvedName > &LastUnresolvedName)
llvm::IntrusiveRefCntPtr< ExternalSemaSource > unresolvedNameRecorder()
Returns an ExternalSemaSource that records failed name lookups in Sema.
std::vector< Fix > fix(DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic &Info) const
Returns include insertions that can potentially recover the diagnostic.
An immutable symbol container that stores a set of symbols.
static llvm::Expected< std::string > resolve(const URI &U, llvm::StringRef HintPath="")
Resolves the absolute path of U.
FIXME: Skip testing on windows temporarily due to the different escaping code mode.
std::pair< StringRef, StringRef > splitQualifiedName(StringRef QName)
@ Info
An information message.
SymbolID getSymbolID(const Decl *D)
Gets the symbol ID for a declaration. Returned SymbolID might be null.
std::optional< CheapUnresolvedName > extractUnresolvedNameCheaply(const SourceManager &SM, const DeclarationNameInfo &Unresolved, CXXScopeSpec *SS, const LangOptions &LangOpts, bool UnresolvedIsSpecifier)
bool isInsideMainFile(SourceLocation Loc, const SourceManager &SM)
Returns true iff Loc is inside the main file.
void vlog(const char *Fmt, Ts &&... Vals)
llvm::Error error(std::error_code EC, const char *Fmt, Ts &&... Vals)
std::vector< std::string > collectAccessibleScopes(Sema &Sem, const DeclarationNameInfo &Typo, Scope *S, Sema::LookupNameKind LookupKind)
Returns all namespace scopes that the unqualified lookup would visit.
std::optional< std::string > getSpelledSpecifier(const CXXScopeSpec &SS, const SourceManager &SM)
std::optional< std::string > qualifiedByUnresolved(const SourceManager &SM, SourceLocation Loc, const LangOptions &LangOpts)
llvm::json::Value toJSON(const FuzzyFindRequest &Request)
llvm::Expected< HeaderFile > toHeaderFile(llvm::StringRef Header, llvm::StringRef HintPath)
Creates a HeaderFile from Header which can be either a URI or a literal include.
llvm::StringRef toSourceCode(const SourceManager &SM, SourceRange R)
Returns the source code covered by the source range.
@ Type
An inlay hint that for a type annotation.
llvm::SmallVector< SymbolInclude, 1 > getRankedIncludes(const Symbol &Sym)
std::string printQualifiedName(const NamedDecl &ND)
Returns the qualified name of ND.
std::string printNamespaceScope(const DeclContext &DC)
Returns the first enclosing namespace scope starting from DC.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
std::optional< std::string > UnresolvedScope
std::optional< std::string > ResolvedScope
A set of edits generated for a single file.
Represents a single fix-it that editor can apply to fix the error.
std::string Message
Message for the fix-it.
llvm::SmallVector< TextEdit, 1 > Edits
TextEdits from clang's fix-its. Must be non-empty.
std::vector< std::string > Scopes
If this is non-empty, symbols must be in at least one of the scopes (e.g.
bool RestrictForCodeCompletion
If set to true, only symbols for completion support will be considered.
std::string Query
A query string for the fuzzy find.
bool AnyScope
If set to true, allow symbols from any scope.
std::optional< uint32_t > Limit
The number of top candidates to return.
The class presents a C++ symbol, e.g.
@ Import
#import "header.h"