11 #include "clang/Format/Format.h" 12 #include "clang/Frontend/CompilerInstance.h" 13 #include "clang/Lex/HeaderSearch.h" 14 #include "clang/Lex/Preprocessor.h" 15 #include "clang/Parse/ParseAST.h" 16 #include "clang/Sema/Sema.h" 17 #include "llvm/Support/Debug.h" 18 #include "llvm/Support/raw_ostream.h" 20 #define DEBUG_TYPE "include-fixer" 22 using namespace clang;
25 namespace include_fixer {
28 class Action :
public clang::ASTFrontendAction {
30 explicit Action(SymbolIndexManager &SymbolIndexMgr,
bool MinimizeIncludePaths)
31 : SemaSource(SymbolIndexMgr, MinimizeIncludePaths,
34 std::unique_ptr<clang::ASTConsumer>
35 CreateASTConsumer(clang::CompilerInstance &Compiler,
36 StringRef InFile)
override {
37 SemaSource.setFilePath(InFile);
38 return llvm::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 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 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 llvm::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());
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 =
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);
173 getIncludeFixerContext(CI->getSourceManager(),
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 (isIdentifierBody(*End) || *End ==
':')
252 return std::string(Source.begin(), End);
256 std::string QueryString;
258 const auto &SM = CI->getSourceManager();
259 auto CreateToolingRange = [&QueryString, &SM](SourceLocation BeginLoc) {
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);
292 Correction, getIncludeFixerContext(
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)
309 StringRef StrippedInclude = Include.trim(
"\"<>");
310 const FileEntry *
Entry =
311 SourceManager.getFileManager().getFile(StrippedInclude);
319 std::string Suggestion =
320 HeaderSearch.suggestPathToFileForDiagnostics(Entry, &IsSystem);
322 return IsSystem ?
'<' + 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) {
333 std::string MinimizedFilePath = minimizeInclude(
334 ((FilePath[0] ==
'"' || FilePath[0] ==
'<') ? FilePath
335 :
"\"" + FilePath +
"\""),
336 SourceManager, HeaderSearch);
337 SymbolCandidates.emplace_back(Symbol.getName(), Symbol.getSymbolKind(),
338 MinimizedFilePath, Symbol.getContexts());
343 std::vector<find_all_symbols::SymbolInfo>
344 IncludeFixerSemaSource::query(StringRef Query, StringRef ScopedQualifiers,
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({Query.str(), 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({Query.str(), ScopedQualifiers, Range});
386 std::string QueryString = ScopedQualifiers.str() + Query.str();
390 std::vector<find_all_symbols::SymbolInfo> MatchedSymbols =
391 SymbolIndexMgr.
search(QueryString,
false, FileName);
392 if (MatchedSymbols.empty())
394 SymbolIndexMgr.
search(Query,
true, FileName);
395 LLVM_DEBUG(llvm::dbgs() <<
"Having found " << MatchedSymbols.size()
399 this->MatchedSymbols = MatchedSymbols;
400 return MatchedSymbols;
407 return tooling::Replacements();
409 std::string IncludeName =
412 clang::tooling::Replacements Insertions;
414 Insertions.add(tooling::Replacement(FilePath, UINT_MAX, 0, IncludeName));
416 return std::move(Err);
418 auto CleanReplaces = cleanupAroundReplacements(Code, Insertions, Style);
420 return CleanReplaces;
422 auto Replaces = std::move(*CleanReplaces);
426 if (
Info.Range.getLength() > 0) {
427 auto R = tooling::Replacement(
428 {FilePath,
Info.Range.getOffset(),
Info.Range.getLength(),
430 auto Err = Replaces.add(R);
432 llvm::consumeError(std::move(Err));
433 R = tooling::Replacement(
434 R.getFilePath(), Replaces.getShiftedCodePosition(R.getOffset()),
435 R.getLength(), R.getReplacementText());
436 Replaces = Replaces.merge(tooling::Replacements(R));
441 return formatReplacements(Code, Replaces, Style);
SourceLocation Loc
'#' location in the include directive
llvm::Expected< tooling::Replacements > createIncludeFixerReplacements(StringRef Code, const IncludeFixerContext &Context, const clang::format::FormatStyle &Style, bool AddQualifiers)
const std::vector< QuerySymbolInfo > & getQuerySymbolInfos() const
Get information of symbols being querid.
StringRef getFilePath() const
Get the file path to the file being processed.
A context for a file being processed.
bool MaybeDiagnoseMissingCompleteType(clang::SourceLocation Loc, clang::QualType T) override
Callback for incomplete types.
const std::vector< HeaderInfo > & getHeaderInfos() const
Get header information.
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.
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 runInvocation(std::shared_ptr< clang::CompilerInvocation > Invocation, clang::FileManager *Files, std::shared_ptr< clang::PCHContainerOperations > PCHContainerOps, clang::DiagnosticConsumer *Diagnostics) override
static bool addDiagnosticsForContext(TypoCorrection &Correction, const IncludeFixerContext &Context, StringRef Code, SourceLocation StartOfFile, ASTContext &Ctx)
llvm::unique_function< void()> Action
This class provides an interface for finding the header files corresponding to an identifier in the s...
~IncludeFixerActionFactory() override
IncludeFixerActionFactory(SymbolIndexManager &SymbolIndexMgr, std::vector< IncludeFixerContext > &Contexts, StringRef StyleName, bool MinimizeIncludePaths=true)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
CharSourceRange Range
SourceRange for the file name.
std::string minimizeInclude(StringRef Include, const clang::SourceManager &SourceManager, clang::HeaderSearch &HeaderSearch) const
Get the minimal include for a given path.
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 cl::opt< std::string > FormatStyle("format-style", cl::desc(R"(
Style for formatting code around applied fixes:
- 'none' (default) turns off formatting
- 'file' (literally 'file', not a placeholder)
uses .clang-format file in the closest parent
directory
- '{ <json> }' specifies options inline, e.g.
-format-style='{BasedOnStyle: llvm, IndentWidth: 8}'
- 'llvm', 'google', 'webkit', 'mozilla'
See clang-format documentation for the up-to-date
information about formatting styles and options.
This option overrides the 'FormatStyle` option in
.clang-tidy file, if any.
)"), cl::init("none"), cl::cat(ClangTidyCategory))