blob: 82ee6020a8031749786090421f9e1249f564d34a [file] [log] [blame]
Manuel Klimek47c245a2012-04-04 12:07:46 +00001//===- unittest/Tooling/ToolingTest.cpp - Tooling unit tests --------------===//
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#include "clang/AST/ASTConsumer.h"
11#include "clang/AST/DeclCXX.h"
12#include "clang/AST/DeclGroup.h"
Peter Collingbournec689ee72013-11-06 20:12:45 +000013#include "clang/Frontend/ASTUnit.h"
Richard Smith9219d1b2012-11-27 21:31:01 +000014#include "clang/Frontend/CompilerInstance.h"
Manuel Klimek47c245a2012-04-04 12:07:46 +000015#include "clang/Frontend/FrontendAction.h"
16#include "clang/Frontend/FrontendActions.h"
17#include "clang/Tooling/CompilationDatabase.h"
18#include "clang/Tooling/Tooling.h"
Peter Collingbournec689ee72013-11-06 20:12:45 +000019#include "llvm/ADT/STLExtras.h"
Alp Toker1d257e12014-06-04 03:28:55 +000020#include "llvm/Config/llvm-config.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000021#include "llvm/Support/Path.h"
Manuel Klimek9b30e2b2015-10-06 10:45:03 +000022#include "llvm/Support/TargetRegistry.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000023#include "llvm/Support/TargetSelect.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000024#include "gtest/gtest.h"
Alexander Kornienko74e1c462014-12-03 17:53:02 +000025#include <algorithm>
Alexander Kornienko55f2ca92012-06-01 14:50:43 +000026#include <string>
Manuel Klimek47c245a2012-04-04 12:07:46 +000027
28namespace clang {
29namespace tooling {
30
31namespace {
32/// Takes an ast consumer and returns it from CreateASTConsumer. This only
33/// works with single translation unit compilations.
34class TestAction : public clang::ASTFrontendAction {
David Blaikie6beb6aa2014-08-10 19:56:51 +000035public:
Manuel Klimek47c245a2012-04-04 12:07:46 +000036 /// Takes ownership of TestConsumer.
David Blaikie6beb6aa2014-08-10 19:56:51 +000037 explicit TestAction(std::unique_ptr<clang::ASTConsumer> TestConsumer)
38 : TestConsumer(std::move(TestConsumer)) {}
Manuel Klimek47c245a2012-04-04 12:07:46 +000039
David Blaikie6beb6aa2014-08-10 19:56:51 +000040protected:
Alexander Kornienko34eb2072015-04-11 02:00:23 +000041 std::unique_ptr<clang::ASTConsumer>
42 CreateASTConsumer(clang::CompilerInstance &compiler,
43 StringRef dummy) override {
Manuel Klimek47c245a2012-04-04 12:07:46 +000044 /// TestConsumer will be deleted by the framework calling us.
David Blaikie6beb6aa2014-08-10 19:56:51 +000045 return std::move(TestConsumer);
Manuel Klimek47c245a2012-04-04 12:07:46 +000046 }
47
David Blaikie6beb6aa2014-08-10 19:56:51 +000048private:
49 std::unique_ptr<clang::ASTConsumer> TestConsumer;
Manuel Klimek47c245a2012-04-04 12:07:46 +000050};
51
52class FindTopLevelDeclConsumer : public clang::ASTConsumer {
53 public:
54 explicit FindTopLevelDeclConsumer(bool *FoundTopLevelDecl)
55 : FoundTopLevelDecl(FoundTopLevelDecl) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +000056 bool HandleTopLevelDecl(clang::DeclGroupRef DeclGroup) override {
Manuel Klimek47c245a2012-04-04 12:07:46 +000057 *FoundTopLevelDecl = true;
58 return true;
59 }
60 private:
61 bool * const FoundTopLevelDecl;
62};
63} // end namespace
64
Meador Inge5d3fb222012-06-16 03:34:49 +000065TEST(runToolOnCode, FindsNoTopLevelDeclOnEmptyCode) {
Manuel Klimek47c245a2012-04-04 12:07:46 +000066 bool FoundTopLevelDecl = false;
David Blaikie6beb6aa2014-08-10 19:56:51 +000067 EXPECT_TRUE(
68 runToolOnCode(new TestAction(llvm::make_unique<FindTopLevelDeclConsumer>(
69 &FoundTopLevelDecl)),
70 ""));
Meador Inge5d3fb222012-06-16 03:34:49 +000071 EXPECT_FALSE(FoundTopLevelDecl);
Manuel Klimek47c245a2012-04-04 12:07:46 +000072}
73
74namespace {
75class FindClassDeclXConsumer : public clang::ASTConsumer {
76 public:
77 FindClassDeclXConsumer(bool *FoundClassDeclX)
78 : FoundClassDeclX(FoundClassDeclX) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +000079 bool HandleTopLevelDecl(clang::DeclGroupRef GroupRef) override {
Manuel Klimek47c245a2012-04-04 12:07:46 +000080 if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>(
81 *GroupRef.begin())) {
82 if (Record->getName() == "X") {
83 *FoundClassDeclX = true;
84 }
85 }
86 return true;
87 }
88 private:
89 bool *FoundClassDeclX;
90};
Peter Collingbournec689ee72013-11-06 20:12:45 +000091bool FindClassDeclX(ASTUnit *AST) {
92 for (std::vector<Decl *>::iterator i = AST->top_level_begin(),
93 e = AST->top_level_end();
94 i != e; ++i) {
95 if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>(*i)) {
96 if (Record->getName() == "X") {
97 return true;
98 }
99 }
100 }
101 return false;
102}
Manuel Klimek47c245a2012-04-04 12:07:46 +0000103} // end namespace
104
105TEST(runToolOnCode, FindsClassDecl) {
106 bool FoundClassDeclX = false;
David Blaikie6beb6aa2014-08-10 19:56:51 +0000107 EXPECT_TRUE(
108 runToolOnCode(new TestAction(llvm::make_unique<FindClassDeclXConsumer>(
109 &FoundClassDeclX)),
110 "class X;"));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000111 EXPECT_TRUE(FoundClassDeclX);
112
113 FoundClassDeclX = false;
David Blaikie6beb6aa2014-08-10 19:56:51 +0000114 EXPECT_TRUE(
115 runToolOnCode(new TestAction(llvm::make_unique<FindClassDeclXConsumer>(
116 &FoundClassDeclX)),
117 "class Y;"));
Manuel Klimek47c245a2012-04-04 12:07:46 +0000118 EXPECT_FALSE(FoundClassDeclX);
119}
120
Peter Collingbournec689ee72013-11-06 20:12:45 +0000121TEST(buildASTFromCode, FindsClassDecl) {
David Blaikie103a2de2014-04-25 17:01:33 +0000122 std::unique_ptr<ASTUnit> AST = buildASTFromCode("class X;");
Peter Collingbournec689ee72013-11-06 20:12:45 +0000123 ASSERT_TRUE(AST.get());
124 EXPECT_TRUE(FindClassDeclX(AST.get()));
125
David Blaikie103a2de2014-04-25 17:01:33 +0000126 AST = buildASTFromCode("class Y;");
Peter Collingbournec689ee72013-11-06 20:12:45 +0000127 ASSERT_TRUE(AST.get());
128 EXPECT_FALSE(FindClassDeclX(AST.get()));
129}
130
Manuel Klimek47c245a2012-04-04 12:07:46 +0000131TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromType) {
Ahmed Charlesb8984322014-03-07 20:03:18 +0000132 std::unique_ptr<FrontendActionFactory> Factory(
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000133 newFrontendActionFactory<SyntaxOnlyAction>());
Ahmed Charlesb8984322014-03-07 20:03:18 +0000134 std::unique_ptr<FrontendAction> Action(Factory->create());
Craig Topper416fa342014-06-08 08:38:12 +0000135 EXPECT_TRUE(Action.get() != nullptr);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000136}
137
138struct IndependentFrontendActionCreator {
David Blaikie6beb6aa2014-08-10 19:56:51 +0000139 std::unique_ptr<ASTConsumer> newASTConsumer() {
140 return llvm::make_unique<FindTopLevelDeclConsumer>(nullptr);
Manuel Klimek5da9dcb2012-07-05 18:13:01 +0000141 }
Manuel Klimek47c245a2012-04-04 12:07:46 +0000142};
143
144TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromFactoryType) {
145 IndependentFrontendActionCreator Creator;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000146 std::unique_ptr<FrontendActionFactory> Factory(
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000147 newFrontendActionFactory(&Creator));
Ahmed Charlesb8984322014-03-07 20:03:18 +0000148 std::unique_ptr<FrontendAction> Action(Factory->create());
Craig Topper416fa342014-06-08 08:38:12 +0000149 EXPECT_TRUE(Action.get() != nullptr);
Manuel Klimek47c245a2012-04-04 12:07:46 +0000150}
151
Alexander Kornienko55f2ca92012-06-01 14:50:43 +0000152TEST(ToolInvocation, TestMapVirtualFile) {
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000153 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
154 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
155 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
156 new vfs::InMemoryFileSystem);
157 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
158 llvm::IntrusiveRefCntPtr<FileManager> Files(
159 new FileManager(FileSystemOptions(), OverlayFileSystem));
Alexander Kornienko55f2ca92012-06-01 14:50:43 +0000160 std::vector<std::string> Args;
161 Args.push_back("tool-executable");
162 Args.push_back("-Idef");
163 Args.push_back("-fsyntax-only");
164 Args.push_back("test.cpp");
Peter Collingbournec689ee72013-11-06 20:12:45 +0000165 clang::tooling::ToolInvocation Invocation(Args, new SyntaxOnlyAction,
Alp Tokerf994cef2014-07-05 03:08:06 +0000166 Files.get());
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000167 InMemoryFileSystem->addFile(
168 "test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("#include <abc>\n"));
169 InMemoryFileSystem->addFile("def/abc", 0,
170 llvm::MemoryBuffer::getMemBuffer("\n"));
Alexander Kornienko55f2ca92012-06-01 14:50:43 +0000171 EXPECT_TRUE(Invocation.run());
172}
173
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000174TEST(ToolInvocation, TestVirtualModulesCompilation) {
175 // FIXME: Currently, this only tests that we don't exit with an error if a
176 // mapped module.map is found on the include path. In the future, expand this
177 // test to run a full modules enabled compilation, so we make sure we can
178 // rerun modules compilations with a virtual file system.
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000179 llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
180 new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
181 llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
182 new vfs::InMemoryFileSystem);
183 OverlayFileSystem->pushOverlay(InMemoryFileSystem);
184 llvm::IntrusiveRefCntPtr<FileManager> Files(
185 new FileManager(FileSystemOptions(), OverlayFileSystem));
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000186 std::vector<std::string> Args;
187 Args.push_back("tool-executable");
188 Args.push_back("-Idef");
189 Args.push_back("-fsyntax-only");
190 Args.push_back("test.cpp");
Peter Collingbournec689ee72013-11-06 20:12:45 +0000191 clang::tooling::ToolInvocation Invocation(Args, new SyntaxOnlyAction,
Alp Tokerf994cef2014-07-05 03:08:06 +0000192 Files.get());
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000193 InMemoryFileSystem->addFile(
194 "test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("#include <abc>\n"));
195 InMemoryFileSystem->addFile("def/abc", 0,
196 llvm::MemoryBuffer::getMemBuffer("\n"));
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000197 // Add a module.map file in the include directory of our header, so we trigger
198 // the module.map header search logic.
Benjamin Kramerc4cb3b12015-10-09 09:54:37 +0000199 InMemoryFileSystem->addFile("def/module.map", 0,
200 llvm::MemoryBuffer::getMemBuffer("\n"));
Manuel Klimek1f76c4e2013-10-24 07:51:24 +0000201 EXPECT_TRUE(Invocation.run());
202}
203
Edwin Vane20c6f542013-05-29 16:01:10 +0000204struct VerifyEndCallback : public SourceFileCallbacks {
205 VerifyEndCallback() : BeginCalled(0), EndCalled(0), Matched(false) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000206 bool handleBeginSource(CompilerInstance &CI, StringRef Filename) override {
Edwin Vane20c6f542013-05-29 16:01:10 +0000207 ++BeginCalled;
208 return true;
209 }
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000210 void handleEndSource() override { ++EndCalled; }
David Blaikie6beb6aa2014-08-10 19:56:51 +0000211 std::unique_ptr<ASTConsumer> newASTConsumer() {
212 return llvm::make_unique<FindTopLevelDeclConsumer>(&Matched);
Manuel Klimek8246d872012-10-25 08:49:11 +0000213 }
Edwin Vane20c6f542013-05-29 16:01:10 +0000214 unsigned BeginCalled;
215 unsigned EndCalled;
Manuel Klimek8246d872012-10-25 08:49:11 +0000216 bool Matched;
217};
218
Hans Wennborg501eadb2014-03-12 16:07:46 +0000219#if !defined(LLVM_ON_WIN32)
Edwin Vane20c6f542013-05-29 16:01:10 +0000220TEST(newFrontendActionFactory, InjectsSourceFileCallbacks) {
Manuel Klimek8246d872012-10-25 08:49:11 +0000221 VerifyEndCallback EndCallback;
222
223 FixedCompilationDatabase Compilations("/", std::vector<std::string>());
224 std::vector<std::string> Sources;
225 Sources.push_back("/a.cc");
226 Sources.push_back("/b.cc");
227 ClangTool Tool(Compilations, Sources);
228
229 Tool.mapVirtualFile("/a.cc", "void a() {}");
230 Tool.mapVirtualFile("/b.cc", "void b() {}");
231
Nico Weber52fbbb12014-04-24 03:48:09 +0000232 std::unique_ptr<FrontendActionFactory> Action(
233 newFrontendActionFactory(&EndCallback, &EndCallback));
234 Tool.run(Action.get());
Manuel Klimek8246d872012-10-25 08:49:11 +0000235
236 EXPECT_TRUE(EndCallback.Matched);
Edwin Vane20c6f542013-05-29 16:01:10 +0000237 EXPECT_EQ(2u, EndCallback.BeginCalled);
238 EXPECT_EQ(2u, EndCallback.EndCalled);
Manuel Klimek8246d872012-10-25 08:49:11 +0000239}
NAKAMURA Takumi95fd41a2012-10-25 09:38:41 +0000240#endif
Manuel Klimek8246d872012-10-25 08:49:11 +0000241
Richard Smith9219d1b2012-11-27 21:31:01 +0000242struct SkipBodyConsumer : public clang::ASTConsumer {
243 /// Skip the 'skipMe' function.
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000244 bool shouldSkipFunctionBody(Decl *D) override {
Olivier Goffartf9e890c2016-06-16 21:40:06 +0000245 NamedDecl *F = dyn_cast<NamedDecl>(D);
Richard Smith9219d1b2012-11-27 21:31:01 +0000246 return F && F->getNameAsString() == "skipMe";
247 }
248};
249
250struct SkipBodyAction : public clang::ASTFrontendAction {
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000251 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler,
252 StringRef) override {
Richard Smith9219d1b2012-11-27 21:31:01 +0000253 Compiler.getFrontendOpts().SkipFunctionBodies = true;
David Blaikie6beb6aa2014-08-10 19:56:51 +0000254 return llvm::make_unique<SkipBodyConsumer>();
Richard Smith9219d1b2012-11-27 21:31:01 +0000255 }
256};
257
Hal Finkel1d3e3d72013-01-28 04:37:38 +0000258TEST(runToolOnCode, TestSkipFunctionBody) {
Olivier Goffartf9e890c2016-06-16 21:40:06 +0000259 std::vector<std::string> Args = {"-std=c++11"};
NAKAMURA Takumic690ee02016-06-17 02:04:51 +0000260 std::vector<std::string> Args2 = {"-fno-delayed-template-parsing"};
Olivier Goffartf9e890c2016-06-16 21:40:06 +0000261
Richard Smith9219d1b2012-11-27 21:31:01 +0000262 EXPECT_TRUE(runToolOnCode(new SkipBodyAction,
263 "int skipMe() { an_error_here }"));
264 EXPECT_FALSE(runToolOnCode(new SkipBodyAction,
265 "int skipMeNot() { an_error_here }"));
Olivier Goffartf9e890c2016-06-16 21:40:06 +0000266
267 // Test constructors with initializers
268 EXPECT_TRUE(runToolOnCodeWithArgs(
269 new SkipBodyAction,
270 "struct skipMe { skipMe() : an_error() { more error } };", Args));
271 EXPECT_TRUE(runToolOnCodeWithArgs(
272 new SkipBodyAction, "struct skipMe { skipMe(); };"
273 "skipMe::skipMe() : an_error([](){;}) { more error }",
274 Args));
275 EXPECT_TRUE(runToolOnCodeWithArgs(
276 new SkipBodyAction, "struct skipMe { skipMe(); };"
277 "skipMe::skipMe() : an_error{[](){;}} { more error }",
278 Args));
279 EXPECT_TRUE(runToolOnCodeWithArgs(
280 new SkipBodyAction,
281 "struct skipMe { skipMe(); };"
282 "skipMe::skipMe() : a<b<c>(e)>>(), f{}, g() { error }",
283 Args));
284 EXPECT_TRUE(runToolOnCodeWithArgs(
285 new SkipBodyAction, "struct skipMe { skipMe() : bases()... { error } };",
286 Args));
287
288 EXPECT_FALSE(runToolOnCodeWithArgs(
289 new SkipBodyAction, "struct skipMeNot { skipMeNot() : an_error() { } };",
290 Args));
291 EXPECT_FALSE(runToolOnCodeWithArgs(new SkipBodyAction,
292 "struct skipMeNot { skipMeNot(); };"
293 "skipMeNot::skipMeNot() : an_error() { }",
294 Args));
295
296 // Try/catch
297 EXPECT_TRUE(runToolOnCode(
298 new SkipBodyAction,
299 "void skipMe() try { an_error() } catch(error) { error };"));
300 EXPECT_TRUE(runToolOnCode(
301 new SkipBodyAction,
302 "struct S { void skipMe() try { an_error() } catch(error) { error } };"));
303 EXPECT_TRUE(
304 runToolOnCode(new SkipBodyAction,
305 "void skipMe() try { an_error() } catch(error) { error; }"
306 "catch(error) { error } catch (error) { }"));
307 EXPECT_FALSE(runToolOnCode(
308 new SkipBodyAction,
309 "void skipMe() try something;")); // don't crash while parsing
310
311 // Template
312 EXPECT_TRUE(runToolOnCode(
313 new SkipBodyAction, "template<typename T> int skipMe() { an_error_here }"
314 "int x = skipMe<int>();"));
NAKAMURA Takumic690ee02016-06-17 02:04:51 +0000315 EXPECT_FALSE(runToolOnCodeWithArgs(
316 new SkipBodyAction,
317 "template<typename T> int skipMeNot() { an_error_here }", Args2));
Richard Smith9219d1b2012-11-27 21:31:01 +0000318}
319
Peter Collingbournec0423b32014-03-02 23:37:26 +0000320TEST(runToolOnCodeWithArgs, TestNoDepFile) {
321 llvm::SmallString<32> DepFilePath;
322 ASSERT_FALSE(
323 llvm::sys::fs::createTemporaryFile("depfile", "d", DepFilePath));
Peter Collingbournef9372542014-03-03 08:13:06 +0000324 std::vector<std::string> Args;
325 Args.push_back("-MMD");
326 Args.push_back("-MT");
327 Args.push_back(DepFilePath.str());
328 Args.push_back("-MF");
329 Args.push_back(DepFilePath.str());
Peter Collingbourne2bbb0292014-03-03 07:49:35 +0000330 EXPECT_TRUE(runToolOnCodeWithArgs(new SkipBodyAction, "", Args));
Peter Collingbournec0423b32014-03-02 23:37:26 +0000331 EXPECT_FALSE(llvm::sys::fs::exists(DepFilePath.str()));
332 EXPECT_FALSE(llvm::sys::fs::remove(DepFilePath.str()));
333}
334
Manuel Klimekd91ac932013-06-04 14:44:44 +0000335TEST(ClangToolTest, ArgumentAdjusters) {
336 FixedCompilationDatabase Compilations("/", std::vector<std::string>());
337
338 ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
339 Tool.mapVirtualFile("/a.cc", "void a() {}");
340
Nico Weber52fbbb12014-04-24 03:48:09 +0000341 std::unique_ptr<FrontendActionFactory> Action(
342 newFrontendActionFactory<SyntaxOnlyAction>());
343
Manuel Klimekd91ac932013-06-04 14:44:44 +0000344 bool Found = false;
345 bool Ran = false;
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000346 ArgumentsAdjuster CheckSyntaxOnlyAdjuster =
Alexander Kornienko857b10f2015-11-05 02:19:53 +0000347 [&Found, &Ran](const CommandLineArguments &Args, StringRef /*unused*/) {
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000348 Ran = true;
349 if (std::find(Args.begin(), Args.end(), "-fsyntax-only") != Args.end())
350 Found = true;
351 return Args;
352 };
353 Tool.appendArgumentsAdjuster(CheckSyntaxOnlyAdjuster);
Nico Weber52fbbb12014-04-24 03:48:09 +0000354 Tool.run(Action.get());
Manuel Klimekd91ac932013-06-04 14:44:44 +0000355 EXPECT_TRUE(Ran);
356 EXPECT_TRUE(Found);
357
358 Ran = Found = false;
359 Tool.clearArgumentsAdjusters();
Alexander Kornienko74e1c462014-12-03 17:53:02 +0000360 Tool.appendArgumentsAdjuster(CheckSyntaxOnlyAdjuster);
361 Tool.appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster());
Nico Weber52fbbb12014-04-24 03:48:09 +0000362 Tool.run(Action.get());
Manuel Klimekd91ac932013-06-04 14:44:44 +0000363 EXPECT_TRUE(Ran);
364 EXPECT_FALSE(Found);
365}
366
Manuel Klimek9b30e2b2015-10-06 10:45:03 +0000367namespace {
368/// Find a target name such that looking for it in TargetRegistry by that name
369/// returns the same target. We expect that there is at least one target
370/// configured with this property.
371std::string getAnyTarget() {
372 llvm::InitializeAllTargets();
373 for (const auto &Target : llvm::TargetRegistry::targets()) {
374 std::string Error;
NAKAMURA Takumife2e6422015-10-06 13:58:13 +0000375 StringRef TargetName(Target.getName());
376 if (TargetName == "x86-64")
377 TargetName = "x86_64";
378 if (llvm::TargetRegistry::lookupTarget(TargetName, Error) == &Target) {
379 return TargetName;
Manuel Klimek9b30e2b2015-10-06 10:45:03 +0000380 }
381 }
382 return "";
383}
384}
385
386TEST(addTargetAndModeForProgramName, AddsTargetAndMode) {
387 std::string Target = getAnyTarget();
388 ASSERT_FALSE(Target.empty());
389
390 std::vector<std::string> Args = {"clang", "-foo"};
391 addTargetAndModeForProgramName(Args, "");
392 EXPECT_EQ((std::vector<std::string>{"clang", "-foo"}), Args);
393 addTargetAndModeForProgramName(Args, Target + "-g++");
394 EXPECT_EQ((std::vector<std::string>{"clang", "-target", Target,
395 "--driver-mode=g++", "-foo"}),
396 Args);
397}
398
399TEST(addTargetAndModeForProgramName, PathIgnored) {
400 std::string Target = getAnyTarget();
401 ASSERT_FALSE(Target.empty());
402
403 SmallString<32> ToolPath;
404 llvm::sys::path::append(ToolPath, "foo", "bar", Target + "-g++");
405
406 std::vector<std::string> Args = {"clang", "-foo"};
407 addTargetAndModeForProgramName(Args, ToolPath);
408 EXPECT_EQ((std::vector<std::string>{"clang", "-target", Target,
409 "--driver-mode=g++", "-foo"}),
410 Args);
411}
412
413TEST(addTargetAndModeForProgramName, IgnoresExistingTarget) {
414 std::string Target = getAnyTarget();
415 ASSERT_FALSE(Target.empty());
416
417 std::vector<std::string> Args = {"clang", "-foo", "-target", "something"};
418 addTargetAndModeForProgramName(Args, Target + "-g++");
419 EXPECT_EQ((std::vector<std::string>{"clang", "--driver-mode=g++", "-foo",
420 "-target", "something"}),
421 Args);
422
423 std::vector<std::string> ArgsAlt = {"clang", "-foo", "-target=something"};
424 addTargetAndModeForProgramName(ArgsAlt, Target + "-g++");
425 EXPECT_EQ((std::vector<std::string>{"clang", "--driver-mode=g++", "-foo",
426 "-target=something"}),
427 ArgsAlt);
428}
429
430TEST(addTargetAndModeForProgramName, IgnoresExistingMode) {
431 std::string Target = getAnyTarget();
432 ASSERT_FALSE(Target.empty());
433
434 std::vector<std::string> Args = {"clang", "-foo", "--driver-mode=abc"};
435 addTargetAndModeForProgramName(Args, Target + "-g++");
436 EXPECT_EQ((std::vector<std::string>{"clang", "-target", Target, "-foo",
437 "--driver-mode=abc"}),
438 Args);
439
440 std::vector<std::string> ArgsAlt = {"clang", "-foo", "--driver-mode", "abc"};
441 addTargetAndModeForProgramName(ArgsAlt, Target + "-g++");
442 EXPECT_EQ((std::vector<std::string>{"clang", "-target", Target, "-foo",
443 "--driver-mode", "abc"}),
444 ArgsAlt);
445}
446
Hans Wennborg501eadb2014-03-12 16:07:46 +0000447#ifndef LLVM_ON_WIN32
Peter Collingbournec689ee72013-11-06 20:12:45 +0000448TEST(ClangToolTest, BuildASTs) {
449 FixedCompilationDatabase Compilations("/", std::vector<std::string>());
450
451 std::vector<std::string> Sources;
452 Sources.push_back("/a.cc");
453 Sources.push_back("/b.cc");
454 ClangTool Tool(Compilations, Sources);
455
456 Tool.mapVirtualFile("/a.cc", "void a() {}");
457 Tool.mapVirtualFile("/b.cc", "void b() {}");
458
David Blaikie39808ff2014-04-25 14:49:37 +0000459 std::vector<std::unique_ptr<ASTUnit>> ASTs;
Peter Collingbournec689ee72013-11-06 20:12:45 +0000460 EXPECT_EQ(0, Tool.buildASTs(ASTs));
461 EXPECT_EQ(2u, ASTs.size());
Peter Collingbournec689ee72013-11-06 20:12:45 +0000462}
463
Manuel Klimek64083012013-11-07 23:18:05 +0000464struct TestDiagnosticConsumer : public DiagnosticConsumer {
465 TestDiagnosticConsumer() : NumDiagnosticsSeen(0) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000466 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
467 const Diagnostic &Info) override {
Manuel Klimek64083012013-11-07 23:18:05 +0000468 ++NumDiagnosticsSeen;
469 }
470 unsigned NumDiagnosticsSeen;
471};
472
473TEST(ClangToolTest, InjectDiagnosticConsumer) {
474 FixedCompilationDatabase Compilations("/", std::vector<std::string>());
475 ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
476 Tool.mapVirtualFile("/a.cc", "int x = undeclared;");
477 TestDiagnosticConsumer Consumer;
478 Tool.setDiagnosticConsumer(&Consumer);
Nico Weber52fbbb12014-04-24 03:48:09 +0000479 std::unique_ptr<FrontendActionFactory> Action(
480 newFrontendActionFactory<SyntaxOnlyAction>());
481 Tool.run(Action.get());
Manuel Klimek64083012013-11-07 23:18:05 +0000482 EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen);
483}
484
Manuel Klimek31cd3fc2013-11-12 17:53:18 +0000485TEST(ClangToolTest, InjectDiagnosticConsumerInBuildASTs) {
486 FixedCompilationDatabase Compilations("/", std::vector<std::string>());
487 ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc"));
488 Tool.mapVirtualFile("/a.cc", "int x = undeclared;");
489 TestDiagnosticConsumer Consumer;
490 Tool.setDiagnosticConsumer(&Consumer);
David Blaikie39808ff2014-04-25 14:49:37 +0000491 std::vector<std::unique_ptr<ASTUnit>> ASTs;
Manuel Klimek31cd3fc2013-11-12 17:53:18 +0000492 Tool.buildASTs(ASTs);
493 EXPECT_EQ(1u, ASTs.size());
494 EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen);
495}
NAKAMURA Takumid3b07c62013-11-13 00:18:50 +0000496#endif
Manuel Klimek31cd3fc2013-11-12 17:53:18 +0000497
Manuel Klimek47c245a2012-04-04 12:07:46 +0000498} // end namespace tooling
499} // end namespace clang