Debian Codegraph @

clang/unittests/Tooling/DependencyScannerTest.cpp

raw
1 //===- DependencyScannerTest.cpp ------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "clang/AST/ASTConsumer.h"
10 #include "clang/AST/DeclCXX.h"
11 #include "clang/AST/DeclGroup.h"
12 #include "clang/DependencyScanning/DependencyScanningWorker.h"
13 #include "clang/Frontend/ASTUnit.h"
14 #include "clang/Frontend/CompilerInstance.h"
15 #include "clang/Frontend/FrontendAction.h"
16 #include "clang/Frontend/FrontendActions.h"
17 #include "clang/Frontend/TextDiagnosticBuffer.h"
18 #include "clang/Tooling/CompilationDatabase.h"
19 #include "clang/Tooling/DependencyScanningTool.h"
20 #include "clang/Tooling/Tooling.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/MC/TargetRegistry.h"
23 #include "llvm/Support/FormatVariadic.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/TargetSelect.h"
26 #include "llvm/Testing/Support/Error.h"
27 #include "gtest/gtest.h"
28 #include <algorithm>
29 #include <string>
30
31 using namespace clang;
32 using namespace tooling;
33 using namespace dependencies;
34
35 namespace {
36
37 /// Prints out all of the gathered dependencies into a string.
38 class TestFileCollector : public DependencyFileGenerator {
39 public:
40 TestFileCollector(DependencyOutputOptions &Opts,
41 std::vector<std::string> &Deps)
42 : DependencyFileGenerator(Opts), Deps(Deps) {}
43
44 void finishedMainFile(DiagnosticsEngine &Diags) override {
45 auto NewDeps = getDependencies();
46 llvm::append_range(Deps, NewDeps);
47 }
48
49 private:
50 std::vector<std::string> &Deps;
51 };
52
53 // FIXME: Use the regular Service/Worker/Collector APIs instead of
54 // reimplementing the action.
55 class TestDependencyScanningAction : public tooling::ToolAction {
56 public:
57 TestDependencyScanningAction(std::vector<std::string> &Deps) : Deps(Deps) {}
58
59 bool runInvocation(std::shared_ptr<CompilerInvocation> Invocation,
60 FileManager *FileMgr,
61 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
62 DiagnosticConsumer *DiagConsumer) override {
63 CompilerInstance Compiler(std::move(Invocation),
64 std::move(PCHContainerOps));
65 Compiler.setVirtualFileSystem(FileMgr->getVirtualFileSystemPtr());
66 Compiler.setFileManager(FileMgr);
67 Compiler.createDiagnostics(DiagConsumer, /*ShouldOwnClient=*/false);
68 Compiler.createSourceManager();
69 Compiler.addDependencyCollector(std::make_shared<TestFileCollector>(
70 Compiler.getInvocation().getDependencyOutputOpts(), Deps));
71
72 auto Action = std::make_unique<PreprocessOnlyAction>();
73 return Compiler.ExecuteAction(*Action);
74 }
75
76 private:
77 std::vector<std::string> &Deps;
78 };
79
80 } // namespace
81
82 TEST(DependencyScanner, ScanDepsReuseFilemanager) {
83 std::vector<std::string> Compilation = {"-c", "-E", "-MT", "test.cpp.o"};
84 StringRef CWD = "/root";
85 FixedCompilationDatabase CDB(CWD, Compilation);
86
87 auto VFS = llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
88 VFS->setCurrentWorkingDirectory(CWD);
89 auto Sept = llvm::sys::path::get_separator();
90 std::string HeaderPath =
91 std::string(llvm::formatv("{0}root{0}header.h", Sept));
92 std::string SymlinkPath =
93 std::string(llvm::formatv("{0}root{0}symlink.h", Sept));
94 std::string TestPath = std::string(llvm::formatv("{0}root{0}test.cpp", Sept));
95
96 VFS->addFile(HeaderPath, 0, llvm::MemoryBuffer::getMemBuffer("\n"));
97 VFS->addHardLink(SymlinkPath, HeaderPath);
98 VFS->addFile(TestPath, 0,
99 llvm::MemoryBuffer::getMemBuffer(
100 "#include \"symlink.h\"\n#include \"header.h\"\n"));
101
102 ClangTool Tool(CDB, {"test.cpp"}, std::make_shared<PCHContainerOperations>(),
103 VFS);
104 Tool.clearArgumentsAdjusters();
105 std::vector<std::string> Deps;
106 TestDependencyScanningAction Action(Deps);
107 Tool.run(&Action);
108 using llvm::sys::path::convert_to_slash;
109 // The first invocation should return dependencies in order of access.
110 ASSERT_EQ(Deps.size(), 3u);
111 EXPECT_EQ(convert_to_slash(Deps[0]), "/root/test.cpp");
112 EXPECT_EQ(convert_to_slash(Deps[1]), "/root/symlink.h");
113 EXPECT_EQ(convert_to_slash(Deps[2]), "/root/header.h");
114
115 // The file manager should still have two FileEntries, as one file is a
116 // hardlink.
117 FileManager &Files = Tool.getFiles();
118 EXPECT_EQ(Files.getNumUniqueRealFiles(), 2u);
119
120 Deps.clear();
121 Tool.run(&Action);
122 // The second invocation should have the same order of dependencies.
123 ASSERT_EQ(Deps.size(), 3u);
124 EXPECT_EQ(convert_to_slash(Deps[0]), "/root/test.cpp");
125 EXPECT_EQ(convert_to_slash(Deps[1]), "/root/symlink.h");
126 EXPECT_EQ(convert_to_slash(Deps[2]), "/root/header.h");
127
128 EXPECT_EQ(Files.getNumUniqueRealFiles(), 2u);
129 }
130
131 TEST(DependencyScanner, ScanDepsReuseFilemanagerSkippedFile) {
132 std::vector<std::string> Compilation = {"-c", "-E", "-MT", "test.cpp.o"};
133 StringRef CWD = "/root";
134 FixedCompilationDatabase CDB(CWD, Compilation);
135
136 auto VFS = llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
137 VFS->setCurrentWorkingDirectory(CWD);
138 auto Sept = llvm::sys::path::get_separator();
139 std::string HeaderPath =
140 std::string(llvm::formatv("{0}root{0}header.h", Sept));
141 std::string SymlinkPath =
142 std::string(llvm::formatv("{0}root{0}symlink.h", Sept));
143 std::string TestPath = std::string(llvm::formatv("{0}root{0}test.cpp", Sept));
144 std::string Test2Path =
145 std::string(llvm::formatv("{0}root{0}test2.cpp", Sept));
146
147 VFS->addFile(HeaderPath, 0,
148 llvm::MemoryBuffer::getMemBuffer("#pragma once\n"));
149 VFS->addHardLink(SymlinkPath, HeaderPath);
150 VFS->addFile(TestPath, 0,
151 llvm::MemoryBuffer::getMemBuffer(
152 "#include \"header.h\"\n#include \"symlink.h\"\n"));
153 VFS->addFile(Test2Path, 0,
154 llvm::MemoryBuffer::getMemBuffer(
155 "#include \"symlink.h\"\n#include \"header.h\"\n"));
156
157 ClangTool Tool(CDB, {"test.cpp", "test2.cpp"},
158 std::make_shared<PCHContainerOperations>(), VFS);
159 Tool.clearArgumentsAdjusters();
160 std::vector<std::string> Deps;
161 TestDependencyScanningAction Action(Deps);
162 Tool.run(&Action);
163 using llvm::sys::path::convert_to_slash;
164 ASSERT_EQ(Deps.size(), 6u);
165 EXPECT_EQ(convert_to_slash(Deps[0]), "/root/test.cpp");
166 EXPECT_EQ(convert_to_slash(Deps[1]), "/root/header.h");
167 EXPECT_EQ(convert_to_slash(Deps[2]), "/root/symlink.h");
168 EXPECT_EQ(convert_to_slash(Deps[3]), "/root/test2.cpp");
169 EXPECT_EQ(convert_to_slash(Deps[4]), "/root/symlink.h");
170 EXPECT_EQ(convert_to_slash(Deps[5]), "/root/header.h");
171 }
172
173 TEST(DependencyScanner, ScanDepsReuseFilemanagerHasInclude) {
174 std::vector<std::string> Compilation = {"-c", "-E", "-MT", "test.cpp.o"};
175 StringRef CWD = "/root";
176 FixedCompilationDatabase CDB(CWD, Compilation);
177
178 auto VFS = llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
179 VFS->setCurrentWorkingDirectory(CWD);
180 auto Sept = llvm::sys::path::get_separator();
181 std::string HeaderPath =
182 std::string(llvm::formatv("{0}root{0}header.h", Sept));
183 std::string SymlinkPath =
184 std::string(llvm::formatv("{0}root{0}symlink.h", Sept));
185 std::string TestPath = std::string(llvm::formatv("{0}root{0}test.cpp", Sept));
186
187 VFS->addFile(HeaderPath, 0, llvm::MemoryBuffer::getMemBuffer("\n"));
188 VFS->addHardLink(SymlinkPath, HeaderPath);
189 VFS->addFile(
190 TestPath, 0,
191 llvm::MemoryBuffer::getMemBuffer("#if __has_include(\"header.h\") && "
192 "__has_include(\"symlink.h\")\n#endif"));
193
194 ClangTool Tool(CDB, {"test.cpp", "test.cpp"},
195 std::make_shared<PCHContainerOperations>(), VFS);
196 Tool.clearArgumentsAdjusters();
197 std::vector<std::string> Deps;
198 TestDependencyScanningAction Action(Deps);
199 Tool.run(&Action);
200 using llvm::sys::path::convert_to_slash;
201 ASSERT_EQ(Deps.size(), 6u);
202 EXPECT_EQ(convert_to_slash(Deps[0]), "/root/test.cpp");
203 EXPECT_EQ(convert_to_slash(Deps[1]), "/root/header.h");
204 EXPECT_EQ(convert_to_slash(Deps[2]), "/root/symlink.h");
205 EXPECT_EQ(convert_to_slash(Deps[3]), "/root/test.cpp");
206 EXPECT_EQ(convert_to_slash(Deps[4]), "/root/header.h");
207 EXPECT_EQ(convert_to_slash(Deps[5]), "/root/symlink.h");
208 }
209
210 TEST(DependencyScanner, ScanDepsWithFS) {
211 std::vector<std::string> CommandLine = {"clang",
212 "-target",
213 "x86_64-apple-macosx10.7",
214 "-c",
215 "test.cpp",
216 "-o"
217 "test.cpp.o"};
218 StringRef CWD = "/root";
219
220 auto VFS = llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
221 VFS->setCurrentWorkingDirectory(CWD);
222 auto Sept = llvm::sys::path::get_separator();
223 std::string HeaderPath =
224 std::string(llvm::formatv("{0}root{0}header.h", Sept));
225 std::string TestPath = std::string(llvm::formatv("{0}root{0}test.cpp", Sept));
226
227 VFS->addFile(HeaderPath, 0, llvm::MemoryBuffer::getMemBuffer("\n"));
228 VFS->addFile(TestPath, 0,
229 llvm::MemoryBuffer::getMemBuffer("#include \"header.h\"\n"));
230
231 DependencyScanningService Service(ScanningMode::DependencyDirectivesScan,
232 ScanningOutputFormat::Make);
233 DependencyScanningTool ScanTool(Service, VFS);
234
235 TextDiagnosticBuffer DiagConsumer;
236 std::optional<std::string> DepFile =
237 ScanTool.getDependencyFile(CommandLine, CWD, DiagConsumer);
238 ASSERT_TRUE(DepFile.has_value());
239 EXPECT_EQ(llvm::sys::path::convert_to_slash(*DepFile),
240 "test.cpp.o: /root/test.cpp /root/header.h\n");
241 }
242
243 TEST(DependencyScanner, ScanDepsWithModuleLookup) {
244 std::vector<std::string> CommandLine = {
245 "clang",
246 "-target",
247 "x86_64-apple-macosx10.7",
248 "-c",
249 "test.m",
250 "-o"
251 "test.m.o",
252 "-fmodules",
253 "-I/root/SomeSources",
254 };
255 StringRef CWD = "/root";
256
257 auto VFS = llvm::makeIntrusiveRefCnt<llvm::vfs::InMemoryFileSystem>();
258 VFS->setCurrentWorkingDirectory(CWD);
259 auto Sept = llvm::sys::path::get_separator();
260 std::string OtherPath =
261 std::string(llvm::formatv("{0}root{0}SomeSources{0}other.h", Sept));
262 std::string TestPath = std::string(llvm::formatv("{0}root{0}test.m", Sept));
263
264 VFS->addFile(OtherPath, 0, llvm::MemoryBuffer::getMemBuffer("\n"));
265 VFS->addFile(TestPath, 0, llvm::MemoryBuffer::getMemBuffer("@import Foo;\n"));
266
267 struct InterceptorFS : llvm::vfs::ProxyFileSystem {
268 std::vector<std::string> StatPaths;
269 std::vector<std::string> ReadFiles;
270
271 InterceptorFS(IntrusiveRefCntPtr<FileSystem> UnderlyingFS)
272 : ProxyFileSystem(UnderlyingFS) {}
273
274 llvm::ErrorOr<llvm::vfs::Status> status(const Twine &Path) override {
275 StatPaths.push_back(Path.str());
276 return ProxyFileSystem::status(Path);
277 }
278
279 llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
280 openFileForRead(const Twine &Path) override {
281 ReadFiles.push_back(Path.str());
282 return ProxyFileSystem::openFileForRead(Path);
283 }
284 };
285
286 auto InterceptFS = llvm::makeIntrusiveRefCnt<InterceptorFS>(VFS);
287
288 DependencyScanningService Service(ScanningMode::DependencyDirectivesScan,
289 ScanningOutputFormat::Make);
290 DependencyScanningTool ScanTool(Service, InterceptFS);
291
292 // This will fail with "fatal error: module 'Foo' not found" but it doesn't
293 // matter, the point of the test is to check that files are not read
294 // unnecessarily.
295 TextDiagnosticBuffer DiagConsumer;
296 std::optional<std::string> DepFile =
297 ScanTool.getDependencyFile(CommandLine, CWD, DiagConsumer);
298 ASSERT_FALSE(DepFile.has_value());
299
300 EXPECT_TRUE(!llvm::is_contained(InterceptFS->StatPaths, OtherPath));
301 EXPECT_EQ(InterceptFS->ReadFiles, std::vector<std::string>{"test.m"});
302 }