15#include "clang/Basic/TokenKinds.h"
16#include "clang/Frontend/CompilerInstance.h"
17#include "clang/Frontend/CompilerInvocation.h"
18#include "clang/Frontend/FrontendActions.h"
19#include "clang/Tooling/Inclusions/HeaderIncludes.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/Support/Error.h"
22#include "llvm/Support/FormatVariadic.h"
23#include "llvm/Support/Path.h"
24#include "llvm/Testing/Support/Error.h"
25#include "gmock/gmock.h"
26#include "gtest/gtest.h"
33using ::testing::AllOf;
34using ::testing::Contains;
35using ::testing::ElementsAre;
36using ::testing::IsEmpty;
38using ::testing::UnorderedElementsAre;
40class HeadersTest :
public ::testing::Test {
46 FS.Files[
testPath(
"sub/EMPTY")] =
"";
50 std::unique_ptr<CompilerInstance> setupClang() {
51 auto Cmd = CDB.getCompileCommand(MainFile);
52 assert(
static_cast<bool>(Cmd));
55 PI.CompileCommand = *Cmd;
58 EXPECT_TRUE(
static_cast<bool>(
CI));
60 CI->getDiagnosticOpts().IgnoreWarnings =
true;
61 auto VFS = PI.TFS->view(Cmd->Directory);
63 std::move(
CI),
nullptr,
64 llvm::MemoryBuffer::getMemBuffer(FS.Files[MainFile], MainFile),
65 std::move(VFS), IgnoreDiags);
67 EXPECT_FALSE(
Clang->getFrontendOpts().Inputs.empty());
73 IncludeStructure &Includes) {
74 auto &SM =
Clang->getSourceManager();
76 EXPECT_THAT_EXPECTED(
Entry, llvm::Succeeded());
77 return Includes.getOrCreateID(*
Entry);
80 IncludeStructure collectIncludes() {
82 PreprocessOnlyAction
Action;
84 Action.BeginSourceFile(*Clang,
Clang->getFrontendOpts().Inputs[0]));
85 IncludeStructure Includes;
86 Includes.collect(*Clang);
87 EXPECT_FALSE(
Action.Execute());
95 const std::vector<Inclusion> &Inclusions = {}) {
97 PreprocessOnlyAction
Action;
99 Action.BeginSourceFile(*Clang,
Clang->getFrontendOpts().Inputs[0]));
101 if (Preferred.empty())
102 Preferred = Original;
103 auto ToHeaderFile = [](llvm::StringRef Header) {
104 return HeaderFile{std::string(Header),
105 !llvm::sys::path::is_absolute(Header)};
108 IncludeInserter Inserter(MainFile,
"", format::getLLVMStyle(),
109 CDB.getCompileCommand(MainFile)->Directory,
110 &
Clang->getPreprocessor().getHeaderSearchInfo());
111 for (
const auto &Inc : Inclusions)
112 Inserter.addExisting(Inc);
113 auto Inserted = ToHeaderFile(Preferred);
114 if (!Inserter.shouldInsertInclude(Original, Inserted))
116 auto Path = Inserter.calculateIncludePath(Inserted, MainFile);
118 return Path.value_or(
"");
121 std::optional<TextEdit> insert(llvm::StringRef VerbatimHeader,
123 Clang = setupClang();
124 PreprocessOnlyAction
Action;
126 Action.BeginSourceFile(*Clang,
Clang->getFrontendOpts().Inputs[0]));
128 IncludeInserter Inserter(MainFile,
"", format::getLLVMStyle(),
129 CDB.getCompileCommand(MainFile)->Directory,
130 &
Clang->getPreprocessor().getHeaderSearchInfo());
131 auto Edit = Inserter.insert(VerbatimHeader,
Directive);
137 MockCompilationDatabase CDB;
142 std::unique_ptr<CompilerInstance>
Clang;
147MATCHER_P(includeLine, N,
"") {
return arg.HashLine == N; }
148MATCHER_P(directive, D,
"") {
return arg.Directive == D; }
151 if (arg.getFirst() !=
File)
152 *result_listener <<
"file =" <<
static_cast<unsigned>(arg.getFirst());
153 if (arg.getSecond() != D)
154 *result_listener <<
"distance =" << arg.getSecond();
155 return arg.getFirst() ==
File && arg.getSecond() == D;
158TEST_F(HeadersTest, CollectRewrittenAndResolved) {
160#include "sub/bar.h" // not shortest
162 std::string BarHeader = testPath("sub/bar.h");
163 FS.Files[BarHeader] =
"";
165 auto Includes = collectIncludes();
167 UnorderedElementsAre(
168 AllOf(written(
"\"sub/bar.h\""), resolved(BarHeader))));
170 UnorderedElementsAre(Distance(getID(
MainFile, Includes), 0u),
171 Distance(getID(BarHeader, Includes), 1u)));
174TEST_F(HeadersTest, OnlyCollectInclusionsInMain) {
175 std::string BazHeader =
testPath(
"sub/baz.h");
176 FS.Files[BazHeader] =
"";
177 std::string BarHeader =
testPath(
"sub/bar.h");
178 FS.Files[BarHeader] = R
"cpp(
184 auto Includes = collectIncludes();
187 UnorderedElementsAre(AllOf(written(
"\"bar.h\""), resolved(BarHeader))));
189 UnorderedElementsAre(Distance(getID(
MainFile, Includes), 0u),
190 Distance(getID(BarHeader, Includes), 1u),
191 Distance(getID(BazHeader, Includes), 2u)));
193 EXPECT_THAT(Includes.
includeDepth(getID(BarHeader, Includes)),
194 UnorderedElementsAre(Distance(getID(BarHeader, Includes), 0u),
195 Distance(getID(BazHeader, Includes), 1u)));
198TEST_F(HeadersTest, CacheBySpellingIsBuiltForMainInclusions) {
199 std::string FooHeader =
testPath(
"foo.h");
200 FS.Files[FooHeader] = R
"cpp(
203 std::string BarHeader = testPath("bar.h");
204 FS.Files[BarHeader] = R
"cpp(
207 std::string BazHeader = testPath("baz.h");
208 FS.Files[BazHeader] = R
"cpp(
216 auto Includes = collectIncludes();
218 UnorderedElementsAre(written(
"\"foo.h\""), written(
"\"bar.h\""),
219 written(
"\"baz.h\"")));
228TEST_F(HeadersTest, PreambleIncludesPresentOnce) {
239 TU.HeaderFilename = "a.h";
240 EXPECT_THAT(TU.build().getIncludeStructure().MainFileIncludes,
241 ElementsAre(includeLine(1), includeLine(3), includeLine(5)));
244TEST_F(HeadersTest, UnResolvedInclusion) {
249 EXPECT_THAT(collectIncludes().MainFileIncludes,
250 UnorderedElementsAre(AllOf(written("\"foo.h\""), resolved(
""))));
251 EXPECT_THAT(collectIncludes().IncludeChildren, IsEmpty());
254TEST_F(HeadersTest, IncludedFilesGraph) {
259 std::string BarHeader = testPath("bar.h");
260 FS.Files[BarHeader] =
"";
261 std::string FooHeader =
testPath(
"foo.h");
262 FS.Files[FooHeader] = R
"cpp(
266 std::string BazHeader = testPath("baz.h");
267 FS.Files[BazHeader] =
"";
269 auto Includes = collectIncludes();
271 SmallVector<IncludeStructure::HeaderID>>
273 {getID(BarHeader, Includes), getID(FooHeader, Includes)}},
274 {getID(FooHeader, Includes),
275 {getID(BarHeader, Includes), getID(BazHeader, Includes)}}};
279TEST_F(HeadersTest, IncludeDirective) {
287 CDB.ExtraClangFlags.push_back(
"-fno-ms-compatibility");
288 EXPECT_THAT(collectIncludes().MainFileIncludes,
289 UnorderedElementsAre(directive(tok::pp_include),
290 directive(tok::pp_import),
291 directive(tok::pp_include_next)));
294TEST_F(HeadersTest, SearchPath) {
295 FS.Files[
"foo/bar.h"] =
"x";
296 FS.Files[
"foo/bar/baz.h"] =
"y";
297 CDB.ExtraClangFlags.push_back(
"-Ifoo/bar");
298 CDB.ExtraClangFlags.push_back(
"-Ifoo/bar/..");
299 EXPECT_THAT(collectIncludes().SearchPathsCanonical,
303TEST_F(HeadersTest, InsertInclude) {
306 EXPECT_EQ(calculate(
Path),
"\"bar.h\"");
309TEST_F(HeadersTest, DoNotInsertIfInSameFile) {
314TEST_F(HeadersTest, DoNotInsertOffIncludePath) {
316 EXPECT_EQ(calculate(
testPath(
"sub2/main.cpp")),
"");
319TEST_F(HeadersTest, ShortenIncludesInSearchPath) {
320 std::string BarHeader =
testPath(
"sub/bar.h");
321 EXPECT_EQ(calculate(BarHeader),
"\"bar.h\"");
326 EXPECT_EQ(calculate(BarHeader),
"\"sub/bar.h\"");
329TEST_F(HeadersTest, ShortenedIncludeNotInSearchPath) {
330 std::string BarHeader =
331 llvm::sys::path::convert_to_slash(
testPath(
"sub-2/bar.h"));
332 EXPECT_EQ(calculate(BarHeader,
""),
"\"sub-2/bar.h\"");
335TEST_F(HeadersTest, PreferredHeader) {
336 std::string BarHeader =
testPath(
"sub/bar.h");
337 EXPECT_EQ(calculate(BarHeader,
"<bar>"),
"<bar>");
339 std::string BazHeader =
testPath(
"sub/baz.h");
340 EXPECT_EQ(calculate(BarHeader, BazHeader),
"\"baz.h\"");
343TEST_F(HeadersTest, DontInsertDuplicatePreferred) {
345 Inc.Written =
"\"bar.h\"";
347 EXPECT_EQ(calculate(
testPath(
"sub/bar.h"),
"\"bar.h\"", {Inc}),
"");
348 EXPECT_EQ(calculate(
"\"x.h\"",
"\"bar.h\"", {Inc}),
"");
351TEST_F(HeadersTest, DontInsertDuplicateResolved) {
353 Inc.Written =
"fake-bar.h";
354 Inc.Resolved =
testPath(
"sub/bar.h");
355 EXPECT_EQ(calculate(Inc.Resolved,
"", {Inc}),
"");
357 EXPECT_EQ(calculate(Inc.Resolved,
"\"BAR.h\"", {Inc}),
"");
360TEST_F(HeadersTest, PreferInserted) {
361 auto Edit = insert(
"<y>", tooling::IncludeDirective::Include);
363 EXPECT_EQ(Edit->newText,
"#include <y>\n");
365 Edit = insert(
"\"header.h\"", tooling::IncludeDirective::Import);
367 EXPECT_EQ(Edit->newText,
"#import \"header.h\"\n");
370TEST(Headers, NoHeaderSearchInfo) {
372 IncludeInserter Inserter(
MainFile,
"", format::getLLVMStyle(),
375 auto HeaderPath =
testPath(
"sub/bar.h");
376 auto Inserting = HeaderFile{HeaderPath,
false};
377 auto Verbatim = HeaderFile{
"<x>",
true};
379 EXPECT_EQ(Inserter.calculateIncludePath(Inserting,
MainFile),
380 std::string(
"\"sub/bar.h\""));
381 EXPECT_EQ(Inserter.shouldInsertInclude(HeaderPath, Inserting),
false);
383 EXPECT_EQ(Inserter.calculateIncludePath(Verbatim,
MainFile),
385 EXPECT_EQ(Inserter.shouldInsertInclude(HeaderPath, Verbatim),
true);
387 EXPECT_EQ(Inserter.calculateIncludePath(Inserting,
"sub2/main2.cpp"),
391TEST_F(HeadersTest, PresumedLocations) {
392 std::string HeaderFile =
"__preamble_patch__.h";
396 llvm::formatv(
"#line 0 \"{0}\"", llvm::sys::path::filename(
MainFile));
403 FS.Files[
MainFile] =
"#include \"__preamble_patch__.h\"\n\n";
404 EXPECT_THAT(collectIncludes().MainFileIncludes,
405 Not(Contains(written(
"<a.h>"))));
408 CDB.ExtraClangFlags = {
"-include",
testPath(HeaderFile)};
409 EXPECT_THAT(collectIncludes().MainFileIncludes,
410 Contains(AllOf(includeLine(2), written(
"<a.h>"))));
llvm::SmallString< 256U > Name
std::string Filename
Filename as a string.
const MacroDirective * Directive
std::vector< HeaderEntry > HeaderContents
std::vector< const char * > Expected
std::unique_ptr< CompilerInvocation > CI
llvm::SmallVector< const Inclusion * > mainFileIncludesWithSpelling(llvm::StringRef Spelling) const
llvm::DenseMap< HeaderID, unsigned > includeDepth(HeaderID Root=MainFileID) const
std::vector< Inclusion > MainFileIncludes
llvm::DenseMap< HeaderID, SmallVector< HeaderID > > IncludeChildren
TEST_F(BackgroundIndexTest, NoCrashOnErrorFile)
std::string Path
A typedef to represent a file path.
std::unique_ptr< CompilerInvocation > buildCompilerInvocation(const ParseInputs &Inputs, clang::DiagnosticConsumer &D, std::vector< std::string > *CC1Args)
Builds compiler invocation that could be used to build AST or preamble.
MATCHER_P2(hasFlag, Flag, Path, "")
std::string testPath(PathRef File, llvm::sys::path::Style Style)
TEST(BackgroundQueueTest, Priority)
std::unique_ptr< CompilerInstance > prepareCompilerInstance(std::unique_ptr< clang::CompilerInvocation > CI, const PrecompiledPreamble *Preamble, std::unique_ptr< llvm::MemoryBuffer > Buffer, llvm::IntrusiveRefCntPtr< llvm::vfs::FileSystem > VFS, DiagnosticConsumer &DiagsClient)
llvm::StringRef PathRef
A typedef to represent a ref to file path.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
static TestTU withCode(llvm::StringRef Code)