clang-tools  3.8.0
IncludeInserter.h
Go to the documentation of this file.
1 //===---------- IncludeInserter.h - clang-tidy ----------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_INCLUDEINSERTER_H
11 #define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_INCLUDEINSERTER_H
12 
13 #include "IncludeSorter.h"
14 #include "clang/Basic/Diagnostic.h"
15 #include "clang/Basic/LangOptions.h"
16 #include "clang/Basic/SourceManager.h"
17 #include "clang/Lex/PPCallbacks.h"
18 #include <memory>
19 #include <string>
20 
21 namespace clang {
22 namespace tidy {
23 
24 // IncludeInserter can be used by ClangTidyChecks in the following fashion:
25 // class MyCheck : public ClangTidyCheck {
26 // public:
27 // void registerPPCallbacks(CompilerInstance& Compiler) override {
28 // Inserter.reset(new IncludeInserter(&Compiler.getSourceManager(),
29 // &Compiler.getLangOpts()));
30 // Compiler.getPreprocessor().addPPCallbacks(
31 // Inserter->CreatePPCallback());
32 // }
33 //
34 // void registerMatchers(ast_matchers::MatchFinder* Finder) override { ... }
35 //
36 // void check(const ast_matchers::MatchFinder::MatchResult& Result) override {
37 // ...
38 // Inserter->CreateIncludeInsertion(
39 // Result.SourceManager->getMainFileID(), "path/to/Header.h",
40 // /*IsAngled=*/false);
41 // ...
42 // }
43 //
44 // private:
45 // std::unique_ptr<IncludeInserter> Inserter;
46 // };
48 public:
49  IncludeInserter(const SourceManager &SourceMgr, const LangOptions &LangOpts,
52 
53  // Create PPCallbacks for registration with the compiler's preprocessor.
54  std::unique_ptr<PPCallbacks> CreatePPCallbacks();
55 
56  // Creates a Header inclusion directive fixit. Returns None on error or
57  // if inclusion directive already exists.
58  llvm::Optional<FixItHint>
59  CreateIncludeInsertion(FileID FileID, llvm::StringRef Header, bool IsAngled);
60 
61 private:
62  void AddInclude(StringRef file_name, bool IsAngled,
63  SourceLocation hash_location, SourceLocation end_location);
64 
65  llvm::DenseMap<FileID, std::unique_ptr<IncludeSorter>> IncludeSorterByFile;
66  llvm::DenseMap<FileID, std::set<std::string>> InsertedHeaders;
67  const SourceManager &SourceMgr;
68  const LangOptions &LangOpts;
69  const IncludeSorter::IncludeStyle Style;
71 };
72 
73 } // namespace tidy
74 } // namespace clang
75 #endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_INCLUDEINSERTER_H
IncludeInserter(const SourceManager &SourceMgr, const LangOptions &LangOpts, IncludeSorter::IncludeStyle Style)
llvm::Optional< FixItHint > CreateIncludeInsertion(FileID FileID, llvm::StringRef Header, bool IsAngled)
bool IsAngled
true if this was an include with angle brackets
std::unique_ptr< PPCallbacks > CreatePPCallbacks()