16#include "clang/Tooling/CompilationDatabase.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallString.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/Support/FormatVariadic.h"
21#include "llvm/Support/Path.h"
22#include "gmock/gmock.h"
23#include "gtest/gtest.h"
32using ::testing::AllOf;
33using ::testing::Contains;
34using ::testing::ElementsAre;
35using ::testing::EndsWith;
36using ::testing::HasSubstr;
37using ::testing::IsEmpty;
39using ::testing::UnorderedElementsAre;
41TEST(GlobalCompilationDatabaseTest, FallbackCommand) {
43 DirectoryBasedGlobalCompilationDatabase DB(TFS);
44 auto Cmd = DB.getFallbackCommand(
testPath(
"foo/bar.cc"));
45 EXPECT_EQ(Cmd.Directory,
testPath(
"foo"));
46 EXPECT_THAT(Cmd.CommandLine, ElementsAre(
"clang",
testPath(
"foo/bar.cc")));
47 EXPECT_EQ(Cmd.Output,
"");
50 Cmd = DB.getFallbackCommand(
testPath(
"foo/bar.h"));
51 EXPECT_THAT(Cmd.CommandLine, ElementsAre(
"clang",
"-xobjective-c++-header",
53 Cmd = DB.getFallbackCommand(
testPath(
"foo/bar"));
54 EXPECT_THAT(Cmd.CommandLine, ElementsAre(
"clang",
"-xobjective-c++-header",
58static tooling::CompileCommand cmd(llvm::StringRef
File, llvm::StringRef Arg) {
59 return tooling::CompileCommand(
63class OverlayCDBTest :
public ::testing::Test {
64 class BaseCDB :
public GlobalCompilationDatabase {
66 std::optional<tooling::CompileCommand>
67 getCompileCommand(llvm::StringRef
File)
const override {
69 return cmd(
File,
"-DA=1");
73 tooling::CompileCommand
74 getFallbackCommand(llvm::StringRef
File)
const override {
75 return cmd(
File,
"-DA=2");
78 std::optional<ProjectInfo> getProjectInfo(
PathRef File)
const override {
84 OverlayCDBTest() : Base(std::make_unique<BaseCDB>()) {}
85 std::unique_ptr<GlobalCompilationDatabase> Base;
88TEST_F(OverlayCDBTest, GetCompileCommand) {
89 OverlayCDB CDB(Base.get());
91 AllOf(Contains(
testPath(
"foo.cc")), Contains(
"-DA=1")));
94 auto Override = cmd(
testPath(
"foo.cc"),
"-DA=3");
95 CDB.setCompileCommand(
testPath(
"foo.cc"), Override);
99 CDB.setCompileCommand(
testPath(
"missing.cc"), Override);
104TEST_F(OverlayCDBTest, GetFallbackCommand) {
105 OverlayCDB CDB(Base.get(), {
"-DA=4"});
107 ElementsAre(
"clang",
"-DA=2",
testPath(
"bar.cc"),
"-DA=4"));
110TEST_F(OverlayCDBTest, NoBase) {
111 OverlayCDB CDB(
nullptr, {
"-DA=6"});
113 auto Override = cmd(
testPath(
"bar.cc"),
"-DA=5");
114 CDB.setCompileCommand(
testPath(
"bar.cc"), Override);
119 ElementsAre(
"clang",
testPath(
"foo.cc"),
"-DA=6"));
122TEST_F(OverlayCDBTest, Watch) {
123 OverlayCDB
Inner(
nullptr);
124 OverlayCDB Outer(&
Inner);
126 std::vector<std::vector<std::string>>
Changes;
127 auto Sub = Outer.watch([&](
const std::vector<std::string> &ChangedFiles) {
128 Changes.push_back(ChangedFiles);
131 Inner.setCompileCommand(
"A.cpp", tooling::CompileCommand());
132 Outer.setCompileCommand(
"B.cpp", tooling::CompileCommand());
133 Inner.setCompileCommand(
"A.cpp", std::nullopt);
134 Outer.setCompileCommand(
"C.cpp", std::nullopt);
135 EXPECT_THAT(
Changes, ElementsAre(ElementsAre(
"A.cpp"), ElementsAre(
"B.cpp"),
136 ElementsAre(
"A.cpp"), ElementsAre(
"C.cpp")));
139TEST_F(OverlayCDBTest, Adjustments) {
140 OverlayCDB CDB(Base.get(), {
"-DFallback"},
141 [](tooling::CompileCommand &Cmd, llvm::StringRef
File) {
142 Cmd.CommandLine.push_back(
143 (
"-DAdjust_" + llvm::sys::path::filename(File)).str());
147 EXPECT_THAT(Cmd.CommandLine, ElementsAre(
"clang",
"-DA=1",
testPath(
"foo.cc"),
151 tooling::CompileCommand BarCommand;
152 BarCommand.Filename =
testPath(
"bar.cc");
153 BarCommand.CommandLine = {
"clang++",
"-DB=1",
testPath(
"bar.cc")};
154 CDB.setCompileCommand(
testPath(
"bar.cc"), BarCommand);
158 ElementsAre(
"clang++",
"-DB=1",
testPath(
"bar.cc"),
"-DAdjust_bar.cc"));
162 EXPECT_THAT(Cmd.CommandLine, ElementsAre(
"clang",
"-DA=2",
"baz.cc",
163 "-DFallback",
"-DAdjust_baz.cc"));
166TEST(GlobalCompilationDatabaseTest, DiscoveryWithNestedCDBs) {
167 const char *
const CDBOuter =
176 "file": "build/gen.cc",
181 "file": "build/gen2.cc",
187 const char *
const CDBInner =
193 "directory": "{0}/build",
198 FS.Files[testPath("compile_commands.json")] =
199 llvm::formatv(CDBOuter, llvm::sys::path::convert_to_slash(
testRoot()));
200 FS.Files[
testPath(
"build/compile_commands.json")] =
201 llvm::formatv(CDBInner, llvm::sys::path::convert_to_slash(
testRoot()));
202 FS.Files[
testPath(
"foo/compile_flags.txt")] =
"-DFOO";
207 SCOPED_TRACE(
"Default ancestor scanning");
208 DirectoryBasedGlobalCompilationDatabase DB(FS);
209 std::vector<std::string> DiscoveredFiles;
211 DB.watch([&DiscoveredFiles](
const std::vector<std::string>
Changes) {
215 DB.getCompileCommand(
testPath(
"build/../a.cc"));
217 EXPECT_THAT(DiscoveredFiles, UnorderedElementsAre(AllOf(
218 EndsWith(
"a.cc"), Not(HasSubstr(
"..")))));
219 DiscoveredFiles.clear();
221 DB.getCompileCommand(
testPath(
"build/gen.cc"));
223 EXPECT_THAT(DiscoveredFiles, UnorderedElementsAre(EndsWith(
"gen.cc")));
227 SCOPED_TRACE(
"With config");
228 DirectoryBasedGlobalCompilationDatabase::Options Opts(FS);
229 Opts.ContextProvider = [&](llvm::StringRef
Path) {
231 if (
Path.endswith(
"a.cc")) {
235 }
else if (
Path.endswith(
"gen.cc")) {
238 }
else if (
Path.endswith(
"gen2.cc")) {
245 DirectoryBasedGlobalCompilationDatabase DB(Opts);
246 std::vector<std::string> DiscoveredFiles;
248 DB.watch([&DiscoveredFiles](
const std::vector<std::string>
Changes) {
253 auto Cmd = DB.getCompileCommand(
testPath(
"build/../a.cc"));
255 EXPECT_THAT(Cmd->CommandLine, Contains(
"-DFOO")) <<
"a.cc uses foo/ CDB";
257 EXPECT_THAT(DiscoveredFiles, IsEmpty()) <<
"Root CDB not discovered yet";
260 DB.getCompileCommand(
testPath(
"b.cc"));
262 EXPECT_THAT(DiscoveredFiles, ElementsAre(
testPath(
"build/gen2.cc")));
263 DiscoveredFiles.clear();
266 DB.getCompileCommand(
testPath(
"build/gen.cc"));
268 EXPECT_THAT(DiscoveredFiles, IsEmpty());
272 SCOPED_TRACE(
"With custom compile commands dir");
273 DirectoryBasedGlobalCompilationDatabase::Options Opts(FS);
274 Opts.CompileCommandsDir =
testRoot();
275 DirectoryBasedGlobalCompilationDatabase DB(Opts);
276 std::vector<std::string> DiscoveredFiles;
278 DB.watch([&DiscoveredFiles](
const std::vector<std::string>
Changes) {
282 DB.getCompileCommand(
testPath(
"a.cc"));
284 EXPECT_THAT(DiscoveredFiles,
285 UnorderedElementsAre(EndsWith(
"a.cc"), EndsWith(
"gen.cc"),
286 EndsWith(
"gen2.cc")));
287 DiscoveredFiles.clear();
289 DB.getCompileCommand(
testPath(
"build/gen.cc"));
291 EXPECT_THAT(DiscoveredFiles, IsEmpty());
295TEST(GlobalCompilationDatabaseTest, BuildDir) {
297 auto Command = [&](llvm::StringRef Relative) {
298 DirectoryBasedGlobalCompilationDatabase::Options Opts(FS);
299 return DirectoryBasedGlobalCompilationDatabase(Opts)
300 .getCompileCommand(
testPath(Relative))
301 .value_or(tooling::CompileCommand())
304 EXPECT_THAT(Command(
"x/foo.cc"), IsEmpty());
305 const char *
const CDB =
309 "file": "{0}/x/foo.cc",
310 "command": "clang -DXYZZY {0}/x/foo.cc",
314 "file": "{0}/bar.cc",
315 "command": "clang -DXYZZY {0}/bar.cc",
320 FS.Files[testPath("x/build/compile_commands.json")] =
321 llvm::formatv(CDB, llvm::sys::path::convert_to_slash(
testRoot()));
322 EXPECT_THAT(Command(
"x/foo.cc"), Contains(
"-DXYZZY"));
323 EXPECT_THAT(Command(
"bar.cc"), IsEmpty())
324 <<
"x/build/compile_flags.json only applicable to x/";
327TEST(GlobalCompilationDatabaseTest, CompileFlagsDirectory) {
329 FS.Files[
testPath(
"x/compile_flags.txt")] =
"-DFOO";
330 DirectoryBasedGlobalCompilationDatabase CDB(FS);
333 EXPECT_THAT(
Commands->CommandLine, Contains(
"-DFOO"));
340 *result_listener <<
"command is null";
343 if (!llvm::is_contained(arg->CommandLine, Flag)) {
344 *result_listener <<
"flags are " <<
printArgv(arg->CommandLine);
350TEST(GlobalCompilationDatabaseTest, Config) {
352 FS.Files[
testPath(
"x/compile_flags.txt")] =
"-DX";
353 FS.Files[
testPath(
"x/y/z/compile_flags.txt")] =
"-DZ";
355 Config::CDBSearchSpec Spec;
356 DirectoryBasedGlobalCompilationDatabase::Options Opts(FS);
357 Opts.ContextProvider = [&](llvm::StringRef
Path) {
359 C.CompileFlags.CDBSearch = Spec;
362 DirectoryBasedGlobalCompilationDatabase CDB(Opts);
383 Spec.FixedCDBPath =
testPath(
"x/y/z");
390TEST(GlobalCompilationDatabaseTest, NonCanonicalFilenames) {
391 OverlayCDB DB(
nullptr);
392 std::vector<std::string> DiscoveredFiles;
394 DB.watch([&DiscoveredFiles](
const std::vector<std::string>
Changes) {
399 llvm::sys::path::append(
Root,
"build",
"..",
"a.cc");
400 DB.setCompileCommand(
Root.str(), tooling::CompileCommand());
401 EXPECT_THAT(DiscoveredFiles, UnorderedElementsAre(
testPath(
"a.cc")));
402 DiscoveredFiles.clear();
405 llvm::sys::path::append(
File,
"blabla",
"..",
"a.cc");
407 EXPECT_TRUE(DB.getCompileCommand(
File));
408 EXPECT_FALSE(DB.getProjectInfo(
File));
411TEST_F(OverlayCDBTest, GetProjectInfo) {
412 OverlayCDB DB(Base.get());
416 EXPECT_EQ(DB.getProjectInfo(
File)->SourceRoot,
testRoot());
417 EXPECT_EQ(DB.getProjectInfo(Header)->SourceRoot,
testRoot());
420 DB.setCompileCommand(
File, tooling::CompileCommand());
421 EXPECT_EQ(DB.getProjectInfo(
File)->SourceRoot,
testRoot());
422 EXPECT_EQ(DB.getProjectInfo(Header)->SourceRoot,
testRoot());
428 :
public ::testing::Test {
430 std::shared_ptr<const tooling::CompilationDatabase>
432 llvm::StringRef
Path,
433 std::chrono::steady_clock::time_point FreshTime) {
434 DirectoryBasedGlobalCompilationDatabase::CDBLookupRequest Req;
436 Req.FreshTime = Req.FreshTimeMissing = FreshTime;
437 if (
auto Result = GDB.lookupCDB(Req))
438 return std::move(Result->CDB);
447 auto Cmds = arg->getCompileCommands(
Path);
449 *result_listener <<
"yields no commands";
452 if (!llvm::is_contained(Cmds.front().CommandLine, Flag)) {
453 *result_listener <<
"flags are: " <<
printArgv(Cmds.front().CommandLine);
460 return hasFlag(Flag,
"mock_file_name.cc");
465 auto Stale = std::chrono::steady_clock::now() - std::chrono::minutes(1);
466 auto Fresh = std::chrono::steady_clock::now() + std::chrono::hours(24);
469 FS.Files[
"compile_flags.txt"] =
"-DROOT";
470 auto Root = lookupCDB(GDB,
testPath(
"foo/test.cc"), Stale);
474 FS.Files[
"foo/compile_flags.txt"] =
"-DFOO";
475 EXPECT_EQ(
Root, lookupCDB(GDB,
testPath(
"foo/test.cc"), Stale))
476 <<
"cache still valid";
477 auto Foo = lookupCDB(GDB,
testPath(
"foo/test.cc"), Fresh);
478 EXPECT_THAT(Foo,
hasFlag(
"-DFOO")) <<
"new cdb loaded";
479 EXPECT_EQ(Foo, lookupCDB(GDB,
testPath(
"foo/test.cc"), Stale))
480 <<
"new cdb in cache";
483 ++FS.Timestamps[
"foo/compile_flags.txt"];
484 auto FooAgain = lookupCDB(GDB,
testPath(
"foo/test.cc"), Fresh);
485 EXPECT_EQ(Foo, FooAgain) <<
"Same content, read but not reloaded";
487 FS.Files[
"foo/compile_flags.txt"] =
"-DBAR";
488 auto FooAgain2 = lookupCDB(GDB,
testPath(
"foo/test.cc"), Fresh);
489 EXPECT_EQ(Foo, FooAgain2) <<
"Same filesize, change not detected";
491 ++FS.Timestamps[
"foo/compile_flags.txt"];
492 auto Bar = lookupCDB(GDB,
testPath(
"foo/test.cc"), Fresh);
493 EXPECT_THAT(
Bar,
hasFlag(
"-DBAR")) <<
"refreshed with mtime change";
496 FS.Files[
"foo/compile_flags.txt"] =
"-DFOOBAR";
497 EXPECT_EQ(
Bar, lookupCDB(GDB,
testPath(
"foo/test.cc"), Stale))
498 <<
"cache still valid";
499 auto FooBar = lookupCDB(GDB,
testPath(
"foo/test.cc"), Fresh);
500 EXPECT_THAT(FooBar,
hasFlag(
"-DFOOBAR")) <<
"cdb reloaded";
503 FS.Files[
"foo/compile_commands.json"] =
504 llvm::formatv(R
"json([{
505 "file": "{0}/foo/mock_file.cc",
506 "command": "clang -DBAZ mock_file.cc",
507 "directory": "{0}/foo",
509 llvm::sys::path::convert_to_slash(testRoot()));
510 EXPECT_EQ(FooBar, lookupCDB(GDB, testPath("foo/test.cc"), Stale))
511 <<
"cache still valid";
512 auto Baz = lookupCDB(GDB,
testPath(
"foo/test.cc"), Fresh);
514 <<
"compile_commands overrides compile_flags";
518 FS.Files.erase(
"foo/compile_commands.json");
519 auto FoobarAgain = lookupCDB(GDB,
testPath(
"foo/test.cc"), Fresh);
520 EXPECT_THAT(FoobarAgain,
hasFlag(
"-DFOOBAR")) <<
"reloaded compile_flags";
521 EXPECT_NE(FoobarAgain, FooBar) <<
"CDB discarded (shadowed within directory)";
525 FS.Files.erase(
"foo/compile_flags.txt");
526 EXPECT_EQ(
Root, lookupCDB(GDB,
testPath(
"foo/test.cc"), Fresh))
527 <<
"CDB retained (shadowed by another directory)";
std::pair< Context, Canceler > Inner
static cl::list< std::string > Commands("c", cl::desc("Specify command to run"), cl::value_desc("command"), cl::cat(ClangQueryCategory))
std::vector< llvm::StringRef > CommandLine
Context derive(const Key< Type > &Key, std::decay_t< Type > Value) const &
Derives a child context It is safe to move or destroy a parent context after calling derive().
static const Context & current()
Returns the context for the current thread, creating it if needed.
std::shared_ptr< const tooling::CompilationDatabase > lookupCDB(const DirectoryBasedGlobalCompilationDatabase &GDB, llvm::StringRef Path, std::chrono::steady_clock::time_point FreshTime)
Gets compile args from tooling::CompilationDatabases built for parent directories.
virtual tooling::CompileCommand getFallbackCommand(PathRef File) const
Makes a guess at how to build a file.
virtual std::optional< tooling::CompileCommand > getCompileCommand(PathRef File) const =0
If there are any known-good commands for building this file, returns one.
TEST_F(BackgroundIndexTest, NoCrashOnErrorFile)
std::string Path
A typedef to represent a file path.
MATCHER_P2(hasFlag, Flag, Path, "")
std::string testPath(PathRef File, llvm::sys::path::Style Style)
TEST(BackgroundQueueTest, Priority)
auto hasFlag(llvm::StringRef Flag)
std::string printArgv(llvm::ArrayRef< llvm::StringRef > Args)
Deadline timeoutSeconds(std::optional< double > Seconds)
Makes a deadline from a timeout in seconds. std::nullopt means wait forever.
llvm::StringRef PathRef
A typedef to represent a ref to file path.
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
enum clang::clangd::Config::CDBSearchSpec::@10 Policy
std::optional< std::string > FixedCDBPath
static clangd::Key< Config > Key
Context key which can be used to set the current Config.
CDBSearchSpec CDBSearch
Where to search for compilation databases for this file's flags.
struct clang::clangd::Config::@2 CompileFlags
Controls how the compile command for the current file is determined.