| 1 |
//===- unittest/Tooling/ToolingTest.cpp - Tooling unit tests --------------===// |
| 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/Tooling/Tooling.h" |
| 10 |
#include "clang/AST/ASTConsumer.h" |
| 11 |
#include "clang/AST/DeclCXX.h" |
| 12 |
#include "clang/AST/DeclGroup.h" |
| 13 |
#include "clang/Driver/Compilation.h" |
| 14 |
#include "clang/Driver/Driver.h" |
| 15 |
#include "clang/Frontend/ASTUnit.h" |
| 16 |
#include "clang/Frontend/CompilerInstance.h" |
| 17 |
#include "clang/Frontend/FrontendAction.h" |
| 18 |
#include "clang/Frontend/FrontendActions.h" |
| 19 |
#include "clang/Frontend/TextDiagnosticBuffer.h" |
| 20 |
#include "clang/Tooling/ArgumentsAdjusters.h" |
| 21 |
#include "clang/Tooling/CompilationDatabase.h" |
| 22 |
#include "llvm/ADT/STLExtras.h" |
| 23 |
#include "llvm/ADT/StringRef.h" |
| 24 |
#include "llvm/MC/TargetRegistry.h" |
| 25 |
#include "llvm/Support/Host.h" |
| 26 |
#include "llvm/Support/Path.h" |
| 27 |
#include "llvm/Support/TargetSelect.h" |
| 28 |
#include "gtest/gtest.h" |
| 29 |
#include <algorithm> |
| 30 |
#include <string> |
| 31 |
#include <vector> |
| 32 |
|
| 33 |
namespace clang { |
| 34 |
namespace tooling { |
| 35 |
|
| 36 |
namespace { |
| 37 |
/// Takes an ast consumer and returns it from CreateASTConsumer. This only |
| 38 |
/// works with single translation unit compilations. |
| 39 |
class TestAction : public clang::ASTFrontendAction { |
| 40 |
public: |
| 41 |
/// Takes ownership of TestConsumer. |
| 42 |
explicit TestAction(std::unique_ptr<clang::ASTConsumer> TestConsumer) |
| 43 |
: TestConsumer(std::move(TestConsumer)) {} |
| 44 |
|
| 45 |
protected: |
| 46 |
std::unique_ptr<clang::ASTConsumer> |
| 47 |
CreateASTConsumer(clang::CompilerInstance &compiler, |
| 48 |
StringRef dummy) override { |
| 49 |
/// TestConsumer will be deleted by the framework calling us. |
| 50 |
return std::move(TestConsumer); |
| 51 |
} |
| 52 |
|
| 53 |
private: |
| 54 |
std::unique_ptr<clang::ASTConsumer> TestConsumer; |
| 55 |
}; |
| 56 |
|
| 57 |
class FindTopLevelDeclConsumer : public clang::ASTConsumer { |
| 58 |
public: |
| 59 |
explicit FindTopLevelDeclConsumer(bool *FoundTopLevelDecl) |
| 60 |
: FoundTopLevelDecl(FoundTopLevelDecl) {} |
| 61 |
bool HandleTopLevelDecl(clang::DeclGroupRef DeclGroup) override { |
| 62 |
*FoundTopLevelDecl = true; |
| 63 |
return true; |
| 64 |
} |
| 65 |
private: |
| 66 |
bool * const FoundTopLevelDecl; |
| 67 |
}; |
| 68 |
} // end namespace |
| 69 |
|
| 70 |
TEST(runToolOnCode, FindsNoTopLevelDeclOnEmptyCode) { |
| 71 |
bool FoundTopLevelDecl = false; |
| 72 |
EXPECT_TRUE(runToolOnCode( |
| 73 |
std::make_unique<TestAction>( |
| 74 |
std::make_unique<FindTopLevelDeclConsumer>(&FoundTopLevelDecl)), |
| 75 |
"")); |
| 76 |
EXPECT_FALSE(FoundTopLevelDecl); |
| 77 |
} |
| 78 |
|
| 79 |
namespace { |
| 80 |
class FindClassDeclXConsumer : public clang::ASTConsumer { |
| 81 |
public: |
| 82 |
FindClassDeclXConsumer(bool *FoundClassDeclX) |
| 83 |
: FoundClassDeclX(FoundClassDeclX) {} |
| 84 |
bool HandleTopLevelDecl(clang::DeclGroupRef GroupRef) override { |
| 85 |
if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>( |
| 86 |
*GroupRef.begin())) { |
| 87 |
if (Record->getName() == "X") { |
| 88 |
*FoundClassDeclX = true; |
| 89 |
} |
| 90 |
} |
| 91 |
return true; |
| 92 |
} |
| 93 |
private: |
| 94 |
bool *FoundClassDeclX; |
| 95 |
}; |
| 96 |
bool FindClassDeclX(ASTUnit *AST) { |
| 97 |
for (std::vector<Decl *>::iterator i = AST->top_level_begin(), |
| 98 |
e = AST->top_level_end(); |
| 99 |
i != e; ++i) { |
| 100 |
if (CXXRecordDecl* Record = dyn_cast<clang::CXXRecordDecl>(*i)) { |
| 101 |
if (Record->getName() == "X") { |
| 102 |
return true; |
| 103 |
} |
| 104 |
} |
| 105 |
} |
| 106 |
return false; |
| 107 |
} |
| 108 |
|
| 109 |
struct TestDiagnosticConsumer : public DiagnosticConsumer { |
| 110 |
TestDiagnosticConsumer() : NumDiagnosticsSeen(0) {} |
| 111 |
void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, |
| 112 |
const Diagnostic &Info) override { |
| 113 |
++NumDiagnosticsSeen; |
| 114 |
} |
| 115 |
unsigned NumDiagnosticsSeen; |
| 116 |
}; |
| 117 |
} // end namespace |
| 118 |
|
| 119 |
TEST(runToolOnCode, FindsClassDecl) { |
| 120 |
bool FoundClassDeclX = false; |
| 121 |
EXPECT_TRUE(runToolOnCode( |
| 122 |
std::make_unique<TestAction>( |
| 123 |
std::make_unique<FindClassDeclXConsumer>(&FoundClassDeclX)), |
| 124 |
"class X;")); |
| 125 |
EXPECT_TRUE(FoundClassDeclX); |
| 126 |
|
| 127 |
FoundClassDeclX = false; |
| 128 |
EXPECT_TRUE(runToolOnCode( |
| 129 |
std::make_unique<TestAction>( |
| 130 |
std::make_unique<FindClassDeclXConsumer>(&FoundClassDeclX)), |
| 131 |
"class Y;")); |
| 132 |
EXPECT_FALSE(FoundClassDeclX); |
| 133 |
} |
| 134 |
|
| 135 |
TEST(buildASTFromCode, FindsClassDecl) { |
| 136 |
std::unique_ptr<ASTUnit> AST = buildASTFromCode("class X;"); |
| 137 |
ASSERT_TRUE(AST.get()); |
| 138 |
EXPECT_TRUE(FindClassDeclX(AST.get())); |
| 139 |
|
| 140 |
AST = buildASTFromCode("class Y;"); |
| 141 |
ASSERT_TRUE(AST.get()); |
| 142 |
EXPECT_FALSE(FindClassDeclX(AST.get())); |
| 143 |
} |
| 144 |
|
| 145 |
TEST(buildASTFromCode, ReportsErrors) { |
| 146 |
TestDiagnosticConsumer Consumer; |
| 147 |
std::unique_ptr<ASTUnit> AST = buildASTFromCodeWithArgs( |
| 148 |
"int x = \"A\";", {}, "input.cc", "clang-tool", |
| 149 |
std::make_shared<PCHContainerOperations>(), |
| 150 |
getClangStripDependencyFileAdjuster(), FileContentMappings(), &Consumer); |
| 151 |
EXPECT_TRUE(AST.get()); |
| 152 |
EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen); |
| 153 |
} |
| 154 |
|
| 155 |
TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromType) { |
| 156 |
std::unique_ptr<FrontendActionFactory> Factory( |
| 157 |
newFrontendActionFactory<SyntaxOnlyAction>()); |
| 158 |
std::unique_ptr<FrontendAction> Action(Factory->create()); |
| 159 |
EXPECT_TRUE(Action.get() != nullptr); |
| 160 |
} |
| 161 |
|
| 162 |
struct IndependentFrontendActionCreator { |
| 163 |
std::unique_ptr<ASTConsumer> newASTConsumer() { |
| 164 |
return std::make_unique<FindTopLevelDeclConsumer>(nullptr); |
| 165 |
} |
| 166 |
}; |
| 167 |
|
| 168 |
TEST(newFrontendActionFactory, CreatesFrontendActionFactoryFromFactoryType) { |
| 169 |
IndependentFrontendActionCreator Creator; |
| 170 |
std::unique_ptr<FrontendActionFactory> Factory( |
| 171 |
newFrontendActionFactory(&Creator)); |
| 172 |
std::unique_ptr<FrontendAction> Action(Factory->create()); |
| 173 |
EXPECT_TRUE(Action.get() != nullptr); |
| 174 |
} |
| 175 |
|
| 176 |
TEST(ToolInvocation, TestMapVirtualFile) { |
| 177 |
llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem( |
| 178 |
new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem())); |
| 179 |
llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem( |
| 180 |
new llvm::vfs::InMemoryFileSystem); |
| 181 |
OverlayFileSystem->pushOverlay(InMemoryFileSystem); |
| 182 |
llvm::IntrusiveRefCntPtr<FileManager> Files( |
| 183 |
new FileManager(FileSystemOptions(), OverlayFileSystem)); |
| 184 |
std::vector<std::string> Args; |
| 185 |
Args.push_back("tool-executable"); |
| 186 |
Args.push_back("-Idef"); |
| 187 |
Args.push_back("-fsyntax-only"); |
| 188 |
Args.push_back("test.cpp"); |
| 189 |
clang::tooling::ToolInvocation Invocation( |
| 190 |
Args, std::make_unique<SyntaxOnlyAction>(), Files.get()); |
| 191 |
InMemoryFileSystem->addFile( |
| 192 |
"test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("#include <abc>\n")); |
| 193 |
InMemoryFileSystem->addFile("def/abc", 0, |
| 194 |
llvm::MemoryBuffer::getMemBuffer("\n")); |
| 195 |
EXPECT_TRUE(Invocation.run()); |
| 196 |
} |
| 197 |
|
| 198 |
TEST(ToolInvocation, TestVirtualModulesCompilation) { |
| 199 |
// FIXME: Currently, this only tests that we don't exit with an error if a |
| 200 |
// mapped module.map is found on the include path. In the future, expand this |
| 201 |
// test to run a full modules enabled compilation, so we make sure we can |
| 202 |
// rerun modules compilations with a virtual file system. |
| 203 |
llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem( |
| 204 |
new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem())); |
| 205 |
llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem( |
| 206 |
new llvm::vfs::InMemoryFileSystem); |
| 207 |
OverlayFileSystem->pushOverlay(InMemoryFileSystem); |
| 208 |
llvm::IntrusiveRefCntPtr<FileManager> Files( |
| 209 |
new FileManager(FileSystemOptions(), OverlayFileSystem)); |
| 210 |
std::vector<std::string> Args; |
| 211 |
Args.push_back("tool-executable"); |
| 212 |
Args.push_back("-Idef"); |
| 213 |
Args.push_back("-fsyntax-only"); |
| 214 |
Args.push_back("test.cpp"); |
| 215 |
clang::tooling::ToolInvocation Invocation( |
| 216 |
Args, std::make_unique<SyntaxOnlyAction>(), Files.get()); |
| 217 |
InMemoryFileSystem->addFile( |
| 218 |
"test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("#include <abc>\n")); |
| 219 |
InMemoryFileSystem->addFile("def/abc", 0, |
| 220 |
llvm::MemoryBuffer::getMemBuffer("\n")); |
| 221 |
// Add a module.map file in the include directory of our header, so we trigger |
| 222 |
// the module.map header search logic. |
| 223 |
InMemoryFileSystem->addFile("def/module.map", 0, |
| 224 |
llvm::MemoryBuffer::getMemBuffer("\n")); |
| 225 |
EXPECT_TRUE(Invocation.run()); |
| 226 |
} |
| 227 |
|
| 228 |
TEST(ToolInvocation, DiagnosticsEngineProperlyInitializedForCC1Construction) { |
| 229 |
llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem( |
| 230 |
new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem())); |
| 231 |
llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem( |
| 232 |
new llvm::vfs::InMemoryFileSystem); |
| 233 |
OverlayFileSystem->pushOverlay(InMemoryFileSystem); |
| 234 |
llvm::IntrusiveRefCntPtr<FileManager> Files( |
| 235 |
new FileManager(FileSystemOptions(), OverlayFileSystem)); |
| 236 |
|
| 237 |
std::vector<std::string> Args; |
| 238 |
Args.push_back("tool-executable"); |
| 239 |
// Unknown warning option will result in a warning. |
| 240 |
Args.push_back("-fexpensive-optimizations"); |
| 241 |
// Argument that will suppress the warning above. |
| 242 |
Args.push_back("-Wno-ignored-optimization-argument"); |
| 243 |
Args.push_back("-E"); |
| 244 |
Args.push_back("test.cpp"); |
| 245 |
|
| 246 |
clang::tooling::ToolInvocation Invocation( |
| 247 |
Args, std::make_unique<SyntaxOnlyAction>(), Files.get()); |
| 248 |
InMemoryFileSystem->addFile("test.cpp", 0, |
| 249 |
llvm::MemoryBuffer::getMemBuffer("")); |
| 250 |
TextDiagnosticBuffer Consumer; |
| 251 |
Invocation.setDiagnosticConsumer(&Consumer); |
| 252 |
EXPECT_TRUE(Invocation.run()); |
| 253 |
// Check that the warning was ignored due to the '-Wno-xxx' argument. |
| 254 |
EXPECT_EQ(std::distance(Consumer.warn_begin(), Consumer.warn_end()), 0u); |
| 255 |
} |
| 256 |
|
| 257 |
TEST(ToolInvocation, CustomDiagnosticOptionsOverwriteParsedOnes) { |
| 258 |
llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem( |
| 259 |
new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem())); |
| 260 |
llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem( |
| 261 |
new llvm::vfs::InMemoryFileSystem); |
| 262 |
OverlayFileSystem->pushOverlay(InMemoryFileSystem); |
| 263 |
llvm::IntrusiveRefCntPtr<FileManager> Files( |
| 264 |
new FileManager(FileSystemOptions(), OverlayFileSystem)); |
| 265 |
|
| 266 |
std::vector<std::string> Args; |
| 267 |
Args.push_back("tool-executable"); |
| 268 |
// Unknown warning option will result in a warning. |
| 269 |
Args.push_back("-fexpensive-optimizations"); |
| 270 |
// Argument that will suppress the warning above. |
| 271 |
Args.push_back("-Wno-ignored-optimization-argument"); |
| 272 |
Args.push_back("-E"); |
| 273 |
Args.push_back("test.cpp"); |
| 274 |
|
| 275 |
clang::tooling::ToolInvocation Invocation( |
| 276 |
Args, std::make_unique<SyntaxOnlyAction>(), Files.get()); |
| 277 |
InMemoryFileSystem->addFile("test.cpp", 0, |
| 278 |
llvm::MemoryBuffer::getMemBuffer("")); |
| 279 |
TextDiagnosticBuffer Consumer; |
| 280 |
Invocation.setDiagnosticConsumer(&Consumer); |
| 281 |
|
| 282 |
// Inject custom `DiagnosticOptions` for command-line parsing. |
| 283 |
auto DiagOpts = llvm::makeIntrusiveRefCnt<DiagnosticOptions>(); |
| 284 |
Invocation.setDiagnosticOptions(&*DiagOpts); |
| 285 |
|
| 286 |
EXPECT_TRUE(Invocation.run()); |
| 287 |
// Check that the warning was issued during command-line parsing due to the |
| 288 |
// custom `DiagnosticOptions` without '-Wno-xxx'. |
| 289 |
EXPECT_EQ(std::distance(Consumer.warn_begin(), Consumer.warn_end()), 1u); |
| 290 |
} |
| 291 |
|
| 292 |
struct DiagnosticConsumerExpectingSourceManager : public DiagnosticConsumer { |
| 293 |
bool SawSourceManager; |
| 294 |
|
| 295 |
DiagnosticConsumerExpectingSourceManager() : SawSourceManager(false) {} |
| 296 |
|
| 297 |
void HandleDiagnostic(clang::DiagnosticsEngine::Level, |
| 298 |
const clang::Diagnostic &info) override { |
| 299 |
SawSourceManager = info.hasSourceManager(); |
| 300 |
} |
| 301 |
}; |
| 302 |
|
| 303 |
TEST(ToolInvocation, DiagConsumerExpectingSourceManager) { |
| 304 |
llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem( |
| 305 |
new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem())); |
| 306 |
llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem( |
| 307 |
new llvm::vfs::InMemoryFileSystem); |
| 308 |
OverlayFileSystem->pushOverlay(InMemoryFileSystem); |
| 309 |
llvm::IntrusiveRefCntPtr<FileManager> Files( |
| 310 |
new FileManager(FileSystemOptions(), OverlayFileSystem)); |
| 311 |
std::vector<std::string> Args; |
| 312 |
Args.push_back("tool-executable"); |
| 313 |
// Note: intentional error; user probably meant -ferror-limit=0. |
| 314 |
Args.push_back("-ferror-limit=-1"); |
| 315 |
Args.push_back("-fsyntax-only"); |
| 316 |
Args.push_back("test.cpp"); |
| 317 |
clang::tooling::ToolInvocation Invocation( |
| 318 |
Args, std::make_unique<SyntaxOnlyAction>(), Files.get()); |
| 319 |
InMemoryFileSystem->addFile( |
| 320 |
"test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int main() {}\n")); |
| 321 |
|
| 322 |
DiagnosticConsumerExpectingSourceManager Consumer; |
| 323 |
Invocation.setDiagnosticConsumer(&Consumer); |
| 324 |
|
| 325 |
EXPECT_TRUE(Invocation.run()); |
| 326 |
EXPECT_TRUE(Consumer.SawSourceManager); |
| 327 |
} |
| 328 |
|
| 329 |
TEST(ToolInvocation, CC1Args) { |
| 330 |
llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem( |
| 331 |
new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem())); |
| 332 |
llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem( |
| 333 |
new llvm::vfs::InMemoryFileSystem); |
| 334 |
OverlayFileSystem->pushOverlay(InMemoryFileSystem); |
| 335 |
llvm::IntrusiveRefCntPtr<FileManager> Files( |
| 336 |
new FileManager(FileSystemOptions(), OverlayFileSystem)); |
| 337 |
std::vector<std::string> Args; |
| 338 |
Args.push_back("tool-executable"); |
| 339 |
Args.push_back("-cc1"); |
| 340 |
Args.push_back("-fsyntax-only"); |
| 341 |
Args.push_back("test.cpp"); |
| 342 |
clang::tooling::ToolInvocation Invocation( |
| 343 |
Args, std::make_unique<SyntaxOnlyAction>(), Files.get()); |
| 344 |
InMemoryFileSystem->addFile( |
| 345 |
"test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("void foo(void);\n")); |
| 346 |
EXPECT_TRUE(Invocation.run()); |
| 347 |
} |
| 348 |
|
| 349 |
TEST(ToolInvocation, CC1ArgsInvalid) { |
| 350 |
llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem( |
| 351 |
new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem())); |
| 352 |
llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem( |
| 353 |
new llvm::vfs::InMemoryFileSystem); |
| 354 |
OverlayFileSystem->pushOverlay(InMemoryFileSystem); |
| 355 |
llvm::IntrusiveRefCntPtr<FileManager> Files( |
| 356 |
new FileManager(FileSystemOptions(), OverlayFileSystem)); |
| 357 |
std::vector<std::string> Args; |
| 358 |
Args.push_back("tool-executable"); |
| 359 |
Args.push_back("-cc1"); |
| 360 |
Args.push_back("-invalid-arg"); |
| 361 |
Args.push_back("test.cpp"); |
| 362 |
clang::tooling::ToolInvocation Invocation( |
| 363 |
Args, std::make_unique<SyntaxOnlyAction>(), Files.get()); |
| 364 |
InMemoryFileSystem->addFile( |
| 365 |
"test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("void foo(void);\n")); |
| 366 |
EXPECT_FALSE(Invocation.run()); |
| 367 |
} |
| 368 |
|
| 369 |
namespace { |
| 370 |
/// Overlays the real filesystem with the given VFS and returns the result. |
| 371 |
llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> |
| 372 |
overlayRealFS(llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS) { |
| 373 |
auto RFS = llvm::vfs::getRealFileSystem(); |
| 374 |
auto OverlayFS = llvm::makeIntrusiveRefCnt<llvm::vfs::OverlayFileSystem>(RFS); |
| 375 |
OverlayFS->pushOverlay(VFS); |
| 376 |
return OverlayFS; |
| 377 |
} |
| 378 |
|
| 379 |
struct CommandLineExtractorTest : public ::testing::Test { |
| 380 |
llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFS; |
| 381 |
llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags; |
| 382 |
driver::Driver Driver; |
| 383 |
|
| 384 |
public: |
| 385 |
CommandLineExtractorTest() |
| 386 |
: InMemoryFS(new llvm::vfs::InMemoryFileSystem), |
| 387 |
Diags(CompilerInstance::createDiagnostics(new DiagnosticOptions)), |
| 388 |
Driver("clang", llvm::sys::getDefaultTargetTriple(), *Diags, |
| 389 |
"clang LLVM compiler", overlayRealFS(InMemoryFS)) {} |
| 390 |
|
| 391 |
void addFile(StringRef Name, StringRef Content) { |
| 392 |
InMemoryFS->addFile(Name, 0, llvm::MemoryBuffer::getMemBuffer(Content)); |
| 393 |
} |
| 394 |
|
| 395 |
const llvm::opt::ArgStringList * |
| 396 |
extractCC1Arguments(llvm::ArrayRef<const char *> Argv) { |
| 397 |
const std::unique_ptr<driver::Compilation> Compilation( |
| 398 |
Driver.BuildCompilation(llvm::ArrayRef(Argv))); |
| 399 |
|
| 400 |
return getCC1Arguments(Diags.get(), Compilation.get()); |
| 401 |
} |
| 402 |
}; |
| 403 |
} // namespace |
| 404 |
|
| 405 |
TEST_F(CommandLineExtractorTest, AcceptOffloading) { |
| 406 |
addFile("test.c", "int main() {}\n"); |
| 407 |
const char *Args[] = {"clang", "-target", "arm64-apple-macosx11.0.0", |
| 408 |
"-x", "hip", "test.c", |
| 409 |
"-nogpulib", "-nogpuinc"}; |
| 410 |
EXPECT_NE(extractCC1Arguments(Args), nullptr); |
| 411 |
} |
| 412 |
|
| 413 |
TEST_F(CommandLineExtractorTest, AcceptOffloadingCompile) { |
| 414 |
addFile("test.c", "int main() {}\n"); |
| 415 |
const char *Args[] = {"clang", "-target", "arm64-apple-macosx11.0.0", |
| 416 |
"-c", "-x", "hip", |
| 417 |
"test.c", "-nogpulib", "-nogpuinc"}; |
| 418 |
EXPECT_NE(extractCC1Arguments(Args), nullptr); |
| 419 |
} |
| 420 |
|
| 421 |
TEST_F(CommandLineExtractorTest, AcceptOffloadingSyntaxOnly) { |
| 422 |
addFile("test.c", "int main() {}\n"); |
| 423 |
const char *Args[] = { |
| 424 |
"clang", "-target", "arm64-apple-macosx11.0.0", |
| 425 |
"-fsyntax-only", "-x", "hip", |
| 426 |
"test.c", "-nogpulib", "-nogpuinc"}; |
| 427 |
EXPECT_NE(extractCC1Arguments(Args), nullptr); |
| 428 |
} |
| 429 |
|
| 430 |
TEST_F(CommandLineExtractorTest, AcceptExternalAssembler) { |
| 431 |
addFile("test.c", "int main() {}\n"); |
| 432 |
const char *Args[] = { |
| 433 |
"clang", "-target", "arm64-apple-macosx11.0.0", "-fno-integrated-as", |
| 434 |
"-c", "test.c"}; |
| 435 |
EXPECT_NE(extractCC1Arguments(Args), nullptr); |
| 436 |
} |
| 437 |
|
| 438 |
TEST_F(CommandLineExtractorTest, AcceptEmbedBitcode) { |
| 439 |
addFile("test.c", "int main() {}\n"); |
| 440 |
const char *Args[] = {"clang", "-target", "arm64-apple-macosx11.0.0", |
| 441 |
"-c", "-fembed-bitcode", "test.c"}; |
| 442 |
EXPECT_NE(extractCC1Arguments(Args), nullptr); |
| 443 |
} |
| 444 |
|
| 445 |
TEST_F(CommandLineExtractorTest, AcceptSaveTemps) { |
| 446 |
addFile("test.c", "int main() {}\n"); |
| 447 |
const char *Args[] = {"clang", "-target", "arm64-apple-macosx11.0.0", |
| 448 |
"-c", "-save-temps", "test.c"}; |
| 449 |
EXPECT_NE(extractCC1Arguments(Args), nullptr); |
| 450 |
} |
| 451 |
|
| 452 |
TEST_F(CommandLineExtractorTest, RejectMultipleArchitectures) { |
| 453 |
addFile("test.c", "int main() {}\n"); |
| 454 |
const char *Args[] = {"clang", "-target", "arm64-apple-macosx11.0.0", |
| 455 |
"-arch", "x86_64", "-arch", |
| 456 |
"arm64", "-c", "test.c"}; |
| 457 |
EXPECT_EQ(extractCC1Arguments(Args), nullptr); |
| 458 |
} |
| 459 |
|
| 460 |
TEST_F(CommandLineExtractorTest, RejectMultipleInputFiles) { |
| 461 |
addFile("one.c", "void one() {}\n"); |
| 462 |
addFile("two.c", "void two() {}\n"); |
| 463 |
const char *Args[] = {"clang", "-target", "arm64-apple-macosx11.0.0", |
| 464 |
"-c", "one.c", "two.c"}; |
| 465 |
EXPECT_EQ(extractCC1Arguments(Args), nullptr); |
| 466 |
} |
| 467 |
|
| 468 |
struct VerifyEndCallback : public SourceFileCallbacks { |
| 469 |
VerifyEndCallback() : BeginCalled(0), EndCalled(0), Matched(false) {} |
| 470 |
bool handleBeginSource(CompilerInstance &CI) override { |
| 471 |
++BeginCalled; |
| 472 |
return true; |
| 473 |
} |
| 474 |
void handleEndSource() override { ++EndCalled; } |
| 475 |
std::unique_ptr<ASTConsumer> newASTConsumer() { |
| 476 |
return std::make_unique<FindTopLevelDeclConsumer>(&Matched); |
| 477 |
} |
| 478 |
unsigned BeginCalled; |
| 479 |
unsigned EndCalled; |
| 480 |
bool Matched; |
| 481 |
}; |
| 482 |
|
| 483 |
#if !defined(_WIN32) |
| 484 |
TEST(newFrontendActionFactory, InjectsSourceFileCallbacks) { |
| 485 |
VerifyEndCallback EndCallback; |
| 486 |
|
| 487 |
FixedCompilationDatabase Compilations("/", std::vector<std::string>()); |
| 488 |
std::vector<std::string> Sources; |
| 489 |
Sources.push_back("/a.cc"); |
| 490 |
Sources.push_back("/b.cc"); |
| 491 |
ClangTool Tool(Compilations, Sources); |
| 492 |
|
| 493 |
Tool.mapVirtualFile("/a.cc", "void a() {}"); |
| 494 |
Tool.mapVirtualFile("/b.cc", "void b() {}"); |
| 495 |
|
| 496 |
std::unique_ptr<FrontendActionFactory> Action( |
| 497 |
newFrontendActionFactory(&EndCallback, &EndCallback)); |
| 498 |
Tool.run(Action.get()); |
| 499 |
|
| 500 |
EXPECT_TRUE(EndCallback.Matched); |
| 501 |
EXPECT_EQ(2u, EndCallback.BeginCalled); |
| 502 |
EXPECT_EQ(2u, EndCallback.EndCalled); |
| 503 |
} |
| 504 |
#endif |
| 505 |
|
| 506 |
struct SkipBodyConsumer : public clang::ASTConsumer { |
| 507 |
/// Skip the 'skipMe' function. |
| 508 |
bool shouldSkipFunctionBody(Decl *D) override { |
| 509 |
NamedDecl *F = dyn_cast<NamedDecl>(D); |
| 510 |
return F && F->getNameAsString() == "skipMe"; |
| 511 |
} |
| 512 |
}; |
| 513 |
|
| 514 |
struct SkipBodyAction : public clang::ASTFrontendAction { |
| 515 |
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler, |
| 516 |
StringRef) override { |
| 517 |
Compiler.getFrontendOpts().SkipFunctionBodies = true; |
| 518 |
return std::make_unique<SkipBodyConsumer>(); |
| 519 |
} |
| 520 |
}; |
| 521 |
|
| 522 |
TEST(runToolOnCode, TestSkipFunctionBody) { |
| 523 |
std::vector<std::string> Args = {"-std=c++11"}; |
| 524 |
std::vector<std::string> Args2 = {"-fno-delayed-template-parsing"}; |
| 525 |
|
| 526 |
EXPECT_TRUE(runToolOnCode(std::make_unique<SkipBodyAction>(), |
| 527 |
"int skipMe() { an_error_here }")); |
| 528 |
EXPECT_FALSE(runToolOnCode(std::make_unique<SkipBodyAction>(), |
| 529 |
"int skipMeNot() { an_error_here }")); |
| 530 |
|
| 531 |
// Test constructors with initializers |
| 532 |
EXPECT_TRUE(runToolOnCodeWithArgs( |
| 533 |
std::make_unique<SkipBodyAction>(), |
| 534 |
"struct skipMe { skipMe() : an_error() { more error } };", Args)); |
| 535 |
EXPECT_TRUE(runToolOnCodeWithArgs( |
| 536 |
std::make_unique<SkipBodyAction>(), "struct skipMe { skipMe(); };" |
| 537 |
"skipMe::skipMe() : an_error([](){;}) { more error }", |
| 538 |
Args)); |
| 539 |
EXPECT_TRUE(runToolOnCodeWithArgs( |
| 540 |
std::make_unique<SkipBodyAction>(), "struct skipMe { skipMe(); };" |
| 541 |
"skipMe::skipMe() : an_error{[](){;}} { more error }", |
| 542 |
Args)); |
| 543 |
EXPECT_TRUE(runToolOnCodeWithArgs( |
| 544 |
std::make_unique<SkipBodyAction>(), |
| 545 |
"struct skipMe { skipMe(); };" |
| 546 |
"skipMe::skipMe() : a<b<c>(e)>>(), f{}, g() { error }", |
| 547 |
Args)); |
| 548 |
EXPECT_TRUE(runToolOnCodeWithArgs( |
| 549 |
std::make_unique<SkipBodyAction>(), "struct skipMe { skipMe() : bases()... { error } };", |
| 550 |
Args)); |
| 551 |
|
| 552 |
EXPECT_FALSE(runToolOnCodeWithArgs( |
| 553 |
std::make_unique<SkipBodyAction>(), "struct skipMeNot { skipMeNot() : an_error() { } };", |
| 554 |
Args)); |
| 555 |
EXPECT_FALSE(runToolOnCodeWithArgs(std::make_unique<SkipBodyAction>(), |
| 556 |
"struct skipMeNot { skipMeNot(); };" |
| 557 |
"skipMeNot::skipMeNot() : an_error() { }", |
| 558 |
Args)); |
| 559 |
|
| 560 |
// Try/catch |
| 561 |
EXPECT_TRUE(runToolOnCode( |
| 562 |
std::make_unique<SkipBodyAction>(), |
| 563 |
"void skipMe() try { an_error() } catch(error) { error };")); |
| 564 |
EXPECT_TRUE(runToolOnCode( |
| 565 |
std::make_unique<SkipBodyAction>(), |
| 566 |
"struct S { void skipMe() try { an_error() } catch(error) { error } };")); |
| 567 |
EXPECT_TRUE( |
| 568 |
runToolOnCode(std::make_unique<SkipBodyAction>(), |
| 569 |
"void skipMe() try { an_error() } catch(error) { error; }" |
| 570 |
"catch(error) { error } catch (error) { }")); |
| 571 |
EXPECT_FALSE(runToolOnCode( |
| 572 |
std::make_unique<SkipBodyAction>(), |
| 573 |
"void skipMe() try something;")); // don't crash while parsing |
| 574 |
|
| 575 |
// Template |
| 576 |
EXPECT_TRUE(runToolOnCode( |
| 577 |
std::make_unique<SkipBodyAction>(), "template<typename T> int skipMe() { an_error_here }" |
| 578 |
"int x = skipMe<int>();")); |
| 579 |
EXPECT_FALSE(runToolOnCodeWithArgs( |
| 580 |
std::make_unique<SkipBodyAction>(), |
| 581 |
"template<typename T> int skipMeNot() { an_error_here }", Args2)); |
| 582 |
} |
| 583 |
|
| 584 |
TEST(runToolOnCodeWithArgs, TestNoDepFile) { |
| 585 |
llvm::SmallString<32> DepFilePath; |
| 586 |
ASSERT_FALSE(llvm::sys::fs::getPotentiallyUniqueTempFileName("depfile", "d", |
| 587 |
DepFilePath)); |
| 588 |
std::vector<std::string> Args; |
| 589 |
Args.push_back("-MMD"); |
| 590 |
Args.push_back("-MT"); |
| 591 |
Args.push_back(std::string(DepFilePath.str())); |
| 592 |
Args.push_back("-MF"); |
| 593 |
Args.push_back(std::string(DepFilePath.str())); |
| 594 |
EXPECT_TRUE(runToolOnCodeWithArgs(std::make_unique<SkipBodyAction>(), "", Args)); |
| 595 |
EXPECT_FALSE(llvm::sys::fs::exists(DepFilePath.str())); |
| 596 |
EXPECT_FALSE(llvm::sys::fs::remove(DepFilePath.str())); |
| 597 |
} |
| 598 |
|
| 599 |
struct CheckColoredDiagnosticsAction : public clang::ASTFrontendAction { |
| 600 |
CheckColoredDiagnosticsAction(bool ShouldShowColor) |
| 601 |
: ShouldShowColor(ShouldShowColor) {} |
| 602 |
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler, |
| 603 |
StringRef) override { |
| 604 |
if (Compiler.getDiagnosticOpts().ShowColors != ShouldShowColor) |
| 605 |
Compiler.getDiagnostics().Report( |
| 606 |
Compiler.getDiagnostics().getCustomDiagID( |
| 607 |
DiagnosticsEngine::Fatal, |
| 608 |
"getDiagnosticOpts().ShowColors != ShouldShowColor")); |
| 609 |
return std::make_unique<ASTConsumer>(); |
| 610 |
} |
| 611 |
|
| 612 |
private: |
| 613 |
bool ShouldShowColor = true; |
| 614 |
}; |
| 615 |
|
| 616 |
TEST(runToolOnCodeWithArgs, DiagnosticsColor) { |
| 617 |
EXPECT_TRUE(runToolOnCodeWithArgs( |
| 618 |
std::make_unique<CheckColoredDiagnosticsAction>(true), "", |
| 619 |
{"-fcolor-diagnostics"})); |
| 620 |
EXPECT_TRUE(runToolOnCodeWithArgs( |
| 621 |
std::make_unique<CheckColoredDiagnosticsAction>(false), "", |
| 622 |
{"-fno-color-diagnostics"})); |
| 623 |
EXPECT_TRUE(runToolOnCodeWithArgs( |
| 624 |
std::make_unique<CheckColoredDiagnosticsAction>(true), "", |
| 625 |
{"-fno-color-diagnostics", "-fcolor-diagnostics"})); |
| 626 |
EXPECT_TRUE(runToolOnCodeWithArgs( |
| 627 |
std::make_unique<CheckColoredDiagnosticsAction>(false), "", |
| 628 |
{"-fcolor-diagnostics", "-fno-color-diagnostics"})); |
| 629 |
EXPECT_TRUE(runToolOnCodeWithArgs( |
| 630 |
std::make_unique<CheckColoredDiagnosticsAction>(true), "", |
| 631 |
{"-fno-color-diagnostics", "-fdiagnostics-color=always"})); |
| 632 |
|
| 633 |
// Check that this test would fail if ShowColors is not what it should. |
| 634 |
EXPECT_FALSE(runToolOnCodeWithArgs( |
| 635 |
std::make_unique<CheckColoredDiagnosticsAction>(false), "", |
| 636 |
{"-fcolor-diagnostics"})); |
| 637 |
} |
| 638 |
|
| 639 |
TEST(ClangToolTest, ArgumentAdjusters) { |
| 640 |
FixedCompilationDatabase Compilations("/", std::vector<std::string>()); |
| 641 |
|
| 642 |
ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc")); |
| 643 |
Tool.mapVirtualFile("/a.cc", "void a() {}"); |
| 644 |
|
| 645 |
std::unique_ptr<FrontendActionFactory> Action( |
| 646 |
newFrontendActionFactory<SyntaxOnlyAction>()); |
| 647 |
|
| 648 |
bool Found = false; |
| 649 |
bool Ran = false; |
| 650 |
ArgumentsAdjuster CheckSyntaxOnlyAdjuster = |
| 651 |
[&Found, &Ran](const CommandLineArguments &Args, StringRef /*unused*/) { |
| 652 |
Ran = true; |
| 653 |
if (llvm::is_contained(Args, "-fsyntax-only")) |
| 654 |
Found = true; |
| 655 |
return Args; |
| 656 |
}; |
| 657 |
Tool.appendArgumentsAdjuster(CheckSyntaxOnlyAdjuster); |
| 658 |
Tool.run(Action.get()); |
| 659 |
EXPECT_TRUE(Ran); |
| 660 |
EXPECT_TRUE(Found); |
| 661 |
|
| 662 |
Ran = Found = false; |
| 663 |
Tool.clearArgumentsAdjusters(); |
| 664 |
Tool.appendArgumentsAdjuster(CheckSyntaxOnlyAdjuster); |
| 665 |
Tool.appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster()); |
| 666 |
Tool.run(Action.get()); |
| 667 |
EXPECT_TRUE(Ran); |
| 668 |
EXPECT_FALSE(Found); |
| 669 |
} |
| 670 |
|
| 671 |
TEST(ClangToolTest, NoDoubleSyntaxOnly) { |
| 672 |
FixedCompilationDatabase Compilations("/", {"-fsyntax-only"}); |
| 673 |
|
| 674 |
ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc")); |
| 675 |
Tool.mapVirtualFile("/a.cc", "void a() {}"); |
| 676 |
|
| 677 |
std::unique_ptr<FrontendActionFactory> Action( |
| 678 |
newFrontendActionFactory<SyntaxOnlyAction>()); |
| 679 |
|
| 680 |
size_t SyntaxOnlyCount = 0; |
| 681 |
ArgumentsAdjuster CheckSyntaxOnlyAdjuster = |
| 682 |
[&SyntaxOnlyCount](const CommandLineArguments &Args, |
| 683 |
StringRef /*unused*/) { |
| 684 |
for (llvm::StringRef Arg : Args) { |
| 685 |
if (Arg == "-fsyntax-only") |
| 686 |
++SyntaxOnlyCount; |
| 687 |
} |
| 688 |
return Args; |
| 689 |
}; |
| 690 |
|
| 691 |
Tool.clearArgumentsAdjusters(); |
| 692 |
Tool.appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster()); |
| 693 |
Tool.appendArgumentsAdjuster(CheckSyntaxOnlyAdjuster); |
| 694 |
Tool.run(Action.get()); |
| 695 |
EXPECT_EQ(SyntaxOnlyCount, 1U); |
| 696 |
} |
| 697 |
|
| 698 |
TEST(ClangToolTest, NoOutputCommands) { |
| 699 |
FixedCompilationDatabase Compilations("/", {"-save-temps", "-save-temps=cwd", |
| 700 |
"--save-temps", |
| 701 |
"--save-temps=somedir"}); |
| 702 |
|
| 703 |
ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc")); |
| 704 |
Tool.mapVirtualFile("/a.cc", "void a() {}"); |
| 705 |
|
| 706 |
std::unique_ptr<FrontendActionFactory> Action( |
| 707 |
newFrontendActionFactory<SyntaxOnlyAction>()); |
| 708 |
|
| 709 |
const std::vector<llvm::StringRef> OutputCommands = {"-save-temps"}; |
| 710 |
bool Ran = false; |
| 711 |
ArgumentsAdjuster CheckSyntaxOnlyAdjuster = |
| 712 |
[&OutputCommands, &Ran](const CommandLineArguments &Args, |
| 713 |
StringRef /*unused*/) { |
| 714 |
for (llvm::StringRef Arg : Args) { |
| 715 |
for (llvm::StringRef OutputCommand : OutputCommands) |
| 716 |
EXPECT_FALSE(Arg.contains(OutputCommand)); |
| 717 |
} |
| 718 |
Ran = true; |
| 719 |
return Args; |
| 720 |
}; |
| 721 |
|
| 722 |
Tool.clearArgumentsAdjusters(); |
| 723 |
Tool.appendArgumentsAdjuster(getClangSyntaxOnlyAdjuster()); |
| 724 |
Tool.appendArgumentsAdjuster(CheckSyntaxOnlyAdjuster); |
| 725 |
Tool.run(Action.get()); |
| 726 |
EXPECT_TRUE(Ran); |
| 727 |
} |
| 728 |
|
| 729 |
TEST(ClangToolTest, BaseVirtualFileSystemUsage) { |
| 730 |
FixedCompilationDatabase Compilations("/", std::vector<std::string>()); |
| 731 |
llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> OverlayFileSystem( |
| 732 |
new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem())); |
| 733 |
llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem( |
| 734 |
new llvm::vfs::InMemoryFileSystem); |
| 735 |
OverlayFileSystem->pushOverlay(InMemoryFileSystem); |
| 736 |
|
| 737 |
InMemoryFileSystem->addFile( |
| 738 |
"a.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int main() {}")); |
| 739 |
|
| 740 |
ClangTool Tool(Compilations, std::vector<std::string>(1, "a.cpp"), |
| 741 |
std::make_shared<PCHContainerOperations>(), OverlayFileSystem); |
| 742 |
std::unique_ptr<FrontendActionFactory> Action( |
| 743 |
newFrontendActionFactory<SyntaxOnlyAction>()); |
| 744 |
EXPECT_EQ(0, Tool.run(Action.get())); |
| 745 |
} |
| 746 |
|
| 747 |
// Check getClangStripDependencyFileAdjuster doesn't strip args after -MD/-MMD. |
| 748 |
TEST(ClangToolTest, StripDependencyFileAdjuster) { |
| 749 |
FixedCompilationDatabase Compilations("/", {"-MD", "-c", "-MMD", "-w"}); |
| 750 |
|
| 751 |
ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc")); |
| 752 |
Tool.mapVirtualFile("/a.cc", "void a() {}"); |
| 753 |
|
| 754 |
std::unique_ptr<FrontendActionFactory> Action( |
| 755 |
newFrontendActionFactory<SyntaxOnlyAction>()); |
| 756 |
|
| 757 |
CommandLineArguments FinalArgs; |
| 758 |
ArgumentsAdjuster CheckFlagsAdjuster = |
| 759 |
[&FinalArgs](const CommandLineArguments &Args, StringRef /*unused*/) { |
| 760 |
FinalArgs = Args; |
| 761 |
return Args; |
| 762 |
}; |
| 763 |
Tool.clearArgumentsAdjusters(); |
| 764 |
Tool.appendArgumentsAdjuster(getClangStripDependencyFileAdjuster()); |
| 765 |
Tool.appendArgumentsAdjuster(CheckFlagsAdjuster); |
| 766 |
Tool.run(Action.get()); |
| 767 |
|
| 768 |
auto HasFlag = [&FinalArgs](const std::string &Flag) { |
| 769 |
return llvm::find(FinalArgs, Flag) != FinalArgs.end(); |
| 770 |
}; |
| 771 |
EXPECT_FALSE(HasFlag("-MD")); |
| 772 |
EXPECT_FALSE(HasFlag("-MMD")); |
| 773 |
EXPECT_TRUE(HasFlag("-c")); |
| 774 |
EXPECT_TRUE(HasFlag("-w")); |
| 775 |
} |
| 776 |
|
| 777 |
// Check getClangStripDependencyFileAdjuster strips /showIncludes and variants |
| 778 |
TEST(ClangToolTest, StripDependencyFileAdjusterShowIncludes) { |
| 779 |
FixedCompilationDatabase Compilations( |
| 780 |
"/", {"/showIncludes", "/showIncludes:user", "-showIncludes", |
| 781 |
"-showIncludes:user", "-c"}); |
| 782 |
|
| 783 |
ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc")); |
| 784 |
Tool.mapVirtualFile("/a.cc", "void a() {}"); |
| 785 |
|
| 786 |
std::unique_ptr<FrontendActionFactory> Action( |
| 787 |
newFrontendActionFactory<SyntaxOnlyAction>()); |
| 788 |
|
| 789 |
CommandLineArguments FinalArgs; |
| 790 |
ArgumentsAdjuster CheckFlagsAdjuster = |
| 791 |
[&FinalArgs](const CommandLineArguments &Args, StringRef /*unused*/) { |
| 792 |
FinalArgs = Args; |
| 793 |
return Args; |
| 794 |
}; |
| 795 |
Tool.clearArgumentsAdjusters(); |
| 796 |
Tool.appendArgumentsAdjuster(getClangStripDependencyFileAdjuster()); |
| 797 |
Tool.appendArgumentsAdjuster(CheckFlagsAdjuster); |
| 798 |
Tool.run(Action.get()); |
| 799 |
|
| 800 |
auto HasFlag = [&FinalArgs](const std::string &Flag) { |
| 801 |
return llvm::find(FinalArgs, Flag) != FinalArgs.end(); |
| 802 |
}; |
| 803 |
EXPECT_FALSE(HasFlag("/showIncludes")); |
| 804 |
EXPECT_FALSE(HasFlag("/showIncludes:user")); |
| 805 |
EXPECT_FALSE(HasFlag("-showIncludes")); |
| 806 |
EXPECT_FALSE(HasFlag("-showIncludes:user")); |
| 807 |
EXPECT_TRUE(HasFlag("-c")); |
| 808 |
} |
| 809 |
|
| 810 |
// Check getClangStripDependencyFileAdjuster doesn't strip args when using the |
| 811 |
// MSVC cl.exe driver |
| 812 |
TEST(ClangToolTest, StripDependencyFileAdjusterMsvc) { |
| 813 |
FixedCompilationDatabase Compilations( |
| 814 |
"/", {"--driver-mode=cl", "-MD", "-MDd", "-MT", "-O1", "-MTd", "-MP"}); |
| 815 |
|
| 816 |
ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc")); |
| 817 |
Tool.mapVirtualFile("/a.cc", "void a() {}"); |
| 818 |
|
| 819 |
std::unique_ptr<FrontendActionFactory> Action( |
| 820 |
newFrontendActionFactory<SyntaxOnlyAction>()); |
| 821 |
|
| 822 |
CommandLineArguments FinalArgs; |
| 823 |
ArgumentsAdjuster CheckFlagsAdjuster = |
| 824 |
[&FinalArgs](const CommandLineArguments &Args, StringRef /*unused*/) { |
| 825 |
FinalArgs = Args; |
| 826 |
return Args; |
| 827 |
}; |
| 828 |
Tool.clearArgumentsAdjusters(); |
| 829 |
Tool.appendArgumentsAdjuster(getClangStripDependencyFileAdjuster()); |
| 830 |
Tool.appendArgumentsAdjuster(CheckFlagsAdjuster); |
| 831 |
Tool.run(Action.get()); |
| 832 |
|
| 833 |
auto HasFlag = [&FinalArgs](const std::string &Flag) { |
| 834 |
return llvm::find(FinalArgs, Flag) != FinalArgs.end(); |
| 835 |
}; |
| 836 |
EXPECT_TRUE(HasFlag("-MD")); |
| 837 |
EXPECT_TRUE(HasFlag("-MDd")); |
| 838 |
EXPECT_TRUE(HasFlag("-MT")); |
| 839 |
EXPECT_TRUE(HasFlag("-O1")); |
| 840 |
EXPECT_TRUE(HasFlag("-MTd")); |
| 841 |
EXPECT_TRUE(HasFlag("-MP")); |
| 842 |
} |
| 843 |
|
| 844 |
// Check getClangStripPluginsAdjuster strips plugin related args. |
| 845 |
TEST(ClangToolTest, StripPluginsAdjuster) { |
| 846 |
FixedCompilationDatabase Compilations( |
| 847 |
"/", {"-Xclang", "-add-plugin", "-Xclang", "random-plugin"}); |
| 848 |
|
| 849 |
ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc")); |
| 850 |
Tool.mapVirtualFile("/a.cc", "void a() {}"); |
| 851 |
|
| 852 |
std::unique_ptr<FrontendActionFactory> Action( |
| 853 |
newFrontendActionFactory<SyntaxOnlyAction>()); |
| 854 |
|
| 855 |
CommandLineArguments FinalArgs; |
| 856 |
ArgumentsAdjuster CheckFlagsAdjuster = |
| 857 |
[&FinalArgs](const CommandLineArguments &Args, StringRef /*unused*/) { |
| 858 |
FinalArgs = Args; |
| 859 |
return Args; |
| 860 |
}; |
| 861 |
Tool.clearArgumentsAdjusters(); |
| 862 |
Tool.appendArgumentsAdjuster(getStripPluginsAdjuster()); |
| 863 |
Tool.appendArgumentsAdjuster(CheckFlagsAdjuster); |
| 864 |
Tool.run(Action.get()); |
| 865 |
|
| 866 |
auto HasFlag = [&FinalArgs](const std::string &Flag) { |
| 867 |
return llvm::find(FinalArgs, Flag) != FinalArgs.end(); |
| 868 |
}; |
| 869 |
EXPECT_FALSE(HasFlag("-Xclang")); |
| 870 |
EXPECT_FALSE(HasFlag("-add-plugin")); |
| 871 |
EXPECT_FALSE(HasFlag("-random-plugin")); |
| 872 |
} |
| 873 |
|
| 874 |
namespace { |
| 875 |
/// Find a target name such that looking for it in TargetRegistry by that name |
| 876 |
/// returns the same target. We expect that there is at least one target |
| 877 |
/// configured with this property. |
| 878 |
std::string getAnyTarget() { |
| 879 |
llvm::InitializeAllTargets(); |
| 880 |
for (const auto &Target : llvm::TargetRegistry::targets()) { |
| 881 |
std::string Error; |
| 882 |
StringRef TargetName(Target.getName()); |
| 883 |
if (TargetName == "x86-64") |
| 884 |
TargetName = "x86_64"; |
| 885 |
if (llvm::TargetRegistry::lookupTarget(std::string(TargetName), Error) == |
| 886 |
&Target) { |
| 887 |
return std::string(TargetName); |
| 888 |
} |
| 889 |
} |
| 890 |
return ""; |
| 891 |
} |
| 892 |
} |
| 893 |
|
| 894 |
TEST(addTargetAndModeForProgramName, AddsTargetAndMode) { |
| 895 |
std::string Target = getAnyTarget(); |
| 896 |
ASSERT_FALSE(Target.empty()); |
| 897 |
|
| 898 |
std::vector<std::string> Args = {"clang", "-foo"}; |
| 899 |
addTargetAndModeForProgramName(Args, ""); |
| 900 |
EXPECT_EQ((std::vector<std::string>{"clang", "-foo"}), Args); |
| 901 |
addTargetAndModeForProgramName(Args, Target + "-g++"); |
| 902 |
EXPECT_EQ((std::vector<std::string>{"clang", "--target=" + Target, |
| 903 |
"--driver-mode=g++", "-foo"}), |
| 904 |
Args); |
| 905 |
} |
| 906 |
|
| 907 |
TEST(addTargetAndModeForProgramName, PathIgnored) { |
| 908 |
std::string Target = getAnyTarget(); |
| 909 |
ASSERT_FALSE(Target.empty()); |
| 910 |
|
| 911 |
SmallString<32> ToolPath; |
| 912 |
llvm::sys::path::append(ToolPath, "foo", "bar", Target + "-g++"); |
| 913 |
|
| 914 |
std::vector<std::string> Args = {"clang", "-foo"}; |
| 915 |
addTargetAndModeForProgramName(Args, ToolPath); |
| 916 |
EXPECT_EQ((std::vector<std::string>{"clang", "--target=" + Target, |
| 917 |
"--driver-mode=g++", "-foo"}), |
| 918 |
Args); |
| 919 |
} |
| 920 |
|
| 921 |
TEST(addTargetAndModeForProgramName, IgnoresExistingTarget) { |
| 922 |
std::string Target = getAnyTarget(); |
| 923 |
ASSERT_FALSE(Target.empty()); |
| 924 |
|
| 925 |
std::vector<std::string> Args = {"clang", "-foo", "-target", "something"}; |
| 926 |
addTargetAndModeForProgramName(Args, Target + "-g++"); |
| 927 |
EXPECT_EQ((std::vector<std::string>{"clang", "--driver-mode=g++", "-foo", |
| 928 |
"-target", "something"}), |
| 929 |
Args); |
| 930 |
|
| 931 |
std::vector<std::string> ArgsAlt = {"clang", "-foo", "--target=something"}; |
| 932 |
addTargetAndModeForProgramName(ArgsAlt, Target + "-g++"); |
| 933 |
EXPECT_EQ((std::vector<std::string>{"clang", "--driver-mode=g++", "-foo", |
| 934 |
"--target=something"}), |
| 935 |
ArgsAlt); |
| 936 |
} |
| 937 |
|
| 938 |
TEST(addTargetAndModeForProgramName, IgnoresExistingMode) { |
| 939 |
std::string Target = getAnyTarget(); |
| 940 |
ASSERT_FALSE(Target.empty()); |
| 941 |
|
| 942 |
std::vector<std::string> Args = {"clang", "-foo", "--driver-mode=abc"}; |
| 943 |
addTargetAndModeForProgramName(Args, Target + "-g++"); |
| 944 |
EXPECT_EQ((std::vector<std::string>{"clang", "--target=" + Target, "-foo", |
| 945 |
"--driver-mode=abc"}), |
| 946 |
Args); |
| 947 |
} |
| 948 |
|
| 949 |
#ifndef _WIN32 |
| 950 |
TEST(ClangToolTest, BuildASTs) { |
| 951 |
FixedCompilationDatabase Compilations("/", std::vector<std::string>()); |
| 952 |
|
| 953 |
std::vector<std::string> Sources; |
| 954 |
Sources.push_back("/a.cc"); |
| 955 |
Sources.push_back("/b.cc"); |
| 956 |
ClangTool Tool(Compilations, Sources); |
| 957 |
|
| 958 |
Tool.mapVirtualFile("/a.cc", "void a() {}"); |
| 959 |
Tool.mapVirtualFile("/b.cc", "void b() {}"); |
| 960 |
|
| 961 |
std::vector<std::unique_ptr<ASTUnit>> ASTs; |
| 962 |
EXPECT_EQ(0, Tool.buildASTs(ASTs)); |
| 963 |
EXPECT_EQ(2u, ASTs.size()); |
| 964 |
} |
| 965 |
|
| 966 |
TEST(ClangToolTest, InjectDiagnosticConsumer) { |
| 967 |
FixedCompilationDatabase Compilations("/", std::vector<std::string>()); |
| 968 |
ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc")); |
| 969 |
Tool.mapVirtualFile("/a.cc", "int x = undeclared;"); |
| 970 |
TestDiagnosticConsumer Consumer; |
| 971 |
Tool.setDiagnosticConsumer(&Consumer); |
| 972 |
std::unique_ptr<FrontendActionFactory> Action( |
| 973 |
newFrontendActionFactory<SyntaxOnlyAction>()); |
| 974 |
Tool.run(Action.get()); |
| 975 |
EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen); |
| 976 |
} |
| 977 |
|
| 978 |
TEST(ClangToolTest, InjectDiagnosticConsumerInBuildASTs) { |
| 979 |
FixedCompilationDatabase Compilations("/", std::vector<std::string>()); |
| 980 |
ClangTool Tool(Compilations, std::vector<std::string>(1, "/a.cc")); |
| 981 |
Tool.mapVirtualFile("/a.cc", "int x = undeclared;"); |
| 982 |
TestDiagnosticConsumer Consumer; |
| 983 |
Tool.setDiagnosticConsumer(&Consumer); |
| 984 |
std::vector<std::unique_ptr<ASTUnit>> ASTs; |
| 985 |
Tool.buildASTs(ASTs); |
| 986 |
EXPECT_EQ(1u, ASTs.size()); |
| 987 |
EXPECT_EQ(1u, Consumer.NumDiagnosticsSeen); |
| 988 |
} |
| 989 |
#endif |
| 990 |
|
| 991 |
TEST(runToolOnCode, TestResetDiagnostics) { |
| 992 |
// This is a tool that resets the diagnostic during the compilation. |
| 993 |
struct ResetDiagnosticAction : public clang::ASTFrontendAction { |
| 994 |
std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &Compiler, |
| 995 |
StringRef) override { |
| 996 |
struct Consumer : public clang::ASTConsumer { |
| 997 |
bool HandleTopLevelDecl(clang::DeclGroupRef D) override { |
| 998 |
auto &Diags = (*D.begin())->getASTContext().getDiagnostics(); |
| 999 |
// Ignore any error |
| 1000 |
Diags.Reset(); |
| 1001 |
// Disable warnings because computing the CFG might crash. |
| 1002 |
Diags.setIgnoreAllWarnings(true); |
| 1003 |
return true; |
| 1004 |
} |
| 1005 |
}; |
| 1006 |
return std::make_unique<Consumer>(); |
| 1007 |
} |
| 1008 |
}; |
| 1009 |
|
| 1010 |
// Should not crash |
| 1011 |
EXPECT_FALSE( |
| 1012 |
runToolOnCode(std::make_unique<ResetDiagnosticAction>(), |
| 1013 |
"struct Foo { Foo(int); ~Foo(); struct Fwd _fwd; };" |
| 1014 |
"void func() { long x; Foo f(x); }")); |
| 1015 |
} |
| 1016 |
|
| 1017 |
} // end namespace tooling |
| 1018 |
} // end namespace clang |