10#include "clang/Format/Format.h"
11#include "clang/Frontend/CompilerInstance.h"
12#include "clang/Lex/HeaderSearch.h"
13#include "clang/Lex/Preprocessor.h"
14#include "clang/Parse/ParseAST.h"
15#include "clang/Sema/Sema.h"
16#include "llvm/Support/Debug.h"
17#include "llvm/Support/raw_ostream.h"
19#define DEBUG_TYPE "clang-include-fixer"
24namespace include_fixer {
27class Action :
public clang::ASTFrontendAction {
29 explicit Action(SymbolIndexManager &SymbolIndexMgr,
bool MinimizeIncludePaths)
30 : SemaSource(
new IncludeFixerSemaSource(SymbolIndexMgr,
34 std::unique_ptr<clang::ASTConsumer>
35 CreateASTConsumer(clang::CompilerInstance &Compiler,
36 StringRef InFile)
override {
37 SemaSource->setFilePath(InFile);
38 return std::make_unique<clang::ASTConsumer>();
41 void ExecuteAction()
override {
42 clang::CompilerInstance *Compiler = &getCompilerInstance();
43 assert(!Compiler->hasSema() &&
"CI already has Sema");
46 if (hasCodeCompletionSupport() &&
47 !Compiler->getFrontendOpts().CodeCompletionAt.FileName.empty())
48 Compiler->createCodeCompletionConsumer();
50 clang::CodeCompleteConsumer *CompletionConsumer =
nullptr;
51 if (Compiler->hasCodeCompletionConsumer())
52 CompletionConsumer = &Compiler->getCodeCompletionConsumer();
54 Compiler->createSema(getTranslationUnitKind(), CompletionConsumer);
55 SemaSource->setCompilerInstance(Compiler);
56 Compiler->getSema().addExternalSource(SemaSource.get());
58 clang::ParseAST(Compiler->getSema(), Compiler->getFrontendOpts().ShowStats,
59 Compiler->getFrontendOpts().SkipFunctionBodies);
63 getIncludeFixerContext(
const clang::SourceManager &SourceManager,
64 clang::HeaderSearch &HeaderSearch)
const {
65 return SemaSource->getIncludeFixerContext(SourceManager, HeaderSearch,
66 SemaSource->getMatchedSymbols());
70 IntrusiveRefCntPtr<IncludeFixerSemaSource> SemaSource;
77 std::vector<IncludeFixerContext> &Contexts, StringRef StyleName,
78 bool MinimizeIncludePaths)
79 : SymbolIndexMgr(SymbolIndexMgr), Contexts(Contexts),
80 MinimizeIncludePaths(MinimizeIncludePaths) {}
85 std::shared_ptr<clang::CompilerInvocation> Invocation,
86 clang::FileManager *Files,
87 std::shared_ptr<clang::PCHContainerOperations> PCHContainerOps,
89 assert(Invocation->getFrontendOpts().Inputs.size() == 1);
92 clang::CompilerInstance Compiler(PCHContainerOps);
93 Compiler.setInvocation(std::move(Invocation));
94 Compiler.setFileManager(Files);
98 Compiler.createDiagnostics(
new clang::IgnoringDiagConsumer,
100 Compiler.createSourceManager(*Files);
104 Compiler.getDiagnostics().setErrorLimit(0);
107 auto ScopedToolAction =
108 std::make_unique<Action>(SymbolIndexMgr, MinimizeIncludePaths);
109 Compiler.ExecuteAction(*ScopedToolAction);
111 Contexts.push_back(ScopedToolAction->getIncludeFixerContext(
112 Compiler.getSourceManager(),
113 Compiler.getPreprocessor().getHeaderSearchInfo()));
118 return !Compiler.getDiagnostics().hasFatalErrorOccurred();
123 StringRef
Code, SourceLocation StartOfFile,
126 Code, Context, format::getLLVMStyle(),
false);
127 if (!Reps || Reps->size() != 1)
130 unsigned DiagID = Ctx.getDiagnostics().getCustomDiagID(
131 DiagnosticsEngine::Note,
"Add '#include %0' to provide the missing "
132 "declaration [clang-include-fixer]");
136 const tooling::Replacement &Placed = *Reps->begin();
138 auto Begin = StartOfFile.getLocWithOffset(Placed.getOffset());
139 auto End = Begin.getLocWithOffset(std::max(0, (
int)Placed.getLength() - 1));
140 PartialDiagnostic PD(DiagID, Ctx.getDiagAllocator());
141 PD << Context.getHeaderInfos().front().Header
142 << FixItHint::CreateReplacement(CharSourceRange::getCharRange(Begin, End),
143 Placed.getReplacementText());
144 Correction.addExtraDiagnostic(std::move(PD));
151 clang::SourceLocation
Loc, clang::QualType T) {
153 if (CI->getSema().isSFINAEContext())
156 clang::ASTContext &context = CI->getASTContext();
157 std::string QueryString = QualType(T->getUnqualifiedDesugaredType(), 0)
158 .getAsString(context.getPrintingPolicy());
159 LLVM_DEBUG(llvm::dbgs() <<
"Query missing complete type '" << QueryString
162 std::vector<find_all_symbols::SymbolInfo> MatchedSymbols =
163 query(QueryString,
"", tooling::Range());
165 if (!MatchedSymbols.empty() && GenerateDiagnostics) {
166 TypoCorrection Correction;
167 FileID FID = CI->getSourceManager().getFileID(
Loc);
168 StringRef
Code = CI->getSourceManager().getBufferData(FID);
169 SourceLocation StartOfFile =
170 CI->getSourceManager().getLocForStartOfFile(FID);
174 CI->getPreprocessor().getHeaderSearchInfo(),
176 Code, StartOfFile, CI->getASTContext());
177 for (
const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
178 CI->getSema().Diag(
Loc, PD);
186 const DeclarationNameInfo &Typo,
int LookupKind, Scope *S, CXXScopeSpec *SS,
187 CorrectionCandidateCallback &CCC, DeclContext *MemberContext,
188 bool EnteringContext,
const ObjCObjectPointerType *OPT) {
190 if (CI->getSema().isSFINAEContext())
191 return clang::TypoCorrection();
212 if (!CI->getSourceManager().isWrittenInMainFile(Typo.getLoc()))
213 return clang::TypoCorrection();
215 std::string TypoScopeString;
219 for (
const auto *Context = S->getEntity(); Context;
220 Context = Context->getParent()) {
221 if (
const auto *ND = dyn_cast<NamespaceDecl>(Context)) {
222 if (!ND->getName().empty())
223 TypoScopeString = ND->getNameAsString() +
"::" + TypoScopeString;
228 auto ExtendNestedNameSpecifier = [
this](CharSourceRange
Range) {
230 Lexer::getSourceText(
Range, CI->getSourceManager(), CI->getLangOpts());
248 const char *End = Source.end();
249 while (isAsciiIdentifierContinue(*End) || *End ==
':')
252 return std::string(Source.begin(), End);
256 std::string QueryString;
257 tooling::Range SymbolRange;
258 const auto &SM = CI->getSourceManager();
259 auto CreateToolingRange = [&QueryString, &SM](SourceLocation BeginLoc) {
260 return tooling::Range(SM.getDecomposedLoc(BeginLoc).second,
263 if (SS && SS->getRange().isValid()) {
264 auto Range = CharSourceRange::getTokenRange(SS->getRange().getBegin(),
267 QueryString = ExtendNestedNameSpecifier(
Range);
268 SymbolRange = CreateToolingRange(
Range.getBegin());
269 }
else if (Typo.getName().isIdentifier() && !Typo.getLoc().isMacroID()) {
271 CharSourceRange::getTokenRange(Typo.getBeginLoc(), Typo.getEndLoc());
273 QueryString = ExtendNestedNameSpecifier(
Range);
274 SymbolRange = CreateToolingRange(
Range.getBegin());
276 QueryString = Typo.getAsString();
277 SymbolRange = CreateToolingRange(Typo.getLoc());
280 LLVM_DEBUG(llvm::dbgs() <<
"TypoScopeQualifiers: " << TypoScopeString
282 std::vector<find_all_symbols::SymbolInfo> MatchedSymbols =
283 query(QueryString, TypoScopeString, SymbolRange);
285 if (!MatchedSymbols.empty() && GenerateDiagnostics) {
286 TypoCorrection Correction(Typo.getName());
287 Correction.setCorrectionRange(SS, Typo);
288 FileID FID = SM.getFileID(Typo.getLoc());
289 StringRef
Code = SM.getBufferData(FID);
290 SourceLocation StartOfFile = SM.getLocForStartOfFile(FID);
293 SM, CI->getPreprocessor().getHeaderSearchInfo(),
295 Code, StartOfFile, CI->getASTContext()))
298 return TypoCorrection();
303 StringRef Include,
const clang::SourceManager &SourceManager,
304 clang::HeaderSearch &HeaderSearch)
const {
305 if (!MinimizeIncludePaths)
306 return std::string(Include);
309 StringRef StrippedInclude = Include.trim(
"\"<>");
311 SourceManager.getFileManager().getOptionalFileRef(StrippedInclude);
316 return std::string(Include);
319 std::string Suggestion =
320 HeaderSearch.suggestPathToFileForDiagnostics(*
Entry,
"", &
IsAngled);
322 return IsAngled ?
'<' + Suggestion +
'>' :
'"' + Suggestion +
'"';
327 const clang::SourceManager &SourceManager,
328 clang::HeaderSearch &HeaderSearch,
329 ArrayRef<find_all_symbols::SymbolInfo> MatchedSymbols)
const {
330 std::vector<find_all_symbols::SymbolInfo> SymbolCandidates;
331 for (
const auto &Symbol : MatchedSymbols) {
332 std::string FilePath = Symbol.getFilePath().str();
334 ((FilePath[0] ==
'"' || FilePath[0] ==
'<') ? FilePath
335 :
"\"" + FilePath +
"\""),
336 SourceManager, HeaderSearch);
337 SymbolCandidates.emplace_back(Symbol.getName(), Symbol.getSymbolKind(),
338 MinimizedFilePath, Symbol.getContexts());
343std::vector<find_all_symbols::SymbolInfo>
344IncludeFixerSemaSource::query(StringRef Query, StringRef ScopedQualifiers,
345 tooling::Range Range) {
346 assert(!Query.empty() &&
"Empty query!");
354 if (!GenerateDiagnostics && !QuerySymbolInfos.empty()) {
355 if (ScopedQualifiers == QuerySymbolInfos.front().ScopedQualifiers &&
356 Query == QuerySymbolInfos.front().RawIdentifier) {
357 QuerySymbolInfos.push_back(
358 {Query.str(), std::string(ScopedQualifiers), Range});
363 LLVM_DEBUG(llvm::dbgs() <<
"Looking up '" << Query <<
"' at ");
364 LLVM_DEBUG(CI->getSourceManager()
365 .getLocForStartOfFile(CI->getSourceManager().getMainFileID())
366 .getLocWithOffset(
Range.getOffset())
367 .print(llvm::dbgs(), CI->getSourceManager()));
368 LLVM_DEBUG(llvm::dbgs() <<
" ...");
369 llvm::StringRef
FileName = CI->getSourceManager().getFilename(
370 CI->getSourceManager().getLocForStartOfFile(
371 CI->getSourceManager().getMainFileID()));
373 QuerySymbolInfos.push_back(
374 {Query.str(), std::string(ScopedQualifiers), Range});
388 std::string QueryString = ScopedQualifiers.str() + Query.str();
392 std::vector<find_all_symbols::SymbolInfo> MatchedSymbols =
394 if (MatchedSymbols.empty())
397 LLVM_DEBUG(llvm::dbgs() <<
"Having found " << MatchedSymbols.size()
401 this->MatchedSymbols = MatchedSymbols;
402 return MatchedSymbols;
407 const clang::format::FormatStyle &Style,
bool AddQualifiers) {
408 if (Context.getHeaderInfos().empty())
409 return tooling::Replacements();
410 StringRef FilePath = Context.getFilePath();
411 std::string IncludeName =
412 "#include " + Context.getHeaderInfos().front().Header +
"\n";
414 clang::tooling::Replacements Insertions;
416 Insertions.add(tooling::Replacement(FilePath, UINT_MAX, 0, IncludeName));
418 return std::move(Err);
420 auto CleanReplaces = cleanupAroundReplacements(
Code, Insertions, Style);
422 return CleanReplaces;
424 auto Replaces = std::move(*CleanReplaces);
426 for (
const auto &
Info : Context.getQuerySymbolInfos()) {
428 if (
Info.Range.getLength() > 0) {
429 auto R = tooling::Replacement(
430 {FilePath,
Info.Range.getOffset(),
Info.Range.getLength(),
431 Context.getHeaderInfos().front().QualifiedName});
434 llvm::consumeError(std::move(Err));
435 R = tooling::Replacement(
436 R.getFilePath(),
Replaces.getShiftedCodePosition(R.getOffset()),
437 R.getLength(), R.getReplacementText());
CharSourceRange Range
SourceRange for the file name.
bool IsAngled
true if this was an include with angle brackets
WantDiagnostics Diagnostics
bool runInvocation(std::shared_ptr< clang::CompilerInvocation > Invocation, clang::FileManager *Files, std::shared_ptr< clang::PCHContainerOperations > PCHContainerOps, clang::DiagnosticConsumer *Diagnostics) override
IncludeFixerActionFactory(SymbolIndexManager &SymbolIndexMgr, std::vector< IncludeFixerContext > &Contexts, StringRef StyleName, bool MinimizeIncludePaths=true)
~IncludeFixerActionFactory() override
A context for a file being processed.
IncludeFixerContext getIncludeFixerContext(const clang::SourceManager &SourceManager, clang::HeaderSearch &HeaderSearch, ArrayRef< find_all_symbols::SymbolInfo > MatchedSymbols) const
Get the include fixer context for the queried symbol.
std::string minimizeInclude(StringRef Include, const clang::SourceManager &SourceManager, clang::HeaderSearch &HeaderSearch) const
Get the minimal include for a given path.
clang::TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, int LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT) override
Callback for unknown identifiers.
bool MaybeDiagnoseMissingCompleteType(clang::SourceLocation Loc, clang::QualType T) override
Callback for incomplete types.
This class provides an interface for finding the header files corresponding to an identifier in the s...
std::vector< find_all_symbols::SymbolInfo > search(llvm::StringRef Identifier, bool IsNestedSearch=true, llvm::StringRef FileName="") const
Search for header files to be included for an identifier.
static bool addDiagnosticsForContext(TypoCorrection &Correction, const IncludeFixerContext &Context, StringRef Code, SourceLocation StartOfFile, ASTContext &Ctx)
llvm::Expected< tooling::Replacements > createIncludeFixerReplacements(StringRef Code, const IncludeFixerContext &Context, const clang::format::FormatStyle &Style, bool AddQualifiers)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//