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"
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);
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,
88 clang::DiagnosticConsumer *Diagnostics) {
89 assert(Invocation->getFrontendOpts().Inputs.size() == 1);
92 CompilerInstance Compiler(std::move(Invocation), std::move(PCHContainerOps));
93 Compiler.setFileManager(Files);
97 Compiler.createDiagnostics(
new clang::IgnoringDiagConsumer,
99 Compiler.createSourceManager(*Files);
103 Compiler.getDiagnostics().setErrorLimit(0);
106 auto ScopedToolAction =
107 std::make_unique<Action>(SymbolIndexMgr, MinimizeIncludePaths);
108 Compiler.ExecuteAction(*ScopedToolAction);
110 Contexts.push_back(ScopedToolAction->getIncludeFixerContext(
111 Compiler.getSourceManager(),
112 Compiler.getPreprocessor().getHeaderSearchInfo()));
117 return !Compiler.getDiagnostics().hasFatalErrorOccurred();
122 StringRef Code, SourceLocation StartOfFile,
125 Code, Context, format::getLLVMStyle(),
false);
126 if (!Reps || Reps->size() != 1)
129 unsigned DiagID = Ctx.getDiagnostics().getCustomDiagID(
130 DiagnosticsEngine::Note,
"Add '#include %0' to provide the missing "
131 "declaration [clang-include-fixer]");
135 const tooling::Replacement &Placed = *Reps->begin();
137 auto Begin = StartOfFile.getLocWithOffset(Placed.getOffset());
138 auto End = Begin.getLocWithOffset(std::max(0, (
int)Placed.getLength() - 1));
139 PartialDiagnostic PD(DiagID, Ctx.getDiagAllocator());
141 << FixItHint::CreateReplacement(CharSourceRange::getCharRange(Begin, End),
142 Placed.getReplacementText());
143 Correction.addExtraDiagnostic(std::move(PD));
150 clang::SourceLocation Loc, clang::QualType T) {
152 if (CI->getSema().isSFINAEContext())
155 clang::ASTContext &context = CI->getASTContext();
156 std::string QueryString = QualType(T->getUnqualifiedDesugaredType(), 0)
157 .getAsString(context.getPrintingPolicy());
158 LLVM_DEBUG(llvm::dbgs() <<
"Query missing complete type '" << QueryString
161 std::vector<find_all_symbols::SymbolInfo> MatchedSymbols =
162 query(QueryString,
"", tooling::Range());
164 if (!MatchedSymbols.empty() && GenerateDiagnostics) {
165 TypoCorrection Correction;
166 FileID FID = CI->getSourceManager().getFileID(Loc);
167 StringRef Code = CI->getSourceManager().getBufferData(FID);
168 SourceLocation StartOfFile =
169 CI->getSourceManager().getLocForStartOfFile(FID);
173 CI->getPreprocessor().getHeaderSearchInfo(),
175 Code, StartOfFile, CI->getASTContext());
176 for (
const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
177 CI->getSema().Diag(Loc, PD);
185 const DeclarationNameInfo &Typo,
int LookupKind, Scope *S, CXXScopeSpec *SS,
186 CorrectionCandidateCallback &CCC, DeclContext *MemberContext,
187 bool EnteringContext,
const ObjCObjectPointerType *OPT) {
189 if (CI->getSema().isSFINAEContext())
190 return clang::TypoCorrection();
211 if (!CI->getSourceManager().isWrittenInMainFile(Typo.getLoc()))
212 return clang::TypoCorrection();
214 std::string TypoScopeString;
218 for (
const auto *Context = S->getEntity(); Context;
219 Context = Context->getParent()) {
220 if (
const auto *ND = dyn_cast<NamespaceDecl>(Context)) {
221 if (!ND->getName().empty())
222 TypoScopeString = ND->getNameAsString() +
"::" + TypoScopeString;
227 auto ExtendNestedNameSpecifier = [
this](CharSourceRange Range) {
229 Lexer::getSourceText(Range, CI->getSourceManager(), CI->getLangOpts());
247 const char *End = Source.end();
248 while (isAsciiIdentifierContinue(*End) || *End ==
':')
251 return std::string(Source.begin(), End);
255 std::string QueryString;
256 tooling::Range SymbolRange;
257 const auto &SM = CI->getSourceManager();
258 auto CreateToolingRange = [&QueryString, &SM](SourceLocation BeginLoc) {
259 return tooling::Range(SM.getDecomposedLoc(BeginLoc).second,
262 if (SS && SS->getRange().isValid()) {
263 auto Range = CharSourceRange::getTokenRange(SS->getRange().getBegin(),
266 QueryString = ExtendNestedNameSpecifier(Range);
267 SymbolRange = CreateToolingRange(Range.getBegin());
268 }
else if (Typo.getName().isIdentifier() && !Typo.getLoc().isMacroID()) {
270 CharSourceRange::getTokenRange(Typo.getBeginLoc(), Typo.getEndLoc());
272 QueryString = ExtendNestedNameSpecifier(Range);
273 SymbolRange = CreateToolingRange(Range.getBegin());
275 QueryString = Typo.getAsString();
276 SymbolRange = CreateToolingRange(Typo.getLoc());
279 LLVM_DEBUG(llvm::dbgs() <<
"TypoScopeQualifiers: " << TypoScopeString
281 std::vector<find_all_symbols::SymbolInfo> MatchedSymbols =
282 query(QueryString, TypoScopeString, SymbolRange);
284 if (!MatchedSymbols.empty() && GenerateDiagnostics) {
285 TypoCorrection Correction(Typo.getName());
286 Correction.setCorrectionRange(SS, Typo);
287 FileID FID = SM.getFileID(Typo.getLoc());
288 StringRef Code = SM.getBufferData(FID);
289 SourceLocation StartOfFile = SM.getLocForStartOfFile(FID);
292 SM, CI->getPreprocessor().getHeaderSearchInfo(),
294 Code, StartOfFile, CI->getASTContext()))
297 return TypoCorrection();
302 StringRef Include,
const clang::SourceManager &SourceManager,
303 clang::HeaderSearch &HeaderSearch)
const {
304 if (!MinimizeIncludePaths)
305 return std::string(Include);
308 StringRef StrippedInclude = Include.trim(
"\"<>");
310 SourceManager.getFileManager().getOptionalFileRef(StrippedInclude);
315 return std::string(Include);
317 bool IsAngled =
false;
318 std::string Suggestion =
319 HeaderSearch.suggestPathToFileForDiagnostics(*
Entry,
"", &IsAngled);
321 return IsAngled ?
'<' + Suggestion +
'>' :
'"' + Suggestion +
'"';
326 const clang::SourceManager &SourceManager,
327 clang::HeaderSearch &HeaderSearch,
328 ArrayRef<find_all_symbols::SymbolInfo> MatchedSymbols)
const {
329 std::vector<find_all_symbols::SymbolInfo> SymbolCandidates;
330 for (
const auto &Symbol : MatchedSymbols) {
331 std::string FilePath = Symbol.getFilePath().str();
333 ((FilePath[0] ==
'"' || FilePath[0] ==
'<') ? FilePath
334 :
"\"" + FilePath +
"\""),
335 SourceManager, HeaderSearch);
336 SymbolCandidates.emplace_back(Symbol.getName(), Symbol.getSymbolKind(),
337 MinimizedFilePath, Symbol.getContexts());
342std::vector<find_all_symbols::SymbolInfo>
343IncludeFixerSemaSource::query(StringRef Query, StringRef ScopedQualifiers,
344 tooling::Range Range) {
345 assert(!Query.empty() &&
"Empty query!");
353 if (!GenerateDiagnostics && !QuerySymbolInfos.empty()) {
354 if (ScopedQualifiers == QuerySymbolInfos.front().ScopedQualifiers &&
355 Query == QuerySymbolInfos.front().RawIdentifier) {
356 QuerySymbolInfos.push_back(
357 {Query.str(), std::string(ScopedQualifiers), Range});
362 LLVM_DEBUG(llvm::dbgs() <<
"Looking up '" << Query <<
"' at ");
363 LLVM_DEBUG(CI->getSourceManager()
364 .getLocForStartOfFile(CI->getSourceManager().getMainFileID())
365 .getLocWithOffset(Range.getOffset())
366 .print(llvm::dbgs(), CI->getSourceManager()));
367 LLVM_DEBUG(llvm::dbgs() <<
" ...");
368 llvm::StringRef FileName = CI->getSourceManager().getFilename(
369 CI->getSourceManager().getLocForStartOfFile(
370 CI->getSourceManager().getMainFileID()));
372 QuerySymbolInfos.push_back(
373 {Query.str(), std::string(ScopedQualifiers), Range});
387 std::string QueryString = ScopedQualifiers.str() + Query.str();
391 std::vector<find_all_symbols::SymbolInfo> MatchedSymbols =
392 SymbolIndexMgr.search(QueryString,
false, FileName);
393 if (MatchedSymbols.empty())
395 SymbolIndexMgr.search(Query,
true, FileName);
396 LLVM_DEBUG(llvm::dbgs() <<
"Having found " << MatchedSymbols.size()
400 this->MatchedSymbols = MatchedSymbols;
401 return MatchedSymbols;
406 const clang::format::FormatStyle &Style,
bool AddQualifiers) {
408 return tooling::Replacements();
410 std::string IncludeName =
413 clang::tooling::Replacements Insertions;
415 Insertions.add(tooling::Replacement(FilePath, UINT_MAX, 0, IncludeName));
417 return std::move(Err);
419 auto CleanReplaces = cleanupAroundReplacements(Code, Insertions, Style);
421 return CleanReplaces;
423 auto Replaces = std::move(*CleanReplaces);
427 if (Info.Range.getLength() > 0) {
428 auto R = tooling::Replacement(
429 {FilePath, Info.Range.getOffset(), Info.Range.getLength(),
431 auto Err = Replaces.add(R);
433 llvm::consumeError(std::move(Err));
434 R = tooling::Replacement(
435 R.getFilePath(), Replaces.getShiftedCodePosition(R.getOffset()),
436 R.getLength(), R.getReplacementText());
437 Replaces = Replaces.merge(tooling::Replacements(R));
442 return formatReplacements(Code, Replaces, Style);
A context for a file being processed.
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.
const std::vector< HeaderInfo > & getHeaderInfos() const
Get header information.
StringRef getFilePath() const
Get the file path to the file being processed.
const std::vector< QuerySymbolInfo > & getQuerySymbolInfos() const
Get information of symbols being querid.
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...
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++ -*-===//